answer
stringlengths
17
10.2M
package intellimate.izou.main; import intellimate.izou.activator.ActivatorManager; import intellimate.izou.addon.AddOn; import intellimate.izou.addon.AddOnManager; import intellimate.izou.events.EventDistributor; import intellimate.izou.events.EventPropertiesManager; import intellimate.izou.events.LocalEventManager; import intellimate.izou.output.OutputManager; import intellimate.izou.resource.ResourceManager; import intellimate.izou.system.*; import intellimate.izou.threadpool.ThreadPoolManager; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.IOException; import java.nio.file.Paths; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; /** * Main Class. * * This is where our journey begins and all the Managers get initialized */ @SuppressWarnings("FieldCanBeLocal") public class Main { public static AtomicBoolean jfxToolKitInit; private static final long INIT_TIME_LIMIT = 10000; private final OutputManager outputManager; private final ResourceManager resourceManager; private final EventDistributor eventDistributor; private final LocalEventManager localEventManager; private final ActivatorManager activatorManager; private final AddOnManager addOnManager; private final FileManager fileManager; private final FilePublisher filePublisher; private final IzouLogger izouLogger; private final ThreadPoolManager threadPoolManager; private final EventPropertiesManager eventPropertiesManager; private final Logger fileLogger = LogManager.getLogger(this.getClass()); /** * Creates a new Main instance with debugging enabled (doesn't search the lib-folder) * * @param javaFX true if javaFX should be started, false otherwise * @param debug if true, izou will not load plugin from the lib-folder */ private Main(boolean javaFX, boolean debug) { this(null, javaFX, debug); } /** * If you want to debug your Plugin, you can get an Main instance with this Method, JavaFX is disabled * * @param addOns a List of AddOns to run */ public Main(List<AddOn> addOns) { this(addOns, false, false); } /** * If you want to debug your Plugin, you can get an Main instance with this Method * * @param debug if true, izou will not load plugin from the lib-folder * @param addOns a List of AddOns to run */ public Main(List<AddOn> addOns, boolean debug) { this(addOns, false, debug); } /** * If you want to debug your Plugin, you can get an Main instance with this Method * * @param javaFX true if javaFX should be started, false otherwise * @param debug if true, izou will not load plugin from the lib-folder * @param addOns a List of AddOns to run */ public Main(List<AddOn> addOns, boolean javaFX, boolean debug) { if (javaFX) { jfxToolKitInit = new AtomicBoolean(false); JavaFXInitializer.initToolKit(); fileLogger.debug("Initializing JavaFX ToolKit"); long startTime = System.currentTimeMillis(); long duration = 0; while (!jfxToolKitInit.get() && duration < INIT_TIME_LIMIT) { duration = System.currentTimeMillis() - startTime; try { Thread.sleep(5000); } catch (InterruptedException e) { fileLogger.error("Error happened while thread was sleeping", e); } } if (!jfxToolKitInit.get()) { fileLogger.error("Unable to Initialize JavaFX ToolKit"); } fileLogger.debug("Done initializing JavaFX ToolKit"); } FileSystemManager fileSystemManager = new FileSystemManager(); try { fileSystemManager.createIzouFileSystem(); } catch (IOException e) { fileLogger.fatal("Failed to create the FileSystemManager", e); } threadPoolManager = new ThreadPoolManager(); izouLogger = new IzouLogger(); outputManager = new OutputManager(this); resourceManager = new ResourceManager(this); eventDistributor = new EventDistributor(this); localEventManager = new LocalEventManager(eventDistributor); threadPoolManager.getIzouThreadPool().submit(localEventManager); activatorManager = new ActivatorManager(this); filePublisher = new FilePublisher(this); eventPropertiesManager = new EventPropertiesManager(); FileManager fileManagerTemp; try { fileManagerTemp = new FileManager(filePublisher); } catch (IOException e) { fileManagerTemp = null; fileLogger.fatal("Failed to create the FileManager", e); } fileManager = fileManagerTemp; try { if (fileManager != null) { fileManager.registerFileDir(Paths.get(FileSystemManager.PROPERTIES_PATH), "PopularEvents.properties", eventPropertiesManager); } } catch (IOException e) { fileLogger.error("Unable to register the eventPropertiesManager", e); } addOnManager = new AddOnManager(this); if(addOns != null && !debug) { addOnManager.addAddOnsWithoutRegistering(addOns); } else if(addOns != null) { addOnManager.addAndRegisterAddOns(addOns); } if(!debug) addOnManager.retrieveAndRegisterAddOns(); } public static void main(String[] args) { @SuppressWarnings("UnusedAssignment") Main main = new Main(true, false); } public OutputManager getOutputManager() { return outputManager; } public LocalEventManager getLocalEventManager() { return localEventManager; } public ActivatorManager getActivatorManager() { return activatorManager; } public AddOnManager getAddOnManager() { return addOnManager; } public ResourceManager getResourceManager() { return resourceManager; } public EventDistributor getEventDistributor() { return eventDistributor; } public EventPropertiesManager getEventPropertiesManager() { return eventPropertiesManager; } public ThreadPoolManager getThreadPoolManager() { return threadPoolManager; } public FileManager getFileManager() { return fileManager; } public FilePublisher getFilePublisher() { return filePublisher; } public IzouLogger getIzouLogger() { return izouLogger; } }
package com.cctintl.c3dfx.controls; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javafx.animation.Interpolator; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.Timeline; import javafx.animation.Transition; import javafx.beans.DefaultProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.css.CssMetaData; import javafx.css.SimpleStyleableObjectProperty; import javafx.css.Styleable; import javafx.css.StyleableObjectProperty; import javafx.css.StyleableProperty; import javafx.event.EventHandler; import javafx.geometry.Pos; import javafx.scene.Parent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.Pane; import javafx.scene.layout.Region; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.util.Duration; import com.cctintl.c3dfx.controls.events.C3DDialogEvent; import com.cctintl.c3dfx.converters.DialogTransitionConverter; import com.cctintl.c3dfx.jidefx.CachedTimelineTransition; @DefaultProperty(value="content") public class C3DDialog extends StackPane { // public static enum C3DDialogLayout{PLAIN, HEADING, ACTIONS, BACKDROP}; public static enum C3DDialogTransition{CENTER, TOP, RIGHT, BOTTOM, LEFT}; private StackPane contentHolder; private StackPane overlayPane; private double offsetX = 0; private double offsetY = 0; private Pane dialogContainer; private Region content; private Transition animation; public C3DDialog(){ this(null,null,C3DDialogTransition.CENTER); } public C3DDialog(Pane dialogContainer, Region content, C3DDialogTransition transitionType) { initialize(); setContent(content,true); setDialogContainer(dialogContainer); this.transitionType.set(transitionType); } public C3DDialog(Pane dialogContainer, Region content, C3DDialogTransition transitionType, boolean overlayClose) { initialize(); setContent(content, overlayClose); setDialogContainer(dialogContainer); this.transitionType.set(transitionType); } private void initialize() { this.setVisible(false); this.getStyleClass().add(DEFAULT_STYLE_CLASS); } public Pane getDialogContainer() { return dialogContainer; } public void setDialogContainer(Pane dialogContainer) { if(dialogContainer!=null){ this.dialogContainer = dialogContainer; this.getChildren().clear(); this.getChildren().add(overlayPane); this.visibleProperty().unbind(); this.visibleProperty().bind(overlayPane.visibleProperty()); this.dialogContainer.getChildren().remove(this); this.dialogContainer.getChildren().add(this); // FIXME: need to be improved to consider only the parent boundary offsetX = (this.getParent().getBoundsInLocal().getWidth()); offsetY = (this.getParent().getBoundsInLocal().getHeight()); animation = getShowAnimation(transitionType.get()); } } public Region getContent() { return content; } public void setContent(Region content) { if(content!=null) this.setContent(content,true); } public void setContent(Region content, boolean overlayClose) { if(content!=null){ this.content = content; contentHolder = new StackPane(); contentHolder.getChildren().add(content); contentHolder.setBackground(new Background(new BackgroundFill(Color.WHITE, new CornerRadii(2), null))); DepthManager.setDepth(contentHolder, 4); contentHolder.setPickOnBounds(false); // ensure stackpane is never resized beyond it's preferred size contentHolder.setMaxSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE); overlayPane = new StackPane(); overlayPane.getChildren().add(contentHolder); overlayPane.getStyleClass().add("c3d-dialog-overlay-pane"); StackPane.setAlignment(contentHolder, Pos.CENTER); overlayPane.setVisible(false); overlayPane.setBackground(new Background(new BackgroundFill(Color.rgb(0, 0, 0, 0.1), null, null))); // close the dialog if clicked on the overlay pane if(overlayClose) overlayPane.setOnMousePressed((e)->close()); // prevent propagating the events to overlay pane contentHolder.addEventHandler(MouseEvent.ANY, (e)->e.consume()); } } public void show(Pane dialogContainer){ this.setDialogContainer(dialogContainer); animation.play(); } public void show(){ animation.play(); } public void close(){ animation.setRate(-1); animation.play(); animation.setOnFinished((e)->{ resetProperties(); }); onDialogClosedProperty.get().handle(new C3DDialogEvent(C3DDialogEvent.CLOSED)); } private Transition getShowAnimation(C3DDialogTransition transitionType){ Transition animation = null; if(contentHolder!=null){ switch (transitionType) { case LEFT: contentHolder.setTranslateX(-offsetX); animation = new LeftTransition(); break; case RIGHT: contentHolder.setTranslateX(offsetX); animation = new RightTransition(); break; case TOP: contentHolder.setTranslateY(-offsetY); animation = new TopTransition(); break; case BOTTOM: contentHolder.setTranslateY(offsetY); animation = new BottomTransition(); break; default: contentHolder.setScaleX(0); contentHolder.setScaleY(0); animation = new CenterTransition(); break; } } animation.setOnFinished((finish)->onDialogOpenedProperty.get().handle(new C3DDialogEvent(C3DDialogEvent.OPENED))); return animation; } private void resetProperties(){ overlayPane.setVisible(false); contentHolder.setTranslateX(0); contentHolder.setTranslateY(0); contentHolder.setScaleX(1); contentHolder.setScaleY(1); } private class LeftTransition extends CachedTimelineTransition { public LeftTransition() { super(contentHolder, new Timeline( new KeyFrame(Duration.ZERO, new KeyValue(contentHolder.translateXProperty(), -offsetX ,Interpolator.EASE_BOTH), new KeyValue(overlayPane.visibleProperty(), false ,Interpolator.EASE_BOTH) ), new KeyFrame(Duration.millis(10), new KeyValue(overlayPane.visibleProperty(), true ,Interpolator.EASE_BOTH), new KeyValue(overlayPane.opacityProperty(), 0,Interpolator.EASE_BOTH) ), new KeyFrame(Duration.millis(1000), new KeyValue(contentHolder.translateXProperty(), 0,Interpolator.EASE_BOTH), new KeyValue(overlayPane.opacityProperty(), 1,Interpolator.EASE_BOTH) )) ); // reduce the number to increase the shifting , increase number to reduce shifting setCycleDuration(Duration.seconds(0.4)); setDelay(Duration.seconds(0)); } } private class RightTransition extends CachedTimelineTransition { public RightTransition() { super(contentHolder, new Timeline( new KeyFrame(Duration.ZERO, new KeyValue(contentHolder.translateXProperty(), offsetX ,Interpolator.EASE_BOTH), new KeyValue(overlayPane.visibleProperty(), false ,Interpolator.EASE_BOTH) ), new KeyFrame(Duration.millis(10), new KeyValue(overlayPane.visibleProperty(), true ,Interpolator.EASE_BOTH), new KeyValue(overlayPane.opacityProperty(), 0, Interpolator.EASE_BOTH) ), new KeyFrame(Duration.millis(1000), new KeyValue(contentHolder.translateXProperty(), 0,Interpolator.EASE_BOTH), new KeyValue(overlayPane.opacityProperty(), 1, Interpolator.EASE_BOTH))) ); // reduce the number to increase the shifting , increase number to reduce shifting setCycleDuration(Duration.seconds(0.4)); setDelay(Duration.seconds(0)); } } private class TopTransition extends CachedTimelineTransition { public TopTransition() { super(contentHolder, new Timeline( new KeyFrame(Duration.ZERO, new KeyValue(contentHolder.translateYProperty(), -offsetY ,Interpolator.EASE_BOTH), new KeyValue(overlayPane.visibleProperty(), false ,Interpolator.EASE_BOTH) ), new KeyFrame(Duration.millis(10), new KeyValue(overlayPane.visibleProperty(), true ,Interpolator.EASE_BOTH), new KeyValue(overlayPane.opacityProperty(), 0, Interpolator.EASE_BOTH) ), new KeyFrame(Duration.millis(1000), new KeyValue(contentHolder.translateYProperty(), 0,Interpolator.EASE_BOTH), new KeyValue(overlayPane.opacityProperty(), 1, Interpolator.EASE_BOTH))) ); // reduce the number to increase the shifting , increase number to reduce shifting setCycleDuration(Duration.seconds(0.4)); setDelay(Duration.seconds(0)); } } private class BottomTransition extends CachedTimelineTransition { public BottomTransition() { super(contentHolder, new Timeline( new KeyFrame(Duration.ZERO, new KeyValue(contentHolder.translateYProperty(), offsetY ,Interpolator.EASE_BOTH), new KeyValue(overlayPane.visibleProperty(), false ,Interpolator.EASE_BOTH) ), new KeyFrame(Duration.millis(10), new KeyValue(overlayPane.visibleProperty(), true ,Interpolator.EASE_BOTH), new KeyValue(overlayPane.opacityProperty(), 0, Interpolator.EASE_BOTH) ), new KeyFrame(Duration.millis(1000), new KeyValue(contentHolder.translateYProperty(), 0,Interpolator.EASE_BOTH), new KeyValue(overlayPane.opacityProperty(), 1, Interpolator.EASE_BOTH))) ); // reduce the number to increase the shifting , increase number to reduce shifting setCycleDuration(Duration.seconds(0.4)); setDelay(Duration.seconds(0)); } } private class CenterTransition extends CachedTimelineTransition { public CenterTransition() { super(contentHolder, new Timeline( new KeyFrame(Duration.ZERO, new KeyValue(contentHolder.scaleXProperty(), 0 ,Interpolator.EASE_BOTH), new KeyValue(contentHolder.scaleYProperty(), 0 ,Interpolator.EASE_BOTH), new KeyValue(overlayPane.visibleProperty(), false ,Interpolator.EASE_BOTH) ), new KeyFrame(Duration.millis(10), new KeyValue(overlayPane.visibleProperty(), true ,Interpolator.EASE_BOTH), new KeyValue(overlayPane.opacityProperty(), 0,Interpolator.EASE_BOTH) ), new KeyFrame(Duration.millis(1000), new KeyValue(contentHolder.scaleXProperty(), 1 ,Interpolator.EASE_BOTH), new KeyValue(contentHolder.scaleYProperty(), 1 ,Interpolator.EASE_BOTH), new KeyValue(overlayPane.opacityProperty(), 1, Interpolator.EASE_BOTH) )) ); // reduce the number to increase the shifting , increase number to reduce shifting setCycleDuration(Duration.seconds(0.4)); setDelay(Duration.seconds(0)); } } private static final String DEFAULT_STYLE_CLASS = "c3d-dialog"; private StyleableObjectProperty<C3DDialogTransition> transitionType = new SimpleStyleableObjectProperty<C3DDialogTransition>(StyleableProperties.DIALOG_TRANSITION, C3DDialog.this, "dialogTransition", C3DDialogTransition.CENTER ); public C3DDialogTransition getTransitionType(){ return transitionType == null ? C3DDialogTransition.CENTER : transitionType.get(); } public StyleableObjectProperty<C3DDialogTransition> transitionTypeProperty(){ return this.transitionType; } public void setTransitionType(C3DDialogTransition transition){ this.transitionType.set(transition); } private static class StyleableProperties { private static final CssMetaData< C3DDialog, C3DDialogTransition> DIALOG_TRANSITION = new CssMetaData< C3DDialog, C3DDialogTransition>("-fx-dialog-transition", DialogTransitionConverter.getInstance(), C3DDialogTransition.CENTER) { @Override public boolean isSettable(C3DDialog control) { return control.transitionType == null || !control.transitionType.isBound(); } @Override public StyleableProperty<C3DDialogTransition> getStyleableProperty(C3DDialog control) { return control.transitionTypeProperty(); } }; private static final List<CssMetaData<? extends Styleable, ?>> CHILD_STYLEABLES; static { final List<CssMetaData<? extends Styleable, ?>> styleables = new ArrayList<CssMetaData<? extends Styleable, ?>>(Parent.getClassCssMetaData()); Collections.addAll(styleables, DIALOG_TRANSITION ); CHILD_STYLEABLES = Collections.unmodifiableList(styleables); } } // inherit the styleable properties from parent private List<CssMetaData<? extends Styleable, ?>> STYLEABLES; @Override public List<CssMetaData<? extends Styleable, ?>> getCssMetaData() { if(STYLEABLES == null){ final List<CssMetaData<? extends Styleable, ?>> styleables = new ArrayList<CssMetaData<? extends Styleable, ?>>(Parent.getClassCssMetaData()); styleables.addAll(getClassCssMetaData()); styleables.addAll(super.getClassCssMetaData()); STYLEABLES = Collections.unmodifiableList(styleables); } return STYLEABLES; } public static List<CssMetaData<? extends Styleable, ?>> getClassCssMetaData() { return StyleableProperties.CHILD_STYLEABLES; } public void setOnDialogClosed(EventHandler<? super C3DDialogEvent> handler){ onDialogClosedProperty.set(handler); } public void getOnDialogClosed(EventHandler<? super C3DDialogEvent> handler){ onDialogClosedProperty.get(); } private ObjectProperty<EventHandler<? super C3DDialogEvent>> onDialogClosedProperty = new SimpleObjectProperty<>((closed)->{}); public void setOnDialogOpened(EventHandler<? super C3DDialogEvent> handler){ onDialogOpenedProperty.set(handler); } public void getOnDialogOpened(EventHandler<? super C3DDialogEvent> handler){ onDialogOpenedProperty.get(); } private ObjectProperty<EventHandler<? super C3DDialogEvent>> onDialogOpenedProperty = new SimpleObjectProperty<>((opened)->{}); }
package io.luna.game.action; import io.luna.game.model.EntityState; import io.luna.game.model.World; import io.luna.game.model.mobile.Mob; import io.luna.game.task.Task; public abstract class Action<T extends Mob> { /** * A {@link Task} implementation that processes an Action. */ private final class ActionRunner extends Task { /** * Creates a new {@link ActionRunner}. */ private ActionRunner() { super(instant, delay); } @Override protected void onSchedule() { onInit(); } @Override protected void onCancel() { onInterrupt(); } @Override protected void execute() { if (mob.getState() == EntityState.INACTIVE) { interrupt(); } else { call(); } } } /** * The mob assigned to this action. */ protected final T mob; /** * If this action executes instantly. */ protected final boolean instant; /** * The delay of this action. */ protected final int delay; /** * The task processing this action. */ private final ActionRunner runner; /** * Creates a new {@link Action}. * * @param mob The {@link Mob} assigned to this action. * @param instant If this action executes instantly. * @param delay The delay of this action. */ public Action(T mob, boolean instant, int delay) { this.mob = mob; this.instant = instant; this.delay = delay; runner = new ActionRunner(); } /** * Will always throw an {@link UnsupportedOperationException}. */ @Override public final boolean equals(Object obj) { throw new UnsupportedOperationException("equals(Object) is not supported for type Action"); } /** * Will always throw an {@link UnsupportedOperationException}. */ @Override public final int hashCode() { throw new UnsupportedOperationException("hashCode() is not supported for type Action"); } /** * Initializes this action by scheduling the {@link ActionRunner}. */ protected final void init() { World world = mob.getWorld(); world.schedule(runner); } /** * Interrupts this action by cancelling the {@link ActionRunner}. */ protected final void interrupt() { runner.cancel(); } /** * Function invoked when this action initializes. */ protected void onInit() { } /** * Function invoked when this action is interrupted. */ protected void onInterrupt() { } /** * Function called every {@code delay} by the {@link ActionRunner}. */ protected abstract void call(); /** * @return {@code true} if this Action has been interrupted, {@code false} otherwise. */ public final boolean isInterrupted() { return !runner.isRunning(); } /** * @return The mob assigned to this action. */ public final T getMob() { return mob; } }
package io.measures.passage; import com.google.common.base.Joiner; import io.measures.passage.geometry.Model3D; import io.measures.passage.geometry.Point2D; import io.measures.passage.geometry.Projectable2D; import io.measures.passage.geometry.Projectable3D; import io.measures.passage.geometry.SphericalPoint; import io.measures.passage.geometry.Triangle3D; import processing.core.PApplet; import processing.core.PGraphics; import processing.event.KeyEvent; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Sketch * @author Dietrich Featherston */ public class Sketch extends PApplet { protected final long startedAt = System.currentTimeMillis()/1000L; protected final String homeDir; protected final String baseDataDir; protected static final Joiner pathJoiner = Joiner.on(File.separatorChar); public final int slate = color(50); public final int gray = color(180); public final int yellow = color(255, 255, 1); public final int pink = color(255, 46, 112); public final int teal = color(85, 195, 194); public final int nak = color(0, 170, 255); public final int blue = color(49, 130, 189); public final int darkblue = color(49, 130, 189); public final int lightblue = color(222, 235, 247); private PGraphics paperGraphics; public Sketch() { String homeDir = getParameter("PASSAGE_HOME"); String userDir = System.getProperty("user.dir"); if(homeDir == null) { homeDir = userDir; } this.homeDir = homeDir; baseDataDir = getParameter("PASSAGE_DATA") == null ? homeDir : getParameter("PASSAGE_DATA"); // ensure the snapshot directory exists new File(getSnapshotDir()).mkdirs(); // ensure the data dir exists new File(getDataDir()).mkdirs(); } public void initSize(String type) { size(getTargetWidth(), getTargetHeight(), type); } public int getTargetWidth() { return 1280; } public int getTargetHeight() { return 720; } public float getAspectRatio() { return (float)getTargetWidth() / (float)getTargetHeight(); } @Override public final void draw() { beforeFrame(); renderFrame(); afterFrame(); } public void beforeFrame() {} public void renderFrame() {} public void afterFrame() {} public int darker(int c) { return color(round(red(c)*0.6f), round(green(c)*0.6f), round(blue(c)*0.6f)); } public int lighter(int c) { return color( constrain(round(red(c)*1.1f), 0, 255), constrain(round(green(c)*1.1f), 0, 255), constrain(round(blue(c)*1.1f), 0, 255)); } public void point(Projectable2D p) { point(p.x(), p.y()); } public void point(Projectable3D p) { point(p.x(), p.y(), p.z()); } public void vertex(Projectable3D p) { vertex(p.x(), p.y(), p.z()); } public void line(Projectable3D a, Projectable3D b) { line(a.x(), a.y(), a.z(), b.x(), b.y(), b.z()); } public void renderModel(Model3D model) { beginShape(TRIANGLES); for(Triangle3D t : model.getTriangles()) { vertex(t.a()); vertex(t.b()); vertex(t.c()); } endShape(); } public void triangle(Triangle3D t) { beginShape(TRIANGLE); vertex(t.a()); vertex(t.b()); vertex(t.c()); endShape(); } public void translate(Projectable3D p) { translate(p.x(), p.y(), p.z()); } public void translateNormal(SphericalPoint p) { rotateZ(p.phi()); rotateY(p.theta()); translate(0, 0, p.r()); } public float noiseZ(float noiseScale, float x, float y, float z) { return noise(noiseScale*(x+10000), noiseScale*(y+10000), noiseScale*(z+10000)); } @Override public void keyPressed(KeyEvent e) { super.keyPressed(); println("key pressed"); if (key == ' ') { snapshot(); } } public void snapshot() { System.out.println("saving code and raster"); long now = System.currentTimeMillis()/1000L; copyFile(getSketchSourceFile(), getSnapshotPath("code-" + now + ".java")); saveFrame(getSnapshotPath("raster-" + now + ".png")); } // todo - compatibility public void copyFile(String from, String to) { try { String command = "cp " + from + " " + to; println("running command \"" + command + "\""); Process p = Runtime.getRuntime().exec(command); copy(p.getInputStream(), System.out); copy(p.getErrorStream(), System.err); int exitValue = p.waitFor(); println("command exited with code " + exitValue); } catch(Exception ignored) { println(ignored.getMessage()); ignored.printStackTrace(); } } public void copy(InputStream in, OutputStream out) throws IOException { while (true) { int c = in.read(); if (c == -1) break; out.write((char)c); } } public String getSketchSourceFile() { return pathJoiner.join(getSketchSourcePath(), getSketchPathComponent() + ".java"); } private String getSketchSourcePath() { return pathJoiner.join(homeDir, "src/main/java"); } public String getSketchPathComponent() { return this.getClass().getName().replace('.', File.separatorChar); } /** * @return the directory to which progress artifacts should be saved */ public String getSnapshotDir() { return pathJoiner.join(baseDataDir, getSketchPathComponent(), "snapshots"); } public String getSnapshotPath(String name) { return pathJoiner.join(getSnapshotDir(), name); } public String getDataDir() { return pathJoiner.join(baseDataDir, getSketchPathComponent(), "data"); } public String getDataPath(String name) { return pathJoiner.join(getDataDir(), name); } @Override public File dataFile(String where) { File why = new File(where); if (why.isAbsolute()) return why; File sketchSpecificFile = new File(getDataPath(where)); if(sketchSpecificFile.exists()) { return sketchSpecificFile; } else { return why; } } @Override public String getParameter(String name) { return System.getenv(name); } public void printenv() { System.out.println("sketch name: " + this.getClass().getName()); System.out.println("PASSAGE_HOME=" + homeDir); System.out.println("PASSAGE_DATA=" + baseDataDir); System.out.println("sketch-specific path = " + getSketchPathComponent()); System.out.println("sketch source = " + getSketchSourcePath()); System.out.println("sketch source file = " + getSketchSourceFile()); System.out.println("snapshot dir = " + getSnapshotDir()); } public void oldPaperBackground() { if(paperGraphics == null) { int center = color(252, 243, 211); int edge = color(245, 222, 191); PGraphics g = createGraphics(10, 10); g.beginDraw(); g.noStroke(); g.background(edge); g.fill(center); g.ellipse(g.width/2, g.height/2, g.width*0.8f, g.height*0.8f); g.filter(BLUR, 2); g.endDraw(); /* g.filter(BLUR, width/30); g.filter(BLUR, width/30); g.filter(BLUR, width/30); */ paperGraphics = g; } image(paperGraphics, 0, 0, width, height); } }
package jkanvas.groups; import static jkanvas.util.ArrayUtil.*; import java.awt.Graphics2D; import java.awt.event.MouseEvent; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.List; import java.util.Objects; import jkanvas.KanvasContext; import jkanvas.animation.AnimatedPosition; import jkanvas.animation.AnimationAction; import jkanvas.animation.AnimationList; import jkanvas.animation.AnimationTiming; import jkanvas.animation.Animator; import jkanvas.animation.GenericAnimated; import jkanvas.painter.AbstractRenderpass; import jkanvas.painter.Renderpass; import jkanvas.painter.RenderpassPainter; import jkanvas.util.PaintUtil; import jkanvas.util.VecUtil; /** * A group of render passes. The layout of the render passes is determined by * subclasses. Render passes without bounding boxes may or may not be allowed * depending of the implementation of the subclass. Transitions between layouts * can be animated. * * @author Joschi <josua.krause@googlemail.com> * @param <T> The type of layouted render passes. */ public abstract class RenderGroup<T extends AbstractRenderpass> extends AbstractRenderpass { /** * The offset of a render pass as {@link AnimatedPosition}. * * @author Joschi <josua.krause@googlemail.com> * @param <T> The type of the render pass. */ protected static final class RenderpassPosition<T extends AbstractRenderpass> extends GenericAnimated<Point2D> { /** The render pass. */ public final T pass; /** The current render pass bounding box. */ private Rectangle2D bbox; /** * Creates a render pass position. * * @param pass The render pass. * @param list The animation list. */ public RenderpassPosition(final T pass, final AnimationList list) { super(new Point2D.Double(pass.getOffsetX(), pass.getOffsetY())); bbox = pass.getBoundingBox(); this.pass = pass; list.addAnimated(this); pass.setAnimationList(list); } @Override protected AnimationAction beforeAnimation(final AnimationAction onFinish) { pass.setForceCache(true); return new AnimationAction() { @Override public void animationFinished() { pass.setForceCache(false); if(onFinish != null) { onFinish.animationFinished(); } } }; } @Override protected Point2D interpolate(final Point2D from, final Point2D to, final double t) { return VecUtil.interpolate(from, to, t); } @Override protected void doSet(final Point2D t) { super.doSet(t); pass.setOffset(t.getX(), t.getY()); } /** * Checks whether the bounding box has changed since the last call and sets * the current bounding box. * * @return Whether the bounding box has changed. */ public boolean checkBBoxChange() { final Rectangle2D oldBBox = bbox; bbox = RenderpassPainter.getPassBoundingBox(pass); if(bbox == null || oldBBox == null) return bbox != oldBBox; return bbox.getWidth() != oldBBox.getWidth() || bbox.getHeight() != oldBBox.getHeight(); } /** * Getter. * * @return The render pass bounding box. The value is refreshed by calling * {@link #checkBBoxChange()}. */ public Rectangle2D getPassBBox() { return bbox; } /** * Getter. * * @return When the position is in animation the result is the destination * bounding-box of the render pass. Otherwise the current bounding * box is returned. */ public Rectangle2D getPredictBBox() { final Rectangle2D rect = pass.getBoundingBox(); if(rect == null) return null; final Point2D pred = getPredict(); return new Rectangle2D.Double(rect.getX() + pred.getX(), rect.getY() + pred.getY(), rect.getWidth(), rect.getHeight()); } /** * Properly removes this render pass position. * * @param list The animation list. */ public void dispose(final AnimationList list) { list.removeAnimated(this); pass.dispose(); } } // RenderpassPosition /** If this flag is set the layout is recomputed when the group is drawn. */ private boolean redoLayout; /** The list of group members. */ private final List<RenderpassPosition<T>> members; /** The list of non layouted members in front of the layouted members. */ private final List<Renderpass> nlFront = new ArrayList<>(); /** The list of non layouted members behind the layouted members. */ private final List<Renderpass> nlBack = new ArrayList<>(); /** The underlying animator. */ private final Animator animator; /** * Creates a new render pass group. * * @param animator The underlying animator. */ public RenderGroup(final Animator animator) { this.animator = Objects.requireNonNull(animator); members = new ArrayList<>(); redoLayout = true; } /** * Getter. * * @return The animator for this render group. */ public Animator getAnimator() { return animator; } @Override public void setAnimationList(final AnimationList list) { if(animator.getAnimationList() != list) throw new IllegalArgumentException( "attempt to set group to other animation list"); } /** * Creates a render pass position directly without adding it to the member * list yet. Note that if this position will not be used it must be removed * with {@link #remove(RenderpassPosition)}. This method is a convenience * method for methods that have direct access to the member list like * {@link #doLayout(List)}. * * @param pass The render pass. * @return The converted render pass position. */ protected RenderpassPosition<T> create(final T pass) { final RenderpassPosition<T> rp = convert(pass); rp.checkBBoxChange(); addedRenderpassIntern(rp); return rp; } /** * Safely removes a render pass position directly without altering the member * list. This method is a convenience method for methods that have direct * access to the member list like {@link #doLayout(List)}. * * @param rp The render pass position. */ protected void remove(final RenderpassPosition<T> rp) { removedRenderpassIntern(rp); } /** * Converts a render pass to a render pass position. * * @param pass The render pass. * @return The position. */ private RenderpassPosition<T> convert(final T pass) { if(this == pass) throw new IllegalArgumentException("cannot add itself"); Objects.requireNonNull(pass); return new RenderpassPosition<T>(pass, animator.getAnimationList()); } /** * This method is called after a render pass is added. * * @param rp The render pass position. */ protected void addedRenderpass( @SuppressWarnings("unused") final RenderpassPosition<T> rp) { // nothing to do } /** * This method is always called after a render pass is added. * * @param p The render pass position. */ private void addedRenderpassIntern(final RenderpassPosition<T> p) { p.pass.setParent(this); addedRenderpass(p); } /** * This method is called after a render pass is removed. * * @param rp The render pass position. */ protected void removedRenderpass( @SuppressWarnings("unused") final RenderpassPosition<T> rp) { // nothing to do } /** * This method is always called after a render pass is removed. * * @param p The render pass position. */ private void removedRenderpassIntern(final RenderpassPosition<T> p) { removedRenderpass(p); p.dispose(animator.getAnimationList()); p.pass.setParent(null); } /** * Adds a render pass. * * @param pass The render pass. */ public void addRenderpass(final T pass) { final RenderpassPosition<T> p = convert(pass); members.add(p); addedRenderpassIntern(p); invalidate(); } /** * Inserts a render pass. * * @param index The index where the render pass will be inserted. * @param pass The render pass. */ public void addRenderpass(final int index, final T pass) { final RenderpassPosition<T> p = convert(pass); members.add(index, p); addedRenderpassIntern(p); invalidate(); } /** * Getter. * * @param r The abstract render pass to find. * @return The index of the given render pass or <code>-1</code> if the pass * could not be found. Equality is defined by identity. */ public int indexOf(final T r) { for(int i = 0; i < members.size(); ++i) { final RenderpassPosition<T> rp = members.get(i); if(rp.pass == r) return i; } return -1; } /** * Removes the render pass at the given index. * * @param index The index. */ public void removeRenderpass(final int index) { final RenderpassPosition<T> p = members.remove(index); removedRenderpassIntern(p); invalidate(); } /** Clears all render passes. */ public void clearRenderpasses() { final RenderpassPosition<T>[] rps = members(); members.clear(); for(final RenderpassPosition<T> p : rps) { removedRenderpassIntern(p); } invalidate(); } /** * Getter. * * @return The number of render passes. */ public int renderpassCount() { return members.size(); } /** * Getter. * * @param index The index. * @return The render pass at the given position. */ public T getRenderpass(final int index) { return members.get(index).pass; } /** * Sets the position of the given render pass and executes the given action * afterwards. * * @param pass The render pass. * @param pos The new position. * @param onFinish The (optional) action to execute afterwards. */ public void setPosition(final T pass, final Point2D pos, final AnimationAction onFinish) { setPosition(indexOf(pass), pos, onFinish); } /** * Sets the position of the given render pass and executes the given action * afterwards. * * @param index The index of the render pass. * @param pos The new position. * @param onFinish The (optional) action to execute afterwards. */ public void setPosition(final int index, final Point2D pos, final AnimationAction onFinish) { members.get(index).set(pos, onFinish); } /** * Transitions a render pass to the given position and executes the given * action afterwards. * * @param pass The render pass. * @param pos The new position. * @param timing The animation timing. * @param onFinish The (optional) action to execute afterwards. */ public void setPosition(final T pass, final Point2D pos, final AnimationTiming timing, final AnimationAction onFinish) { setPosition(indexOf(pass), pos, timing, onFinish); } /** * Transitions a render pass to the given position and executes the given * action afterwards. * * @param index The index of the render pass. * @param pos The new position. * @param timing The animation timing. * @param onFinish The (optional) action to execute afterwards. */ public void setPosition(final int index, final Point2D pos, final AnimationTiming timing, final AnimationAction onFinish) { members.get(index).startAnimationTo(pos, timing, onFinish); } /** * Setter. * * @param index The index. * @param pass The render pass. */ public void setRenderpass(final int index, final T pass) { final RenderpassPosition<T> p = convert(pass); final RenderpassPosition<T> o = members.set(index, p); removedRenderpassIntern(o); addedRenderpassIntern(p); invalidate(); } /** * Adds a render pass that is not used for the layout. * * @param pass The render pass. * @param front Whether this pass is added in front of the layouted passes. */ public void addNonLayouted(final Renderpass pass, final boolean front) { if(front) { nlFront.add(pass); } else { nlBack.add(pass); } animator.quickRefresh(); } /** * Inserts a render pass that is not used for the layout. * * @param index The index where the render pass will be inserted. * @param pass The render pass. * @param front Whether this pass is added in front of the layouted passes. */ public void addNonLayouted(final int index, final Renderpass pass, final boolean front) { if(front) { nlFront.add(index, pass); } else { nlBack.add(index, pass); } animator.quickRefresh(); } /** * Removes a render pass that is not used for the layout. * * @param index The index of the render pass. * @param front Whether this pass is found in front of the layouted passes. */ public void removeNonLayouted(final int index, final boolean front) { if(front) { nlFront.remove(index); } else { nlBack.remove(index); } animator.quickRefresh(); } /** * Sets the render pass that is not used for the layout at the given position. * * @param index The index. * @param pass The render pass. * @param front Whether this method addresses passes in front of the layouted * passes. */ public void setNonLayouted(final int index, final Renderpass pass, final boolean front) { if(front) { nlFront.set(index, pass); } else { nlBack.set(index, pass); } animator.quickRefresh(); } /** * Getter. * * @param index The index. * @param front Whether this method addresses passes in front of the layouted * passes. * @return The render pass at the given index that is not used for the layout. */ public Renderpass getNonLayouted(final int index, final boolean front) { return front ? nlFront.get(index) : nlBack.get(index); } /** Clears all render passes that are not used for the layout. */ public void clearNonLayouted() { nlFront.clear(); nlBack.clear(); animator.quickRefresh(); } /** * Getter. * * @param front Whether this method addresses passes in front of the layouted * passes. * @return The number of render passes that are not used for the layout. */ public int nonLayoutedSize(final boolean front) { return front ? nlFront.size() : nlBack.size(); } /** Invalidates the current layout, recomputes the layout, and repaints. */ public void invalidate() { redoLayout = true; animator.quickRefresh(); } /** * Computes the current layout. The implementation may decide whether to allow * render passes without bounding box. * * @param members The positions of the render passes. */ protected abstract void doLayout(List<RenderpassPosition<T>> members); /** Immediately computes the current layout. */ public void forceLayout() { invalidate(); doLayout(members); redoLayout = false; animator.forceNextFrame(); } /** Ensures that the layout is computed. */ private void ensureLayout() { if(!redoLayout) return; forceLayout(); } @Override public void draw(final Graphics2D gfx, final KanvasContext ctx) { ensureLayout(); gfx.setColor(java.awt.Color.GREEN); RenderpassPainter.draw(nlBack, gfx, ctx); final Rectangle2D view = ctx.getVisibleCanvas(); boolean changed = false; for(final RenderpassPosition<T> p : members) { final Renderpass r = p.pass; if(!r.isVisible()) { continue; } if(p.checkBBoxChange()) { changed = true; } final Rectangle2D bbox = p.getPassBBox(); if(bbox != null && !view.intersects(bbox)) { continue; } final Graphics2D g = (Graphics2D) gfx.create(); if(bbox != null) { g.setClip(bbox); } final double dx = r.getOffsetX(); final double dy = r.getOffsetY(); g.translate(dx, dy); final KanvasContext c = RenderpassPainter.getContextFor(r, ctx); r.draw(g, c); g.dispose(); } if(jkanvas.Canvas.DEBUG_BBOX) { final Graphics2D g = (Graphics2D) gfx.create(); PaintUtil.setAlpha(g, 0.3); g.setColor(java.awt.Color.BLUE); for(final RenderpassPosition<T> rp : members) { final Renderpass r = rp.pass; if(!r.isVisible()) { continue; } if(rp.checkBBoxChange()) { changed = true; } final Rectangle2D bbox = rp.getPassBBox(); if(bbox == null || !view.intersects(bbox)) { continue; } g.fill(bbox); } } gfx.setColor(java.awt.Color.GREEN); RenderpassPainter.draw(nlFront, gfx, ctx); if(changed) { invalidate(); } } /** * Copies the member list for iterations that allow modifications to the list. * * @return The member list as array. */ private RenderpassPosition<T>[] members() { return members.toArray(new RenderpassPosition[members.size()]); } @Override public boolean click(final Point2D position, final MouseEvent e) { if(RenderpassPainter.click(nlFront, position, e)) return true; for(final RenderpassPosition<T> p : reverseArray(members())) { final Renderpass r = p.pass; if(!r.isVisible()) { continue; } final Rectangle2D bbox = r.getBoundingBox(); final Point2D pos = RenderpassPainter.getPositionFromCanvas(r, position); if(bbox != null && !bbox.contains(pos)) { continue; } if(r.click(pos, e)) return true; } return RenderpassPainter.click(nlBack, position, e); } @Override public String getTooltip(final Point2D position) { final String tt = RenderpassPainter.getTooltip(nlFront, position); if(tt != null) return tt; for(final RenderpassPosition<T> p : reverseArray(members())) { final Renderpass r = p.pass; if(!r.isVisible()) { continue; } final Rectangle2D bbox = r.getBoundingBox(); final Point2D pos = RenderpassPainter.getPositionFromCanvas(r, position); if(bbox != null && !bbox.contains(pos)) { continue; } final String tooltip = r.getTooltip(pos); if(tooltip != null) return tooltip; } return RenderpassPainter.getTooltip(nlBack, position); } @Override public boolean moveMouse(final Point2D cur) { boolean moved = RenderpassPainter.moveMouse(nlFront, cur); for(final RenderpassPosition<T> p : reverseArray(members())) { final Renderpass r = p.pass; if(!r.isVisible()) { continue; } final Point2D pos = RenderpassPainter.getPositionFromCanvas(r, cur); if(r.moveMouse(pos)) { moved = true; } } return RenderpassPainter.moveMouse(nlBack, cur) || moved; } /** * Picks a layouted render pass. * * @param position The position. * @return The render pass at the given position or <code>null</code> if there * is none. */ protected Renderpass pickLayouted(final Point2D position) { for(final RenderpassPosition<T> p : reverseArray(members())) { final Renderpass r = p.pass; if(!r.isVisible()) { continue; } final Rectangle2D bbox = r.getBoundingBox(); final Point2D pos = RenderpassPainter.getPositionFromCanvas(r, position); if(bbox != null && !bbox.contains(pos)) { continue; } return r; } return null; } /** The render pass currently responsible for dragging. */ private Renderpass dragging = null; /** The start position of the drag in the render pass coordinates. */ private Point2D start = null; /** * Checks whether the given render pass accepts the drag. When the render pass * accepts the drag everything is set up properly. * * @param r The render pass to check. * @param position The position in canvas coordinates. * @param e The mouse event. * @return Whether the drag was accepted. * @see #acceptDrag(Point2D, MouseEvent) */ private boolean acceptDrag( final Renderpass r, final Point2D position, final MouseEvent e) { if(!r.isVisible()) return false; final Rectangle2D bbox = r.getBoundingBox(); final Point2D pos = RenderpassPainter.getPositionFromCanvas(r, position); if(bbox != null && !bbox.contains(pos)) return false; if(!r.acceptDrag(pos, e)) return false; start = pos; dragging = r; return true; } @Override public final boolean acceptDrag(final Point2D position, final MouseEvent e) { for(final Renderpass r : reverseList(nlFront)) { if(acceptDrag(r, position, e)) return true; } for(final RenderpassPosition<T> p : reverseArray(members())) { if(acceptDrag(p.pass, position, e)) return true; } for(final Renderpass r : reverseList(nlBack)) { if(acceptDrag(r, position, e)) return true; } return false; } @Override public final void drag(final Point2D _, final Point2D cur, final double dx, final double dy) { if(dragging == null) return; // dx and dy do not change final Point2D pos = RenderpassPainter.getPositionFromCanvas(dragging, cur); dragging.drag(start, pos, dx, dy); } @Override public final void endDrag(final Point2D _, final Point2D end, final double dx, final double dy) { if(dragging == null) return; // dx and dy do not change final Point2D pos = RenderpassPainter.getPositionFromCanvas(dragging, end); dragging.endDrag(start, pos, dx, dy); dragging = null; } @Override public Rectangle2D getBoundingBox() { ensureLayout(); boolean change = false; Rectangle2D res = RenderpassPainter.getBoundingBox(nlFront); final Rectangle2D other = RenderpassPainter.getBoundingBox(nlBack); if(res == null) { res = other; } else if(other != null) { res.add(other); } for(final RenderpassPosition<T> p : members) { if(!p.pass.isVisible()) { continue; } if(p.checkBBoxChange()) { change = true; } final Rectangle2D bbox = p.getPassBBox(); if(bbox == null) { continue; } if(res == null) { res = new Rectangle2D.Double(bbox.getX(), bbox.getY(), bbox.getWidth(), bbox.getHeight()); } else { res.add(bbox); } } if(change) { invalidate(); } return res == null ? new Rectangle2D.Double() : res; } @Override public boolean isChanging() { for(final Renderpass r : nlBack) { if(r.isChanging()) return true; } for(final Renderpass r : nlFront) { if(r.isChanging()) return true; } for(final RenderpassPosition<T> rp : members) { if(rp.inAnimation()) return true; } return false; } }
package net.time4j.engine; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.List; /** * <p>Represents a common time span with an associated sign and a * sequence of time units and related amounts. </p> * * @param <U> generic type of time unit * @author Meno Hochschild */ /*[deutsch] * <p>Repr&auml;sentiert eine allgemeine vorzeichenbehaftete Zeitspannem * in mehreren Zeiteinheiten mit deren zugeordneten Betr&auml;gen. </p> * * @param <U> generic type of time unit * @author Meno Hochschild */ public interface TimeSpan<U> { /** * <p>Yields all containted time span items with amount and unit in * the order from largest to smallest time units. </p> * * @return unmodifiable list sorted by precision of units in ascending * order where every time unit exists at most once */ /*[deutsch] * <p>Liefert alle enthaltenen Zeitspannenelemente mit Einheit und Betrag * in der Reihenfolge von den gr&ouml;&szlig;ten zu den kleinsten und * genauesten Zeiteinheiten. </p> * * @return unmodifiable list sorted by precision of units in ascending * order where every time unit exists at most once */ List<Item<U>> getTotalLength(); /** * <p>Queries if given time unit is part of this time span. </p> * * <p>By default the implementation uses following expression: </p> * * <pre> * for (Item&lt;?&gt; item : getTotalLength()) { * if (item.getUnit().equals(unit)) { * return (item.getAmount > 0); * } * } * return false; * </pre> * * @param unit time unit to be asked (optional) * @return {@code true} if exists else {@code false} * @see #getPartialAmount(ChronoUnit) */ /*[deutsch] * <p>Ist die angegebene Zeiteinheit in dieser Zeitspanne enthalten? </p> * * <p>Standardm&auml;&szlig;ig entspricht die konkrete * Implementierung folgendem Ausdruck: </p> * * <pre> * for (Item&lt;?&gt; item : getTotalLength()) { * if (item.getUnit().equals(unit)) { * return (item.getAmount > 0); * } * } * return false; * </pre> * * @param unit time unit to be asked (optional) * @return {@code true} if exists else {@code false} * @see #getPartialAmount(ChronoUnit) */ boolean contains(ChronoUnit unit); /** * <p>Yields the partial amount associated with given time unit. </p> * * <p>The method returns {@code 0} if this time span does not contain * given time unit. In order to get the total length/amount of this * time span users have to evaluate the method {@link #getTotalLength()} * instead. </p> * * @param unit time unit (optional) * @return amount as part of time span ({@code >= 0}) */ /*[deutsch] * <p>Liefert den Teilbetrag zur angegebenen Einheit als Absolutwert. </p> * * <p>Die Methode liefert {@code 0}, wenn die Zeiteinheit nicht enthalten * ist. Um den Gesamtwert der Zeitspanne zu bekommen, ist in der Regel * nicht diese Methode, sondern {@link #getTotalLength()} auszuwerten. </p> * * @param unit time unit (optional) * @return amount as part of time span ({@code >= 0}) */ long getPartialAmount(ChronoUnit unit); /** * <p>Queries if this time span is negative. </p> * * <p>A negative time span relates to the subtraction of two time * points where first one is after second one. The partial amounts * of every time span are never negative. Hence this attribute is not * associated with the partial amounts but only with the time span * itself. </p> * * <p>Note: An empty time span itself is never negative in agreement * with the mathematical relation {@code (-1) * 0 = 0}. </p> * * @return {@code true} if negative and not empty else {@code false} */ /*[deutsch] * <p>Ist diese Zeitspanne negativ? </p> * * <p>Der Begriff der negativen Zeitspanne bezieht sich auf die Subtraktion * zweier Zeitpunkte, von denen der erste vor dem zweiten liegt. Die * einzelnen Betr&auml;ge der Zeitspanne sind nie negativ. Dieses Attribut * ist daher nicht mit den einzelnen Betr&auml;gen assoziiert, sondern * bezieht sich nur auf die Zeitspanne insgesamt. </p> * * <p>Notiz: Eine leere Zeitspanne ist selbst niemals negativ in * &Uuml;bereinstimmung mit der mathematischen Relation * {@code (-1) * 0 = 0}. </p> * * @return {@code true} if negative and not empty else {@code false} */ boolean isNegative(); /** * <p>Queries if this time span is positive. </p> * * <p>A time span is positive if it is neither empty nor negative. </p> * * @return {@code true} if positive and not empty else {@code false} * @see #isEmpty() * @see #isNegative() */ /*[deutsch] * <p>Ist diese Zeitspanne positiv? </p> * * <p>Eine Zeitspanne ist genau dann positiv, wenn sie weder leer noch * negativ ist. </p> * * @return {@code true} if positive and not empty else {@code false} * @see #isEmpty() * @see #isNegative() */ boolean isPositive(); /** * <p>Queries if this time span is empty. </p> * * <p>Per definition an empty time span has no items with a partial * amount different from {@code 0}. </p> * * @return {@code true} if empty else {@code false} */ /*[deutsch] * <p>Liegt eine leere Zeitspanne vor? </p> * * <p>Per Definition hat eine leere Zeitspanne keine Elemente mit * einem von {@code 0} verschiedenen Teilbetrag. </p> * * @return {@code true} if empty else {@code false} */ boolean isEmpty(); /** * <p>Adds this time span to given time point. </p> * * <p>Is equivalent to the expression {@link TimePoint#plus(TimeSpan) * time.plus(this)}. Due to better readability usage of the * {@code TimePoint}-method is recommended. Implementations are * required to document the used algorithm in detailed manner. </p> * * @param <T> generic type of time point * @param time reference time point to add this time span to * @return new time point as result of addition * @see #subtractFrom(TimePoint) */ /*[deutsch] * <p>Addiert diese Zeitspanne zum angegebenen Zeitpunkt. </p> * * <p>Entspricht dem Ausdruck {@link TimePoint#plus(TimeSpan) * time.plus(this)}. Aus Gr&uuml;nden des besseren Lesestils empfiehlt * sich jedoch meistens die Verwendung der {@code TimePoint}-Methode. * Implementierungen m&uuml;ssen den verwendeten Algorithmus genau * dokumentieren. </p> * * @param <T> generic type of time point * @param time reference time point to add this time span to * @return new time point as result of addition * @see #subtractFrom(TimePoint) */ <T extends TimePoint<? super U, T>> T addTo(T time); /** * <p>Subtracts this time span from given time point. </p> * * <p>Is equivalent to the expression {@link TimePoint#minus(TimeSpan) * time.minus(this)}. Due to better readability usage of the * {@code TimePoint}-method is recommended. Implementations are * required to document the used algorithm in detailed manner. </p> * * @param <T> generic type of time point * @param time reference time point to subtract this time span from * @return new time point as result of subtraction * @see #addTo(TimePoint) */ /*[deutsch] * <p>Subtrahiert diese Zeitspanne vom angegebenen Zeitpunkt. </p> * * <p>Entspricht dem Ausdruck {@link TimePoint#minus(TimeSpan) * time.minus(this)}. Aus Gr&uuml;nden des besseren Lesestils empfiehlt * sich jedoch meistens die Verwendung der {@code TimePoint}-Methode. * Implementierungen m&uuml;ssen den verwendeten Algorithmus genau * dokumentieren. </p> * * @param <T> generic type of time point * @param time reference time point to subtract this time span from * @return new time point as result of subtraction * @see #addTo(TimePoint) */ <T extends TimePoint<? super U, T>> T subtractFrom(T time); /** * <p>Represents a single item of a time span which is based on only one * time unit and has a non-negative amount. </p> * * @param <U> type of time unit * @concurrency <immutable> */ /*[deutsch] * <p>Repr&auml;sentiert ein atomares Element einer Zeitspanne, das auf nur * einer Zeiteinheit beruht und einen nicht-negativen Betrag hat. </p> * * @param <U> type of time unit * @concurrency <immutable> */ public static final class Item<U> implements Serializable { private static final long serialVersionUID = 1564804888291509484L; /** * @serial time unit */ private final U unit; /** * @serial amount associated with a time unit {@code > 0} */ private final long amount; private Item( long amount, U unit ) { super(); if (unit == null) { throw new NullPointerException("Missing chronological unit."); } else if (amount < 0) { throw new IllegalArgumentException( "Temporal amount must be positive or zero: " + amount); } this.amount = amount; this.unit = unit; } public static <U> Item<U> of( long amount, U unit ) { return new Item<U>(amount, unit); } /** * <p>Yields the non-negative amount. </p> * * @return amount in units ({@code >= 0}) */ /*[deutsch] * <p>Liefert den nicht-negativen Betrag. </p> * * @return amount in units ({@code >= 0}) */ public long getAmount() { return this.amount; } /** * <p>Yields the time unit. </p> * * @return time unit */ /*[deutsch] * <p>Liefert die Zeiteinheit. </p> * * @return time unit */ public U getUnit() { return this.unit; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } else if (obj instanceof Item) { Item<?> that = Item.class.cast(obj); return ( (this.amount == that.amount) && this.unit.equals(that.unit) ); } else { return false; } } @Override public int hashCode() { int hash = this.unit.hashCode(); hash = 29 * hash + (int) (this.amount ^ (this.amount >>> 32)); return hash; } /** * <p>Provides a canonical representation in the format * 'P' amount '{' unit '}', for example &quot;P4{YEARS}&quot;. </p> * * @return String */ /*[deutsch] * <p>Liefert eine kanonische Darstellung im Format * 'P' amount '{' unit '}', zum Beispiel &quot;P4{YEARS}&quot;. </p> * * @return String */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append('P'); sb.append(this.amount); sb.append('{'); sb.append(this.unit); sb.append('}'); return sb.toString(); } /** * @serialData Checks the consistency. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); if ( (this.unit == null) || (this.amount < 0) ) { throw new InvalidObjectException("Inconsistent state."); } } } }
package net.xprova.piccolo; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; import java.util.TreeSet; import jline.TerminalFactory; import jline.console.ConsoleReader; public class Console { private String banner; private String prompt; private int exitFlag; private PrintStream out; private HashSet<MethodData> availMethods; private HashMap<String, MethodData> methodAliases; private HashSet<Object> handlers; private class MethodData { public Method method; public Object object; public MethodData(Method method, Object object) { this.method = method; this.object = object; } }; // public functions /** * Constructors */ public Console() { methodAliases = new HashMap<String, MethodData>(); availMethods = new HashSet<Console.MethodData>(); handlers = new HashSet<Object>(); out = System.out; // load banner String bannerFileContent = ""; Scanner s = null; try { final InputStream stream; stream = Console.class.getClassLoader().getResourceAsStream("piccolo_banner.txt"); s = new Scanner(stream); bannerFileContent = s.useDelimiter("\\Z").next(); } catch (Exception e) { bannerFileContent = "<could not load internal banner file>\n"; } finally { if (s != null) s.close(); } setBanner(bannerFileContent).setPrompt(">> "); } /** * Add a handler class to the console * * @param handler * @return same Console object for chaining */ public Console addHandler(Object handler) { handlers.add(handler); scanForMethods(); return this; } /** * Remove handler class from the console * * @param handler * @return same Console object for chaining */ public Console removeHandler(@SuppressWarnings("rawtypes") Class handler) { handlers.remove(handler); scanForMethods(); return this; } /** * Set console banner * * @param newBanner * @return same Console object for chaining */ public Console setBanner(String newBanner) { banner = newBanner; return this; } /** * Set console prompt * * @param newPrompt * @return same Console object for chaining */ public Console setPrompt(String newPrompt) { prompt = newPrompt; return this; } /** * Start the console */ public void run() { try { ConsoleReader console = new ConsoleReader(); out.println(banner); console.setPrompt(prompt); String line = null; exitFlag = 0; while ((line = console.readLine()) != null) { try { runCommand(line); } catch (Exception e) { prettyPrintStackTrace(e); } if (exitFlag != 0) break; out.println(""); // new line after each command } } catch (IOException e) { e.printStackTrace(); } finally { try { TerminalFactory.get().restore(); } catch (Exception e) { e.printStackTrace(); } } } private void prettyPrintStackTrace(Exception e) { StackTraceElement[] trace = e.getCause().getStackTrace(); ArrayList<StackTraceElement> stackArr = new ArrayList<StackTraceElement>(); for (StackTraceElement s : trace) { if (!s.getClassName().contains(".reflect.")) stackArr.add(s); } StackTraceElement[] newTrace = new StackTraceElement[stackArr.size()]; stackArr.toArray(newTrace); e.getCause().setStackTrace(newTrace); e.getCause().printStackTrace(); } /** * Run a console command * * @param line * string containing both command name and arguments, separated * by spaces * @return true if the command runs successfully and false otherwise * @throws Exception * if the command is not found or fails during execution */ public void runCommand(String line) throws Exception { String[] parts = line.split(" "); String cmd = parts[0]; String[] args = Arrays.copyOfRange(parts, 1, parts.length); runCommand(cmd, args); } /** * Runs a console command * * @param methodAlias * command (method) name * @param args * command arguments * @throws Exception * if the command is not found or fails during execution */ public void runCommand(String methodAlias, String args[]) throws Exception { if (methodAlias.isEmpty() || methodAlias.startsWith(" return; MethodData methodData = methodAliases.get(methodAlias); if (methodData == null) { throw new Exception(String.format("Unknown command <%s>", methodAlias)); } else { smartInvoke(methodAlias, methodData.method, methodData.object, args); } } @Command(aliases = { ":type" }, description = "print type information for a given command") public boolean getType(String methodAlias) { MethodData md = methodAliases.get(methodAlias); if (md == null) { out.printf("command <%s> does not exist", methodAlias); return false; } else { printParameters(methodAlias, md.method); return true; } } @Command(aliases = { ":shell", ":!" }, description = "run shell command") public boolean runShellCmd(String args[]) { String cmd = String.join(" ", args); final Runtime rt = Runtime.getRuntime(); try { Process proc = rt.exec(cmd); BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream())); String s = null; while ((s = stdInput.readLine()) != null) out.println(s); while ((s = stdError.readLine()) != null) out.println(s); return true; } catch (IOException e) { return false; } } @Command(aliases = { ":source", ":s" }, description = "run script file") public void runScript(String scriptFile) throws Exception { BufferedReader br = new BufferedReader(new FileReader(scriptFile)); try { exitFlag = 0; String line; while ((line = br.readLine()) != null && exitFlag == 0) { if (!line.isEmpty()) { try { this.runCommand(line); } catch (Exception e) { prettyPrintStackTrace(e); return; } } } exitFlag = 0; } finally { br.close(); } } @Command(aliases = { ":quit", ":q" }, description = "exit program") public boolean exitConsole() { exitFlag = 1; return true; } @Command(aliases = { ":help", ":h" }, description = "print help text of a command", help = { "Uage:", " :help <command>" }) public void printHelp(String methodAlias) { MethodData md = methodAliases.get(methodAlias); if (md == null) { System.out.println("Unrecognized command"); } else { Command anot = getCommandAnnotation(md.method); System.out.printf("%s : %s\n\n", methodAlias, anot.description()); for (String s : anot.help()) System.out.println(s); } } @Command(aliases = { ":time", ":t" }, description = "time the execution of a command") public void timeCommand(String args[]) throws Exception { long startTime = System.nanoTime(); runCommand(String.join(" ", args)); long endTime = System.nanoTime(); double searchTime = (endTime - startTime) / 1e9; System.out.printf("Completed execution in %f seconds\n", searchTime); } // internal (private) functions /* * this function returns true when `method` has 1 parameter and of the type * String[] */ private boolean isMethodGeneric(Method method) { @SuppressWarnings("rawtypes") Class[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 1) { return isStringArray(parameterTypes[0]); } else { return false; } } private boolean isStringArray(@SuppressWarnings("rawtypes") Class clazz) { boolean isArr = clazz.isArray(); boolean isCompString = clazz.getComponentType() == String.class; return isArr && isCompString; } /* * return true if command executes successfully and false otherwise */ private boolean smartInvoke(String usedAlias, Method method, Object object, String[] args) throws Exception { Object[] noargs = new Object[] { new String[] {} }; int nArgs = args.length; Class<?>[] paramTypes = method.getParameterTypes(); int nMethodArgs = paramTypes.length; // determine type of invocation if (nMethodArgs == 0) { if (nArgs == 0) { // simple case, invoke with no parameters method.invoke(object); return true; } else { printParameters(usedAlias, method); return false; } } else if (nMethodArgs == 1 && isMethodGeneric(method)) { // this method takes one parameter of type String[] that // contains all user parameters if (nArgs == 0) { // user supplied no parameters method.invoke(object, noargs); return true; } else { // user supplied 1+ parameters method.invoke(object, new Object[] { args }); return true; } } else if (nMethodArgs == nArgs) { // the method accepts several parameters, attempt to convert // parameters to the correct types and pass them to the method ArrayList<Object> objs = new ArrayList<Object>(); try { for (int i = 0; i < paramTypes.length; i++) { objs.add(toObject(paramTypes[i], args[i])); } } catch (Exception e) { out.println("Unable to parse parameters"); printParameters(usedAlias, method); return false; } Object[] objsArr = objs.toArray(); method.invoke(object, objsArr); return true; } else { out.printf("command <%s> requires %d parameter(s) (%d supplied)", usedAlias, nMethodArgs, nArgs); return false; } } private static Object toObject(@SuppressWarnings("rawtypes") Class clazz, String value) throws Exception { if (Boolean.class == clazz || Boolean.TYPE == clazz) return Boolean.parseBoolean(value); if (Byte.class == clazz || Byte.TYPE == clazz) return Byte.parseByte(value); if (Short.class == clazz || Short.TYPE == clazz) return Short.parseShort(value); if (Integer.class == clazz || Integer.TYPE == clazz) return Integer.parseInt(value); if (Long.class == clazz || Long.TYPE == clazz) return Long.parseLong(value); if (Float.class == clazz || Float.TYPE == clazz) return Float.parseFloat(value); if (Double.class == clazz || Double.TYPE == clazz) return Double.parseDouble(value); if (String.class == clazz) return value; throw new Exception("Attempted to parse non-primitive type"); } private void printParameters(String usedAlias, Method method) { Class<?>[] paramTypes = method.getParameterTypes(); if (paramTypes.length == 0) { out.printf("command <%s> takes no parameters\n", usedAlias); } else if (paramTypes.length == 1) { if (isStringArray(paramTypes[0])) { out.printf("command <%s> takes arbitrary parameters\n", usedAlias); } else { out.printf("command <%s> takes <%s> parameter\n", usedAlias, paramTypes[0].getName()); } } else { StringBuilder sb = new StringBuilder(); sb.append("command <" + method.getName() + "> takes <"); sb.append(paramTypes[0].getName()); int j = paramTypes.length; for (int i = 1; i < j - 1; i++) { sb.append(", " + paramTypes[i].getName()); } sb.append(", " + paramTypes[j - 1].getName() + "> parameters"); out.println(sb.toString()); } } @Command(aliases = { ":list", ":l" }, description = "lists available commands") private void listMethods() { TreeSet<String> methodList = new TreeSet<String>(); for (MethodData md : availMethods) { Command anot = getCommandAnnotation(md.method); if (anot.visible()) { String[] aliases = anot.aliases(); String cmd = aliases.length == 0 ? md.method.getName() : aliases[0]; methodList.add(cmd); } } out.println("Available commands:"); for (String cmd : methodList) { Method m = methodAliases.get(cmd).method; String desc = getCommandAnnotation(m).description(); out.printf("%-20s : %s\n", cmd, desc); } } @Command(aliases = { ":aliases", ":a" }, description = "list command aliases") private void listAliases() { TreeSet<String> methodList = new TreeSet<String>(); for (MethodData md : availMethods) { Command anot = getCommandAnnotation(md.method); if (anot.visible()) { String[] aliases = anot.aliases(); if (aliases.length > 1) { String cmd = aliases.length == 0 ? md.method.getName() : aliases[0]; methodList.add(cmd); } } } out.println("Available command aliases:"); for (String cmd : methodList) { Method m = methodAliases.get(cmd).method; Command anot = getCommandAnnotation(m); String aliases = ""; if (anot.aliases().length < 2) { aliases = "n/a"; } else { aliases = anot.aliases()[1]; for (int i = 2; i < anot.aliases().length; i++) { aliases += ", " + anot.aliases()[i]; } } out.printf("%-20s : %s\n", cmd, aliases); } } private Command getCommandAnnotation(Method method) { Command[] anots = method.getDeclaredAnnotationsByType(Command.class); return anots[0]; } /** * Return a list of command aliases for a method annotated with Command * * <p> * If any aliases are defined in the Command annotation then these are * returned. Otherwise the method name is returned as the only alias. * * @param method * @return */ private ArrayList<String> getCommandNames(Method method) { Command[] anots = method.getDeclaredAnnotationsByType(Command.class); ArrayList<String> result = new ArrayList<String>(); if (anots.length > 0) { if (anots[0].aliases().length > 0) { // this command has aliases for (String a : anots[0].aliases()) { result.add(a); } } else { // no defined aliases, use command line as only alias result.add(method.getName()); } } return result; } private void scanForMethods() { HashSet<Object> allHandlers = new HashSet<Object>(handlers); allHandlers.add(this); for (Object handler : allHandlers) { Method[] methods = handler.getClass().getDeclaredMethods(); for (Method method : methods) { Command[] anots = method.getDeclaredAnnotationsByType(Command.class); if (anots.length > 0) { MethodData md = new MethodData(method, handler); availMethods.add(md); ArrayList<String> aliases; aliases = getCommandNames(method); for (String a : aliases) { methodAliases.put(a, md); } } } } } @Command(aliases = { ":print", ":p" }, description = "print a text to the console") private void print(String[] args) { out.println(String.join(" ", args)); } }
package org.basex.query.ft; import static org.basex.query.QueryTokens.*; import static org.basex.util.Token.*; import static org.basex.util.ft.FTFlag.*; import java.io.IOException; import org.basex.data.Data; import org.basex.data.FTMatches; import org.basex.data.MetaData; import org.basex.data.Serializer; import org.basex.index.FTIndexIterator; import org.basex.query.IndexContext; import org.basex.query.QueryContext; import org.basex.query.QueryException; import org.basex.query.expr.Expr; import org.basex.query.item.FTNode; import org.basex.query.item.Item; import org.basex.query.item.Str; import org.basex.query.iter.FTIter; import org.basex.query.iter.Iter; import org.basex.query.util.Var; import org.basex.util.InputInfo; import org.basex.util.TokenBuilder; import org.basex.util.TokenList; import org.basex.util.TokenSet; import org.basex.util.ft.FTLexer; import org.basex.util.ft.FTOpt; import org.basex.util.ft.Scoring; public final class FTWords extends FTExpr { /** Words mode. */ public enum FTMode { /** All option. */ M_ALL, /** All words option. */ M_ALLWORDS, /** Any option. */ M_ANY, /** Any words option. */ M_ANYWORD, /** Phrase search. */ M_PHRASE } /** Full-text tokenizer. */ FTTokenizer ftt; /** Data reference. */ Data data; /** Single string. */ TokenList txt; /** All matches. */ FTMatches all = new FTMatches((byte) 0); /** Flag for first evaluation. */ boolean first; /** Search mode; default: {@link FTMode#M_ANY}. */ FTMode mode = FTMode.M_ANY; /** Query expression. */ private Expr query; /** Minimum and maximum occurrences. */ private Expr[] occ; /** Current token number. */ private int tokNum; /** Fast evaluation. */ private boolean fast; /** * Constructor for scan-based evaluation. * @param ii input info * @param e expression * @param m search mode * @param o occurrences */ public FTWords(final InputInfo ii, final Expr e, final FTMode m, final Expr[] o) { super(ii); query = e; mode = m; occ = o; } /** * Constructor for index-based evaluation. * @param ii input info * @param d data reference * @param str string * @param ctx query context * @throws QueryException query exception */ public FTWords(final InputInfo ii, final Data d, final Item str, final QueryContext ctx) throws QueryException { super(ii); query = str; data = d; comp(ctx); } @Override public FTExpr comp(final QueryContext ctx) throws QueryException { // compile only once if(ftt == null) { if(occ != null) { for(int o = 0; o < occ.length; ++o) occ[o] = occ[o].comp(ctx); } query = query.comp(ctx); if(query.value()) { txt = new TokenList(); final Iter iter = query.iter(ctx); byte[] t; while((t = nextToken(iter)) != null) if(t.length != 0) txt.add(t); } // choose fast evaluation for default settings fast = mode == FTMode.M_ANY && txt != null && occ == null; ftt = new FTTokenizer(this, ctx.ftopt, ctx.context.prop); } return this; } @Override public FTNode item(final QueryContext ctx, final InputInfo ii) throws QueryException { if(tokNum == 0) tokNum = ++ctx.ftoknum; all.reset(tokNum); final int c = contains(ctx); if(c == 0) all.size = 0; // scoring: include number of tokens for calculations return new FTNode(all, c == 0 ? 0 : Scoring.word(c, ctx.fttoken.count())); } @Override public FTIter iter(final QueryContext ctx) { return new FTIter() { /** Index iterator. */ FTIndexIterator iat; /** Text length. */ int tl; @Override public FTNode next() { if(iat == null) { final FTLexer lex = new FTLexer(ftt.opt); // index iterator tree FTIndexIterator ia = null; // number of distinct tokens int t = 0; // loop through all tokens final TokenSet ts = tokens(txt, ftt.opt); for(final byte[] k : ts) { lex.init(k); ia = null; int d = 0; while(lex.hasNext()) { final byte[] token = lex.nextToken(); t += token.length; if(ftt.opt.sw != null && ftt.opt.sw.id(token) != 0) { ++d; } else { final FTIndexIterator ir = (FTIndexIterator) data.ids(lex); if(ia == null) { ia = ir; } else { ia = FTIndexIterator.intersect(ia, ir, ++d); d = 0; } } } if(iat == null) { tl = t; iat = ia; } else if(mode == FTMode.M_ALL || mode == FTMode.M_ALLWORDS) { if(ia.indexSize() == 0) return null; tl += t; iat = FTIndexIterator.intersect(ia, iat, 0); } else { if(ia.indexSize() == 0) continue; tl = Math.max(t, tl); iat = FTIndexIterator.union(ia, iat); } iat.tokenNum(++ctx.ftoknum); } } return iat != null && iat.more() ? new FTNode(iat.matches(), data, iat.next(), tl, iat.indexSize(), iat.score()) : null; } }; } /** * Evaluates the full-text match. * @param ctx query context * @return number of tokens, used for scoring * @throws QueryException query exception */ private int contains(final QueryContext ctx) throws QueryException { first = true; final FTLexer intok = ftt.copy(ctx.fttoken); // use shortcut for default processing int num = 0; if(fast) { for(final byte[] t : txt) { final FTTokens qtok = ftt.cache(t); num = Math.max(num, ftt.contains(qtok, intok) * qtok.length()); } return num; } final TokenList tl = new TokenList(); final Iter ir = ctx.iter(query); byte[] qu; while((qu = nextToken(ir)) != null) tl.add(qu); // find and count all occurrences final TokenSet ts = tokens(tl, intok.ftOpt()); final boolean a = mode == FTMode.M_ALL || mode == FTMode.M_ALLWORDS; int oc = 0; for(final byte[] k : ts) { final FTTokens qtok = ftt.cache(k); final int o = ftt.contains(qtok, intok); if(a && o == 0) return 0; num = Math.max(num, o * qtok.length()); oc += o; } // check if occurrences are in valid range. if yes, return number of tokens final long mn = occ != null ? checkItr(occ[0], ctx) : 1; final long mx = occ != null ? checkItr(occ[1], ctx) : Long.MAX_VALUE; if(mn == 0 && oc == 0) all = FTNot.not(all); return oc >= mn && oc <= mx ? Math.max(1, num) : 0; } /** * Caches and returns all unique tokens specified in a query. * @param list token list * @param ftopt full-text options * @return token set */ TokenSet tokens(final TokenList list, final FTOpt ftopt) { // cache all query tokens (remove duplicates) final TokenSet ts = new TokenSet(); switch(mode) { case M_ALL: case M_ANY: for(final byte[] t : list) ts.add(t); break; case M_ALLWORDS: case M_ANYWORD: final FTLexer l = new FTLexer(ftopt); for(final byte[] t : list) { l.init(t); while(l.hasNext()) ts.add(l.nextToken()); } break; case M_PHRASE: final TokenBuilder tb = new TokenBuilder(); for(final byte[] t : list) tb.add(t).add(' '); ts.add(tb.trim().finish()); } return ts; } /** * Returns the next token of the specified iterator, or {@code null}. * @param iter iterator to be checked * @return item * @throws QueryException query exception */ private byte[] nextToken(final Iter iter) throws QueryException { final Item it = iter.next(); return it == null ? null : checkEStr(it); } /** * Adds a match. * @param s start position * @param e end position */ void add(final int s, final int e) { if(!first && (mode == FTMode.M_ALL || mode == FTMode.M_ALLWORDS)) all.and(s, e); else all.or(s, e); } @Override public boolean indexAccessible(final IndexContext ic) { /* If the following conditions yield true, the index is accessed: * - all query terms are statically available * - no FTTimes option is specified * - explicitly set case, diacritics and stemming match options do not * conflict with index options. */ final MetaData md = ic.data.meta; final FTOpt fto = ftt.opt; // skip index access if index does not support wildcards final boolean wc = fto.is(WC); if(wc && !md.wildcards) return false; /* Index will be applied if no explicit match options have been set * that conflict with the index options. As a consequence, though, index- * based querying might yield other results than sequential scanning. */ if(fto.isSet(CS) && md.casesens != fto.is(CS) || fto.isSet(DC) && md.diacritics != fto.is(DC) || fto.isSet(ST) && md.stemming != fto.is(ST) || fto.ln != null && md.language != fto.ln || occ != null) return false; // skip index access if text is not statically known if(txt == null) return false; // no index results if(txt.size() == 0) { ic.costs = 0; return true; } // adopt database options to tokenizer fto.set(CS, md.casesens); fto.set(DC, md.diacritics); fto.set(ST, md.stemming); fto.ln = md.language; // summarize number of hits; break loop if no hits are expected final FTLexer ft = new FTLexer(fto); ic.costs = 0; for(byte[] t : txt) { ft.init(t); while(ft.hasNext()) { final byte[] tok = ft.nextToken(); if(tok.length > MAXLEN) return false; if(fto.sw != null && fto.sw.id(tok) != 0) continue; if(wc) { // don't use index if one of the terms starts with a wildcard t = ft.get(); if(t[0] == '.') return false; // don't use index if certain characters, or more than 1 dot are found int d = 0; for(final byte w : t) { if(w == '{' || w == '\\' || w == '.' && ++d > 1) return false; } } // reduce number of expected results to favor full-text index requests ic.costs += ic.data.nrIDs(ft) + 3 >> 2; } } return true; } @Override public FTExpr indexEquivalent(final IndexContext ic) { data = ic.data; return this; } @Override public boolean usesExclude() { return occ != null; } @Override public boolean uses(final Use u) { if(occ != null) for(final Expr o : occ) if(o.uses(u)) return true; return query.uses(u); } @Override public int count(final Var v) { int c = 0; if(occ != null) for(final Expr o : occ) c += o.count(v); return c + query.count(v); } @Override public boolean removable(final Var v) { if(occ != null) for(final Expr o : occ) if(!o.removable(v)) return false; return query.removable(v); } @Override public FTExpr remove(final Var v) { if(occ != null) { for(int o = 0; o < occ.length; ++o) occ[o] = occ[o].remove(v); } query = query.remove(v); return this; } @Override public void plan(final Serializer ser) throws IOException { ser.openElement(this); if(occ != null) { occ[0].plan(ser); occ[1].plan(ser); } query.plan(ser); ser.closeElement(); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); if(!(query instanceof Str)) sb.append("{ "); sb.append(query); if(!(query instanceof Str)) sb.append(" }"); switch(mode) { case M_ALL: sb.append(' ' + ALL); break; case M_ALLWORDS: sb.append(' ' + ALL + ' ' + WORDS); break; case M_ANYWORD: sb.append(' ' + ANY + ' ' + WORD); break; case M_PHRASE: sb.append(' ' + PHRASE); break; default: } if(occ != null) { sb.append(OCCURS + " " + occ[0] + " " + TO + " " + occ[1] + " " + TIMES); } return sb.toString(); } }
package org.basex.query.func; import static org.basex.util.Token.*; import org.basex.query.QueryContext; import org.basex.query.QueryException; import org.basex.query.expr.Expr; import org.basex.query.item.Item; import org.basex.query.item.Str; import org.basex.query.iter.ItemCache; import org.basex.query.iter.Iter; import org.basex.query.util.pkg.Package; import org.basex.query.util.pkg.RepoManager; import org.basex.util.InputInfo; public final class FNPkg extends FuncCall { /** * Constructor. * @param ii input info * @param f function definition * @param e arguments */ protected FNPkg(final InputInfo ii, final Function f, final Expr[] e) { super(ii, f, e); } @Override public Iter iter(final QueryContext ctx) throws QueryException { checkAdmin(ctx); switch(def) { case _PKG_LIST: final ItemCache cache = new ItemCache(); for(final byte[] p : ctx.context.repo.pkgDict()) if(p != null) cache.add(Str.get(Package.name(p))); return cache; default: return super.iter(ctx); } } @Override public Item item(final QueryContext ctx, final InputInfo ii) throws QueryException { checkAdmin(ctx); final RepoManager repoMng = new RepoManager(ctx.context.repo); // either path to package or package name final String pkg = string(checkStr(expr[0], ctx)); switch(def) { case _PKG_INSTALL: repoMng.install(pkg, ii); return null; case _PKG_DELETE: repoMng.delete(pkg, ii); return null; default: return super.item(ctx, ii); } } @Override public boolean uses(final Use u) { // don't allow pre-evaluation return u == Use.CTX || super.uses(u); } }
package org.gitlab4j.api; import java.util.Map; import javax.ws.rs.core.Response; import org.gitlab4j.api.Constants.TokenType; import org.gitlab4j.api.models.OauthTokenResponse; import org.gitlab4j.api.models.Session; import org.gitlab4j.api.models.User; import org.gitlab4j.api.models.Version; /** * This class is provides a simplified interface to a GitLab API server, and divides the API up into * a separate API class for each concern. */ public class GitLabApi { /** GitLab4J default per page. GitLab will ignore anything over 100. */ public static final int DEFAULT_PER_PAGE = 100; /** Specifies the version of the GitLab API to communicate with. */ public enum ApiVersion { V3, V4, OAUTH2_CLIENT; public String getApiNamespace() { return ("/api/" + name().toLowerCase()); } } GitLabApiClient apiClient; private ApiVersion apiVersion; private String gitLabServerUrl; private Map<String, Object> clientConfigProperties; private int defaultPerPage = DEFAULT_PER_PAGE; private Session session; private CommitsApi commitsApi; private DeployKeysApi deployKeysApi; private GroupApi groupApi; private IssuesApi issuesApi; private MergeRequestApi mergeRequestApi; private MilestonesApi milestonesApi; private NamespaceApi namespaceApi; private PipelineApi pipelineApi; private ProjectApi projectApi; private RepositoryApi repositoryApi; private RepositoryFileApi repositoryFileApi; private ServicesApi servicesApi; private SessionApi sessionApi; private SystemHooksApi systemHooksApi; private UserApi userApi; private JobApi jobApi; private LabelsApi labelsApi; private NotesApi notesApi; private EventsApi eventsApi; /** * Create a new GitLabApi instance that is logically a duplicate of this instance, with the exception off sudo state. * * @return a new GitLabApi instance that is logically a duplicate of this instance, with the exception off sudo state. */ public final GitLabApi duplicate() { Integer sudoUserId = this.getSudoAsId(); GitLabApi gitLabApi = new GitLabApi(apiVersion, gitLabServerUrl, getTokenType(), getAuthToken(), getSecretToken(), clientConfigProperties); if (sudoUserId != null) { gitLabApi.apiClient.setSudoAsId(sudoUserId); } if (getIgnoreCertificateErrors()) { gitLabApi.setIgnoreCertificateErrors(true); } gitLabApi.defaultPerPage = this.defaultPerPage; return (gitLabApi); } /** * <p>Logs into GitLab using OAuth2 with the provided {@code username} and {@code password}, * and creates a new {@code GitLabApi} instance using returned access token.</p> * * @param url GitLab URL * @param username user name for which private token should be obtained * @param password password for a given {@code username} * @return new {@code GitLabApi} instance configured for a user-specific token * @throws GitLabApiException GitLabApiException if any exception occurs during execution */ public static GitLabApi oauth2Login(String url, String username, String password) throws GitLabApiException { return (GitLabApi.oauth2Login(ApiVersion.V4, url, username, password, null, null, false)); } /** * <p>Logs into GitLab using OAuth2 with the provided {@code username} and {@code password}, * and creates a new {@code GitLabApi} instance using returned access token.</p> * * @param url GitLab URL * @param username user name for which private token should be obtained * @param password password for a given {@code username} * @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate errors * @return new {@code GitLabApi} instance configured for a user-specific token * @throws GitLabApiException GitLabApiException if any exception occurs during execution */ public static GitLabApi oauth2Login(String url, String username, String password, boolean ignoreCertificateErrors) throws GitLabApiException { return (GitLabApi.oauth2Login(ApiVersion.V4, url, username, password, null, null, ignoreCertificateErrors)); } /** * <p>Logs into GitLab using OAuth2 with the provided {@code username} and {@code password}, * and creates a new {@code GitLabApi} instance using returned access token.</p> * * @param url GitLab URL * @param username user name for which private token should be obtained * @param password password for a given {@code username} * @param secretToken use this token to validate received payloads * @param clientConfigProperties Map instance with additional properties for the Jersey client connection * @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate errors * @return new {@code GitLabApi} instance configured for a user-specific token * @throws GitLabApiException GitLabApiException if any exception occurs during execution */ public static GitLabApi oauth2Login(String url, String username, String password, String secretToken, Map<String, Object> clientConfigProperties, boolean ignoreCertificateErrors) throws GitLabApiException { return (GitLabApi.oauth2Login(ApiVersion.V4, url, username, password, secretToken, clientConfigProperties, ignoreCertificateErrors)); } /** * <p>Logs into GitLab using OAuth2 with the provided {@code username} and {@code password}, * and creates a new {@code GitLabApi} instance using returned access token.</p> * * @param url GitLab URL * @param apiVersion the ApiVersion specifying which version of the API to use * @param username user name for which private token should be obtained * @param password password for a given {@code username} * @param secretToken use this token to validate received payloads * @param clientConfigProperties Map instance with additional properties for the Jersey client connection * @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate errors * @return new {@code GitLabApi} instance configured for a user-specific token * @throws GitLabApiException GitLabApiException if any exception occurs during execution */ public static GitLabApi oauth2Login(ApiVersion apiVersion, String url, String username, String password, String secretToken, Map<String, Object> clientConfigProperties, boolean ignoreCertificateErrors) throws GitLabApiException { if (username == null || username.trim().length() == 0) { throw new IllegalArgumentException("both username and email cannot be empty or null"); } GitLabApi gitLabApi = new GitLabApi(ApiVersion.OAUTH2_CLIENT, url, (String)null); if (ignoreCertificateErrors) { gitLabApi.setIgnoreCertificateErrors(true); } class Oauth2Api extends AbstractApi { Oauth2Api(GitLabApi gitlabApi) { super(gitlabApi); } } GitLabApiForm formData = new GitLabApiForm() .withParam("grant_type", "password", true) .withParam("username", username, true) .withParam("password", password, true); Response response = new Oauth2Api(gitLabApi).post(Response.Status.OK, formData, "oauth", "token"); OauthTokenResponse oauthToken = response.readEntity(OauthTokenResponse.class); gitLabApi = new GitLabApi(apiVersion, url, TokenType.ACCESS, oauthToken.getAccessToken(), secretToken, clientConfigProperties); if (ignoreCertificateErrors) { gitLabApi.setIgnoreCertificateErrors(true); } return (gitLabApi); } /** * <p>Logs into GitLab using provided {@code username} and {@code password}, and creates a new {@code GitLabApi} instance * using returned private token and the specified GitLab API version.</p> * * <strong>NOTE</strong: For GitLab servers 10.2 and above this will utilize OAUTH2 for login. For GitLab servers prior to * 10.2, the Session API login is utilized. * * @param apiVersion the ApiVersion specifying which version of the API to use * @param url GitLab URL * @param username user name for which private token should be obtained * @param password password for a given {@code username} * @return new {@code GitLabApi} instance configured for a user-specific token * @throws GitLabApiException GitLabApiException if any exception occurs during execution */ public static GitLabApi login(ApiVersion apiVersion, String url, String username, String password) throws GitLabApiException { return (GitLabApi.login(apiVersion, url, username, password, false)); } /** * <p>Logs into GitLab using provided {@code username} and {@code password}, and creates a new {@code GitLabApi} instance * using returned private token using GitLab API version 4.</p> * * <strong>NOTE</strong: For GitLab servers 10.2 and above this will utilize OAUTH2 for login. For GitLab servers prior to * 10.2, the Session API login is utilized. * * @param url GitLab URL * @param username user name for which private token should be obtained * @param password password for a given {@code username} * @return new {@code GitLabApi} instance configured for a user-specific token * @throws GitLabApiException GitLabApiException if any exception occurs during execution */ public static GitLabApi login(String url, String username, String password) throws GitLabApiException { return (GitLabApi.login(ApiVersion.V4, url, username, password, false)); } /** * <p>Logs into GitLab using provided {@code username} and {@code password}, and creates a new {@code GitLabApi} instance * using returned private token and the specified GitLab API version.</p> * * <strong>NOTE</strong: For GitLab servers 10.2 and above this will utilize OAUTH2 for login. For GitLab servers prior to * 10.2, the Session API login is utilized. * * @param apiVersion the ApiVersion specifying which version of the API to use * @param url GitLab URL * @param username user name for which private token should be obtained * @param password password for a given {@code username} * @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate errors * @return new {@code GitLabApi} instance configured for a user-specific token * @throws GitLabApiException GitLabApiException if any exception occurs during execution */ public static GitLabApi login(ApiVersion apiVersion, String url, String username, String password, boolean ignoreCertificateErrors) throws GitLabApiException { GitLabApi gitLabApi = new GitLabApi(apiVersion, url, (String)null); if (ignoreCertificateErrors) { gitLabApi.setIgnoreCertificateErrors(true); } try { SessionApi sessionApi = gitLabApi.getSessionApi(); Session session = sessionApi.login(username, null, password); gitLabApi = new GitLabApi(apiVersion, url, session); if (ignoreCertificateErrors) { gitLabApi.setIgnoreCertificateErrors(true); } } catch (GitLabApiException gle) { if (gle.getHttpStatus() != Response.Status.NOT_FOUND.getStatusCode()) { throw (gle); } else { gitLabApi = GitLabApi.oauth2Login(apiVersion, url, username, password, null, null, ignoreCertificateErrors); } } return (gitLabApi); } /** * <p>Logs into GitLab using provided {@code username} and {@code password}, and creates a new {@code GitLabApi} instance * using returned private token using GitLab API version 4.</p> * * <strong>NOTE</strong: For GitLab servers 10.2 and above this will utilize OAUTH2 for login. For GitLab servers prior to * 10.2, the Session API login is utilized. * * @param url GitLab URL * @param username user name for which private token should be obtained * @param password password for a given {@code username} * @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate errors * @return new {@code GitLabApi} instance configured for a user-specific token * @throws GitLabApiException GitLabApiException if any exception occurs during execution */ public static GitLabApi login(String url, String username, String password, boolean ignoreCertificateErrors) throws GitLabApiException { return (GitLabApi.login(ApiVersion.V4, url, username, password, ignoreCertificateErrors)); } /** * <p>Logs into GitLab using provided {@code username} and {@code password}, and creates a new {@code GitLabApi} instance * using returned private token and specified GitLab API version.</p> * * @param url GitLab URL * @param username user name for which private token should be obtained * @param password password for a given {@code username} * @return new {@code GitLabApi} instance configured for a user-specific token * @throws GitLabApiException GitLabApiException if any exception occurs during execution * @deprecated As of release 4.2.0, replaced by {@link #login(String, String, String)}, will be removed in 5.0.0 */ @Deprecated public static GitLabApi create(String url, String username, String password) throws GitLabApiException { return (GitLabApi.login(url, username, password)); } /** * <p>If this instance was created with {@link #login(String, String, String)} this method will * return the Session instance returned by the GitLab API on login, otherwise returns null.</p> * * <strong>NOTE</strong: For GitLab servers 10.2 and above this method will always return null. * * @return the Session instance * @deprecated This method will be removed in Release 5.0.0 */ public Session getSession() { return session; } /** * Constructs a GitLabApi instance set up to interact with the GitLab server using the specified GitLab API version. * * @param apiVersion the ApiVersion specifying which version of the API to use * @param hostUrl the URL of the GitLab server * @param tokenType the type of auth the token is for, PRIVATE or ACCESS * @param authToken the token to use for access to the API */ public GitLabApi(ApiVersion apiVersion, String hostUrl, TokenType tokenType, String authToken) { this(apiVersion, hostUrl, tokenType, authToken, null); } /** * Constructs a GitLabApi instance set up to interact with the GitLab server using the specified GitLab API version. * * @param apiVersion the ApiVersion specifying which version of the API to use * @param hostUrl the URL of the GitLab server * @param privateToken to private token to use for access to the API */ public GitLabApi(ApiVersion apiVersion, String hostUrl, String privateToken) { this(apiVersion, hostUrl, privateToken, null); } /** * Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API version 4. * * @param hostUrl the URL of the GitLab server * @param tokenType the type of auth the token is for, PRIVATE or ACCESS * @param authToken the token to use for access to the API */ public GitLabApi(String hostUrl, TokenType tokenType, String authToken) { this(ApiVersion.V4, hostUrl, tokenType, authToken, null); } /** * Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API version 4. * * @param hostUrl the URL of the GitLab server * @param privateToken to private token to use for access to the API */ public GitLabApi(String hostUrl, String privateToken) { this(ApiVersion.V4, hostUrl, privateToken, null); } /** * Constructs a GitLabApi instance set up to interact with the GitLab server using the specified GitLab API version. * * @param apiVersion the ApiVersion specifying which version of the API to use * @param hostUrl the URL of the GitLab server * @param session the Session instance obtained by logining into the GitLab server */ public GitLabApi(ApiVersion apiVersion, String hostUrl, Session session) { this(apiVersion, hostUrl, TokenType.PRIVATE, session.getPrivateToken(), null); this.session = session; } /** * Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API version 4. * * @param hostUrl the URL of the GitLab server * @param session the Session instance obtained by logining into the GitLab server */ public GitLabApi(String hostUrl, Session session) { this(ApiVersion.V4, hostUrl, session); } /** * Constructs a GitLabApi instance set up to interact with the GitLab server using the specified GitLab API version. * * @param apiVersion the ApiVersion specifying which version of the API to use * @param hostUrl the URL of the GitLab server * @param tokenType the type of auth the token is for, PRIVATE or ACCESS * @param authToken the token to use for access to the API * @param secretToken use this token to validate received payloads */ public GitLabApi(ApiVersion apiVersion, String hostUrl, TokenType tokenType, String authToken, String secretToken) { this(apiVersion, hostUrl, tokenType, authToken, secretToken, null); } /** * Constructs a GitLabApi instance set up to interact with the GitLab server using the specified GitLab API version. * * @param apiVersion the ApiVersion specifying which version of the API to use * @param hostUrl the URL of the GitLab server * @param privateToken to private token to use for access to the API * @param secretToken use this token to validate received payloads */ public GitLabApi(ApiVersion apiVersion, String hostUrl, String privateToken, String secretToken) { this(apiVersion, hostUrl, privateToken, secretToken, null); } /** * Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API version 4. * * @param hostUrl the URL of the GitLab server * @param tokenType the type of auth the token is for, PRIVATE or ACCESS * @param authToken the token to use for access to the API * @param secretToken use this token to validate received payloads */ public GitLabApi(String hostUrl, TokenType tokenType, String authToken, String secretToken) { this(ApiVersion.V4, hostUrl, tokenType, authToken, secretToken); } /** * Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API version 4. * * @param hostUrl the URL of the GitLab server * @param privateToken to private token to use for access to the API * @param secretToken use this token to validate received payloads */ public GitLabApi(String hostUrl, String privateToken, String secretToken) { this(ApiVersion.V4, hostUrl, TokenType.PRIVATE, privateToken, secretToken); } /** * Constructs a GitLabApi instance set up to interact with the GitLab server specified by GitLab API version. * * @param apiVersion the ApiVersion specifying which version of the API to use * @param hostUrl the URL of the GitLab server * @param privateToken to private token to use for access to the API * @param secretToken use this token to validate received payloads * @param clientConfigProperties Map instance with additional properties for the Jersey client connection */ public GitLabApi(ApiVersion apiVersion, String hostUrl, String privateToken, String secretToken, Map<String, Object> clientConfigProperties) { this(apiVersion, hostUrl, TokenType.PRIVATE, privateToken, secretToken, clientConfigProperties); } /** * Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API version 4. * * @param hostUrl the URL of the GitLab server * @param tokenType the type of auth the token is for, PRIVATE or ACCESS * @param authToken the token to use for access to the API * @param secretToken use this token to validate received payloads * @param clientConfigProperties Map instance with additional properties for the Jersey client connection */ public GitLabApi(String hostUrl, TokenType tokenType, String authToken, String secretToken, Map<String, Object> clientConfigProperties) { this(ApiVersion.V4, hostUrl, tokenType, authToken, secretToken, clientConfigProperties); } /** * Constructs a GitLabApi instance set up to interact with the GitLab server using GitLab API version 4. * * @param hostUrl the URL of the GitLab server * @param privateToken to private token to use for access to the API * @param secretToken use this token to validate received payloads * @param clientConfigProperties Map instance with additional properties for the Jersey client connection */ public GitLabApi(String hostUrl, String privateToken, String secretToken, Map<String, Object> clientConfigProperties) { this(ApiVersion.V4, hostUrl, TokenType.PRIVATE, privateToken, secretToken, clientConfigProperties); } /** * Constructs a GitLabApi instance set up to interact with the GitLab server specified by GitLab API version. * * @param apiVersion the ApiVersion specifying which version of the API to use * @param hostUrl the URL of the GitLab server * @param tokenType the type of auth the token is for, PRIVATE or ACCESS * @param authToken to token to use for access to the API * @param secretToken use this token to validate received payloads * @param clientConfigProperties Map instance with additional properties for the Jersey client connection */ public GitLabApi(ApiVersion apiVersion, String hostUrl, TokenType tokenType, String authToken, String secretToken, Map<String, Object> clientConfigProperties) { this.apiVersion = apiVersion; this.gitLabServerUrl = hostUrl; this.clientConfigProperties = clientConfigProperties; apiClient = new GitLabApiClient(apiVersion, hostUrl, tokenType, authToken, secretToken, clientConfigProperties); } /** * Sets up all future calls to the GitLab API to be done as another user specified by sudoAsUsername. * To revert back to normal non-sudo operation you must call unsudo(), or pass null as the username. * * @param sudoAsUsername the username to sudo as, null will turn off sudo * @throws GitLabApiException if any exception occurs */ public void sudo(String sudoAsUsername) throws GitLabApiException { if (sudoAsUsername == null || sudoAsUsername.trim().length() == 0) { apiClient.setSudoAsId(null); return; } // Get the User specified by username, if you are not an admin or the username is not found, this will fail User user = getUserApi().getUser(sudoAsUsername); if (user == null || user.getId() == null) { throw new GitLabApiException("the specified username was not found"); } Integer sudoAsId = user.getId(); apiClient.setSudoAsId(sudoAsId); } /** * Turns off the currently configured sudo as ID. */ public void unsudo() { apiClient.setSudoAsId(null); } /** * Sets up all future calls to the GitLab API to be done as another user specified by provided user ID. * To revert back to normal non-sudo operation you must call unsudo(), or pass null as the sudoAsId. * * @param sudoAsId the ID of the user to sudo as, null will turn off sudo * @throws GitLabApiException if any exception occurs */ public void setSudoAsId(Integer sudoAsId) throws GitLabApiException { if (sudoAsId == null) { apiClient.setSudoAsId(null); return; } // Get the User specified by the sudoAsId, if you are not an admin or the username is not found, this will fail User user = getUserApi().getUser(sudoAsId); if (user == null || user.getId() != sudoAsId) { throw new GitLabApiException("the specified user ID was not found"); } apiClient.setSudoAsId(sudoAsId); } /** * Get the current sudo as ID, will return null if not in sudo mode. * * @return the current sudo as ID, will return null if not in sudo mode */ public Integer getSudoAsId() { return (apiClient.getSudoAsId()); } /** * Get the auth token being used by this client. * * @return the auth token being used by this client */ public String getAuthToken() { return (apiClient.getAuthToken()); } /** * Get the secret token. * * @return the secret token */ public String getSecretToken() { return (apiClient.getSecretToken()); } /** * Get the TokenType this client is using. * * @return the TokenType this client is using */ public TokenType getTokenType() { return (apiClient.getTokenType()); } /** * Return the GitLab API version that this instance is using. * * @return the GitLab API version that this instance is using */ public ApiVersion getApiVersion() { return (apiVersion); } /** * Get the URL to the GitLab server. * * @return the URL to the GitLab server */ public String getGitLabServerUrl() { return (gitLabServerUrl); } /** * Get the default number per page for calls that return multiple items. * * @return the default number per page for calls that return multiple item */ public int getDefaultPerPage() { return (defaultPerPage); } /** * Set the default number per page for calls that return multiple items. * * @param defaultPerPage the new default number per page for calls that return multiple item */ public void setDefaultPerPage(int defaultPerPage) { this.defaultPerPage = defaultPerPage; } /** * Return the GitLabApiClient associated with this instance. This is used by all the sub API classes * to communicate with the GitLab API. * * @return the GitLabApiClient associated with this instance */ GitLabApiClient getApiClient() { return (apiClient); } /** * Returns true if the API is setup to ignore SSL certificate errors, otherwise returns false. * * @return true if the API is setup to ignore SSL certificate errors, otherwise returns false */ public boolean getIgnoreCertificateErrors() { return (apiClient.getIgnoreCertificateErrors()); } /** * Sets up the Jersey system ignore SSL certificate errors or not. * * @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate errors */ public void setIgnoreCertificateErrors(boolean ignoreCertificateErrors) { apiClient.setIgnoreCertificateErrors(ignoreCertificateErrors); } /** * Get the version info for the GitLab server using the GitLab Version API. * * @return the version info for the GitLab server * @throws GitLabApiException if any exception occurs */ public Version getVersion() throws GitLabApiException { class VersionApi extends AbstractApi { VersionApi(GitLabApi gitlabApi) { super(gitlabApi); } } Response response = new VersionApi(this).get(Response.Status.OK, null, "version"); return (response.readEntity(Version.class)); } /** * Gets the CommitsApi instance owned by this GitLabApi instance. The CommitsApi is used * to perform all commit related API calls. * * @return the CommitsApi instance owned by this GitLabApi instance */ public CommitsApi getCommitsApi() { if (commitsApi == null) { synchronized (this) { if (commitsApi == null) { commitsApi = new CommitsApi(this); } } } return (commitsApi); } /** * Gets the DeployKeysApi instance owned by this GitLabApi instance. The DeployKeysApi is used * to perform all deploy key related API calls. * * @return the CommitsApi instance owned by this GitLabApi instance */ public DeployKeysApi getDeployKeysApi() { if (deployKeysApi == null) { synchronized (this) { if (deployKeysApi == null) { deployKeysApi = new DeployKeysApi(this); } } } return (deployKeysApi); } /** * Gets the EventsApi instance owned by this GitLabApi instance. The EventsApi is used * to perform all events related API calls. * * @return the EventsApi instance owned by this GitLabApi instance */ public EventsApi getEventsApi() { if (eventsApi == null) { synchronized (this) { if (eventsApi == null) { eventsApi = new EventsApi(this); } } } return (eventsApi); } /** * Gets the GroupApi instance owned by this GitLabApi instance. The GroupApi is used * to perform all group related API calls. * * @return the GroupApi instance owned by this GitLabApi instance */ public GroupApi getGroupApi() { if (groupApi == null) { synchronized (this) { if (groupApi == null) { groupApi = new GroupApi(this); } } } return (groupApi); } /** * Gets the IssuesApi instance owned by this GitLabApi instance. The IssuesApi is used * to perform all iossue related API calls. * * @return the CommitsApi instance owned by this GitLabApi instance */ public IssuesApi getIssuesApi() { if (issuesApi == null) { synchronized (this) { if (issuesApi == null) { issuesApi = new IssuesApi(this); } } } return (issuesApi); } /** * Gets the JobApi instance owned by this GitLabApi instance. The JobApi is used * to perform all jobs related API calls. * * @return the JobsApi instance owned by this GitLabApi instance */ public JobApi getJobApi() { if (jobApi == null) { synchronized (this) { if (jobApi == null) { jobApi = new JobApi(this); } } } return (jobApi); } public LabelsApi getLabelsApi() { if (labelsApi == null) { synchronized (this) { if (labelsApi == null) { labelsApi = new LabelsApi(this); } } } return (labelsApi); } /** * Gets the MergeRequestApi instance owned by this GitLabApi instance. The MergeRequestApi is used * to perform all merge request related API calls. * * @return the MergeRequestApi instance owned by this GitLabApi instance */ public MergeRequestApi getMergeRequestApi() { if (mergeRequestApi == null) { synchronized (this) { if (mergeRequestApi == null) { mergeRequestApi = new MergeRequestApi(this); } } } return (mergeRequestApi); } /** * Gets the MilsestonesApi instance owned by this GitLabApi instance. * * @return the MilsestonesApi instance owned by this GitLabApi instance */ public MilestonesApi getMilestonesApi() { if (milestonesApi == null) { synchronized (this) { if (milestonesApi == null) { milestonesApi = new MilestonesApi(this); } } } return (milestonesApi); } /** * Gets the NamespaceApi instance owned by this GitLabApi instance. The NamespaceApi is used * to perform all namespace related API calls. * * @return the NamespaceApi instance owned by this GitLabApi instance */ public NamespaceApi getNamespaceApi() { if (namespaceApi == null) { synchronized (this) { if (namespaceApi == null) { namespaceApi = new NamespaceApi(this); } } } return (namespaceApi); } /** * Gets the NotesApi instance owned by this GitLabApi instance. The NotesApi is used * to perform all notes related API calls. * * @return the NotesApi instance owned by this GitLabApi instance */ public NotesApi getNotesApi() { if (notesApi == null) { synchronized (this) { if (notesApi == null) { notesApi = new NotesApi(this); } } } return (notesApi); } /** * Gets the PipelineApi instance owned by this GitLabApi instance. The PipelineApi is used * to perform all pipeline related API calls. * * @return the PipelineApi instance owned by this GitLabApi instance */ public PipelineApi getPipelineApi() { if (pipelineApi == null) { synchronized (this) { if (pipelineApi == null) { pipelineApi = new PipelineApi(this); } } } return (pipelineApi); } /** * Gets the ProjectApi instance owned by this GitLabApi instance. The ProjectApi is used * to perform all project related API calls. * * @return the ProjectApi instance owned by this GitLabApi instance */ public ProjectApi getProjectApi() { if (projectApi == null) { synchronized (this) { if (projectApi == null) { projectApi = new ProjectApi(this); } } } return (projectApi); } /** * Gets the RepositoryApi instance owned by this GitLabApi instance. The RepositoryApi is used * to perform all repository related API calls. * * @return the RepositoryApi instance owned by this GitLabApi instance */ public RepositoryApi getRepositoryApi() { if (repositoryApi == null) { synchronized (this) { if (repositoryApi == null) { repositoryApi = new RepositoryApi(this); } } } return (repositoryApi); } /** * Gets the RepositoryFileApi instance owned by this GitLabApi instance. The RepositoryFileApi is used * to perform all repository files related API calls. * * @return the RepositoryFileApi instance owned by this GitLabApi instance */ public RepositoryFileApi getRepositoryFileApi() { if (repositoryFileApi == null) { synchronized (this) { if (repositoryFileApi == null) { repositoryFileApi = new RepositoryFileApi(this); } } } return (repositoryFileApi); } /** * Gets the ServicesApi instance owned by this GitLabApi instance. The ServicesApi is used * to perform all services related API calls. * * @return the ServicesApi instance owned by this GitLabApi instance */ public ServicesApi getServicesApi() { if (servicesApi == null) { synchronized (this) { if (servicesApi == null) { servicesApi = new ServicesApi(this); } } } return (servicesApi); } /** * Gets the SessionApi instance owned by this GitLabApi instance. The SessionApi is used * to perform a login to the GitLab API. * * @return the SessionApi instance owned by this GitLabApi instance */ public SessionApi getSessionApi() { if (sessionApi == null) { synchronized (this) { if (sessionApi == null) { sessionApi = new SessionApi(this); } } } return (sessionApi); } /** * Gets the SystemHooksApi instance owned by this GitLabApi instance. All methods * require administrator authorization. * * @return the SystemHooksApi instance owned by this GitLabApi instance */ public SystemHooksApi getSystemHooksApi() { if (systemHooksApi == null) { synchronized (this) { if (systemHooksApi == null) { systemHooksApi = new SystemHooksApi(this); } } } return (systemHooksApi); } /** * Gets the UserApi instance owned by this GitLabApi instance. The UserApi is used * to perform all user related API calls. * * @return the UserApi instance owned by this GitLabApi instance */ public UserApi getUserApi() { if (userApi == null) { synchronized (this) { if (userApi == null) { userApi = new UserApi(this); } } } return (userApi); } }
package org.jgum.category; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.common.base.Function; import com.google.common.base.Optional; /** * A hierarchical category associated with named properties. * @author sergioc * */ public class Category { private final Map<Object, Object> properties; //properties associated with this category are backed up in this map. private Categorization categorization; //the categorization where this category exists. private final List<? extends Category> parents; //default placeholder for the parents of this category. Subclasses may choose to store parents in a different structure. private final List<? extends Category> children; //default placeholder for the children of this category. Subclasses may choose to store children in a different structure. private List<? extends Category> bottomUpLinearization; //lazily initialized bottom-up linearization /** * @param categorization the categorization where this category exists. */ public Category(Categorization<?> categorization) { this(new ArrayList()); setCategorization(categorization); } /** * @parem parents the parents of this category. */ public Category(List<? extends Category> parents) { this.parents = parents; children = new ArrayList<>(); properties = new HashMap<>(); } private void setCategorization(Categorization categorization) { this.categorization = categorization; categorization.setRoot(this); } /** * * @return the categorization where this category exists. */ public Categorization<?> getCategorization() { if(categorization == null) //implies that this is not the root category categorization = getParents().get(0).getCategorization(); //there is at least one parent return categorization; } /** * @param property a property name. * @return a category property. */ public CategoryProperty<?> getProperty(Object property) { return new CategoryProperty<>(this, property); } /** * * @param property a property name. * @return true if the property is defined in the category. false otherwise. It attempts to find it in ancestor categories if the property is not locally present. */ public boolean containsProperty(Object property) { return getProperty(property).isPresent(); } /** * @param property a property name. * @return an optional with the property value in the current category (if any). It does not query ancestor categories if the property is not locally present. */ public Optional<?> getLocalProperty(Object property) { return Optional.fromNullable(properties.get(property)); } /** * * @param property a property name. * @return true if the property exists in the current category. false otherwise. It does not query ancestor categories if the property is not locally present. */ public boolean containsLocalProperty(Object property) { return properties.containsKey(property); } /** * Set a property to a given value. * @param property the property name to set. * @param value the value of the property. */ public void setProperty(Object property, Object value) { properties.put(property, value); } /** * Set a property to a given value. Rises an exception if the property is already set and the canOverride parameter is false. * @param property the property to set. * @param value the label of the property. * @param canOverride a boolean indicating if the property can be overridden or not. * @throws RuntimeException if the property exists and it cannot be overridden. */ public void setProperty(Object property, Object value, boolean canOverride) { Object currentPropertyValue = getLocalProperty(property); if(currentPropertyValue!=null && !canOverride) throw new RuntimeException("The node already has a label for the property \"" + property + "\":" + currentPropertyValue + ". Attempting to override this property with: " + value + "."); else setProperty(property, value); } /** * * @param linearizationFunction is a linearization function. * @return A list of categories, according to the given linearization function. */ public <U extends Category> List<U> linearize(Function<U,List<U>> linearizationFunction) { return linearizationFunction.apply((U)this); } /** * * @return an optional with the super category. */ public <U extends Category> Optional<U> getSuper() { List bottomUpLinearization = bottomUpLinearization(); if(bottomUpLinearization.size() == 1) //there are no super categories (according to the default linearization function) return Optional.absent(); else return Optional.of((U)bottomUpLinearization.get(1)); } /** * * @return a linearization using the default bottom-up linearization function. */ public <U extends Category> List<U> bottomUpLinearization() { if(bottomUpLinearization == null) { bottomUpLinearization = linearize(getCategorization().getBottomUpLinearizationFunction()); } return (List<U>)bottomUpLinearization; } /** * * @return a linearization using the default top-down linearization function. */ public <U extends Category> List<U> topDownLinearization() { return (List<U>)linearize(getCategorization().getTopDownLinearizationFunction()); } /** * * @return the parents of this category. The ordering in which parents are returned is determined by subclasses. */ public <U extends Category> List<U> getParents() { return (List)parents; } /** * * @return the children of this category. The ordering in which children are returned is determined by subclasses. */ public <U extends Category> List<U> getChildren() { return (List)children; } // protected void onAddChild(Category category) { // categorization.notifyCategorizationListeners(category); /** * * @return true if the current category corresponds to the root category. false otherwise. */ public boolean isRoot() { return getParents().isEmpty(); } @Override public String toString() { return properties.toString(); } }
package org.jtrfp.trcl.core; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.RealMatrix; import org.jtrfp.trcl.gpu.GPU; public class Camera { private Vector3D lookAtVector = new Vector3D(0, 0, 1); private Vector3D upVector = new Vector3D(0, 1, 0); private Vector3D cameraPosition = new Vector3D(50000, 0, 50000); private RealMatrix cameraMatrix; private double viewDepth; private RealMatrix projectionMatrix; private final GPU gpu; private int updateDebugStateCounter; public Camera(GPU gpu) {this.gpu=gpu;} private void updateProjectionMatrix(){ final float fov = 70f;// In degrees final float aspect = (float) gpu.getComponent().getWidth() / (float) gpu.getComponent().getHeight(); final float zF = (float) (viewDepth * 1.5); final float zN = (float) (TR.mapSquareSize / 10); final float f = (float) (1. / Math.tan(fov * Math.PI / 360.)); projectionMatrix = new Array2DRowRealMatrix(new double[][] { new double[] { f / aspect, 0, 0, 0 }, new double[] { 0, f, 0, 0 }, new double[] { 0, 0, (zF + zN) / (zN - zF), -1f }, new double[] { 0, 0, (2f * zF * zN) / (zN - zF), 0 } }).transpose(); } /** * @return the lookAtVector */ public Vector3D getLookAtVector() {return lookAtVector;} /** * @param lookAtVector the lookAtVector to set */ public void setLookAtVector(Vector3D lookAtVector){ this.lookAtVector = lookAtVector; cameraMatrix=null; } /** * @return the upVector */ public Vector3D getUpVector() {return upVector;} /** * @param upVector the upVector to set */ public void setUpVector(Vector3D upVector){ this.upVector = upVector; cameraMatrix=null; } /** * @return the cameraPosition */ public Vector3D getCameraPosition() {return cameraPosition;} /** * @param cameraPosition the cameraPosition to set */ public void setPosition(Vector3D cameraPosition){ this.cameraPosition = cameraPosition; cameraMatrix=null; } private void applyMatrix(){ Vector3D eyeLoc = getCameraPosition(); Vector3D aZ = getLookAtVector().negate(); Vector3D aX = getUpVector().crossProduct(aZ).normalize(); Vector3D aY = /*aZ.crossProduct(aX)*/getUpVector(); RealMatrix rM = new Array2DRowRealMatrix(new double[][] { new double[] { aX.getX(), aX.getY(), aX.getZ(), 0 }, new double[] { aY.getX(), aY.getY(), aY.getZ(), 0 }, new double[] { aZ.getX(), aZ.getY(), aZ.getZ(), 0 }, new double[] { 0, 0, 0, 1 } }); RealMatrix tM = new Array2DRowRealMatrix(new double[][] { new double[] { 1, 0, 0, -eyeLoc.getX() }, new double[] { 0, 1, 0, -eyeLoc.getY() }, new double[] { 0, 0, 1, -eyeLoc.getZ() }, new double[] { 0, 0, 0, 1 } }); cameraMatrix = getProjectionMatrix().multiply(rM.multiply(tM)); }//end applyMatrix() public void setViewDepth(double cameraViewDepth){ this.viewDepth=cameraViewDepth; cameraMatrix=null; projectionMatrix=null; } private RealMatrix getProjectionMatrix(){ if(projectionMatrix==null)updateProjectionMatrix(); return projectionMatrix; } public double getViewDepth() {return viewDepth;} public RealMatrix getMatrix() {if(cameraMatrix==null){ applyMatrix(); if(updateDebugStateCounter++ % 30 ==0){ gpu.getTr().getReporter().report("org.jtrfp.trcl.core.Camera.position", cameraPosition); gpu.getTr().getReporter().report("org.jtrfp.trcl.core.Camera.lookAt", lookAtVector); gpu.getTr().getReporter().report("org.jtrfp.trcl.core.Camera.up", upVector); }} return cameraMatrix; } }//end Camera
package org.osgl.mvc.result; import org.osgl.exception.FastRuntimeException; import org.osgl.http.H; import org.osgl.http.Http; import org.osgl.util.S; public class Result extends FastRuntimeException { private final Http.Status status; protected Result() {status = null;} protected Result(Http.Status status) { this.status = status; } protected Result(Http.Status status, String message) { super(message); this.status = status; } protected Result(Http.Status status, String message, Object... args) { super(message, args); this.status = status; } protected Result(Http.Status status, Throwable cause) { super(cause); this.status = status; } protected Result(Http.Status status, Throwable cause, String message, Object... args) { super(cause, message, args); this.status = status; } public Http.Status status() { return status; } public int statusCode() { return status().code(); } protected final void applyStatus(H.Response response) { response.status(statusCode()); } protected void applyMessage(H.Request request, H.Response response) { String msg = getMessage(); if (S.notBlank(msg)) { response.writeContent(msg); } } public void apply(H.Request req, H.Response resp) { applyStatus(resp); applyMessage(req, resp); } }
package ru.r2cloud; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry.MetricSupplier; import com.codahale.metrics.health.HealthCheck; import ru.r2cloud.metrics.FormattedGauge; import ru.r2cloud.metrics.MetricFormat; import ru.r2cloud.metrics.Metrics; import ru.r2cloud.model.RtlSdrStatus; import ru.r2cloud.util.Configuration; import ru.r2cloud.util.NamingThreadFactory; import ru.r2cloud.util.ResultUtil; import ru.r2cloud.util.Util; public class RtlSdrStatusDao implements Lifecycle { private static final Logger LOG = LoggerFactory.getLogger(RtlSdrStatusDao.class); private static final Pattern DEVICEPATTERN = Pattern.compile("^ 0: (.*?), (.*?), SN: (.*?)$"); private static final Pattern PPMPATTERN = Pattern.compile("real sample rate: \\d+ current PPM: \\d+ cumulative PPM: (\\d+)"); private final Configuration config; private final RtlSdrLock lock; private ScheduledExecutorService executor = null; private RtlSdrStatus status = null; private String rtltestError = null; private volatile Integer currentPpm; public RtlSdrStatusDao(Configuration config, RtlSdrLock lock) { this.config = config; this.lock = lock; this.currentPpm = config.getInteger("ppm.current"); } @SuppressWarnings("rawtypes") @Override public synchronized void start() { if (executor != null) { return; } executor = Executors.newScheduledThreadPool(1, new NamingThreadFactory("rtlsdr-tester")); executor.scheduleAtFixedRate(new Runnable() { @Override public void run() { reload(); } }, 0, config.getLong("rtltest.interval.seconds"), TimeUnit.SECONDS); if (config.getBoolean("ppm.calculate")) { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); try { Date date = sdf.parse(config.getProperty("ppm.calculate.timeUTC")); Calendar cal = Calendar.getInstance(); cal.setTime(date); Calendar executeAt = Calendar.getInstance(); executeAt.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY)); executeAt.set(Calendar.MINUTE, cal.get(Calendar.MINUTE)); executeAt.set(Calendar.SECOND, 0); executeAt.set(Calendar.MILLISECOND, 0); long current = System.currentTimeMillis(); if (executeAt.getTimeInMillis() < current) { executeAt.add(Calendar.DAY_OF_MONTH, 1); } LOG.info("next ppm execution at: {}", executeAt.getTime()); executor.scheduleAtFixedRate(new Runnable() { @Override public void run() { reloadPpm(); } }, executeAt.getTimeInMillis() - current, TimeUnit.DAYS.toMillis(1), TimeUnit.MILLISECONDS); } catch (ParseException e) { LOG.info("invalid time. ppm will be disabled", e); } } Metrics.HEALTH_REGISTRY.register("rtltest", new HealthCheck() { @Override protected Result check() throws Exception { if (rtltestError == null) { return ResultUtil.healthy(); } else { return ResultUtil.unhealthy(rtltestError); } } }); Metrics.HEALTH_REGISTRY.register("rtldongle", new HealthCheck() { @Override protected Result check() throws Exception { if (status != null) { return ResultUtil.healthy(); } else { return ResultUtil.unhealthy("No supported devices found"); } } }); Metrics.REGISTRY.gauge("ppm", new MetricSupplier<Gauge>() { @Override public Gauge<?> newMetric() { return new FormattedGauge<Integer>(MetricFormat.NORMAL) { @Override public Integer getValue() { // graph will be displayed anyway. // fill it with 0 if (currentPpm == null) { return 0; } return currentPpm; } }; } }); LOG.info("started"); } @Override public synchronized void stop() { Util.shutdown(executor, config.getThreadPoolShutdownMillis()); executor = null; LOG.info("stopped"); } private void reloadPpm() { if (LOG.isDebugEnabled()) { LOG.debug("ppm calculation"); } if (!lock.tryLock(this)) { LOG.info("unable to lock for ppm calculation"); return; } Process rtlTest = null; try { rtlTest = new ProcessBuilder().command(config.getProperty("stdbuf.path"), "-i0", "-o0", "-e0", config.getProperty("rtltest.path"), "-p2").redirectErrorStream(true).start(); BufferedReader r = new BufferedReader(new InputStreamReader(rtlTest.getInputStream())); String curLine = null; int numberOfSamples = 0; while ((curLine = r.readLine()) != null && !Thread.currentThread().isInterrupted()) { if (LOG.isDebugEnabled()) { LOG.debug(curLine); } if (curLine.startsWith("No supported")) { break; } else if (curLine.startsWith("real sample rate")) { numberOfSamples++; if (numberOfSamples >= 10) { Matcher m = PPMPATTERN.matcher(curLine); if (m.find()) { String ppmStr = m.group(1); currentPpm = Integer.valueOf(ppmStr); config.setProperty("ppm.current", currentPpm); config.update(); } break; } } } } catch (IOException e) { LOG.error("unable to calculate ppm", e); } finally { Util.shutdown("ppm-test", rtlTest, 5000); lock.unlock(this); } } private void reload() { try { Process rtlTest = new ProcessBuilder().command(config.getProperty("rtltest.path"), "-t").start(); BufferedReader r = new BufferedReader(new InputStreamReader(rtlTest.getErrorStream())); String curLine = null; while ((curLine = r.readLine()) != null && !Thread.currentThread().isInterrupted()) { if (curLine.startsWith("No supported")) { status = null; return; } else { Matcher m = DEVICEPATTERN.matcher(curLine); if (m.find()) { status = new RtlSdrStatus(); status.setVendor(m.group(1)); status.setChip(m.group(2)); status.setSerialNumber(m.group(3)); break; } } } rtltestError = null; } catch (IOException e) { rtltestError = "unable to read status"; LOG.error(rtltestError, e); } } }
//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.3"; public static final String versionDate = "January 5, 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 tachyon.client; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.RandomAccessFile; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SocketChannel; import java.nio.channels.FileChannel.MapMode; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.log4j.Logger; import org.apache.thrift.TException; import tachyon.Config; import tachyon.DataServerMessage; import tachyon.CommonUtils; import tachyon.HdfsClient; import tachyon.thrift.ClientFileInfo; import tachyon.thrift.FailedToCheckpointException; import tachyon.thrift.FileDoesNotExistException; import tachyon.thrift.NetAddress; import tachyon.thrift.SuspectedFileSizeException; /** * Tachyon File. * @author haoyuan */ public class TachyonFile { private final Logger LOG = Logger.getLogger(Config.LOGGER_TYPE); private final TachyonClient mTachyonClient; private final ClientFileInfo mClientFileInfo; private final int mId; private OpType mIoType = null; private long mSizeBytes; private ByteBuffer mBuffer; private RandomAccessFile mLocalFile; private FileChannel mLocalFileChannel; // TODO Use mCheckpointInputStream private InputStream mCheckpointInputStream; private OutputStream mCheckpointOutputStream; public TachyonFile(TachyonClient tachyonClient, ClientFileInfo fileInfo) { mTachyonClient = tachyonClient; mClientFileInfo = fileInfo; mId = mClientFileInfo.getId(); } /** * This API is not recommended to use. * * @param path file's checkpoint path. * @return true if the checkpoint path is added successfully, false otherwise. * @throws TException * @throws SuspectedFileSizeException * @throws FileDoesNotExistException */ public boolean addCheckpointPath(String path) throws FileDoesNotExistException, SuspectedFileSizeException, TException { HdfsClient tHdfsClient = new HdfsClient(path); long sizeBytes = tHdfsClient.getFileSize(path); if (mTachyonClient.addCheckpointPath(mId, path)) { mClientFileInfo.sizeBytes = sizeBytes; mClientFileInfo.checkpointPath = path; return true; } return false; } private synchronized void appendCurrentBuffer(int minimalPosition) throws IOException { if (mBuffer.position() >= minimalPosition) { if (mIoType.isWriteCache()) { // if (Config.DEBUG && mSizeBytes != mLocalFile.length()) { // CommonUtils.runtimeException( // String.format("mSize (%d) != mFile.length() (%d)", mSizeBytes, mLocalFile.length())); if (!mTachyonClient.requestSpace(mBuffer.position())) { if (mClientFileInfo.isNeedPin()) { mTachyonClient.outOfMemoryForPinFile(mId); throw new IOException("Local tachyon worker does not have enough " + "space or no worker for " + mId); } throw new IOException("Local tachyon worker does not have enough space."); } mBuffer.flip(); MappedByteBuffer out = mLocalFileChannel.map(MapMode.READ_WRITE, mSizeBytes, mBuffer.limit()); out.put(mBuffer); } if (mIoType.isWriteThrough()) { mBuffer.flip(); mCheckpointOutputStream.write(mBuffer.array(), 0, mBuffer.limit()); } mSizeBytes += mBuffer.limit(); mBuffer.clear(); } } public void append(byte b) throws IOException { // validateIO(false); appendCurrentBuffer(Config.USER_BUFFER_PER_PARTITION_BYTES); mBuffer.put(b); } public void append(int b) throws IOException { // validateIO(false); appendCurrentBuffer(Config.USER_BUFFER_PER_PARTITION_BYTES); mBuffer.putInt(b); } public void append(byte[] buf) throws IOException { append(buf, 0, buf.length); } public void append(byte[] b, int off, int len) throws IOException { if (b == null) { throw new NullPointerException(); } else if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } // validateIO(false); if (mBuffer.position() + len >= Config.USER_BUFFER_PER_PARTITION_BYTES) { if (mIoType.isWriteCache()) { // if (Config.DEBUG && mSizeBytes != mLocalFile.length()) { // CommonUtils.runtimeException( // String.format("mSize (%d) != mFile.length() (%d)", mSizeBytes, mLocalFile.length())); if (!mTachyonClient.requestSpace(mBuffer.position() + len)) { if (mClientFileInfo.isNeedPin()) { mTachyonClient.outOfMemoryForPinFile(mId); throw new IOException("Local tachyon worker does not have enough " + "space or no worker for " + mId); } throw new IOException("Local tachyon worker does not have enough space or no worker."); } mBuffer.flip(); MappedByteBuffer out = mLocalFileChannel.map(MapMode.READ_WRITE, mSizeBytes, mBuffer.limit() + len); out.put(mBuffer); out.put(b, off, len); } if (mIoType.isWriteThrough()) { mBuffer.flip(); mCheckpointOutputStream.write(mBuffer.array(), 0, mBuffer.limit()); mCheckpointOutputStream.write(b, off, len); } mSizeBytes += mBuffer.limit() + len; mBuffer.clear(); } else { mBuffer.put(b, off, len); } } public void append(ByteBuffer buf) throws IOException { append(buf.array(), buf.position(), buf.limit() - buf.position()); } public void append(ArrayList<ByteBuffer> bufs) throws IOException { for (int k = 0; k < bufs.size(); k ++) { append(bufs.get(k)); } } public void cancel() throws IOException { close(true); } public void close() throws IOException { close(false); } private void close(boolean cancel) throws IOException { if (mIoType == null) { return; } IOException ioE = null; try { if (mIoType.isRead()) { if (mLocalFileChannel != null) { mLocalFileChannel.close(); mLocalFile.close(); } } else { if (!cancel) { appendCurrentBuffer(1); } if (mLocalFileChannel != null) { mLocalFileChannel.close(); mLocalFile.close(); } if (cancel) { mTachyonClient.releaseSpace(mSizeBytes); } else { if (mIoType.isWriteThrough()) { mCheckpointOutputStream.flush(); mCheckpointOutputStream.close(); mTachyonClient.addCheckpoint(mId); } if (mIoType.isWriteCache()) { mTachyonClient.cacheFile(mId); } } } } catch (IOException e) { LOG.error(e.getMessage(), e); ioE = e; } catch (SuspectedFileSizeException e) { LOG.error(e.getMessage(), e); ioE = new IOException(e); } catch (FileDoesNotExistException e) { LOG.error(e.getMessage(), e); ioE = new IOException(e); } catch (FailedToCheckpointException e) { LOG.error(e.getMessage(), e); ioE = new IOException(e); } mTachyonClient.unlockFile(mId); mIoType = null; if (ioE != null) { throw ioE; } } public InputStream getInputStream() throws IOException { // validateIO(true); return new TFileInputStream(this); } public OutputStream getOutputStream() throws IOException { // validateIO(false); return new TFileOutputStream(this); } public long getSize() { return mSizeBytes; } public List<String> getLocationHosts() throws IOException { List<NetAddress> locations = mTachyonClient.getFileNetAddresses(mId); List<String> ret = new ArrayList<String>(locations.size()); if (locations != null) { for (int k = 0; k < locations.size(); k ++) { ret.add(locations.get(k).mHost); } } return ret; } public void open(OpType io) throws IOException { if (io == null) { throw new IOException("OpType can not be null."); } mIoType = io; if (mIoType.isWrite()) { mBuffer = ByteBuffer.allocate(Config.USER_BUFFER_PER_PARTITION_BYTES + 4); mBuffer.order(ByteOrder.nativeOrder()); if (mIoType.isWriteCache()) { if (!mTachyonClient.hasLocalWorker()) { throw new IOException("No local worker on this machine."); } File localFolder = mTachyonClient.createAndGetUserTempFolder(); if (localFolder == null) { throw new IOException("Failed to create temp user folder for tachyon client."); } String localFilePath = localFolder.getPath() + "/" + mId; mLocalFile = new RandomAccessFile(localFilePath, "rw"); mLocalFileChannel = mLocalFile.getChannel(); mSizeBytes = 0; LOG.info("File " + localFilePath + " was created!"); } if (mIoType.isWriteThrough()) { String hdfsFolder = mTachyonClient.createAndGetUserHDFSTempFolder(); HdfsClient tHdfsClient = new HdfsClient(hdfsFolder); mCheckpointOutputStream = tHdfsClient.create(hdfsFolder + "/" + mId); } } else { mTachyonClient.lockFile(mId); mBuffer = null; mCheckpointInputStream = null; if (mIoType.isReadTryCache()) { mBuffer = readByteBuffer(); } if (mBuffer == null && !mClientFileInfo.checkpointPath.equals("")) { LOG.warn("Will stream from underlayer fs."); HdfsClient tHdfsClient = new HdfsClient(mClientFileInfo.checkpointPath); mCheckpointInputStream = tHdfsClient.open(mClientFileInfo.checkpointPath); } if (mBuffer == null && mCheckpointInputStream == null) { try { mTachyonClient.reportLostFile(mId); } catch (FileDoesNotExistException e) { throw new IOException("File does not exist anymore: " + mClientFileInfo); } catch (TException e) { throw new IOException("Can not connect to Tachyon system."); } throw new IOException("Can not find file " + mClientFileInfo.getPath()); } } } public int read() throws IOException { // validateIO(true); if (mBuffer != null) { try { return mBuffer.get(); } catch (java.nio.BufferUnderflowException e) { close(); return -1; } } return mCheckpointInputStream.read(); } public int read(byte b[]) throws IOException { return read(b, 0, b.length); } public int read(byte b[], int off, int len) throws IOException { if (b == null) { throw new NullPointerException(); } else if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } // validateIO(true); if (mBuffer != null) { int ret = Math.min(len, mBuffer.remaining()); if (ret == 0) { close(); return -1; } mBuffer.get(b, off, len); return ret; } return mCheckpointInputStream.read(b, off, len); } public ByteBuffer readByteBuffer() throws UnknownHostException, FileNotFoundException, IOException { validateIO(true); ByteBuffer ret = null; ret = readByteBufferFromLocal(); if (ret == null) { ret = readByteBufferFromRemote(); } if (ret != null) { return ret; } if (mClientFileInfo.checkpointPath.equals("")) { throw new IOException("Failed to read file " + mClientFileInfo.getPath() + " no CK or Cache"); } if (mIoType.isReadTryCache() && mTachyonClient.hasLocalWorker()) { boolean recacheSucceed = recacheData(); if (recacheSucceed) { ret = readByteBufferFromLocal(); } } return ret; } private ByteBuffer readByteBufferFromLocal() throws IOException { ByteBuffer ret = null; if (mTachyonClient.getRootFolder() != null) { String localFileName = mTachyonClient.getRootFolder() + "/" + mId; try { mLocalFile = new RandomAccessFile(localFileName, "r"); mSizeBytes = mLocalFile.length(); mLocalFileChannel = mLocalFile.getChannel(); ret = mLocalFileChannel.map(FileChannel.MapMode.READ_ONLY, 0, mSizeBytes); ret.order(ByteOrder.nativeOrder()); mTachyonClient.accessLocalFile(mId); return ret; } catch (FileNotFoundException e) { LOG.info(localFileName + " is not on local disk."); ret = null; } } return ret; } private ByteBuffer readByteBufferFromRemote() throws IOException { ByteBuffer ret = null; LOG.info("Try to find and read from remote workers."); List<NetAddress> fileLocations = mTachyonClient.getFileNetAddresses(mId); if (fileLocations == null) { throw new IOException("Can not find location info: " + mClientFileInfo.getPath() + " " + mId); } LOG.info("readByteBufferFromRemote() " + fileLocations); for (int k = 0 ;k < fileLocations.size(); k ++) { String host = fileLocations.get(k).mHost; if (host.equals(InetAddress.getLocalHost().getHostName()) || host.equals(InetAddress.getLocalHost().getHostAddress())) { String localFileName = mTachyonClient.getRootFolder() + "/" + mId; LOG.warn("Master thinks the local machine has data! But " + localFileName + " is not!"); } else { LOG.info("readByteBufferFromRemote() : " + host + ":" + Config.WORKER_DATA_SERVER_PORT + " current host is " + InetAddress.getLocalHost().getHostName() + " " + InetAddress.getLocalHost().getHostAddress()); try { // TODO Using Config.WORKER_DATA_SERVER_PORT here is a bug. Fix it later. ret = retrieveByteBufferFromRemoteMachine( new InetSocketAddress(host, Config.WORKER_DATA_SERVER_PORT)); if (ret != null) { break; } } catch (IOException e) { LOG.error(e.getMessage()); } } } if (ret != null) { mSizeBytes = ret.limit(); ret.order(ByteOrder.nativeOrder()); } return ret; } private boolean recacheData() throws IOException { String path = mClientFileInfo.checkpointPath; HdfsClient tHdfsClient = new HdfsClient(path); FSDataInputStream inputStream = tHdfsClient.open(path); TachyonFile tTFile = mTachyonClient.getFile(mClientFileInfo.getId()); tTFile.open(OpType.WRITE_CACHE); byte buffer[] = new byte[Config.USER_BUFFER_PER_PARTITION_BYTES * 4]; int limit; while ((limit = inputStream.read(buffer)) >= 0) { if (limit != 0) { tTFile.append(buffer, 0, limit); } } tTFile.close(); return true; } private ByteBuffer retrieveByteBufferFromRemoteMachine(InetSocketAddress address) throws IOException { SocketChannel socketChannel = SocketChannel.open(); socketChannel.connect(address); LOG.info("Connected to remote machine " + address + " sent"); DataServerMessage sendMsg = DataServerMessage.createPartitionRequestMessage(mId); while (!sendMsg.finishSending()) { sendMsg.send(socketChannel); } LOG.info("Data " + mId + " to remote machine " + address + " sent"); DataServerMessage recvMsg = DataServerMessage.createPartitionResponseMessage(false, mId); while (!recvMsg.isMessageReady()) { int numRead = recvMsg.recv(socketChannel); if (numRead == -1) { break; } } LOG.info("Data " + mId + " from remote machine " + address + " received"); socketChannel.close(); if (!recvMsg.isMessageReady()) { LOG.info("Data " + mId + " from remote machine is not ready."); return null; } if (recvMsg.getFileId() < 0) { LOG.info("Data " + recvMsg.getFileId() + " is not in remote machine."); return null; } return recvMsg.getReadOnlyData(); } private void validateIO(boolean read) throws IOException { if (mIoType == null) { CommonUtils.runtimeException("The partition was never openned or has been closed."); } if (read != mIoType.isRead()) { CommonUtils.runtimeException("The partition was opened for " + (mIoType.isRead() ? "Read" : "Write") + ". " + (read ? "Read" : "Write") + " operation is not available."); } } public boolean isReady() { return mClientFileInfo.isReady(); } }
package com.dmdirc.addons.ui_swing; import com.dmdirc.FrameContainer; import com.dmdirc.actions.ActionManager; import com.dmdirc.actions.CoreActionType; import com.dmdirc.addons.ui_swing.components.LoggingSwingWorker; import com.dmdirc.addons.ui_swing.components.SplitPane; import com.dmdirc.addons.ui_swing.components.frames.TextFrame; import com.dmdirc.addons.ui_swing.components.menubar.MenuBar; import com.dmdirc.addons.ui_swing.components.statusbar.SwingStatusBar; import com.dmdirc.addons.ui_swing.dialogs.ConfirmQuitDialog; import com.dmdirc.addons.ui_swing.dialogs.StandardQuestionDialog; import com.dmdirc.addons.ui_swing.framemanager.FrameManager; import com.dmdirc.addons.ui_swing.framemanager.FramemanagerPosition; import com.dmdirc.addons.ui_swing.framemanager.ctrltab.CtrlTabWindowManager; import com.dmdirc.addons.ui_swing.framemanager.tree.TreeFrameManager; import com.dmdirc.interfaces.config.ConfigChangeListener; import com.dmdirc.interfaces.FrameInfoListener; import com.dmdirc.interfaces.LifecycleController; import com.dmdirc.interfaces.NotificationListener; import com.dmdirc.logger.ErrorLevel; import com.dmdirc.logger.Logger; import com.dmdirc.ui.Colour; import com.dmdirc.ui.CoreUIUtils; import com.dmdirc.util.collections.ListenerList; import com.dmdirc.util.collections.QueuedLinkedHashSet; import java.awt.Dimension; import java.awt.Font; import java.awt.event.WindowEvent; import java.awt.event.WindowFocusListener; import java.awt.event.WindowListener; import java.lang.reflect.InvocationTargetException; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JSplitPane; import javax.swing.MenuSelectionManager; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import net.miginfocom.swing.MigLayout; /** * The main application frame. */ @Slf4j public final class MainFrame extends JFrame implements WindowListener, ConfigChangeListener, SwingWindowListener, FrameInfoListener, NotificationListener { /** * A version number for this class. It should be changed whenever the class * structure is changed (or anything else that would prevent serialized * objects being unserialized with the new class). */ private static final long serialVersionUID = 9; /** Focus queue. */ private final QueuedLinkedHashSet<TextFrame> focusOrder; /** Swing Controller. */ private final SwingController controller; /** Controller to use to end the program. */ private final LifecycleController lifecycleController; /** Client Version. */ private final String version; /** Frame manager used for ctrl tab frame switching. */ private final CtrlTabWindowManager frameManager; /** The listeners registered with this class. */ private final ListenerList listeners = new ListenerList(); /** The main application icon. */ private ImageIcon imageIcon; /** The frame manager that's being used. */ private FrameManager mainFrameManager; /** Active frame. */ private TextFrame activeFrame; /** Panel holding frame. */ private JPanel framePanel; /** Main panel. */ private JPanel frameManagerPanel; /** Frame manager position. */ private FramemanagerPosition position; /** Show version? */ private boolean showVersion; /** Exit code. */ private int exitCode = 0; /** Status bar. */ @Getter private SwingStatusBar statusBar; /** Main split pane. */ private SplitPane mainSplitPane; /** Are we quitting or closing? */ private boolean quitting = false; /** * Creates new form MainFrame. * * @param controller Swing controller * @param lifecycleController Controller to use to end the application. */ public MainFrame( final SwingController controller, final LifecycleController lifecycleController) { super(); this.controller = controller; this.lifecycleController = lifecycleController; focusOrder = new QueuedLinkedHashSet<>(); initComponents(); imageIcon = new ImageIcon(controller.getIconManager().getImage("icon")); setIconImage(imageIcon.getImage()); CoreUIUtils.centreWindow(this); addWindowListener(this); showVersion = controller.getGlobalConfig().getOptionBool("ui", "showversion"); version = controller.getGlobalConfig().getOption("version", "version"); controller.getGlobalConfig().addChangeListener("ui", "lookandfeel", this); controller.getGlobalConfig().addChangeListener("ui", "showversion", this); controller.getGlobalConfig().addChangeListener("ui", "framemanager", this); controller.getGlobalConfig().addChangeListener("ui", "framemanagerPosition", this); controller.getGlobalConfig().addChangeListener("ui", "textPaneFontName", this); controller.getGlobalConfig().addChangeListener("icon", "icon", this); addWindowFocusListener(new WindowFocusListener() { /** {@inheritDoc} */ @Override public void windowGainedFocus(final WindowEvent e) { ActionManager.getActionManager().triggerEvent( CoreActionType.CLIENT_FOCUS_GAINED, null); } /** {@inheritDoc} */ @Override public void windowLostFocus(final WindowEvent e) { ActionManager.getActionManager().triggerEvent( CoreActionType.CLIENT_FOCUS_LOST, null); } }); controller.getWindowFactory().addWindowListener(this); setTitle(getTitlePrefix()); frameManager = new CtrlTabWindowManager(controller, this, rootPane); } /** * Returns the size of the frame manager. * * @return Frame manager size. */ public int getFrameManagerSize() { if (position == FramemanagerPosition.LEFT || position == FramemanagerPosition.RIGHT) { return frameManagerPanel.getWidth(); } else { return frameManagerPanel.getHeight(); } } /** * Returns the window that is currently active. * * @return The active window */ public TextFrame getActiveFrame() { return activeFrame; } /** {@inheritDoc} */ @Override public MenuBar getJMenuBar() { return (MenuBar) super.getJMenuBar(); } /** {@inheritDoc}. */ @Override public void setTitle(final String title) { UIUtilities.invokeLater(new Runnable() { /** {@inheritDoc}. */ @Override public void run() { if (title == null || activeFrame == null) { MainFrame.super.setTitle(getTitlePrefix()); } else { MainFrame.super.setTitle(getTitlePrefix() + " - " + title); } } }); } /** * Gets the string which should be prefixed to this frame's title. * * @return This frame's title prefix */ private String getTitlePrefix() { return "DMDirc" + (showVersion ? " " + version : ""); } /** * {@inheritDoc}. * * @param windowEvent Window event */ @Override public void windowOpened(final WindowEvent windowEvent) { //ignore } /** * {@inheritDoc}. * * @param windowEvent Window event */ @Override public void windowClosing(final WindowEvent windowEvent) { quit(exitCode); } /** * {@inheritDoc}. * * @param windowEvent Window event */ @Override public void windowClosed(final WindowEvent windowEvent) { new Thread(new Runnable() { /** {@inheritDoc} */ @Override public void run() { lifecycleController.quit(exitCode); } }, "Quit thread").start(); } /** * {@inheritDoc}. * * @param windowEvent Window event */ @Override public void windowIconified(final WindowEvent windowEvent) { ActionManager.getActionManager().triggerEvent( CoreActionType.CLIENT_MINIMISED, null); } /** * {@inheritDoc}. * * @param windowEvent Window event */ @Override public void windowDeiconified(final WindowEvent windowEvent) { ActionManager.getActionManager().triggerEvent( CoreActionType.CLIENT_UNMINIMISED, null); } /** * {@inheritDoc}. * * @param windowEvent Window event */ @Override public void windowActivated(final WindowEvent windowEvent) { //ignore } /** * {@inheritDoc}. * * @param windowEvent Window event */ @Override public void windowDeactivated(final WindowEvent windowEvent) { //ignore } /** Initialiases the frame managers. */ private void initFrameManagers() { UIUtilities.invokeAndWait(new Runnable() { /** {@inheritDoc} */ @Override public void run() { frameManagerPanel.removeAll(); if (mainFrameManager != null) { controller.getWindowFactory().removeWindowListener( mainFrameManager); } final String manager = controller.getGlobalConfig() .getOption("ui", "framemanager"); try { mainFrameManager = (FrameManager) Class.forName(manager) .getConstructor().newInstance(); } catch (final InvocationTargetException ex) { Logger.appError(ErrorLevel.MEDIUM, "Unable to load frame " + "manager, falling back to default.", ex); } catch (final InstantiationException ex) { Logger.userError(ErrorLevel.MEDIUM, "Unable to load frame " + "manager, falling back to default.", ex); } catch (final NoSuchMethodException ex) { Logger.userError(ErrorLevel.MEDIUM, "Unable to load frame " + "manager, falling back to default.", ex); } catch (final SecurityException ex) { Logger.userError(ErrorLevel.MEDIUM, "Unable to load frame " + "manager, falling back to default.", ex); } catch (final IllegalAccessException ex) { Logger.userError(ErrorLevel.MEDIUM, "Unable to load frame " + "manager, falling back to default.", ex); } catch (final IllegalArgumentException ex) { Logger.userError(ErrorLevel.MEDIUM, "Unable to load frame " + "manager, falling back to default.", ex); } catch (final ClassNotFoundException ex) { Logger.userError(ErrorLevel.MEDIUM, "Unable to load frame " + "manager, falling back to default.", ex); } catch (final LinkageError ex) { Logger.userError(ErrorLevel.MEDIUM, "Unable to load frame " + "manager, falling back to default.", ex); } finally { if (mainFrameManager == null) { mainFrameManager = new TreeFrameManager(); } } mainFrameManager.setController(controller); mainFrameManager.setParent(frameManagerPanel); addSelectionListener(mainFrameManager); controller.getWindowFactory().addWindowListener( mainFrameManager); } }); } /** * Initialises the components for this frame. */ private void initComponents() { statusBar = new SwingStatusBar(controller, this); frameManagerPanel = new JPanel(); activeFrame = null; framePanel = new JPanel(new MigLayout("fill, ins 0")); initFrameManagers(); mainSplitPane = initSplitPane(); final MenuBar menu = new MenuBar(controller, this); controller.getApple().setMenuBar(menu); setJMenuBar(menu); setPreferredSize(new Dimension(800, 600)); getContentPane().setLayout(new MigLayout( "fill, ins rel, wrap 1, hidemode 2")); layoutComponents(); setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); pack(); } /** * Lays out the this component. */ private void layoutComponents() { getContentPane().add(mainSplitPane, "grow, push"); getContentPane().add(statusBar, "wmax 100%-2*rel, " + "wmin 100%-2*rel, south, gap rel rel 0 rel"); } /** * Initialises the split pane. * * @return Returns the initialised split pane */ private SplitPane initSplitPane() { final SplitPane splitPane = new SplitPane(controller.getGlobalConfig(), SplitPane.Orientation.HORIZONTAL); position = FramemanagerPosition.getPosition(controller .getGlobalConfig().getOption("ui", "framemanagerPosition")); if (position == FramemanagerPosition.UNKNOWN) { position = FramemanagerPosition.LEFT; } if (!mainFrameManager.canPositionVertically() && (position == FramemanagerPosition.LEFT || position == FramemanagerPosition.RIGHT)) { position = FramemanagerPosition.BOTTOM; } if (!mainFrameManager.canPositionHorizontally() && (position == FramemanagerPosition.TOP || position == FramemanagerPosition.BOTTOM)) { position = FramemanagerPosition.LEFT; } switch (position) { case TOP: splitPane.setTopComponent(frameManagerPanel); splitPane.setBottomComponent(framePanel); splitPane.setResizeWeight(0.0); splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); frameManagerPanel.setPreferredSize(new Dimension( Integer.MAX_VALUE, controller.getGlobalConfig(). getOptionInt("ui", "frameManagerSize"))); break; case LEFT: splitPane.setLeftComponent(frameManagerPanel); splitPane.setRightComponent(framePanel); splitPane.setResizeWeight(0.0); splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT); frameManagerPanel.setPreferredSize(new Dimension( controller.getGlobalConfig().getOptionInt("ui", "frameManagerSize"), Integer.MAX_VALUE)); break; case BOTTOM: splitPane.setTopComponent(framePanel); splitPane.setBottomComponent(frameManagerPanel); splitPane.setResizeWeight(1.0); splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); frameManagerPanel.setPreferredSize(new Dimension( Integer.MAX_VALUE, controller.getGlobalConfig(). getOptionInt("ui", "frameManagerSize"))); break; case RIGHT: splitPane.setLeftComponent(framePanel); splitPane.setRightComponent(frameManagerPanel); splitPane.setResizeWeight(1.0); splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT); frameManagerPanel.setPreferredSize(new Dimension( controller.getGlobalConfig().getOptionInt("ui", "frameManagerSize"), Integer.MAX_VALUE)); break; default: break; } return splitPane; } /** * Exits with an "OK" status code. */ public void quit() { quit(0); } /** * Exit code call to quit. * * @param exitCode Exit code */ public void quit(final int exitCode) { if (exitCode == 0 && controller.getGlobalConfig().getOptionBool( "ui", "confirmQuit")) { final StandardQuestionDialog dialog = new ConfirmQuitDialog(controller) { /** Serial version UID. */ private static final long serialVersionUID = 9; /** {@inheritDoc} */ @Override protected void handleQuit() { doQuit(exitCode); } }; dialog.display(); return; } doQuit(exitCode); } /** * Exit code call to quit. * * @param exitCode Exit code */ public void doQuit(final int exitCode) { this.exitCode = exitCode; quitting = true; new LoggingSwingWorker<Void, Void>() { /** {@inheritDoc} */ @Override protected Void doInBackground() { ActionManager.getActionManager().triggerEvent( CoreActionType.CLIENT_CLOSING, null); controller.getServerManager().closeAll(controller .getGlobalConfig().getOption("general", "closemessage")); controller.getGlobalIdentity().setOption("ui", "frameManagerSize", String.valueOf(getFrameManagerSize())); return null; } /** {@inheritDoc} */ @Override protected void done() { super.done(); dispose(); } }.executeInExecutor(); } /** {@inheritDoc} */ @Override public void configChanged(final String domain, final String key) { if ("ui".equals(domain)) { switch (key) { case "lookandfeel": controller.updateLookAndFeel(); break; case "framemanager": case "framemanagerPosition": UIUtilities.invokeLater(new Runnable() { /** {@inheritDoc} */ @Override public void run() { setVisible(false); getContentPane().remove(mainSplitPane); initFrameManagers(); getContentPane().removeAll(); layoutComponents(); setVisible(true); } }); break; case "textPaneFontName": final String font = controller.getGlobalConfig() .getOptionString("ui", "textPaneFontName"); log.debug("Changing textpane font: {}", font); UIUtilities.setUIFont(new Font(font, Font.PLAIN, 12)); controller.updateComponentTrees(); break; default: showVersion = controller.getGlobalConfig().getOptionBool( "ui", "showversion"); break; } } else { imageIcon = new ImageIcon(controller.getIconManager().getImage("icon")); UIUtilities.invokeLater(new Runnable() { /** {@inheritDoc} */ @Override public void run() { setIconImage(imageIcon.getImage()); } }); } } /** * Changes the visible frame. * * @param activeFrame The frame to be activated, or null to show none */ public void setActiveFrame(final TextFrame activeFrame) { UIUtilities.invokeLater(new Runnable() { /** {@inheritDoc} */ @Override public void run() { focusOrder.offerAndMove(activeFrame); framePanel.setVisible(false); framePanel.removeAll(); if (MainFrame.this.activeFrame != null) { MainFrame.this.activeFrame.getContainer() .removeNotificationListener(MainFrame.this); } MainFrame.this.activeFrame = activeFrame; if (activeFrame == null) { framePanel.add(new JPanel(), "grow"); setTitle(null); } else { framePanel.add(activeFrame.getDisplayFrame(), "grow"); setTitle(activeFrame.getContainer().getTitle()); activeFrame.getContainer().addNotificationListener( MainFrame.this); } framePanel.setVisible(true); if (activeFrame != null) { activeFrame.requestFocus(); activeFrame.requestFocusInWindow(); activeFrame.activateFrame(); } for (final SelectionListener listener : listeners.get( SelectionListener.class)) { listener.selectionChanged(activeFrame); } } }); } /** * Registers a new selection listener with this frame. The listener will * be notified whenever the currently selected frame is changed. * * @param listener The listener to be added * @see #setActiveFrame(com.dmdirc.addons.ui_swing.components.frames.TextFrame) * @see #getActiveFrame() */ public void addSelectionListener(final SelectionListener listener) { listeners.add(SelectionListener.class, listener); } /** * Removes a previously registered selection listener. * * @param listener The listener to be removed * @see #addSelectionListener(com.dmdirc.addons.ui_swing.SelectionListener) */ public void removeSelectionListener(final SelectionListener listener) { listeners.remove(SelectionListener.class, listener); } /** {@inheritDoc} */ @Override public void windowAdded(final TextFrame parent, final TextFrame window) { if (activeFrame == null) { setActiveFrame(window); } window.getContainer().addFrameInfoListener(this); } /** {@inheritDoc} */ @Override public void windowDeleted(final TextFrame parent, final TextFrame window) { focusOrder.remove(window); if (activeFrame.equals(window)) { activeFrame = null; framePanel.setVisible(false); framePanel.removeAll(); framePanel.setVisible(true); if (focusOrder.peek() == null) { SwingUtilities.invokeLater(new Runnable() { /** {@inheritDoc} */ @Override public void run() { frameManager.scrollUp(); } }); } else { setActiveFrame(focusOrder.peek()); } } window.getContainer().removeFrameInfoListener(this); } /** {@inheritDoc} */ @Override public void iconChanged(final FrameContainer window, final String icon) { //Ignore } /** {@inheritDoc} */ @Override public void nameChanged(final FrameContainer window, final String name) { //Ignore } /** {@inheritDoc} */ @Override public void titleChanged(final FrameContainer window, final String title) { if (activeFrame != null && activeFrame.getContainer().equals(window)) { setTitle(title); } } /** {@inheritDoc} */ @Override public void notificationSet(final FrameContainer window, final Colour colour) { if (activeFrame.getContainer().equals(window)) { window.clearNotification(); } } /** {@inheritDoc} */ @Override public void notificationCleared(final FrameContainer window) { //Ignore } /** {@inheritDoc} */ @Override public void dispose() { if (!quitting) { removeWindowListener(this); } controller.getGlobalConfig().removeListener(this); super.dispose(); } }
package net.wurstclient.features.mods; import java.lang.reflect.Field; import java.util.Collection; import java.util.Comparator; import java.util.TreeMap; import net.wurstclient.features.Mod; import net.wurstclient.features.mods.blocks.*; import net.wurstclient.features.mods.chat.AntiSpamMod; import net.wurstclient.features.mods.chat.FancyChatMod; import net.wurstclient.features.mods.chat.ForceOpMod; import net.wurstclient.features.mods.chat.HomeMod; import net.wurstclient.features.mods.chat.MassTpaMod; import net.wurstclient.features.mods.chat.SpammerMod; import net.wurstclient.features.mods.combat.*; import net.wurstclient.features.mods.fun.*; import net.wurstclient.features.mods.items.CmdBlockMod; import net.wurstclient.features.mods.items.CrashChestMod; import net.wurstclient.features.mods.items.CrashTagMod; import net.wurstclient.features.mods.items.KillPotionMod; import net.wurstclient.features.mods.items.TrollPotionMod; import net.wurstclient.features.mods.movement.*; import net.wurstclient.features.mods.other.*; import net.wurstclient.features.mods.render.*; import net.wurstclient.features.mods.retro.AntiFireMod; import net.wurstclient.features.mods.retro.AntiPotionMod; import net.wurstclient.features.mods.retro.FastBowMod; import net.wurstclient.features.mods.retro.FastEatMod; import net.wurstclient.features.mods.retro.ForcePushMod; import net.wurstclient.features.mods.retro.RegenMod; public class ModManager { private final TreeMap<String, Mod> mods = new TreeMap<>(new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }); public final AntiAfkMod antiAfkMod = new AntiAfkMod(); public final AntiBlindMod antiBlindMod = new AntiBlindMod(); public final AntiCactusMod antiCactusMod = new AntiCactusMod(); public final AntiFireMod antiFireMod = new AntiFireMod(); public final AntiKnockbackMod antiKnockbackMod = new AntiKnockbackMod(); public final AntiPotionMod antiPotionMod = new AntiPotionMod(); public final AntiSpamMod antiSpamMod = new AntiSpamMod(); public final AutoArmorMod autoArmorMod = new AutoArmorMod(); public final AutoBuildMod autoBuildMod = new AutoBuildMod(); public final AutoLeaveMod autoLeaveMod = new AutoLeaveMod(); public final AutoEatMod autoEatMod = new AutoEatMod(); public final AutoFishMod autoFishMod = new AutoFishMod(); public final AutoMineMod autoMineMod = new AutoMineMod(); public final AutoRespawnMod autoRespawnMod = new AutoRespawnMod(); public final AutoSignMod autoSignMod = new AutoSignMod(); public final AutoSplashPotMod autoSplashPotMod = new AutoSplashPotMod(); public final AutoSoupMod autoSoupMod = new AutoSoupMod(); public final AutoSprintMod autoSprintMod = new AutoSprintMod(); public final AutoStealMod autoStealMod = new AutoStealMod(); public final AutoSwitchMod autoSwitchMod = new AutoSwitchMod(); public final AutoSwordMod autoSwordMod = new AutoSwordMod(); public final AutoToolMod autoToolMod = new AutoToolMod(); public final AutoWalkMod autoWalkMod = new AutoWalkMod(); public final BaseFinderMod baseFinderMod = new BaseFinderMod(); public final BlinkMod blinkMod = new BlinkMod(); public final BoatFlyMod boatFlyMod = new BoatFlyMod(); public final BonemealAuraMod bonemealAuraMod = new BonemealAuraMod(); public final BowAimbotMod bowAimbotMod = new BowAimbotMod(); public final BuildRandomMod buildRandomMod = new BuildRandomMod(); public final BunnyHopMod bunnyHopMod = new BunnyHopMod(); public final CameraNoClipMod cameraNoClipMod = new CameraNoClipMod(); public final CaveFinderMod caveFinderMod = new CaveFinderMod(); public final ChestEspMod chestEspMod = new ChestEspMod(); public final ClickAuraMod clickAuraMod = new ClickAuraMod(); public final ClickGuiMod clickGuiMod = new ClickGuiMod(); public final CmdBlockMod cmdBlockMod = new CmdBlockMod(); public final CrashChestMod crashChestMod = new CrashChestMod(); public final CrashTagMod crashTagMod = new CrashTagMod(); public final CriticalsMod criticalsMod = new CriticalsMod(); public final DerpMod derpMod = new DerpMod(); public final DolphinMod dolphinMod = new DolphinMod(); public final ExtraElytraMod extraElytraMod = new ExtraElytraMod(); public final FancyChatMod fancyChatMod = new FancyChatMod(); public final FastBreakMod fastBreakMod = new FastBreakMod(); public final FastBowMod fastBowMod = new FastBowMod(); public final FastEatMod fastEatMod = new FastEatMod(); public final FastLadderMod fastLadderMod = new FastLadderMod(); public final FastPlaceMod fastPlaceMod = new FastPlaceMod(); public final FightBotMod fightBotMod = new FightBotMod(); public final FlightMod flightMod = new FlightMod(); public final FollowMod followMod = new FollowMod(); public final ForceOpMod forceOpMod = new ForceOpMod(); public final ForcePushMod forcePushMod = new ForcePushMod(); public final FreecamMod freecamMod = new FreecamMod(); public final FullbrightMod fullbrightMod = new FullbrightMod(); public final GhostHandMod ghostHandMod = new GhostHandMod(); public final GlideMod glideMod = new GlideMod(); public final HeadlessMod headlessMod = new HeadlessMod(); public final HeadRollMod headRollMod = new HeadRollMod(); public final HealthTagsMod healthTagsMod = new HealthTagsMod(); public final HighJumpMod highJumpMod = new HighJumpMod(); public final HomeMod homeMod = new HomeMod(); public final InstantBunkerMod instantBunkerMod = new InstantBunkerMod(); public final InvWalkMod invWalkMod = new InvWalkMod(); public final ItemEspMod itemEspMod = new ItemEspMod(); public final JesusMod jesusMod = new JesusMod(); public final JetpackMod jetpackMod = new JetpackMod(); public final KaboomMod kaboomMod = new KaboomMod(); public final KillauraLegitMod killauraLegitMod = new KillauraLegitMod(); public final KillauraMod killauraMod = new KillauraMod(); public final KillPotionMod killPotionMod = new KillPotionMod(); public final LiquidsMod liquidsMod = new LiquidsMod(); public final LogSpammerMod logSpammerMod = new LogSpammerMod(); public final LsdMod lsdMod = new LsdMod(); public final MassTpaMod massTpaMod = new MassTpaMod(); public final MileyCyrusMod mileyCyrusMod = new MileyCyrusMod(); public final MobEspMod mobEspMod = new MobEspMod(); public final MultiAuraMod multiAuraMod = new MultiAuraMod(); public final NameProtectMod nameProtectMod = new NameProtectMod(); public final NameTagsMod nameTagsMod = new NameTagsMod(); public final NavigatorMod navigatorMod = new NavigatorMod(); public final NoClipMod noClipMod = new NoClipMod(); public final NoFallMod noFallMod = new NoFallMod(); public final NoHurtcamMod noHurtcamMod = new NoHurtcamMod(); public final NoOverlayMod noOverlayMod = new NoOverlayMod(); public final NoSlowdownMod noSlowdownMod = new NoSlowdownMod(); public final NoWeatherMod noWeatherMod = new NoWeatherMod(); public final NoWebMod noWebMod = new NoWebMod(); public final NukerMod nukerMod = new NukerMod(); public final NukerLegitMod nukerLegitMod = new NukerLegitMod(); public final OverlayMod overlayMod = new OverlayMod(); public final PanicMod panicMod = new PanicMod(); public final ParkourMod parkourMod = new ParkourMod(); public final PhaseMod phaseMod = new PhaseMod(); public final PlayerEspMod playerEspMod = new PlayerEspMod(); public final PlayerFinderMod playerFinderMod = new PlayerFinderMod(); public final PotionSaverMod potionSaverMod = new PotionSaverMod(); public final ProphuntEspMod prophuntEspMod = new ProphuntEspMod(); public final ProtectMod protectMod = new ProtectMod(); public final RainbowUiMod rainbowUiMod = new RainbowUiMod(); public final RegenMod regenMod = new RegenMod(); public final RemoteViewMod remoteViewMod = new RemoteViewMod(); public final SafeWalkMod safeWalkMod = new SafeWalkMod(); public final ScaffoldWalkMod scaffoldWalkMod = new ScaffoldWalkMod(); public final SearchMod searchMod = new SearchMod(); public final SkinDerpMod skinDerpMod = new SkinDerpMod(); public final SneakMod sneakMod = new SneakMod(); public final SpammerMod spammerMod = new SpammerMod(); public final SpeedHackMod speedHackMod = new SpeedHackMod(); public final SpeedNukerMod speedNukerMod = new SpeedNukerMod(); public final SpiderMod spiderMod = new SpiderMod(); public final StepMod stepMod = new StepMod(); public final TemplateToolMod templateToolMod = new TemplateToolMod(); public final ThrowMod throwMod = new ThrowMod(); public final TimerMod timerMod = new TimerMod(); public final TiredMod tiredMod = new TiredMod(); public final TracersMod tracersMod = new TracersMod(); public final TpAuraMod tpAuraMod = new TpAuraMod(); public final TrajectoriesMod trajectoriesMod = new TrajectoriesMod(); public final TriggerBotMod triggerBotMod = new TriggerBotMod(); public final TrollPotionMod trollPotionMod = new TrollPotionMod(); public final TrueSightMod trueSightMod = new TrueSightMod(); public final TunnellerMod tunnellerMod = new TunnellerMod(); public final XRayMod xRayMod = new XRayMod(); public ModManager() { try { for(Field field : ModManager.class.getFields()) if(field.getName().endsWith("Mod")) { Mod mod = (Mod)field.get(this); mods.put(mod.getName(), mod); mod.initSettings(); } }catch(Exception e) { e.printStackTrace(); } } public Mod getModByName(String name) { return mods.get(name); } public Collection<Mod> getAllMods() { return mods.values(); } public int countMods() { return mods.size(); } }
package fi.tnie.db.expr; public class OrdinaryIdentifier extends AbstractIdentifier { private static final long serialVersionUID = -8379767503417798479L; /** * No-argument constructor for GWT Serialization */ protected OrdinaryIdentifier() { } public OrdinaryIdentifier(String name) throws IllegalIdentifierException { super(name); validateOrdinary(name); } @Override public boolean isOrdinary() { return true; } @Override public String toString() { return "[" + getName() + ": " + super.toString() + "]"; } @Override public void traverse(VisitContext vc, ElementVisitor v) { v.start(vc, this); v.end(this); } public static void validateOrdinary(String token) throws IllegalIdentifierException { StringBuffer details = new StringBuffer(); if (!isValidOrdinary(token, details)) { throw new IllegalIdentifierException(details.toString()); } } public static boolean isValidOrdinary(String token) { return isValidOrdinary(token, null); } private static boolean isValidOrdinary(String token, StringBuffer details) { String p = "[A-Za-z][A-Za-z0-9_]*"; if (!token.matches(p)) { return fail("token '" + token + "' doesn't match the pattern: " + p, details); } if (SQLKeyword.isKeyword(token.toUpperCase())) { return fail( "token '" + token + "' is identical to a keyword and " + "can not be used as a ordinary identifier", details); } return true; } @Override public String getTerminalSymbol() { return getName(); } }
package net.wurstclient.features.mods; import java.lang.reflect.Field; import java.util.Collection; import java.util.Comparator; import java.util.TreeMap; import net.wurstclient.features.Mod; import net.wurstclient.features.mods.blocks.*; import net.wurstclient.features.mods.chat.AntiSpamMod; import net.wurstclient.features.mods.chat.FancyChatMod; import net.wurstclient.features.mods.chat.HomeMod; import net.wurstclient.features.mods.combat.*; import net.wurstclient.features.mods.fun.DerpMod; import net.wurstclient.features.mods.fun.HeadRollMod; import net.wurstclient.features.mods.fun.HeadlessMod; import net.wurstclient.features.mods.fun.LsdMod; import net.wurstclient.features.mods.fun.MileyCyrusMod; import net.wurstclient.features.mods.fun.SkinDerpMod; import net.wurstclient.features.mods.fun.TiredMod; import net.wurstclient.features.mods.items.CmdBlockMod; import net.wurstclient.features.mods.items.CrashChestMod; import net.wurstclient.features.mods.items.CrashTagMod; import net.wurstclient.features.mods.items.KillPotionMod; import net.wurstclient.features.mods.items.TrollPotionMod; import net.wurstclient.features.mods.movement.*; import net.wurstclient.features.mods.other.AntiAfkMod; import net.wurstclient.features.mods.other.AutoEatMod; import net.wurstclient.features.mods.other.AutoFishMod; import net.wurstclient.features.mods.other.AutoStealMod; import net.wurstclient.features.mods.other.AutoSwitchMod; import net.wurstclient.features.mods.render.AntiBlindMod; import net.wurstclient.features.mods.render.BaseFinderMod; import net.wurstclient.features.mods.render.CaveFinderMod; import net.wurstclient.features.mods.render.FreecamMod; import net.wurstclient.features.mods.render.FullbrightMod; import net.wurstclient.features.mods.render.HealthTagsMod; import net.wurstclient.features.mods.render.ItemEspMod; import net.wurstclient.features.mods.retro.AntiFireMod; import net.wurstclient.features.mods.retro.AntiPotionMod; import net.wurstclient.features.mods.retro.CriticalsMod; import net.wurstclient.features.mods.retro.FastBowMod; import net.wurstclient.features.mods.retro.FastEatMod; import net.wurstclient.features.mods.retro.ForcePushMod; import net.wurstclient.features.mods.retro.RegenMod; public class ModManager { private final TreeMap<String, Mod> mods = new TreeMap<>(new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }); public final AntiAfkMod antiAfkMod = new AntiAfkMod(); public final AntiBlindMod antiBlindMod = new AntiBlindMod(); public final AntiCactusMod antiCactusMod = new AntiCactusMod(); public final AntiFireMod antiFireMod = new AntiFireMod(); public final AntiKnockbackMod antiKnockbackMod = new AntiKnockbackMod(); public final AntiPotionMod antiPotionMod = new AntiPotionMod(); public final AntiSpamMod antiSpamMod = new AntiSpamMod(); public final AutoArmorMod autoArmorMod = new AutoArmorMod(); public final AutoBuildMod autoBuildMod = new AutoBuildMod(); public final AutoLeaveMod autoLeaveMod = new AutoLeaveMod(); public final AutoEatMod autoEatMod = new AutoEatMod(); public final AutoFishMod autoFishMod = new AutoFishMod(); public final AutoMineMod autoMineMod = new AutoMineMod(); public final AutoRespawnMod autoRespawnMod = new AutoRespawnMod(); public final AutoSignMod autoSignMod = new AutoSignMod(); public final AutoSplashPotMod autoSplashPotMod = new AutoSplashPotMod(); public final AutoSoupMod autoSoupMod = new AutoSoupMod(); public final AutoSprintMod autoSprintMod = new AutoSprintMod(); public final AutoStealMod autoStealMod = new AutoStealMod(); public final AutoSwitchMod autoSwitchMod = new AutoSwitchMod(); public final AutoSwordMod autoSwordMod = new AutoSwordMod(); public final AutoToolMod autoToolMod = new AutoToolMod(); public final AutoWalkMod autoWalkMod = new AutoWalkMod(); public final BaseFinderMod baseFinderMod = new BaseFinderMod(); public final BlinkMod blinkMod = new BlinkMod(); public final BoatFlyMod boatFlyMod = new BoatFlyMod(); public final BonemealAuraMod bonemealAuraMod = new BonemealAuraMod(); public final BowAimbotMod bowAimbotMod = new BowAimbotMod(); public final BuildRandomMod buildRandomMod = new BuildRandomMod(); public final BunnyHopMod bunnyHopMod = new BunnyHopMod(); public final CaveFinderMod caveFinderMod = new CaveFinderMod(); public final ChestEspMod chestEspMod = new ChestEspMod(); public final ClickAuraMod clickAuraMod = new ClickAuraMod(); public final CmdBlockMod cmdBlockMod = new CmdBlockMod(); public final CrashChestMod crashChestMod = new CrashChestMod(); public final CrashTagMod crashTagMod = new CrashTagMod(); public final CriticalsMod criticalsMod = new CriticalsMod(); public final DerpMod derpMod = new DerpMod(); public final DolphinMod dolphinMod = new DolphinMod(); public final ExtraElytraMod extraElytraMod = new ExtraElytraMod(); public final FancyChatMod fancyChatMod = new FancyChatMod(); public final FastBreakMod fastBreakMod = new FastBreakMod(); public final FastBowMod fastBowMod = new FastBowMod(); public final FastEatMod fastEatMod = new FastEatMod(); public final FastLadderMod fastLadderMod = new FastLadderMod(); public final FastPlaceMod fastPlaceMod = new FastPlaceMod(); public final FightBotMod fightBotMod = new FightBotMod(); public final FlightMod flightMod = new FlightMod(); public final FollowMod followMod = new FollowMod(); public final ForceOpMod forceOpMod = new ForceOpMod(); public final ForcePushMod forcePushMod = new ForcePushMod(); public final FreecamMod freecamMod = new FreecamMod(); public final FullbrightMod fullbrightMod = new FullbrightMod(); public final GhostHandMod ghostHandMod = new GhostHandMod(); public final GlideMod glideMod = new GlideMod(); public final HeadlessMod headlessMod = new HeadlessMod(); public final HeadRollMod headRollMod = new HeadRollMod(); public final HealthTagsMod healthTagsMod = new HealthTagsMod(); public final HighJumpMod highJumpMod = new HighJumpMod(); public final HomeMod homeMod = new HomeMod(); public final InstantBunkerMod instantBunkerMod = new InstantBunkerMod(); public final ItemEspMod itemEspMod = new ItemEspMod(); public final JesusMod jesusMod = new JesusMod(); public final JetpackMod jetpackMod = new JetpackMod(); public final KaboomMod kaboomMod = new KaboomMod(); public final KillauraLegitMod killauraLegitMod = new KillauraLegitMod(); public final KillauraMod killauraMod = new KillauraMod(); public final KillPotionMod killPotionMod = new KillPotionMod(); public final LiquidsMod liquidsMod = new LiquidsMod(); public final LogSpammerMod logSpammerMod = new LogSpammerMod(); public final LsdMod lsdMod = new LsdMod(); public final MassTpaMod massTpaMod = new MassTpaMod(); public final MenuWalkMod menuWalkMod = new MenuWalkMod(); public final MileyCyrusMod mileyCyrusMod = new MileyCyrusMod(); public final MobEspMod mobEspMod = new MobEspMod(); public final MultiAuraMod multiAuraMod = new MultiAuraMod(); public final NameProtectMod nameProtectMod = new NameProtectMod(); public final NameTagsMod nameTagsMod = new NameTagsMod(); public final NavigatorMod navigatorMod = new NavigatorMod(); public final NoClipMod noClipMod = new NoClipMod(); public final NoFallMod noFallMod = new NoFallMod(); public final NoHurtcamMod noHurtcamMod = new NoHurtcamMod(); public final NoOverlayMod noOverlayMod = new NoOverlayMod(); public final NoSlowdownMod noSlowdownMod = new NoSlowdownMod(); public final NoWeatherMod noWeatherMod = new NoWeatherMod(); public final NoWebMod noWebMod = new NoWebMod(); public final NukerMod nukerMod = new NukerMod(); public final NukerLegitMod nukerLegitMod = new NukerLegitMod(); public final OverlayMod overlayMod = new OverlayMod(); public final PanicMod panicMod = new PanicMod(); public final ParkourMod parkourMod = new ParkourMod(); public final PhaseMod phaseMod = new PhaseMod(); public final PlayerEspMod playerEspMod = new PlayerEspMod(); public final PlayerFinderMod playerFinderMod = new PlayerFinderMod(); public final PotionSaverMod potionSaverMod = new PotionSaverMod(); public final ProphuntEspMod prophuntEspMod = new ProphuntEspMod(); public final ProtectMod protectMod = new ProtectMod(); public final RegenMod regenMod = new RegenMod(); public final RemoteViewMod remoteViewMod = new RemoteViewMod(); public final SafeWalkMod safeWalkMod = new SafeWalkMod(); public final ScaffoldWalkMod scaffoldWalkMod = new ScaffoldWalkMod(); public final SearchMod searchMod = new SearchMod(); public final SkinDerpMod skinDerpMod = new SkinDerpMod(); public final SneakMod sneakMod = new SneakMod(); public final SpammerMod spammerMod = new SpammerMod(); public final SpeedHackMod speedHackMod = new SpeedHackMod(); public final SpeedNukerMod speedNukerMod = new SpeedNukerMod(); public final SpiderMod spiderMod = new SpiderMod(); public final StepMod stepMod = new StepMod(); public final TemplateToolMod templateToolMod = new TemplateToolMod(); public final ThrowMod throwMod = new ThrowMod(); public final TimerMod timerMod = new TimerMod(); public final TiredMod tiredMod = new TiredMod(); public final TracersMod tracersMod = new TracersMod(); public final TpAuraMod tpAuraMod = new TpAuraMod(); public final TrajectoriesMod trajectoriesMod = new TrajectoriesMod(); public final TriggerBotMod triggerBotMod = new TriggerBotMod(); public final TrollPotionMod trollPotionMod = new TrollPotionMod(); public final TrueSightMod trueSightMod = new TrueSightMod(); public final TunnellerMod tunnellerMod = new TunnellerMod(); public final XRayMod xRayMod = new XRayMod(); public ModManager() { try { for(Field field : ModManager.class.getFields()) if(field.getName().endsWith("Mod")) { Mod mod = (Mod)field.get(this); mods.put(mod.getName(), mod); mod.initSettings(); } }catch(Exception e) { e.printStackTrace(); } } public Mod getModByName(String name) { return mods.get(name); } public Collection<Mod> getAllMods() { return mods.values(); } public int countMods() { return mods.size(); } }
package net.wurstclient.features.mods; import java.lang.reflect.Field; import java.util.Collection; import java.util.Comparator; import java.util.TreeMap; import net.wurstclient.features.Mod; import net.wurstclient.features.mods.combat.*; import net.wurstclient.features.mods.fun.DerpMod; import net.wurstclient.features.mods.fun.HeadRollMod; import net.wurstclient.features.mods.fun.HeadlessMod; import net.wurstclient.features.mods.fun.LsdMod; import net.wurstclient.features.mods.fun.MileyCyrusMod; import net.wurstclient.features.mods.fun.SkinDerpMod; import net.wurstclient.features.mods.fun.TiredMod; import net.wurstclient.features.mods.items.CmdBlockMod; import net.wurstclient.features.mods.items.CrashChestMod; import net.wurstclient.features.mods.items.CrashTagMod; import net.wurstclient.features.mods.items.KillPotionMod; import net.wurstclient.features.mods.items.TrollPotionMod; import net.wurstclient.features.mods.movement.AutoSprintMod; import net.wurstclient.features.mods.movement.FastLadderMod; import net.wurstclient.features.mods.movement.JesusMod; import net.wurstclient.features.mods.movement.SpiderMod; import net.wurstclient.features.mods.movement.StepMod; import net.wurstclient.features.mods.retro.CriticalsMod; import net.wurstclient.features.mods.retro.FastBowMod; import net.wurstclient.features.mods.retro.FastEatMod; import net.wurstclient.features.mods.retro.ForcePushMod; import net.wurstclient.features.mods.retro.RegenMod; public class ModManager { private final TreeMap<String, Mod> mods = new TreeMap<>(new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }); public final AntiAfkMod antiAfkMod = new AntiAfkMod(); public final AntiBlindMod antiBlindMod = new AntiBlindMod(); public final AntiCactusMod antiCactusMod = new AntiCactusMod(); public final AntiFireMod antiFireMod = new AntiFireMod(); public final AntiKnockbackMod antiKnockbackMod = new AntiKnockbackMod(); public final AntiPotionMod antiPotionMod = new AntiPotionMod(); public final AntiSpamMod antiSpamMod = new AntiSpamMod(); public final AutoArmorMod autoArmorMod = new AutoArmorMod(); public final AutoBuildMod autoBuildMod = new AutoBuildMod(); public final AutoLeaveMod autoLeaveMod = new AutoLeaveMod(); public final AutoEatMod autoEatMod = new AutoEatMod(); public final AutoFishMod autoFishMod = new AutoFishMod(); public final AutoMineMod autoMineMod = new AutoMineMod(); public final AutoRespawnMod autoRespawnMod = new AutoRespawnMod(); public final AutoSignMod autoSignMod = new AutoSignMod(); public final AutoSplashPotMod autoSplashPotMod = new AutoSplashPotMod(); public final AutoSoupMod autoSoupMod = new AutoSoupMod(); public final AutoSprintMod autoSprintMod = new AutoSprintMod(); public final AutoStealMod autoStealMod = new AutoStealMod(); public final AutoSwitchMod autoSwitchMod = new AutoSwitchMod(); public final AutoSwordMod autoSwordMod = new AutoSwordMod(); public final AutoToolMod autoToolMod = new AutoToolMod(); public final AutoWalkMod autoWalkMod = new AutoWalkMod(); public final BaseFinderMod baseFinderMod = new BaseFinderMod(); public final BlinkMod blinkMod = new BlinkMod(); public final BoatFlyMod boatFlyMod = new BoatFlyMod(); public final BonemealAuraMod bonemealAuraMod = new BonemealAuraMod(); public final BowAimbotMod bowAimbotMod = new BowAimbotMod(); public final BuildRandomMod buildRandomMod = new BuildRandomMod(); public final BunnyHopMod bunnyHopMod = new BunnyHopMod(); public final CaveFinderMod caveFinderMod = new CaveFinderMod(); public final ChestEspMod chestEspMod = new ChestEspMod(); public final ClickAuraMod clickAuraMod = new ClickAuraMod(); public final CmdBlockMod cmdBlockMod = new CmdBlockMod(); public final CrashChestMod crashChestMod = new CrashChestMod(); public final CrashTagMod crashTagMod = new CrashTagMod(); public final CriticalsMod criticalsMod = new CriticalsMod(); public final DerpMod derpMod = new DerpMod(); public final DolphinMod dolphinMod = new DolphinMod(); public final ExtraElytraMod extraElytraMod = new ExtraElytraMod(); public final FancyChatMod fancyChatMod = new FancyChatMod(); public final FastBreakMod fastBreakMod = new FastBreakMod(); public final FastBowMod fastBowMod = new FastBowMod(); public final FastEatMod fastEatMod = new FastEatMod(); public final FastLadderMod fastLadderMod = new FastLadderMod(); public final FastPlaceMod fastPlaceMod = new FastPlaceMod(); public final FightBotMod fightBotMod = new FightBotMod(); public final FlightMod flightMod = new FlightMod(); public final FollowMod followMod = new FollowMod(); public final ForceOpMod forceOpMod = new ForceOpMod(); public final ForcePushMod forcePushMod = new ForcePushMod(); public final FreecamMod freecamMod = new FreecamMod(); public final FullbrightMod fullbrightMod = new FullbrightMod(); public final GhostHandMod ghostHandMod = new GhostHandMod(); public final GlideMod glideMod = new GlideMod(); public final HeadlessMod headlessMod = new HeadlessMod(); public final HeadRollMod headRollMod = new HeadRollMod(); public final HealthTagsMod healthTagsMod = new HealthTagsMod(); public final HighJumpMod highJumpMod = new HighJumpMod(); public final HomeMod homeMod = new HomeMod(); public final InstantBunkerMod instantBunkerMod = new InstantBunkerMod(); public final InvisibilityMod invisibilityMod = new InvisibilityMod(); public final ItemEspMod itemEspMod = new ItemEspMod(); public final JesusMod jesusMod = new JesusMod(); public final JetpackMod jetpackMod = new JetpackMod(); public final KaboomMod kaboomMod = new KaboomMod(); public final KillauraLegitMod killauraLegitMod = new KillauraLegitMod(); public final KillauraMod killauraMod = new KillauraMod(); public final KillPotionMod killPotionMod = new KillPotionMod(); public final LiquidsMod liquidsMod = new LiquidsMod(); public final LogSpammerMod logSpammerMod = new LogSpammerMod(); public final LsdMod lsdMod = new LsdMod(); public final MassTpaMod massTpaMod = new MassTpaMod(); public final MenuWalkMod menuWalkMod = new MenuWalkMod(); public final MileyCyrusMod mileyCyrusMod = new MileyCyrusMod(); public final MobEspMod mobEspMod = new MobEspMod(); public final MultiAuraMod multiAuraMod = new MultiAuraMod(); public final NameProtectMod nameProtectMod = new NameProtectMod(); public final NameTagsMod nameTagsMod = new NameTagsMod(); public final NavigatorMod navigatorMod = new NavigatorMod(); public final NoClipMod noClipMod = new NoClipMod(); public final NoFallMod noFallMod = new NoFallMod(); public final NoHurtcamMod noHurtcamMod = new NoHurtcamMod(); public final NoOverlayMod noOverlayMod = new NoOverlayMod(); public final NoSlowdownMod noSlowdownMod = new NoSlowdownMod(); public final NoWeatherMod noWeatherMod = new NoWeatherMod(); public final NoWebMod noWebMod = new NoWebMod(); public final NukerMod nukerMod = new NukerMod(); public final NukerLegitMod nukerLegitMod = new NukerLegitMod(); public final OverlayMod overlayMod = new OverlayMod(); public final PanicMod panicMod = new PanicMod(); public final ParkourMod parkourMod = new ParkourMod(); public final PhaseMod phaseMod = new PhaseMod(); public final PlayerEspMod playerEspMod = new PlayerEspMod(); public final PlayerFinderMod playerFinderMod = new PlayerFinderMod(); public final PotionSaverMod potionSaverMod = new PotionSaverMod(); public final ProphuntEspMod prophuntEspMod = new ProphuntEspMod(); public final ProtectMod protectMod = new ProtectMod(); public final RegenMod regenMod = new RegenMod(); public final RemoteViewMod remoteViewMod = new RemoteViewMod(); public final SafeWalkMod safeWalkMod = new SafeWalkMod(); public final ScaffoldWalkMod scaffoldWalkMod = new ScaffoldWalkMod(); public final SearchMod searchMod = new SearchMod(); public final SkinDerpMod skinDerpMod = new SkinDerpMod(); public final SneakMod sneakMod = new SneakMod(); public final SpammerMod spammerMod = new SpammerMod(); public final SpeedHackMod speedHackMod = new SpeedHackMod(); public final SpeedNukerMod speedNukerMod = new SpeedNukerMod(); public final SpiderMod spiderMod = new SpiderMod(); public final StepMod stepMod = new StepMod(); public final TemplateToolMod templateToolMod = new TemplateToolMod(); public final ThrowMod throwMod = new ThrowMod(); public final TimerMod timerMod = new TimerMod(); public final TiredMod tiredMod = new TiredMod(); public final TracersMod tracersMod = new TracersMod(); public final TpAuraMod tpAuraMod = new TpAuraMod(); public final TrajectoriesMod trajectoriesMod = new TrajectoriesMod(); public final TriggerBotMod triggerBotMod = new TriggerBotMod(); public final TrollPotionMod trollPotionMod = new TrollPotionMod(); public final TrueSightMod trueSightMod = new TrueSightMod(); public final TunnellerMod tunnellerMod = new TunnellerMod(); public final XRayMod xRayMod = new XRayMod(); public ModManager() { try { for(Field field : ModManager.class.getFields()) if(field.getName().endsWith("Mod")) { Mod mod = (Mod)field.get(this); mods.put(mod.getName(), mod); mod.initSettings(); } }catch(Exception e) { e.printStackTrace(); } } public Mod getModByName(String name) { return mods.get(name); } public Collection<Mod> getAllMods() { return mods.values(); } public int countMods() { return mods.size(); } }
package ui.issuecolumn; import backend.interfaces.IModel; import backend.resource.TurboIssue; import backend.resource.TurboUser; import filter.ParseException; import filter.Parser; import filter.QualifierApplicationException; import filter.expression.FilterExpression; import filter.expression.Qualifier; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.collections.transformation.SortedList; import javafx.collections.transformation.TransformationList; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import ui.UI; import ui.components.FilterTextField; import util.events.ColumnClickedEvent; import util.events.ModelUpdatedEventHandler; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; /** * An IssueColumn is a Column meant for containing issues. The main additions to * Column are filtering functionality and a list of issues to be maintained. * The IssueColumn does not specify how the list is to be displayed -- subclasses * override methods which determine that. */ public abstract class IssueColumn extends Column { private static final Logger logger = LogManager.getLogger(IssueColumn.class.getName()); // Collection-related private ObservableList<TurboIssue> issues = FXCollections.observableArrayList(); // Filter-related private TransformationList<TurboIssue, TurboIssue> transformedIssueList = null; protected FilterTextField filterTextField; private UI ui; private FilterExpression currentFilterExpression = Qualifier.EMPTY; private Predicate<TurboIssue> predicate = p -> true; private Comparator<TurboIssue> comparator = (a, b) -> 0; // This controls whether a metadata update will be triggered on the next refresh. // It's toggled to false by model updates that are not supposed to trigger updates. // It's toggled to true each time a refresh DOES NOT trigger an update. private boolean triggerMetadataUpdate = true; public IssueColumn(UI ui, IModel model, ColumnControl parentColumnControl, int columnIndex) { super(model, parentColumnControl, columnIndex); this.ui = ui; getChildren().add(createFilterBox()); // setupIssueColumnDragEvents(model, columnIndex); this.setOnMouseClicked(e-> { ui.triggerEvent(new ColumnClickedEvent(columnIndex)); requestFocus(); }); focusedProperty().addListener((unused, wasFocused, isFocused) -> { if (isFocused) { getStyleClass().add("panel-focused"); } else { getStyleClass().remove("panel-focused"); } }); } // private void setupIssueColumnDragEvents(Model model, int columnIndex) { // setOnDragOver(e -> { // if (e.getGestureSource() != this && e.getDragboard().hasString()) { // DragData dd = DragData.deserialise(e.getDragboard().getString()); // if (dd.getSource() == DragData.Source.ISSUE_CARD) { // e.acceptTransferModes(TransferMode.MOVE); // setOnDragDropped(e -> { // Dragboard db = e.getDragboard(); // boolean success = false; // if (db.hasString()) { // success = true; // DragData dd = DragData.deserialise(db.getString()); // if (dd.getColumnIndex() != columnIndex) { // Optional<TurboIssue> rightIssue = model.getIssueById(dd.getIssueIndex()); // assert rightIssue.isPresent(); // applyCurrentFilterExpressionToIssue(rightIssue.get(), true); // e.setDropCompleted(success); // e.consume(); private final ModelUpdatedEventHandler onModelUpdate = e -> { // Update keywords List<String> all = new ArrayList<>(Arrays.asList(Qualifier.KEYWORDS)); all.addAll(e.model.getUsers().stream() .map(TurboUser::getLoginName) .collect(Collectors.toList())); filterTextField.setKeywords(all); // Make metadata update state consistent if (!e.triggerMetadataUpdate) { this.triggerMetadataUpdate = false; } }; private Node createFilterBox() { filterTextField = new FilterTextField("", 0).setOnConfirm((text) -> { applyStringFilter(text); return text; }); filterTextField.setId(model.getDefaultRepo() + "_col" + columnIndex + "_filterTextField"); ui.registerEvent(onModelUpdate); filterTextField.setOnMouseClicked(e -> ui.triggerEvent(new ColumnClickedEvent(columnIndex))); // setupIssueDragEvents(filterTextField); HBox buttonsBox = new HBox(); buttonsBox.setSpacing(5); buttonsBox.setAlignment(Pos.TOP_RIGHT); buttonsBox.setMinWidth(50); buttonsBox.getChildren().addAll(createButtons()); HBox layout = new HBox(); layout.getChildren().addAll(filterTextField, buttonsBox); layout.setPadding(new Insets(0, 0, 3, 0)); return layout; } private Label[] createButtons() { // Label addIssue = new Label(ADD_ISSUE); // addIssue.getStyleClass().add("label-button"); // addIssue.setOnMouseClicked((e) -> { // ui.triggerEvent(new IssueCreatedEvent()); Label closeList = new Label(CLOSE_COLUMN); closeList.getStyleClass().add("label-button"); closeList.setOnMouseClicked((e) -> { e.consume(); parentColumnControl.closeColumn(columnIndex); }); // Label toggleHierarchyMode = new Label(TOGGLE_HIERARCHY); // toggleHierarchyMode.getStyleClass().add("label-button"); // toggleHierarchyMode.setOnMouseClicked((e) -> { // parentColumnControl.toggleColumn(columnIndex); return new Label[] { closeList }; } // private void setupIssueDragEvents(Node filterBox) { // filterBox.setOnDragOver(e -> { // if (e.getGestureSource() != this && e.getDragboard().hasString()) { // DragData dd = DragData.deserialise(e.getDragboard().getString()); // if (dd.getSource() == DragData.Source.ISSUE_CARD) { // e.acceptTransferModes(TransferMode.MOVE); // } else if (dd.getSource() == DragData.Source.LABEL_TAB // || dd.getSource() == DragData.Source.ASSIGNEE_TAB // || dd.getSource() == DragData.Source.MILESTONE_TAB) { // e.acceptTransferModes(TransferMode.COPY); // filterBox.setOnDragEntered(e -> { // if (e.getDragboard().hasString()) { // DragData dd = DragData.deserialise(e.getDragboard().getString()); // if (dd.getSource() == DragData.Source.ISSUE_CARD) { // filterBox.getStyleClass().add("dragged-over"); // } else if (dd.getSource() == DragData.Source.COLUMN) { // if (parentColumnControl.getCurrentlyDraggedColumnIndex() != columnIndex) { // // Apparently the dragboard can't be updated while // // the drag is in progress. This is why we use an // // external source for updates. // assert parentColumnControl.getCurrentlyDraggedColumnIndex() != -1; // int previous = parentColumnControl.getCurrentlyDraggedColumnIndex(); // parentColumnControl.setCurrentlyDraggedColumnIndex(columnIndex); // parentColumnControl.swapColumns(previous, columnIndex); // e.consume(); // filterBox.setOnDragExited(e -> { // filterBox.getStyleClass().remove("dragged-over"); // e.consume(); // filterBox.setOnDragDropped(e -> { // Dragboard db = e.getDragboard(); // boolean success = false; // if (db.hasString()) { // success = true; // DragData dd = DragData.deserialise(db.getString()); // if (dd.getSource() == DragData.Source.ISSUE_CARD) { // assert model.getIssueById(dd.getIssueIndex()).isPresent(); // TurboIssue rightIssue = model.getIssueById(dd.getIssueIndex()).get(); // if (rightIssue.getLabels().size() == 0) { // // If the issue has no labels, show it by its title to inform // // the user that there are no similar issues // filter(new Qualifier("keyword", rightIssue.getTitle())); // } else { // // Otherwise, take the disjunction of its labels to show similar // // issues. // List<TurboLabel> labels = model.getLabelsOfIssue(rightIssue); // FilterExpression result = new Qualifier("label", labels.get(0).getName()); // List<FilterExpression> rest = labels.stream() // .skip(1) // .map(label -> new Qualifier("label", label.getName())) // .collect(Collectors.toList()); // for (FilterExpression label : rest) { // result = new Disjunction(label, result); // filter(result); // } else if (dd.getSource() == DragData.Source.COLUMN) { // // This event is never triggered when the drag is ended. // // It's not a huge deal, as this is only used to // // reinitialise the currently-dragged slot in ColumnControl. // // The other main consequence of this is that we can't // // assert to check if the slot has been cleared when starting a drag-swap. // } else if (dd.getSource() == DragData.Source.LABEL_TAB) { // filter(new Qualifier("label", dd.getEntityName())); // } else if (dd.getSource() == DragData.Source.ASSIGNEE_TAB) { // filter(new Qualifier("assignee", dd.getEntityName())); // } else if (dd.getSource() == DragData.Source.MILESTONE_TAB) { // filter(new Qualifier("milestone", dd.getEntityName())); // e.setDropCompleted(success); // e.consume(); // These two methods are triggered by the contents of the input area // changing. As such they should not be invoked manually, or the input // area won't update. private void applyStringFilter(String filterString) { try { FilterExpression filter = Parser.parse(filterString); if (filter != null) { this.applyFilterExpression(filter); } else { this.applyFilterExpression(Qualifier.EMPTY); } // Clear displayed message on successful filter UI.status.clear(); } catch (ParseException ex) { this.applyFilterExpression(Qualifier.EMPTY); // Overrides message in status bar UI.status.displayMessage("Panel " + (columnIndex + 1) + ": Parse error in filter: " + ex.getMessage()); } } private void applyFilterExpression(FilterExpression filter) { currentFilterExpression = filter; applyCurrentFilterExpression(); refreshItems(); } /** * Same as applyFilterExpression, but does not call refreshItems or change the * current filter. Meant to be called from refreshItems() so as not to go into * infinite mutual recursion. */ private void applyCurrentFilterExpression() { predicate = issue -> Qualifier.process(model, currentFilterExpression, issue); comparator = Qualifier.getSortComparator(model, "id", true); Qualifier.processMetaQualifierEffects(currentFilterExpression, (qualifier, metaQualifierInfo) -> { if (qualifier.getContent().isPresent() && qualifier.getName().equals(Qualifier.REPO)) { ui.logic.openRepository(qualifier.getContent().get()); } else if (qualifier.getName().equals(Qualifier.SORT)) { comparator = qualifier.getCompoundSortComparator(model); } }); } // An odd workaround for the above problem: serialising, then // immediately parsing a filter expression, just so the update can be // triggered through the text contents of the input area changing. public void filter(FilterExpression filterExpr) { filterByString(filterExpr.toString()); } public void filterByString(String filterString) { filterTextField.setFilterText(filterString); } public FilterExpression getCurrentFilterExpression() { return currentFilterExpression; } public String getCurrentFilterString() { return filterTextField.getText(); } // private void applyCurrentFilterExpressionToIssue(TurboIssue issue, boolean updateModel) { // if (currentFilterExpression != Qualifier.EMPTY) { // try { // if (currentFilterExpression.canBeAppliedToIssue()) { // // TODO re-enable //// TurboIssue clone = new TurboIssue(issue); // currentFilterExpression.applyTo(issue, model); // if (updateModel) { // // TODO re-enable //// dragAndDropExecutor.executeCommand(CommandType.EDIT_ISSUE, models, clone, issue); // parentColumnControl.refresh(); // } else { // throw new QualifierApplicationException( // "Could not apply predicate " + currentFilterExpression + "."); // } catch (QualifierApplicationException ex) { // UI.status.displayMessage(ex.getMessage()); public TransformationList<TurboIssue, TurboIssue> getIssueList() { return transformedIssueList; } public void setItems(List<TurboIssue> items) { this.issues = FXCollections.observableArrayList(items); refreshItems(); } @Override public void close() { ui.unregisterEvent(onModelUpdate); } @Override public void refreshItems() { applyCurrentFilterExpression(); transformedIssueList = new SortedList<>(new FilteredList<>(issues, predicate), comparator); if (!triggerMetadataUpdate) { triggerMetadataUpdate = true; } else if (currentFilterExpression.getQualifierNames().contains(Qualifier.UPDATED)) { // Group all filtered issues by repo, then trigger updates for each group transformedIssueList.stream() .collect(Collectors.groupingBy(TurboIssue::getRepoId)) .entrySet().forEach(e -> ui.logic.getIssueMetadata(e.getKey(), e.getValue().stream() .map(TurboIssue::getId) .collect(Collectors.toList()))); } } }
// S c o r e E x p o r t e r // // Please contact users@audiveris.dev.java.net to report bugs & suggestions. // package omr.score.visitor; import omr.Main; import omr.glyph.Shape; import static omr.glyph.Shape.*; import omr.log.Logger; import omr.score.MeasureRange; import omr.score.Score; import omr.score.common.PagePoint; import omr.score.common.SystemPoint; import omr.score.common.SystemRectangle; import omr.score.entity.Arpeggiate; import omr.score.entity.Barline; import omr.score.entity.Beam; import omr.score.entity.Chord; import omr.score.entity.Clef; import omr.score.entity.Coda; import omr.score.entity.DirectionStatement; import omr.score.entity.Dynamics; import omr.score.entity.Fermata; import omr.score.entity.KeySignature; import omr.score.entity.LyricsItem; import omr.score.entity.Measure; import omr.score.entity.Notation; import omr.score.entity.Ornament; import omr.score.entity.Pedal; import omr.score.entity.ScorePart; import omr.score.entity.ScoreSystem; import omr.score.entity.Segno; import omr.score.entity.Slot; import omr.score.entity.Slur; import omr.score.entity.Staff; import omr.score.entity.SystemPart; import omr.score.entity.Text; import omr.score.entity.Text.CreatorText; import omr.score.entity.TimeSignature; import omr.score.entity.TimeSignature.InvalidTimeSignature; import omr.score.entity.Tuplet; import omr.score.entity.Voice; import omr.score.entity.Voice.ChordInfo; import omr.score.entity.Wedge; import omr.score.midi.MidiAbstractions; import static omr.score.visitor.MusicXML.*; import omr.util.TreeNode; import omr.util.Worker; import org.w3c.dom.Node; import proxymusic.*; import proxymusic.util.Marshalling; import java.awt.Font; import java.io.*; import java.lang.reflect.Method; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; /** * Class <code>ScoreExporter</code> can visit the score hierarchy to export * the score to a MusicXML file, stream or DOM. * * @author Herv&eacute Bitteur * @version $Id$ */ public class ScoreExporter extends AbstractScoreVisitor { /** Usual logger utility */ private static final Logger logger = Logger.getLogger(ScoreExporter.class); /** A future which reflects whether JAXB has been initialized **/ private static final Loader loader = new Loader(); static { loader.start(); } /** The related score */ private Score score; /** The score proxy built precisely for export via JAXB */ private final ScorePartwise scorePartwise = new ScorePartwise(); /** Current context */ private Current current = new Current(); /** Current flags */ private IsFirst isFirst = new IsFirst(); /** Map of Slur numbers, reset for every part */ private Map<Slur, Integer> slurNumbers = new HashMap<Slur, Integer>(); /** Map of Tuplet numbers, reset for every measure */ private Map<Tuplet, Integer> tupletNumbers = new HashMap<Tuplet, Integer>(); /** Potential range of selected measures */ private MeasureRange measureRange; /** Factory for proxymusic entities */ private final proxymusic.ObjectFactory factory = new proxymusic.ObjectFactory(); // ScoreExporter // /** * Create a new ScoreExporter object, on a related score instance * * @param score the score to export (cannot be null) */ public ScoreExporter (Score score) { if (score == null) { throw new IllegalArgumentException("Trying to export a null score"); } this.score = score; } // preload // /** * Empty static method, just to trigger class elaboration */ public static void preload () { } // setMeasureRange // /** * Set a specific range of measures to export * * @param measureRange the range of desired measures */ public void setMeasureRange (MeasureRange measureRange) { this.measureRange = measureRange; } // export // /** * Export the score to a file * * @param xmlFile the xml file to write (cannot be null) * @throws java.lang.Exception */ public void export (File xmlFile) throws Exception { export(new FileOutputStream(xmlFile)); } // export // /** * Export the score to an output stream * * @param os the output stream where XML data is written (cannot be null) * @throws java.io.IOException * @throws java.lang.Exception */ public void export (OutputStream os) throws IOException, Exception { if (os == null) { throw new IllegalArgumentException( "Trying to export a score to a null output stream"); } // Let visited nodes fill the scorePartWise proxy score.accept(this); // Finally, marshal the proxy Marshalling.marshal(scorePartwise, os); } // export // /** * Export the score to DOM node * * @param node the DOM node to export to (cannot be null) * @throws java.io.IOException * @throws java.lang.Exception */ public void export (Node node) throws IOException, Exception { if (node == null) { throw new IllegalArgumentException( "Trying to export a score to a null DOM Node"); } // Let visited nodes fill the scorePartWise proxy score.accept(this); // Finally, marshal the proxy Marshalling.marshal(scorePartwise, node, /* Signature => */ true); } // visit Arpeggiate // @Override public boolean visit (Arpeggiate arpeggiate) { proxymusic.Arpeggiate pmArpeggiate = factory.createArpeggiate(); getNotations() .getTiedOrSlurOrTuplet() .add(pmArpeggiate); // relative-x pmArpeggiate.setRelativeX( toTenths(arpeggiate.getPoint().x - current.note.getCenterLeft().x)); // number ??? // TODO return false; } // visit Barline // @Override public boolean visit (Barline barline) { ///logger.info("Visiting " + barline); if (barline == null) { return false; } Shape shape = barline.getShape(); if (shape != omr.glyph.Shape.THIN_BARLINE) { try { proxymusic.Barline pmBarline = factory.createBarline(); proxymusic.BarStyleColor barStyleColor = factory.createBarStyleColor(); pmBarline.setBarStyle(barStyleColor); if (barline == current.measure.getBarline()) { // The bar is on right side pmBarline.setLocation(RightLeftMiddle.RIGHT); if ((shape == RIGHT_REPEAT_SIGN) || (shape == BACK_TO_BACK_REPEAT_SIGN)) { barStyleColor.setValue(BarStyle.LIGHT_HEAVY); Repeat repeat = factory.createRepeat(); pmBarline.setRepeat(repeat); repeat.setDirection(BackwardForward.BACKWARD); } } else { // The bar is on left side pmBarline.setLocation(RightLeftMiddle.LEFT); if ((shape == LEFT_REPEAT_SIGN) || (shape == BACK_TO_BACK_REPEAT_SIGN)) { barStyleColor.setValue(BarStyle.HEAVY_LIGHT); Repeat repeat = factory.createRepeat(); pmBarline.setRepeat(repeat); repeat.setDirection(BackwardForward.FORWARD); } } // Default: use style inferred from shape if (barStyleColor.getValue() == null) { barStyleColor.setValue(barStyleOf(barline.getShape())); } // Everything is now OK current.pmMeasure.getNoteOrBackupOrForward() .add(pmBarline); } catch (Exception ex) { logger.warning("Cannot visit barline", ex); } } return true; } // visit Chord // @Override public boolean visit (Chord chord) { logger.severe("Chord objects should not be visited by ScoreExporter"); return false; } // visit Clef // @Override public boolean visit (Clef clef) { ///logger.info("Visiting " + clef); if (isNewClef(clef)) { proxymusic.Clef pmClef = factory.createClef(); getMeasureAttributes() .getClef() .add(pmClef); // Staff number (only for multi-staff parts) if (current.part.getStaffIds() .size() > 1) { pmClef.setNumber( new BigInteger("" + (clef.getStaff().getId()))); } // Line (General computation that could be overridden by more // specific shape test below) pmClef.setLine( new BigInteger( "" + (3 - (int) Math.rint(clef.getPitchPosition() / 2.0)))); Shape shape = clef.getShape(); switch (shape) { case G_CLEF : pmClef.setSign(ClefSign.G); break; case G_CLEF_OTTAVA_ALTA : pmClef.setSign(ClefSign.G); pmClef.setClefOctaveChange(new BigInteger("1")); break; case G_CLEF_OTTAVA_BASSA : pmClef.setSign(ClefSign.G); pmClef.setClefOctaveChange(new BigInteger("-1")); break; case C_CLEF : pmClef.setSign(ClefSign.C); break; case F_CLEF : pmClef.setSign(ClefSign.F); break; case F_CLEF_OTTAVA_ALTA : pmClef.setSign(ClefSign.F); pmClef.setClefOctaveChange(new BigInteger("1")); break; case F_CLEF_OTTAVA_BASSA : pmClef.setSign(ClefSign.F); pmClef.setClefOctaveChange(new BigInteger("-1")); break; default : } } return true; } // visit Coda // @Override public boolean visit (Coda coda) { Direction direction = factory.createDirection(); current.pmMeasure.getNoteOrBackupOrForward() .add(direction); DirectionType directionType = new DirectionType(); direction.getDirectionType() .add(directionType); proxymusic.EmptyPrintStyle pmCoda = factory.createEmptyPrintStyle(); directionType.getCoda() .add(pmCoda); // Staff ? Staff staff = current.note.getStaff(); insertStaffId(direction, staff); // default-x pmCoda.setDefaultX( toTenths(coda.getPoint().x - current.measure.getLeftX())); // default-y pmCoda.setDefaultY(yOf(coda.getPoint(), staff)); // Need also a Sound element Sound sound = factory.createSound(); direction.setSound(sound); sound.setCoda("" + current.measure.getId()); sound.setDivisions( createDecimal( score.simpleDurationOf(omr.score.entity.Note.QUARTER_DURATION))); return true; } // visit Dynamics // @Override public boolean visit (Dynamics dynamics) { ///logger.info("Visiting " + dynamics); try { Direction direction = factory.createDirection(); current.pmMeasure.getNoteOrBackupOrForward() .add(direction); DirectionType directionType = factory.createDirectionType(); direction.getDirectionType() .add(directionType); proxymusic.Dynamics pmDynamics = factory.createDynamics(); directionType.setDynamics(pmDynamics); // Precise dynamic signature pmDynamics.getPOrPpOrPpp() .add(getDynamicsObject(dynamics.getShape())); // Staff ? Staff staff = current.note.getStaff(); insertStaffId(direction, staff); // Placement if (dynamics.getPoint().y < current.note.getCenter().y) { direction.setPlacement(AboveBelow.ABOVE); } else { direction.setPlacement(AboveBelow.BELOW); } // default-y pmDynamics.setDefaultY(yOf(dynamics.getPoint(), staff)); // Relative-x (No offset for the time being) using note left side pmDynamics.setRelativeX( toTenths( dynamics.getPoint().x - current.note.getCenterLeft().x)); } catch (Exception ex) { logger.warning("Error exporting " + dynamics, ex); } return false; } // visit Fermata // @Override public boolean visit (Fermata fermata) { proxymusic.Fermata pmFermata = factory.createFermata(); getNotations() .getTiedOrSlurOrTuplet() .add(pmFermata); // default-y (of the fermata dot) // For upright we use bottom of the box, for inverted the top of the box SystemRectangle box = fermata.getBox(); SystemPoint dot; if (fermata.getShape() == Shape.FERMATA_BELOW) { dot = new SystemPoint(box.x + (box.width / 2), box.y); } else { dot = new SystemPoint(box.x + (box.width / 2), box.y + box.height); } pmFermata.setDefaultY(yOf(dot, current.note.getStaff())); // Type pmFermata.setType( (fermata.getShape() == Shape.FERMATA) ? UprightInverted.UPRIGHT : UprightInverted.INVERTED); return false; } // visit KeySignature // @Override public boolean visit (KeySignature keySignature) { ///logger.info("Visiting " + keySignature); try { if (isNewKeySignature(keySignature)) { Key key = factory.createKey(); key.setFifths(new BigInteger("" + keySignature.getKey())); // Trick: add this key signature only if it does not already exist List<Key> keys = getMeasureAttributes() .getKey(); for (Key k : keys) { if (areEqual(k, key)) { return true; // Already inserted, so give up } } keys.add(key); } } catch (Exception ex) { logger.warning("Error exporting " + keySignature, ex); } return true; } // visit Measure // @Override public boolean visit (Measure measure) { // Make sure this measure is to be exported if (!isDesired(measure)) { if (logger.isFineEnabled()) { logger.fine(measure + " skipped."); } return false; } ///logger.info("Visiting " + measure); // Do we need to create & export a dummy initial measure? if (((measureRange != null) && !measure.isTemporary() && (measure.getId() > 1)) && (measure.getId() == measureRange.getFirstId())) { visit(measure.createTemporaryBefore()); } if (logger.isFineEnabled()) { logger.fine(measure + " : " + isFirst); } current.measure = measure; tupletNumbers.clear(); // Allocate Measure current.pmMeasure = factory.createScorePartwisePartMeasure(); current.pmPart.getMeasure() .add(current.pmMeasure); current.pmMeasure.setNumber("" + measure.getId()); if (measure.getWidth() != null) { current.pmMeasure.setWidth(toTenths(measure.getWidth())); } if (measure.isImplicit()) { current.pmMeasure.setImplicit(YesNo.YES); } // Right Barline if (!measure.isDummy()) { visit(measure.getBarline()); } // Left barline ? Measure prevMeasure = (Measure) measure.getPreviousSibling(); if ((prevMeasure != null) && !prevMeasure.isDummy()) { visit(prevMeasure.getBarline()); } if (isFirst.measure) { // Allocate Print current.pmPrint = factory.createPrint(); current.pmMeasure.getNoteOrBackupOrForward() .add(current.pmPrint); if (isFirst.system) { // New Page ? TODO // Divisions try { getMeasureAttributes() .setDivisions( createDecimal( score.simpleDurationOf( omr.score.entity.Note.QUARTER_DURATION))); } catch (Exception ex) { if (score.getDurationDivisor() == null) { logger.warning( "Not able to infer division value for part " + current.part.getPid()); } else { logger.warning("Error on divisions", ex); } } // Number of staves, if > 1 if (current.part.isMultiStaff()) { getMeasureAttributes() .setStaves( new BigInteger("" + current.part.getStaffIds().size())); } } else { // New system current.pmPrint.setNewSystem(YesNo.YES); } if (isFirst.part) { // SystemLayout SystemLayout systemLayout = factory.createSystemLayout(); current.pmPrint.setSystemLayout(systemLayout); // SystemMargins SystemMargins systemMargins = factory.createSystemMargins(); systemLayout.setSystemMargins(systemMargins); systemMargins.setLeftMargin( toTenths(current.system.getTopLeft().x)); systemMargins.setRightMargin( toTenths( score.getDimension().width - current.system.getTopLeft().x - current.system.getDimension().width)); if (isFirst.system) { // TopSystemDistance systemLayout.setTopSystemDistance( toTenths(current.system.getTopLeft().y)); // Default tempo? if (current.part.getTempo() != null) { Sound sound = factory.createSound(); current.pmMeasure.getNoteOrBackupOrForward() .add(sound); sound.setTempo(createDecimal(current.part.getTempo())); } // Default velocity? if (score.getVelocity() != null) { Sound sound = factory.createSound(); current.pmMeasure.getNoteOrBackupOrForward() .add(sound); sound.setDynamics(createDecimal(score.getVelocity())); } } else { // SystemDistance ScoreSystem prevSystem = (ScoreSystem) current.system.getPreviousSibling(); systemLayout.setSystemDistance( toTenths( current.system.getTopLeft().y - prevSystem.getTopLeft().y - prevSystem.getDimension().height - prevSystem.getLastPart().getLastStaff().getHeight())); } } // StaffLayout for all staves in this part, except 1st system staff if (!measure.isDummy()) { for (TreeNode sNode : measure.getPart() .getStaves()) { Staff staff = (Staff) sNode; if (!isFirst.part || (staff.getId() > 1)) { try { StaffLayout staffLayout = factory.createStaffLayout(); staffLayout.setNumber( new BigInteger("" + staff.getId())); Staff prevStaff = (Staff) staff.getPreviousSibling(); if (prevStaff == null) { SystemPart prevPart = (SystemPart) measure.getPart() .getPreviousSibling(); prevStaff = prevPart.getLastStaff(); } staffLayout.setStaffDistance( toTenths( staff.getPageTopLeft().y - prevStaff.getPageTopLeft().y - prevStaff.getHeight())); current.pmPrint.getStaffLayout() .add(staffLayout); } catch (Exception ex) { logger.warning( "Error exporting staff layout system current.system.getId() + " part current.part.getId() + " staff staff.getId(), ex); } } } } // Do not print artificial parts StaffDetails staffDetails = factory.createStaffDetails(); staffDetails.setPrintObject( measure.isDummy() ? YesNo.NO : YesNo.YES); getMeasureAttributes() .getStaffDetails() .add(staffDetails); } // Specific browsing down the measure // Clefs, KeySignatures, TimeSignatures measure.getClefList() .acceptChildren(this); measure.getKeySigList() .acceptChildren(this); measure.getTimeSigList() .acceptChildren(this); // Now voice per voice try { int timeCounter = 0; for (Voice voice : measure.getVoices()) { current.voice = voice; // Need a backup ? if (timeCounter != 0) { insertBackup(timeCounter); timeCounter = 0; } if (voice.isWhole()) { // Delegate to the chord children directly voice.getWholeChord() .acceptChildren(this); timeCounter = measure.getExpectedDuration(); } else { for (Slot slot : measure.getSlots()) { ChordInfo info = voice.getSlotInfo(slot); if (info != null) { // Skip free slots if (info.getStatus() == Voice.Status.BEGIN) { Chord chord = info.getChord(); // Need a forward before this chord ? int startTime = chord.getStartTime(); if (timeCounter < startTime) { insertForward( startTime - timeCounter, chord); timeCounter = startTime; } // Delegate to the chord children directly chord.acceptChildren(this); timeCounter += chord.getDuration(); } } } // Need an ending forward ? if (!measure.isImplicit() && !measure.isPartial() && (timeCounter < measure.getExpectedDuration())) { insertForward( measure.getExpectedDuration() - timeCounter, voice.getLastChord()); timeCounter = measure.getExpectedDuration(); } } } } catch (InvalidTimeSignature ex) { } // Safer... current.endMeasure(); tupletNumbers.clear(); isFirst.measure = false; return true; } // visit Note // @Override public boolean visit (omr.score.entity.Note note) { ///logger.info("Visiting " + note); try { current.note = note; Chord chord = note.getChord(); // Chord direction events for first note in chord if (chord.getNotes() .indexOf(note) == 0) { for (omr.score.entity.Direction node : chord.getDirections()) { node.accept(this); } } current.pmNote = factory.createNote(); current.pmMeasure.getNoteOrBackupOrForward() .add(current.pmNote); Staff staff = note.getStaff(); // Chord notation events for first note in chord if (chord.getNotes() .indexOf(note) == 0) { for (Notation node : chord.getNotations()) { node.accept(this); } } else { // Chord indication for every other note current.pmNote.setChord(new Empty()); // Arpeggiate also? for (Notation node : chord.getNotations()) { if (node instanceof Arpeggiate) { node.accept(this); } } } // Rest ? if (note.isRest()) { DisplayStepOctave displayStepOctave = factory.createDisplayStepOctave(); /// TODO ??? Set Step or Octave ??? current.pmNote.setRest(displayStepOctave); } else { // Pitch Pitch pitch = factory.createPitch(); pitch.setStep(stepOf(note.getStep())); pitch.setOctave(note.getOctave()); if (note.getAlter() != 0) { pitch.setAlter(createDecimal(note.getAlter())); } current.pmNote.setPitch(pitch); } // Default-x (use left side of the note wrt measure) if (!note.getMeasure() .isDummy()) { int noteLeft = note.getCenterLeft().x; current.pmNote.setDefaultX( toTenths(noteLeft - note.getMeasure().getLeftX())); } // Tuplet factor ? if (chord.getTupletFactor() != null) { TimeModification timeModification = factory.createTimeModification(); timeModification.setActualNotes( new BigInteger( "" + chord.getTupletFactor().getDenominator())); timeModification.setNormalNotes( new BigInteger("" + chord.getTupletFactor().getNumerator())); current.pmNote.setTimeModification(timeModification); } // Duration try { Integer dur = null; if (chord.isWholeDuration()) { dur = chord.getMeasure() .getActualDuration(); } else { dur = chord.getDuration(); } current.pmNote.setDuration( createDecimal(score.simpleDurationOf(dur))); } catch (Exception ex) { if (score.getDurationDivisor() != null) { logger.warning("Not able to get duration of note", ex); } } // Voice current.pmNote.setVoice("" + chord.getVoice().getId()); // Type NoteType noteType = factory.createNoteType(); noteType.setValue("" + getNoteTypeName(note)); current.pmNote.setType(noteType); // Stem ? if (chord.getStem() != null) { Stem pmStem = factory.createStem(); SystemPoint tail = chord.getTailLocation(); pmStem.setDefaultY(yOf(tail, staff)); if (tail.y < note.getCenter().y) { pmStem.setValue(StemValue.UP); } else { pmStem.setValue(StemValue.DOWN); } current.pmNote.setStem(pmStem); } // Staff ? if (current.part.isMultiStaff()) { current.pmNote.setStaff(new BigInteger("" + staff.getId())); } // Dots for (int i = 0; i < chord.getDotsNumber(); i++) { current.pmNote.getDot() .add(factory.createEmptyPlacement()); } // Accidental ? if (note.getAccidental() != null) { Accidental accidental = factory.createAccidental(); accidental.setValue(accidentalTextOf(note.getAccidental())); current.pmNote.setAccidental(accidental); } // Beams ? for (Beam beam : chord.getBeams()) { proxymusic.Beam pmBeam = factory.createBeam(); pmBeam.setNumber(beam.getLevel()); if (beam.isHook()) { if (beam.getCenter().x > current.system.toSystemPoint( chord.getStem().getLocation()).x) { pmBeam.setValue(BeamValue.FORWARD_HOOK); } else { pmBeam.setValue(BeamValue.BACKWARD_HOOK); } } else { if (beam.getChords() .first() == chord) { pmBeam.setValue(BeamValue.BEGIN); } else if (beam.getChords() .last() == chord) { pmBeam.setValue(BeamValue.END); } else { pmBeam.setValue(BeamValue.CONTINUE); } } current.pmNote.getBeam() .add(pmBeam); } // Ties / Slurs for (Slur slur : note.getSlurs()) { slur.accept(this); } // Lyrics ? if (note.getSyllables() != null) { for (LyricsItem syllable : note.getSyllables()) { if (syllable.getContent() != null) { Lyric pmLyric = factory.createLyric(); pmLyric.setDefaultY(yOf(syllable.getLocation(), staff)); pmLyric.setNumber( "" + syllable.getLyricsLine().getId()); TextElementData pmText = factory.createTextElementData(); pmText.setValue(syllable.getContent()); pmLyric.getElisionAndSyllabicAndText() .add(pmText); pmLyric.getElisionAndSyllabicAndText() .add(getSyllabic(syllable.getSyllabicType())); current.pmNote.getLyric() .add(pmLyric); } } } } catch (Exception ex) { logger.warning("Error exporting " + note, ex); } // Safer... current.endNote(); return true; } // visit Ornament // @Override @SuppressWarnings("unchecked") public boolean visit (Ornament ornament) { JAXBElement<?> element = getOrnamentObject(ornament.getShape()); // Include in ornaments getOrnaments() .getTrillMarkOrTurnOrDelayedTurn() .add(element); // Placement? Class<?> classe = element.getDeclaredType(); try { Method method = classe.getMethod( "setPlacement", java.lang.String.class); method.invoke( element.getValue(), (ornament.getPoint().y < current.note.getCenter().y) ? AboveBelow.ABOVE : AboveBelow.BELOW); } catch (Exception ex) { ///ex.printStackTrace(); logger.severe("Could not setPlacement for element " + classe); } return false; } // visit Pedal // @Override public boolean visit (Pedal pedal) { Direction direction = new Direction(); current.pmMeasure.getNoteOrBackupOrForward() .add(direction); DirectionType directionType = new DirectionType(); direction.getDirectionType() .add(directionType); proxymusic.Pedal pmPedal = new proxymusic.Pedal(); directionType.setPedal(pmPedal); // No line (for the time being) pmPedal.setLine(YesNo.NO); // Start / Stop type pmPedal.setType( pedal.isStart() ? StartStopChange.START : StartStopChange.STOP); // Staff ? Staff staff = current.note.getStaff(); insertStaffId(direction, staff); // default-x pmPedal.setDefaultX( toTenths(pedal.getPoint().x - current.measure.getLeftX())); // default-y pmPedal.setDefaultY(yOf(pedal.getPoint(), staff)); // Placement direction.setPlacement( (pedal.getPoint().y < current.note.getCenter().y) ? AboveBelow.ABOVE : AboveBelow.BELOW); return true; } // visit Score // /** * Allocate/populate everything that directly relates to the score instance. * The rest of processing is delegated to the score children, that is to * say pages (TBI), then systems, etc... * * @param score visit the score to export * @return false, since no further processing is required after this node */ @Override public boolean visit (Score score) { ///logger.info("Visiting " + score); // Reset durations for the score score.setDurationDivisor(null); // No version inserted // Let the marshalling class handle it // Identification Identification identification = factory.createIdentification(); scorePartwise.setIdentification(identification); // Source identification.setSource(score.getImagePath()); // Encoding Encoding encoding = factory.createEncoding(); identification.setEncoding(encoding); // [Encoding]/Software encoding.getEncodingDateOrEncoderOrSoftware() .add( factory.createEncodingSoftware( Main.getToolName() + " " + Main.getToolVersion())); // [Encoding]/EncodingDate // Let the Marshalling class handle it // Defaults Defaults defaults = new Defaults(); scorePartwise.setDefaults(defaults); // [Defaults]/Scaling Scaling scaling = factory.createScaling(); defaults.setScaling(scaling); scaling.setMillimeters( createDecimal( (score.getSheet() .getScale() .interline() * 25.4 * 4) / 300)); // Assuming 300 DPI scaling.setTenths(new BigDecimal("40")); // [Defaults]/PageLayout PageLayout pageLayout = factory.createPageLayout(); defaults.setPageLayout(pageLayout); pageLayout.setPageHeight(toTenths(score.getDimension().height)); pageLayout.setPageWidth(toTenths(score.getDimension().width)); // [Defaults]/LyricFont Font lyricFont = omr.score.entity.Text.getLyricsFont(); LyricFont pmLyricFont = factory.createLyricFont(); defaults.getLyricFont() .add(pmLyricFont); pmLyricFont.setFontFamily(lyricFont.getName()); pmLyricFont.setFontSize("" + omr.score.entity.Text.getLyricsFontSize()); pmLyricFont.setFontStyle( (lyricFont.getStyle() == Font.ITALIC) ? FontStyle.ITALIC : FontStyle.NORMAL); // PartList PartList partList = factory.createPartList(); scorePartwise.setPartList(partList); isFirst.part = true; for (ScorePart p : score.getPartList()) { current.part = p; ///logger.info("Processing " + p); // Scorepart in partList proxymusic.ScorePart scorePart = factory.createScorePart(); partList.getPartGroupOrScorePart() .add(scorePart); scorePart.setId(current.part.getPid()); PartName partName = factory.createPartName(); scorePart.setPartName(partName); partName.setValue(current.part.getName()); if (p.getMidiProgram() != null) { // Score instrument ScoreInstrument scoreInstrument = new ScoreInstrument(); scorePart.getScoreInstrument() .add(scoreInstrument); scoreInstrument.setId(scorePart.getId() + "-I1"); scoreInstrument.setInstrumentName( MidiAbstractions.getProgramName(p.getMidiProgram())); // Midi instrument MidiInstrument midiInstrument = factory.createMidiInstrument(); scorePart.getMidiInstrument() .add(midiInstrument); midiInstrument.setId(scoreInstrument); midiInstrument.setMidiChannel(p.getId()); midiInstrument.setMidiProgram(p.getMidiProgram()); } // ScorePart in scorePartwise current.pmPart = factory.createScorePartwisePart(); scorePartwise.getPart() .add(current.pmPart); current.pmPart.setId(scorePart); // Delegate to children the filling of measures if (logger.isFineEnabled()) { logger.fine("Populating " + current.part); } isFirst.system = true; // TODO: to be reviewed when adding pages slurNumbers.clear(); // Reset slur numbers score.acceptChildren(this); // Next part, if any isFirst.part = false; } return false; // That's all } // visit Segno // @Override public boolean visit (Segno segno) { Direction direction = new Direction(); current.pmMeasure.getNoteOrBackupOrForward() .add(direction); DirectionType directionType = factory.createDirectionType(); direction.getDirectionType() .add(directionType); EmptyPrintStyle empty = factory.createEmptyPrintStyle(); directionType.getSegno() .add(empty); // Staff ? Staff staff = current.note.getStaff(); insertStaffId(direction, staff); // default-x empty.setDefaultX( toTenths(segno.getPoint().x - current.measure.getLeftX())); // default-y empty.setDefaultY(yOf(segno.getPoint(), staff)); // Need also a Sound element Sound sound = factory.createSound(); sound.setSegno("" + current.measure.getId()); sound.setDivisions( createDecimal( score.simpleDurationOf(omr.score.entity.Note.QUARTER_DURATION))); return true; } // visit Slur // @Override public boolean visit (Slur slur) { ///logger.info("Visiting " + slur); // Note contextual data boolean isStart = slur.getLeftNote() == current.note; int noteLeft = current.note.getCenterLeft().x; Staff staff = current.note.getStaff(); if (slur.isTie()) { // Tie element Tie tie = factory.createTie(); tie.setType(isStart ? StartStop.START : StartStop.STOP); current.pmNote.getTie() .add(tie); // Tied element Tied tied = factory.createTied(); // Type tied.setType(isStart ? StartStop.START : StartStop.STOP); // Orientation if (isStart) { tied.setOrientation( slur.isBelow() ? OverUnder.UNDER : OverUnder.OVER); } // Bezier if (isStart) { tied.setDefaultX(toTenths(slur.getCurve().getX1() - noteLeft)); tied.setDefaultY(yOf(slur.getCurve().getY1(), staff)); tied.setBezierX( toTenths(slur.getCurve().getCtrlX1() - noteLeft)); tied.setBezierY(yOf(slur.getCurve().getCtrlY1(), staff)); } else { tied.setDefaultX(toTenths(slur.getCurve().getX2() - noteLeft)); tied.setDefaultY(yOf(slur.getCurve().getY2(), staff)); tied.setBezierX( toTenths(slur.getCurve().getCtrlX2() - noteLeft)); tied.setBezierY(yOf(slur.getCurve().getCtrlY2(), staff)); } getNotations() .getTiedOrSlurOrTuplet() .add(tied); } else { // Slur element proxymusic.Slur pmSlur = factory.createSlur(); // Number attribute Integer num = slurNumbers.get(slur); if (num != null) { pmSlur.setNumber(num); slurNumbers.remove(slur); if (logger.isFineEnabled()) { logger.fine( current.note.getContextString() + " last use " + num + " -> " + slurNumbers.toString()); } } else { // Determine first available number for (num = 1; num <= 6; num++) { if (!slurNumbers.containsValue(num)) { if (slur.getRightExtension() != null) { slurNumbers.put(slur.getRightExtension(), num); } else { slurNumbers.put(slur, num); } pmSlur.setNumber(num); if (logger.isFineEnabled()) { logger.fine( current.note.getContextString() + " first use " + num + " -> " + slurNumbers.toString()); } break; } } } // Type pmSlur.setType( isStart ? StartStopContinue.START : StartStopContinue.STOP); // Placement if (isStart) { pmSlur.setPlacement( slur.isBelow() ? AboveBelow.BELOW : AboveBelow.ABOVE); } // Bezier if (isStart) { pmSlur.setDefaultX( toTenths(slur.getCurve().getX1() - noteLeft)); pmSlur.setDefaultY(yOf(slur.getCurve().getY1(), staff)); pmSlur.setBezierX( toTenths(slur.getCurve().getCtrlX1() - noteLeft)); pmSlur.setBezierY(yOf(slur.getCurve().getCtrlY1(), staff)); } else { pmSlur.setDefaultX( toTenths(slur.getCurve().getX2() - noteLeft)); pmSlur.setDefaultY(yOf(slur.getCurve().getY2(), staff)); pmSlur.setBezierX( toTenths(slur.getCurve().getCtrlX2() - noteLeft)); pmSlur.setBezierY(yOf(slur.getCurve().getCtrlY2(), staff)); } getNotations() .getTiedOrSlurOrTuplet() .add(pmSlur); } return true; } // visit System // /** * Allocate/populate everything that directly relates to this system in the * current part. The rest of processing is directly delegated to the * measures * * @param system visit the system to export * @return false */ @Override public boolean visit (ScoreSystem system) { ///logger.info("Visiting " + system); current.system = system; isFirst.measure = true; SystemPart systemPart = (SystemPart) system.getPart( current.part.getId()); if (systemPart != null) { systemPart.accept(this); } else { // Need to build an artificial system part // Or simply delegating to the series of artificial measures SystemPart dummyPart = system.getFirstRealPart() .createDummyPart(current.part.getId()); visit(dummyPart); } // If we have exported a measure, we are no longer in the first system if (!isFirst.measure) { isFirst.system = false; } return false; // No default browsing this way } // visit SystemPart // @Override public boolean visit (SystemPart systemPart) { ///logger.info("Visiting " + systemPart); // Delegate to texts for (TreeNode node : systemPart.getTexts()) { ((Text) node).accept(this); } // Delegate to measures for (TreeNode node : systemPart.getMeasures()) { ((Measure) node).accept(this); } return false; // No default browsing this way } // visit Text // @Override public boolean visit (Text text) { ///logger.info("Visiting " + text); // Safer if (text.getContent() == null) { return false; } switch (text.getSentence() .getTextRole()) { case Title : getWork() .setWorkTitle(text.getContent()); break; case Number : getWork() .setWorkNumber(text.getContent()); break; case Rights : { // Rights TypedText typedText = factory.createTypedText(); typedText.setValue(text.getContent()); scorePartwise.getIdentification() .getRights() .add(typedText); } break; case Creator : { // Creator TypedText typedText = factory.createTypedText(); typedText.setValue(text.getContent()); CreatorText creatorText = (CreatorText) text; if (creatorText.getCreatorType() != null) { typedText.setType(creatorText.getCreatorType().toString()); } scorePartwise.getIdentification() .getCreator() .add(typedText); } break; default : // LyricsItem, Direction // Handle them through related Note return false; } // Credits Credit pmCredit = factory.createCredit(); FormattedText creditWords = factory.createFormattedText(); creditWords.setValue(text.getContent()); creditWords.setFontSize("" + text.getFontSize()); // Position is wrt to page PagePoint pt = text.getSystem() .toPagePoint(text.getLocation()); creditWords.setDefaultX(toTenths(pt.x)); creditWords.setDefaultY(toTenths(score.getDimension().height - pt.y)); pmCredit.getLinkOrBookmarkOrCreditImage() .add(creditWords); scorePartwise.getCredit() .add(pmCredit); return true; } // visit TimeSignature // @Override public boolean visit (TimeSignature timeSignature) { ///logger.info("Visiting " + timeSignature); try { Time time = factory.createTime(); // Beats time.getBeatsAndBeatType() .add( factory.createTimeBeats("" + timeSignature.getNumerator())); // BeatType time.getBeatsAndBeatType() .add( factory.createTimeBeatType("" + timeSignature.getDenominator())); // Symbol ? if (timeSignature.getShape() != null) { switch (timeSignature.getShape()) { case COMMON_TIME : time.setSymbol(TimeSymbol.COMMON); break; case CUT_TIME : time.setSymbol(TimeSymbol.CUT); break; } } // Trick: add this time signature only if it does not already exist List<Time> times = getMeasureAttributes() .getTime(); for (Time t : times) { if (areEqual(t, time)) { return true; // Already inserted, so give up } } times.add(time); } catch (InvalidTimeSignature ex) { } return true; } // visit Tuplet // @Override public boolean visit (Tuplet tuplet) { proxymusic.Tuplet pmTuplet = factory.createTuplet(); getNotations() .getTiedOrSlurOrTuplet() .add(pmTuplet); // Bracket // TODO // Placement if (tuplet.getChord() == current.note.getChord()) { // i.e. start pmTuplet.setPlacement( (tuplet.getCenter().y <= current.note.getCenter().y) ? AboveBelow.ABOVE : AboveBelow.BELOW); } // Type pmTuplet.setType( (tuplet.getChord() == current.note.getChord()) ? StartStop.START : StartStop.STOP); // Number Integer num = tupletNumbers.get(tuplet); if (num != null) { pmTuplet.setNumber(num); tupletNumbers.remove(tuplet); // Release the number } else { // Determine first available number for (num = 1; num <= 6; num++) { if (!tupletNumbers.containsValue(num)) { tupletNumbers.put(tuplet, num); pmTuplet.setNumber(num); break; } } } return false; } // visit Wedge // @Override public boolean visit (Wedge wedge) { Direction direction = factory.createDirection(); current.pmMeasure.getNoteOrBackupOrForward() .add(direction); DirectionType directionType = factory.createDirectionType(); direction.getDirectionType() .add(directionType); proxymusic.Wedge pmWedge = factory.createWedge(); directionType.setWedge(pmWedge); // Spread pmWedge.setSpread(toTenths(wedge.getSpread())); // Start or stop ? if (wedge.isStart()) { // Type pmWedge.setType( (wedge.getShape() == Shape.CRESCENDO) ? WedgeType.CRESCENDO : WedgeType.DIMINUENDO); // Staff ? Staff staff = current.note.getStaff(); insertStaffId(direction, staff); // Placement direction.setPlacement( (wedge.getPoint().y < current.note.getCenter().y) ? AboveBelow.ABOVE : AboveBelow.BELOW); // default-y pmWedge.setDefaultY(yOf(wedge.getPoint(), staff)); } else { // It's a stop pmWedge.setType(WedgeType.STOP); } // // Relative-x (No offset for the time being) using note left side // pmWedge.setRelativeX( // toTenths(wedge.getPoint().x - current.note.getCenterLeft().x)); // default-x pmWedge.setDefaultX( toTenths(wedge.getPoint().x - current.measure.getLeftX())); return true; } // visit DirectionStatement // @Override public boolean visit (DirectionStatement words) { if (words.getText() .getContent() != null) { Direction direction = factory.createDirection(); current.pmMeasure.getNoteOrBackupOrForward() .add(direction); DirectionType directionType = factory.createDirectionType(); direction.getDirectionType() .add(directionType); FormattedText pmWords = factory.createFormattedText(); directionType.getWords() .add(pmWords); pmWords.setValue(words.getText().getContent()); // Placement direction.setPlacement( (words.getPoint().y < current.note.getCenter().y) ? AboveBelow.ABOVE : AboveBelow.BELOW); // default-y Staff staff = current.note.getStaff(); pmWords.setDefaultY(yOf(words.getPoint(), staff)); // font-size pmWords.setFontSize("" + words.getText().getFontSize()); // relative-x pmWords.setRelativeX( toTenths(words.getPoint().x - current.note.getCenterLeft().x)); } return true; } // getDen // A VERIFIER A VERIFIER A VERIFIER A VERIFIER A VERIFIER private static java.lang.String getDen (Time time) { for (JAXBElement<java.lang.String> elem : time.getBeatsAndBeatType()) { if (elem.getName() .getLocalPart() .equals("beat-type")) { return elem.getValue(); } } logger.severe("No denominator found in " + time); return ""; } // getNum // A VERIFIER A VERIFIER A VERIFIER A VERIFIER A VERIFIER private static java.lang.String getNum (Time time) { for (JAXBElement<java.lang.String> elem : time.getBeatsAndBeatType()) { if (elem.getName() .getLocalPart() .equals("beats")) { return elem.getValue(); } } logger.severe("No numerator found in " + time); return ""; } // isDesired // /** * Check whether the provided measure is to be exported * * @param measure the measure to check * @return true is desired */ private boolean isDesired (Measure measure) { return (measureRange == null) || // No range : take all of them (measure.isTemporary()) || // A temporary measure for export measureRange.contains(measure.getId()); // Part of the range } // areEqual // private static boolean areEqual (Time left, Time right) { return (getNum(left).equals(getNum(right))) && (getDen(left).equals(getDen(right))); } // areEqual // private static boolean areEqual (Key left, Key right) { return left.getFifths() .equals(right.getFifths()); } // getMeasureAttributes // /** * Report (after creating it if necessary) the measure attributes element * * @return the measure attributes element */ private Attributes getMeasureAttributes () { if (current.attributes == null) { current.attributes = new Attributes(); current.pmMeasure.getNoteOrBackupOrForward() .add(current.attributes); } return current.attributes; } // isNewClef // /** * Make sure we have a NEW clef, not already assigned. We have to go back * (on the same staff) in current measure, then in previous measures, * then in same staff in previous systems, until we find a previous clef. * And we compare the two shapes. * @param clef the potentially new clef * @return true if this clef is really new */ private boolean isNewClef (Clef clef) { if (current.measure.isDummy()) { return true; } // Perhaps another clef before this one ? Clef previousClef = current.measure.getClefBefore( new SystemPoint(clef.getCenter().x - 1, clef.getCenter().y)); if (previousClef != null) { return previousClef.getShape() != clef.getShape(); } return true; // Since no previous clef found } // isNewKeySignature // /** * Make sure we have a NEW key, not already assigned. We have to go back * in current measure, then in current staff, then in same staff in previous * systems, until we find a previous key. And we compare the two shapes. * @param key the potentially new key * @return true if this key is really new */ private boolean isNewKeySignature (KeySignature key) { if (current.measure.isDummy()) { return true; } // Perhaps another key before this one ? KeySignature previousKey = current.measure.getKeyBefore( key.getCenter()); if (previousKey != null) { return !previousKey.getKey() .equals(key.getKey()); } return true; // Since no previous key found } // getNotations // /** * Report (after creating it if necessary) the notations element of the * current note * * @return the note notations element */ private Notations getNotations () { // Notations allocated? if (current.notations == null) { current.notations = factory.createNotations(); current.pmNote.getNotations() .add(current.notations); } return current.notations; } // getOrnaments // /** * Report (after creating it if necessary) the ornaments elements in the * notations element of the current note * * @return the note notations ornaments element */ private Ornaments getOrnaments () { for (Object obj : getNotations() .getTiedOrSlurOrTuplet()) { if (obj instanceof Ornaments) { return (Ornaments) obj; } } // Need to allocate ornaments Ornaments ornaments = factory.createOrnaments(); getNotations() .getTiedOrSlurOrTuplet() .add(ornaments); return ornaments; } // getWork // private Work getWork () { if (current.pmWork == null) { current.pmWork = factory.createWork(); scorePartwise.setWork(current.pmWork); } return current.pmWork; } // insertBackup // private void insertBackup (int delta) { try { Backup backup = factory.createBackup(); backup.setDuration(createDecimal(score.simpleDurationOf(delta))); current.pmMeasure.getNoteOrBackupOrForward() .add(backup); } catch (Exception ex) { if (score.getDurationDivisor() != null) { logger.warning("Not able to insert backup", ex); } } } // insertForward // private void insertForward (int delta, Chord chord) { try { Forward forward = factory.createForward(); forward.setDuration(createDecimal(score.simpleDurationOf(delta))); forward.setVoice("" + current.voice.getId()); current.pmMeasure.getNoteOrBackupOrForward() .add(forward); // Staff ? (only if more than one staff in part) insertStaffId(forward, chord.getStaff()); } catch (Exception ex) { if (score.getDurationDivisor() != null) { logger.warning("Not able to insert forward", ex); } } } // insertStaffId // /** * If needed (if current part contains more than one staff), we insert the * id of the staff related to the element at hand * * @param obj the element at hand * @staff the related score staff */ @SuppressWarnings("unchecked") private void insertStaffId (Object obj, Staff staff) { if (current.part.isMultiStaff()) { Class classe = obj.getClass(); try { Method method = classe.getMethod("setStaff", BigInteger.class); method.invoke(obj, new BigInteger("" + staff.getId())); } catch (Exception ex) { ex.printStackTrace(); logger.severe("Could not setStaff for element " + classe); } } } // Current // /** Keep references of all current entities */ private static class Current { // Score dependent proxymusic.Work pmWork; // Part dependent ScorePart part; proxymusic.ScorePartwise.Part pmPart; // System dependent ScoreSystem system; // Measure dependent Measure measure; proxymusic.ScorePartwise.Part.Measure pmMeasure; Voice voice; // Note dependent omr.score.entity.Note note; proxymusic.Note pmNote; proxymusic.Notations notations; proxymusic.Print pmPrint; proxymusic.Attributes attributes; // Cleanup at end of measure void endMeasure () { measure = null; pmMeasure = null; voice = null; endNote(); } // Cleanup at end of note void endNote () { note = null; pmNote = null; notations = null; pmPrint = null; attributes = null; } } // IsFirst // /** Composite flag to help drive processing of any entity */ private static class IsFirst { /** We are writing the first part of the score */ boolean part; /** We are writing the first system in the current page */ boolean system; /** We are writing the first measure in current system (in current part) */ boolean measure; @Override public java.lang.String toString () { StringBuilder sb = new StringBuilder(); if (part) { sb.append(" firstPart"); } if (system) { sb.append(" firstSystem"); } if (measure) { sb.append(" firstMeasure"); } return sb.toString(); } } // Loader // private static class Loader extends Worker<Void> { @Override public Void construct () { try { Marshalling.getContext(); } catch (JAXBException ex) { logger.warning("Error preloading JaxbContext", ex); } return null; } } }
package nl.b3p.viewer.config.services; import java.util.*; import javax.persistence.*; import nl.b3p.viewer.config.ClobElement; import nl.b3p.web.WaitPageStatus; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.stripesstuff.stripersist.Stripersist; /** * * @author Matthijs Laan */ @Entity @DiscriminatorColumn(name="protocol") public abstract class GeoService { public static final String PARAM_ONLINE_CHECK_ONLY = "onlineCheckOnly"; public static final String DETAIL_OVERRIDDEN_URL = "overridenUrl"; public static final String DETAIL_ORIGINAL_NAME = "originalName"; @Id private Long id; @Basic(optional=false) private String name; @ManyToOne(fetch=FetchType.LAZY) private Category category; @Basic(optional=false) private String url; private String username; private String password; private boolean monitoringEnabled; private boolean monitoringStatusOK = true; @OneToOne(cascade=CascadeType.PERSIST) private Layer topLayer; @ElementCollection @Column(name="keyword") private Set<String> keywords = new HashSet<String>(); @Transient private List<Layer> layers; @Transient private Map<Layer,List<Layer>> childrenByParent = null; @Basic(optional=false) @Temporal(TemporalType.TIMESTAMP) private Date authorizationsModified = new Date(); @ElementCollection @JoinTable(joinColumns=@JoinColumn(name="geoservice")) private Map<String,ClobElement> details = new HashMap<String,ClobElement>(); @OneToMany(cascade=CascadeType.PERSIST) // Actually @OneToMany, workaround for HHH-1268 @JoinTable(inverseJoinColumns=@JoinColumn(name="style_library")) @OrderColumn(name="list_index") private List<StyleLibrary> styleLibraries = new ArrayList(); //<editor-fold defaultstate="collapsed" desc="getters en setters"> public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } public Layer getTopLayer() { return topLayer; } public void setTopLayer(Layer topLayer) { this.topLayer = topLayer; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Set<String> getKeywords() { return keywords; } public void setKeywords(Set<String> keywords) { this.keywords = keywords; } public boolean isMonitoringEnabled() { return monitoringEnabled; } public void setMonitoringEnabled(boolean monitoringEnabled) { this.monitoringEnabled = monitoringEnabled; } public Date getAuthorizationsModified() { return authorizationsModified; } public void setAuthorizationsModified(Date authorizationsModified) { this.authorizationsModified = authorizationsModified; } public boolean isMonitoringStatusOK() { return monitoringStatusOK; } public void setMonitoringStatusOK(boolean monitoringStatusOK) { this.monitoringStatusOK = monitoringStatusOK; } public Map<String, ClobElement> getDetails() { return details; } public void setDetails(Map<String, ClobElement> details) { this.details = details; } public List<StyleLibrary> getStyleLibraries() { return styleLibraries; } public void setStyleLibraries(List<StyleLibrary> styleLibraries) { this.styleLibraries = styleLibraries; } //</editor-fold> @PreRemove public void removeAllLayers() { EntityManager em = Stripersist.getEntityManager(); List<Layer> allLayers = em.createQuery("from Layer where service = :this") .setParameter("this", this) .getResultList(); for(Layer l: allLayers) { l.getChildren().clear(); em.remove(l); } } public void initLayerCollectionsForUpdate() { EntityManager em = Stripersist.getEntityManager(); // Use separate query instead of one combined one: may lead to lots of // duplicate fields depending on the size of each collection em.createQuery("from Layer l left join fetch l.crsList where l.service = :this").setParameter("this", this).getResultList(); em.createQuery("from Layer l left join fetch l.boundingBoxes where l.service = :this").setParameter("this", this).getResultList(); em.createQuery("from Layer l left join fetch l.keywords where l.service = :this").setParameter("this", this).getResultList(); em.createQuery("from Layer l left join fetch l.details where l.service = :this").setParameter("this", this).getResultList(); em.createQuery("from Layer l left join fetch l.children where l.service = :this").setParameter("this", this).getResultList(); } public GeoService loadFromUrl(String url, Map params) throws Exception { return loadFromUrl(url, params, new WaitPageStatus()); } public abstract GeoService loadFromUrl(String url, Map params, WaitPageStatus waitStatus) throws Exception; protected static void setAllChildrenDetail(Layer layer) { layer.accept(new Layer.Visitor() { @Override public boolean visit(final Layer l) { if(!l.getChildren().isEmpty()) { final MutableObject<List<String>> layerNames = new MutableObject<List<String>>(new ArrayList()); l.accept(new Layer.Visitor() { @Override public boolean visit(Layer child) { if(child != l && child.getChildren().isEmpty() && !child.isVirtual()) { layerNames.getValue().add(child.getName()); } return true; } }); if(!layerNames.getValue().isEmpty()) { l.getDetails().put(Layer.DETAIL_ALL_CHILDREN, new ClobElement(StringUtils.join(layerNames.getValue(), ","))); l.setVirtual(false); } } return true; } }); } public void checkOnline() throws Exception { Map params = new HashMap(); params.put(PARAM_ONLINE_CHECK_ONLY, Boolean.TRUE); loadFromUrl(getUrl(), params, new WaitPageStatus() { @Override public void setCurrentAction(String currentAction) { // no debug logging super.currentAction.set(currentAction); } @Override public void addLog(String message) { // no debug logging logs.add(message); } }); } public String getProtocol() { return getClass().getAnnotation(DiscriminatorValue.class).value(); } public void authorizationsModified() { authorizationsModified = new Date(); } /** To prevent a lot of SQL requests walking a tree structure of entities, * load all layers using an efficient query. The Layers.children collections * are not initialized, but can be reconstructed from the list of all Layers * for this service returned by the query. Call Layer.getLayerChildrenCache() * to retrieve it without causing a SQL query. * * The cache is not updated on changes, so will only represent the database * state when loadLayerTree() was last called. */ public List<Layer> loadLayerTree() { if(layers != null) { return layers; } if(!Stripersist.getEntityManager().contains(this)) { // Not a persistent entity (for example when loading user specified // service) return Collections.EMPTY_LIST; } // Retrieve layer tree structure in single query layers = Stripersist.getEntityManager().createNamedQuery("getLayerTree") .setParameter("rootId", topLayer.getId()) .getResultList(); childrenByParent = new HashMap<Layer,List<Layer>>(); for(Layer l: layers) { if(l.getParent() != null) { List<Layer> parentChildren = childrenByParent.get(l.getParent()); if(parentChildren == null) { parentChildren = new ArrayList<Layer>(); childrenByParent.put(l.getParent(), parentChildren); } parentChildren.add(l); } } return layers; } public List<Layer> getLayerChildrenCache(Layer l) { if(childrenByParent != null) { EntityManager em = Stripersist.getEntityManager(); if(!em.getEntityManagerFactory().getPersistenceUnitUtil().isLoaded(l.getChildren())) { List<Layer> childrenList = childrenByParent.get(l); if(childrenList == null) { return Collections.EMPTY_LIST; } else { return childrenList; } } else { return l.getChildren(); } } else { return l.getChildren(); } } public JSONObject toJSONObject(boolean includeLayerTree, Set<String> layersToInclude) throws JSONException { JSONObject o = new JSONObject(); o.put("id", id); o.put("name", name); o.put("url", url); o.put("protocol", getProtocol()); JSONObject jStyleLibraries = new JSONObject(); for(StyleLibrary sld: getStyleLibraries()) { JSONObject jsld = new JSONObject(); jStyleLibraries.put("sld:" + sld.getId(),jsld); jsld.put("id", sld.getId()); jsld.put("title", sld.getTitle()); jsld.put("default", sld.isDefaultStyle()); if(sld.isDefaultStyle()) { o.put("defaultStyleLibrary", jsld); } if(sld.getExternalUrl() != null) { jsld.put("externalUrl", sld.getExternalUrl()); } JSONObject userStylesPerNamedLayer = new JSONObject(); if(sld.getNamedLayerUserStylesJson() != null) { userStylesPerNamedLayer = new JSONObject(sld.getNamedLayerUserStylesJson()); } jsld.put("userStylesPerNamedLayer", userStylesPerNamedLayer); if(sld.getExtraLegendParameters() != null) { jsld.put("extraLegendParameters", sld.getExtraLegendParameters()); } jsld.put("hasBody", sld.getExternalUrl() == null); } o.put("styleLibraries", jStyleLibraries); if(topLayer != null) { if(Stripersist.getEntityManager().contains(this)) { List<Layer> layerEntities = loadLayerTree(); if(!layerEntities.isEmpty()) { // Prevent n+1 queries Stripersist.getEntityManager().createQuery("from Layer l " + "left join fetch l.details " + "where l in (:layers)") .setParameter("layers", layerEntities) .getResultList(); } } JSONObject layers = new JSONObject(); o.put("layers", layers); walkLayerJSONFlatten(topLayer, layers, layersToInclude); if(includeLayerTree) { o.put("topLayer", walkLayerJSONTree(topLayer)); } } return o; } private static void walkLayerJSONFlatten(Layer l, JSONObject layers, Set<String> layersToInclude) throws JSONException { /* TODO check readers (and include readers in n+1 prevention query */ /* Flatten tree structure, currently depth-first - later traversed layers * do not overwrite earlier layers with the same name - do not include * virtual layers */ if(layersToInclude == null || layersToInclude.contains(l.getName())) { if(!l.isVirtual() && l.getName() != null && !layers.has(l.getName())) { layers.put(l.getName(), l.toJSONObject()); } } for(Layer child: l.getCachedChildren()) { walkLayerJSONFlatten(child, layers, layersToInclude); } } private static JSONObject walkLayerJSONTree(Layer l) throws JSONException { JSONObject j = l.toJSONObject(); List<Layer> children = l.getCachedChildren(); if(!children.isEmpty()) { JSONArray jc = new JSONArray(); j.put("children", jc); for(Layer child: children) { jc.put(walkLayerJSONTree(child)); } } return j; } public JSONObject toJSONObject(boolean includeLayerTree) throws JSONException { return toJSONObject(includeLayerTree, null); } /** * Gets a single layer without loading all layers. If multiple layers exist * with the same name, a random non-virtual layer is returned. */ public Layer getSingleLayer(final String layerName) { try { return (Layer)Stripersist.getEntityManager().createQuery( "from Layer where service = :service " + "and name = :n order by virtual desc") .setParameter("service", this) .setParameter("n", layerName) .setMaxResults(1) .getSingleResult(); } catch (NoResultException nre) { return null; } } /** * Returns the layer with the given name in this server. The first layer in * a depth-first tree traversal with the name is returned. If a child has * the same name as its parent, the child is returned. * @param layerName the layer name to search for * @return the Layer or null if not found */ public Layer getLayer(final String layerName) { loadLayerTree(); if(layerName == null || topLayer == null) { return null; } final MutableObject<Layer> layer = new MutableObject(null); topLayer.accept(new Layer.Visitor() { @Override public boolean visit(Layer l) { if(StringUtils.equals(l.getName(),layerName)) { layer.setValue(l); return false; } return true; } }); return layer.getValue(); } }
package fr.bmartel.android.apkchecker; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; import java.security.spec.InvalidKeySpecException; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import sun.security.pkcs.PKCS7; import Decoder.BASE64Encoder; public class Main { public static String DEFAULT_FOLDER = "temp"; public static void main(String[] args) throws IOException { boolean isList = false; boolean isVerify = false; boolean isCompare = false; boolean countingApk = false; List<ApkObject> apkList = new ArrayList<ApkObject>(); if (args.length > 0) { for (int i = 0; i < args.length; i++) { if (args[i].equals("-l") || args[i].equals("-list")) { isList = true; countingApk = true; } else if (args[i].equals("-v") || args[i].equals("-verify")) { countingApk = false; isVerify = true; } else if (args[i].equals("-c") || args[i].equals("-comparePubkey")) { countingApk = false; isCompare = true; } else if (countingApk) { apkList.add(new ApkObject(args[i])); } } } else { dispalyUsage(); } if (apkList.size() > 0) { if (isVerify) { for (int i = 0; i < apkList.size(); i++) { CheckJarIntegrity check = new CheckJarIntegrity(); try { boolean status = check.verifyJar(apkList.get(i).getFilePath()); if (status) { System.out.println("[APK CHECKER] " + apkList.get(i).getFilePath() + " verification [ OK ]"); } else { System.out.println("[APK CHECKER] " + apkList.get(i).getFilePath() + " verification [ FAILURE ]"); return; } } catch (Exception e) { e.printStackTrace(); return; } } } if (isCompare) { for (int i = 0; i < apkList.size(); i++) { try { extractCertFromApk(apkList.get(i).getFilePath()); String publicKey = getPublicKey(DEFAULT_FOLDER + File.separator + "META-INF/CERT.RSA"); apkList.get(i).setPublicKey(publicKey); } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { e.printStackTrace(); return; } } for (int i = 0; i < apkList.size(); i++) { if (i + 1 < apkList.size()) { if (!apkList.get(i).getPublicKey().equals(apkList.get(i + 1).getPublicKey())) { System.out.println("[APK CHECKER] apk public key not shared for " + apkList.get(i).getFilePath() + " and " + apkList.get(i + 1).getFilePath() + " [ FAILURE ]"); return; } else { System.out.println("[APK CHECKER] apk public key shared for " + apkList.get(i).getFilePath() + " and " + apkList.get(i + 1).getFilePath() + " [ OK ]"); } } } } System.out.println("[APK CHECKER] Apks refer to the same Android application"); } else { System.out.println("Error apk list is empty"); } } /** * Retrieve public key from PKCS7 certificate * * @param certPath * @return * @throws IOException * @throws InvalidKeySpecException * @throws NoSuchAlgorithmException */ public static String getPublicKey(String certPath) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException { File f = new File(certPath); FileInputStream is = new FileInputStream(f); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); PKCS7 test = new PKCS7(buffer.toByteArray()); X509Certificate[] certs = test.getCertificates(); for (int i = 0; i < certs.length; i++) { if (certs[i] != null && certs[i].getPublicKey() != null) { return new BASE64Encoder().encode(certs[i].getPublicKey().getEncoded()); } } return ""; } public static void extractCertFromApk(String apkFile) throws IOException { File file = new File(apkFile); File folder = new File(DEFAULT_FOLDER); if (!folder.exists()) { folder.mkdir(); } ZipInputStream zipStream = new ZipInputStream(new FileInputStream(file)); ZipEntry zipEntry = zipStream.getNextEntry(); byte[] buffer = new byte[1024]; while (zipEntry != null) { String fileName = zipEntry.getName(); if (fileName.equals("META-INF/CERT.RSA")) { File newFile = new File(DEFAULT_FOLDER + File.separator + fileName); // create all non exists folders // else you will hit // FileNotFoundException for compressed folder new File(newFile.getParent()).mkdirs(); FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zipStream.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); break; } zipEntry = zipStream.getNextEntry(); } zipStream.closeEntry(); zipStream.close(); } private static void dispalyUsage() { System.out.println("Usage : java -jar apkChecker.jar -l <apks> <options>"); System.out.println("-l / -list : list of jars with separated with empty space(s)"); System.out.println("-v / -verify : verify java archive"); System.out.println("-c / -comparePubkey : compare public keys of jars"); } }
package com.haskforce.parsing; import com.haskforce.parsing.jsonParser.JsonParser; import com.haskforce.parsing.srcExtsDatatypes.*; import com.intellij.lang.ASTNode; import com.intellij.lang.PsiBuilder; import com.intellij.lang.PsiParser; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; import static com.haskforce.parsing.HaskellTypes2.*; // These can be imported as * when the old parser is removed. import static com.haskforce.psi.HaskellTypes.OPENPRAGMA; import static com.haskforce.psi.HaskellTypes.CLOSEPRAGMA; import static com.haskforce.psi.HaskellTypes.OPENCOM; import static com.haskforce.psi.HaskellTypes.CLOSECOM; import static com.haskforce.psi.HaskellTypes.CPPIF; import static com.haskforce.psi.HaskellTypes.CPPELSE; import static com.haskforce.psi.HaskellTypes.CPPENDIF; import static com.haskforce.psi.HaskellTypes.COMMENT; import static com.haskforce.psi.HaskellTypes.COMMENTTEXT; import static com.haskforce.psi.HaskellTypes.DOUBLEQUOTE; import static com.haskforce.psi.HaskellTypes.STRINGTOKEN; import static com.haskforce.psi.HaskellTypes.BADSTRINGTOKEN; import static com.haskforce.psi.HaskellTypes.MODULE; import static com.haskforce.psi.HaskellTypes.WHERE; import static com.haskforce.psi.HaskellTypes.PRAGMA; import static com.haskforce.psi.HaskellTypes.EQUALS; import static com.haskforce.psi.HaskellTypes.IMPORT; import static com.haskforce.psi.HaskellTypes.QUALIFIED; import static com.haskforce.psi.HaskellTypes.HIDING; import static com.haskforce.psi.HaskellTypes.PERIOD; import static com.haskforce.psi.HaskellTypes.DOUBLEPERIOD; import static com.haskforce.psi.HaskellTypes.RPAREN; import static com.haskforce.psi.HaskellTypes.LPAREN; import static com.haskforce.psi.HaskellTypes.RBRACKET; import static com.haskforce.psi.HaskellTypes.LBRACKET; import static com.haskforce.psi.HaskellTypes.AS; import static com.haskforce.psi.HaskellTypes.TYPE; import static com.haskforce.psi.HaskellTypes.DATA; import static com.haskforce.psi.HaskellTypes.IN; import static com.haskforce.psi.HaskellTypes.DOUBLECOLON; import static com.haskforce.psi.HaskellTypes.COLON; import static com.haskforce.psi.HaskellTypes.COMMA; import static com.haskforce.psi.HaskellTypes.RIGHTARROW; import static com.haskforce.psi.HaskellTypes.LEFTARROW; import static com.haskforce.psi.HaskellTypes.MINUS; import static com.haskforce.psi.HaskellTypes.DO; import static com.haskforce.psi.HaskellTypes.BACKSLASH; import static com.haskforce.psi.HaskellTypes.HASH; import static com.haskforce.psi.HaskellTypes.FOREIGN; import static com.haskforce.psi.HaskellTypes.EXPORTTOKEN; import static com.haskforce.psi.HaskellTypes.DOUBLEARROW; import static com.haskforce.psi.HaskellTypes.BACKTICK; import static com.haskforce.psi.HaskellTypes.INSTANCE; import static com.haskforce.psi.HaskellTypes.LBRACE; import static com.haskforce.psi.HaskellTypes.RBRACE; import static com.haskforce.psi.HaskellTypes.EXLAMATION; // FIXME: Rename. import static com.haskforce.psi.HaskellTypes.PIPE; import static com.haskforce.psi.HaskellTypes.CHARTOKEN; import static com.haskforce.psi.HaskellTypes.LET; import static com.haskforce.psi.HaskellTypes.INTEGERTOKEN; import static com.haskforce.psi.HaskellTypes.VARIDREGEXP; import static com.haskforce.psi.HaskellTypes.ASTERISK; import static com.haskforce.psi.HaskellTypes.SINGLEQUOTE; import static com.haskforce.psi.HaskellTypes.DEFAULT; import static com.haskforce.psi.HaskellTypes.AMPERSAT; import static com.haskforce.psi.HaskellTypes.PLUS; import static com.haskforce.psi.HaskellTypes.TILDE; import static com.haskforce.psi.HaskellTypes.THEN; import static com.haskforce.psi.HaskellTypes.CASE; import static com.haskforce.psi.HaskellTypes.OF; import static com.haskforce.psi.HaskellTypes.SEMICOLON; import static com.haskforce.psi.HaskellTypes.DERIVING; import static com.haskforce.psi.HaskellTypes.FLOATTOKEN; import static com.haskforce.psi.HaskellTypes.IF; import static com.haskforce.psi.HaskellTypes.ELSE; /** * New Parser using parser-helper. */ public class HaskellParser2 implements PsiParser { private static final Logger LOG = Logger.getInstance(HaskellParser2.class); private final Project myProject; private final JsonParser myJsonParser; public HaskellParser2(@NotNull Project project) { myProject = project; myJsonParser = new JsonParser(project); } @NotNull @Override public ASTNode parse(IElementType root, PsiBuilder builder) { PsiBuilder.Marker rootMarker = builder.mark(); TopPair tp = myJsonParser.parse(builder.getOriginalText()); if (tp.error != null && !tp.error.isEmpty()) { // TODO: Parse failed. Possibly warn. Could be annoying. } IElementType e = builder.getTokenType(); while (!builder.eof() && (isInterruption(e) && e != OPENPRAGMA)) { if (e == COMMENT || e == OPENCOM) { parseComment(e, builder, tp.comments); e = builder.getTokenType(); } else if (e == CPPIF || e == CPPELSE || e == CPPENDIF) { // Ignore CPP-tokens, they are not fed to parser-helper anyways. builder.advanceLexer(); e = builder.getTokenType(); } else { throw new RuntimeException("Unexpected failure on:" + e.toString()); } } parseModule(builder, (Module) tp.moduleType, tp.comments); return chewEverything(rootMarker, root, builder); } private static ASTNode chewEverything(PsiBuilder.Marker marker, IElementType e, PsiBuilder builder) { while (!builder.eof()) { builder.advanceLexer(); } marker.done(e); ASTNode result = builder.getTreeBuilt(); // System.out.println("Psifile:" + builder.getTreeBuilt().getPsi().getContainingFile().getName()); return result; } /** * Parses a complete module. */ private static void parseModule(PsiBuilder builder, Module module, Comment[] comments) { parseModulePragmas(builder, module == null ? null : module.modulePragmas, comments); parseModuleHead(builder, module == null ? null : module.moduleHeadMaybe, comments); parseImportDecls(builder, module == null ? null : module.importDecls, comments); parseBody(builder, module == null ? null : module.decls, comments); } /** * Parses "module NAME [modulepragmas] [exportSpecList] where". */ private static void parseModuleHead(PsiBuilder builder, ModuleHead head, Comment[] comments) { IElementType e = builder.getTokenType(); if (e != MODULE) return; PsiBuilder.Marker moduleMark = builder.mark(); consumeToken(builder, MODULE); parseModuleName(builder, head == null ? null : head.moduleName, comments); // TODO: parseExportSpecList(builder, head.exportSpecList, comments); IElementType e2 = builder.getTokenType(); while (e2 != WHERE) { if (e2 == OPENPRAGMA) { parseGenericPragma(builder, null, comments); } else { builder.advanceLexer(); } e2 = builder.getTokenType(); } consumeToken(builder, WHERE); moduleMark.done(e); } private static void parseModuleName(PsiBuilder builder, ModuleName name, Comment[] comments) { builder.getTokenType(); // Need to getTokenType to advance lexer over whitespace. int startPos = builder.getCurrentOffset(); IElementType e = builder.getTokenType(); while ((name != null && (builder.getCurrentOffset() - startPos) < name.name.length()) || name == null && e != WHERE) { builder.remapCurrentToken(NAME); consumeToken(builder, NAME); e = builder.getTokenType(); if (e == PERIOD) builder.advanceLexer(); } } /** * Parses a list of import statements. */ private static void parseImportDecls(PsiBuilder builder, ImportDecl[] importDecls, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (isInterruption(e) || importDecls != null && i < importDecls.length) { if (e == CPPIF || e == CPPELSE || e == CPPENDIF) { builder.advanceLexer(); e = builder.getTokenType(); continue; } else if (e == OPENCOM) { parseComment(e, builder, comments); e = builder.getTokenType(); continue; } else if (e == OPENPRAGMA) { parseGenericPragma(builder, null, comments); e = builder.getTokenType(); continue; } if (e != IMPORT) return; parseImportDecl(builder, importDecls[i], comments); i++; e = builder.getTokenType(); } } /** * Returns true for elements that can occur anywhere in the tree, * for example comments or pragmas. */ private static boolean isInterruption(IElementType e) { return (e == CPPIF || e == CPPELSE || e == CPPENDIF || e == OPENCOM || e == OPENPRAGMA); } /** * Parses an import statement. */ private static void parseImportDecl(PsiBuilder builder, ImportDecl importDecl, Comment[] comments) { IElementType e = builder.getTokenType(); PsiBuilder.Marker importMark = builder.mark(); consumeToken(builder, IMPORT); IElementType e2 = builder.getTokenType(); if (e2 == QUALIFIED || (importDecl != null && importDecl.importQualified)) { consumeToken(builder, QUALIFIED); } parseModuleName(builder, importDecl == null ? null : importDecl.importModule, comments); e2 = builder.getTokenType(); if (e2 == AS || false) { // TODO: Update. consumeToken(builder, AS); e2 = builder.getTokenType(); parseModuleName(builder, importDecl == null ? null : importDecl.importAs, comments); e2 = builder.getTokenType(); } if (e2 == HIDING || false) { // (importDecl != null && importDecl.importSpecs)) { TODO: FIXME consumeToken(builder, HIDING); e2 = builder.getTokenType(); } int nest = e2 == LPAREN ? 1 : 0; while (nest > 0) { builder.advanceLexer(); e2 = builder.getTokenType(); if (e2 == LPAREN) { nest++; } else if (e2 == RPAREN) { nest } } if (e2 == RPAREN) consumeToken(builder, RPAREN); importMark.done(e); } /** * Parses a foreign import statement. */ private static void parseForeignImportDecl(PsiBuilder builder, ForImp importDecl, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, FOREIGN); consumeToken(builder, IMPORT); IElementType e2 = builder.getTokenType(); builder.advanceLexer(); // TODO: Parse 'ccall' etc. e2 = builder.getTokenType(); if (e2 != DOUBLEQUOTE) { // TODO: Parse safety. builder.advanceLexer(); e2 = builder.getTokenType(); } if (e2 == DOUBLEQUOTE || false) { parseStringLiteral(builder); } e2 = builder.getTokenType(); parseName(builder, importDecl.name, comments); e2 = builder.getTokenType(); consumeToken(builder, DOUBLECOLON); parseTypeTopType(builder, importDecl.type, comments); } /** * Parses a foreign export statement. */ private static void parseForeignExportDecl(PsiBuilder builder, ForExp forExp, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, FOREIGN); e = builder.getTokenType(); consumeToken(builder, EXPORTTOKEN); IElementType e2 = builder.getTokenType(); builder.advanceLexer(); // TODO: Parse 'ccall' etc. e2 = builder.getTokenType(); if (e2 == DOUBLEQUOTE || false) { parseStringLiteral(builder); } e2 = builder.getTokenType(); parseName(builder, forExp.name, comments); e2 = builder.getTokenType(); consumeToken(builder, DOUBLECOLON); parseTypeTopType(builder, forExp.type, comments); } private static void parseBody(PsiBuilder builder, DeclTopType[] decls, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (isInterruption(e) || decls != null && i < decls.length) { if (e == CPPIF || e == CPPELSE || e == CPPENDIF) { builder.advanceLexer(); e = builder.getTokenType(); continue; } else if (e == OPENCOM) { parseComment(e, builder, comments); e = builder.getTokenType(); continue; } else if (e == OPENPRAGMA) { parseGenericPragma(builder, null, comments); e = builder.getTokenType(); continue; } parseDecl(builder, decls[i], comments); e = builder.getTokenType(); i++; } } /** * Parse a list of declarations. */ private static void parseDecls(PsiBuilder builder, DeclTopType[] decl, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (decl != null && i < decl.length) { parseDecl(builder, decl[i], comments); i++; e = builder.getTokenType(); } } /** * Parse a single declaration. */ private static void parseDecl(PsiBuilder builder, DeclTopType decl, Comment[] comments) { IElementType e = builder.getTokenType(); // Pragmas are handled by the outer loop in parseBody, so they are no-ops. if (decl instanceof PatBind) { PsiBuilder.Marker declMark = builder.mark(); parsePatBind(builder, (PatBind) decl, comments); declMark.done(e); } else if (decl instanceof FunBind) { PsiBuilder.Marker declMark = builder.mark(); parseFunBind(builder, (FunBind) decl, comments); declMark.done(e); } else if (decl instanceof DataDecl) { PsiBuilder.Marker declMark = builder.mark(); parseDataDecl(builder, (DataDecl) decl, comments); declMark.done(e); } else if (decl instanceof TypeDecl) { PsiBuilder.Marker declMark = builder.mark(); parseTypeDecl(builder, (TypeDecl) decl, comments); declMark.done(e); } else if (decl instanceof DataInsDecl) { PsiBuilder.Marker declMark = builder.mark(); parseDataInstanceDecl(builder, (DataInsDecl) decl, comments); declMark.done(e); } else if (decl instanceof GDataInsDecl) { PsiBuilder.Marker declMark = builder.mark(); parseGDataInstanceDecl(builder, (GDataInsDecl) decl, comments); declMark.done(e); } else if (decl instanceof InstDecl) { PsiBuilder.Marker declMark = builder.mark(); parseInstDecl(builder, (InstDecl) decl, comments); declMark.done(e); } else if (decl instanceof DerivDecl) { PsiBuilder.Marker declMark = builder.mark(); parseDerivDecl(builder, (DerivDecl) decl, comments); declMark.done(e); } else if (decl instanceof InfixDecl) { PsiBuilder.Marker declMark = builder.mark(); parseInfixDecl(builder, (InfixDecl) decl, comments); declMark.done(e); } else if (decl instanceof DefaultDecl) { PsiBuilder.Marker declMark = builder.mark(); parseDefaultDecl(builder, (DefaultDecl) decl, comments); declMark.done(e); } else if (decl instanceof SpliceDecl) { PsiBuilder.Marker declMark = builder.mark(); parseExpTopType(builder, ((SpliceDecl) decl).exp, comments); declMark.done(e); } else if (decl instanceof TypeSig) { PsiBuilder.Marker declMark = builder.mark(); parseTypeSig(builder, (TypeSig) decl, comments); declMark.done(e); } else if (decl instanceof ForImp) { PsiBuilder.Marker declMark = builder.mark(); parseForeignImportDecl(builder, (ForImp) decl, comments); declMark.done(e); } else if (decl instanceof ForExp) { PsiBuilder.Marker declMark = builder.mark(); parseForeignExportDecl(builder, (ForExp) decl, comments); declMark.done(e); } else if (decl instanceof InlineSig) { // parseGenericPragma(builder, (InlineSig) decl, comments); } else if (decl instanceof InlineConlikeSig) { // parseGenericPragma(builder, (InlineConlikeSig) decl, comments); } else if (decl instanceof SpecSig) { // parseGenericPragma(builder, (SpecSig) decl, comments); } else if (decl instanceof SpecInlineSig) { // parseGenericPragma(builder, (SpecSig) decl, comments); } else if (decl instanceof RulePragmaDecl) { // parseGenericPragma(builder, (SpecSig) decl, comments); } else if (decl instanceof DeprPragmaDecl) { // parseGenericPragma(builder, (DeprPragmaDecl) decl, comments); } else if (decl instanceof WarnPragmaDecl) { // parseGenericPragma(builder, (WarnPragmaDecl) decl, comments); } else if (decl instanceof InstSig) { PsiBuilder.Marker declMark = builder.mark(); parseInstSig(builder, (InstSig) decl, comments); declMark.done(e); } else if (decl instanceof AnnPragma) { // parseGenericPragma(builder, (AnnPragma) decl, comments); } else { throw new RuntimeException("Unexpected decl type: " + decl.toString()); } } /** * Parse a pattern binding. */ private static void parsePatBind(PsiBuilder builder, PatBind patBind, Comment[] comments) { IElementType e = builder.getTokenType(); parsePatTopType(builder, patBind.pat, comments); if (patBind.type != null) throw new RuntimeException("Unexpected type in patbind"); // TODO: parseType(builder, patBind.type, comments); parseRhsTopType(builder, patBind.rhs, comments); if (patBind.binds != null) throw new RuntimeException("Unexpected binds in patbind"); } /** * Parse a function binding. */ private static void parseFunBind(PsiBuilder builder, FunBind funBind, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (funBind.match != null && i < funBind.match.length) { parseMatchTop(builder, funBind.match[i], comments); i++; } } /** * Parse a derive declaration. */ private static void parseDerivDecl(PsiBuilder builder, DerivDecl derivDecl, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, DERIVING); e = builder.getTokenType(); consumeToken(builder, INSTANCE); parseContextTopType(builder, derivDecl.contextMaybe, comments); e = builder.getTokenType(); parseInstHead(builder, derivDecl.instHead, comments); e = builder.getTokenType(); } /** * Parses an instance specialization. */ private static void parseInstSig(PsiBuilder builder, InstSig instSig, Comment[] comments) { IElementType e = builder.getTokenType(); parseGenericPragma(builder, null, null); e = builder.getTokenType(); // TODO: Improve precision of specialize instance pragma parsing. // parseContextTopType(builder, instSig.contextMaybe, comments); // e = builder.getTokenType(); // parseInstHead(builder, instSig.instHead, comments); // e = builder.getTokenType(); } /** * Parse a instance declaration. */ private static void parseInstDecl(PsiBuilder builder, InstDecl instDecl, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, INSTANCE); e = builder.getTokenType(); parseContextTopType(builder, instDecl.contextMaybe, comments); e = builder.getTokenType(); if (instDecl.contextMaybe != null) consumeToken(builder, DOUBLEARROW); parseInstHead(builder, instDecl.instHead, comments); e = builder.getTokenType(); consumeToken(builder, WHERE); parseInstDeclTopTypes(builder, instDecl.instDecls, comments); e = builder.getTokenType(); } /** * Parse a list of instance declarations. */ private static void parseInstDeclTopTypes(PsiBuilder builder, InstDeclTopType[] instDecls, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (instDecls != null && i < instDecls.length) { parseInstDeclTopType(builder, instDecls[i], comments); i++; } } /** * Parses a single instance declaration. */ private static void parseInstDeclTopType(PsiBuilder builder, InstDeclTopType decl, Comment[] comments) { IElementType e = builder.getTokenType(); if (decl instanceof InsDecl) { parseDecl(builder, ((InsDecl) decl).decl, comments); e = builder.getTokenType(); } else if (decl instanceof InsType) { throw new RuntimeException("InsType not implemented: " + decl.toString()); /* Preliminary implementation: parseTypeTopType(builder, ((InsType) decl).t1, comments); e = builder.getTokenType(); parseTypeTopType(builder, ((InsType) decl).t2, comments); e = builder.getTokenType(); */ } else if (decl instanceof InsData) { throw new RuntimeException("InsData not implemented:" + decl.toString()); } else if (decl instanceof InsGData) { throw new RuntimeException("InsGData not implemented:" + decl.toString()); } } /** * Parses a data declaration. */ private static void parseDataDecl(PsiBuilder builder, DataDecl dataDecl, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, DATA); parseDeclHead(builder, dataDecl.declHead, comments); e = builder.getTokenType(); if (e == EQUALS) consumeToken(builder, EQUALS); int i = 0; e = builder.getTokenType(); while (dataDecl.qualConDecls != null && i < dataDecl.qualConDecls.length) { parseQualConDecl(builder, dataDecl.qualConDecls[i], comments); i++; if (i < dataDecl.qualConDecls.length) { builder.advanceLexer(); e = builder.getTokenType(); } } } /** * Parses a data instance declaration. */ private static void parseDataInstanceDecl(PsiBuilder builder, DataInsDecl dataDecl, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, DATA); e = builder.getTokenType(); consumeToken(builder, INSTANCE); e = builder.getTokenType(); parseTypeTopType(builder, dataDecl.type, comments); e = builder.getTokenType(); if (e == EQUALS) consumeToken(builder, EQUALS); int i = 0; e = builder.getTokenType(); while (dataDecl.qualConDecls != null && i < dataDecl.qualConDecls.length) { parseQualConDecl(builder, dataDecl.qualConDecls[i], comments); i++; if (i < dataDecl.qualConDecls.length) { builder.advanceLexer(); e = builder.getTokenType(); } } e = builder.getTokenType(); if (dataDecl.derivingMaybe != null) throw new RuntimeException("TODO: deriving unimplemeted"); } /** * Parses a gadt-style data instance declaration. */ private static void parseGDataInstanceDecl(PsiBuilder builder, GDataInsDecl gDataInsDecl, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, DATA); e = builder.getTokenType(); consumeToken(builder, INSTANCE); e = builder.getTokenType(); parseTypeTopType(builder, gDataInsDecl.type, comments); e = builder.getTokenType(); parseKindTopType(builder, gDataInsDecl.kindMaybe, comments); e = builder.getTokenType(); if (e == WHERE) consumeToken(builder, WHERE); int i = 0; e = builder.getTokenType(); while (gDataInsDecl.gadtDecls != null && i < gDataInsDecl.gadtDecls.length) { parseGadtDecl(builder, gDataInsDecl.gadtDecls[i], comments); i++; if (i < gDataInsDecl.gadtDecls.length) { builder.advanceLexer(); e = builder.getTokenType(); } } e = builder.getTokenType(); if (gDataInsDecl.derivingMaybe != null) throw new RuntimeException("TODO: deriving unimplemeted"); } /** * Parse a single gadt-style declaration. */ private static void parseGadtDecl(PsiBuilder builder, GadtDecl gadtDecl, Comment[] comments) { IElementType e = builder.getTokenType(); parseName(builder, gadtDecl.name, comments); e = builder.getTokenType(); consumeToken(builder, DOUBLECOLON); e = builder.getTokenType(); parseTypeTopType(builder, gadtDecl.type, comments); e = builder.getTokenType(); } /** * Parses the left side of '=' in a data/type declaration. */ private static void parseDeclHead(PsiBuilder builder, DeclHeadTopType declHead, Comment[] comments) { IElementType e = builder.getTokenType(); if (declHead instanceof DHead) { parseName(builder, ((DHead) declHead).name, comments); e = builder.getTokenType(); parseTyVarBinds(builder, ((DHead) declHead).tyVars, comments); } else if (declHead instanceof DHInfix) { parseTyVarBind(builder, ((DHInfix) declHead).tb1, comments); e = builder.getTokenType(); parseName(builder, ((DHInfix) declHead).name, comments); e = builder.getTokenType(); parseTyVarBind(builder, ((DHInfix) declHead).tb2, comments); e = builder.getTokenType(); } else if (declHead instanceof DHParen) { consumeToken(builder, LPAREN); e = builder.getTokenType(); parseDeclHead(builder, ((DHParen) declHead).declHead, comments); e = builder.getTokenType(); consumeToken(builder, RPAREN); e = builder.getTokenType(); } } /** * Parses the left side of '=>' in an instance declaration. */ private static void parseInstHead(PsiBuilder builder, InstHeadTopType instHead, Comment[] comments) { IElementType e = builder.getTokenType(); if (instHead instanceof IHead) { parseQName(builder, ((IHead) instHead).qName, comments); e = builder.getTokenType(); parseTypeTopTypes(builder, ((IHead) instHead).types, comments); e = builder.getTokenType(); } else if (instHead instanceof IHInfix) { parseTypeTopType(builder, ((IHInfix) instHead).t1, comments); e = builder.getTokenType(); parseQName(builder, ((IHInfix) instHead).qName, comments); e = builder.getTokenType(); parseTypeTopType(builder, ((IHInfix) instHead).t2, comments); e = builder.getTokenType(); } else if (instHead instanceof IHParen) { consumeToken(builder, LPAREN); e = builder.getTokenType(); parseInstHead(builder, ((IHParen) instHead).instHead, comments); consumeToken(builder, RPAREN); e = builder.getTokenType(); } } /** * Parses the type variables in a data declaration. */ private static void parseTyVarBinds(PsiBuilder builder, TyVarBindTopType[] tyVarBindTopType, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (tyVarBindTopType != null && i < tyVarBindTopType.length) { parseTyVarBind(builder, tyVarBindTopType[i], comments); i++; } e = builder.getTokenType(); } /** * Parses the type variables in a data declaration. */ private static void parseTyVarBind(PsiBuilder builder, TyVarBindTopType tyVarBindTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (tyVarBindTopType instanceof KindedVar) { consumeToken(builder, LPAREN); e = builder.getTokenType(); parseName(builder, ((KindedVar) tyVarBindTopType).name, comments); e = builder.getTokenType(); consumeToken(builder, DOUBLECOLON); e = builder.getTokenType(); parseKindTopType(builder, ((KindedVar) tyVarBindTopType).kind, comments); consumeToken(builder, RPAREN); } else if (tyVarBindTopType instanceof UnkindedVar) { parseName(builder, ((UnkindedVar) tyVarBindTopType).name, comments); } e = builder.getTokenType(); } /** * Parses a type declaration. */ private static void parseTypeDecl(PsiBuilder builder, TypeDecl typeDecl, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, TYPE); parseDeclHead(builder, typeDecl.declHead, comments); e = builder.getTokenType(); if (e == EQUALS) consumeToken(builder, EQUALS); parseTypeTopType(builder, typeDecl.type, comments); e = builder.getTokenType(); } /** * Parses a type signature. */ private static void parseTypeSig(PsiBuilder builder, TypeSig dataDecl, Comment[] comments) { IElementType e = builder.getTokenType(); parseNames(builder, dataDecl.names, comments); e = builder.getTokenType(); consumeToken(builder, DOUBLECOLON); e = builder.getTokenType(); parseTypeTopType(builder, dataDecl.type, comments); } /** * Parses a qualified constructor declaration. */ private static void parseQualConDecl(PsiBuilder builder, QualConDecl qualConDecl, Comment[] comments) { IElementType e = builder.getTokenType(); parseConDecl(builder, qualConDecl == null ? null : qualConDecl.conDecl, comments); } /** * Parses a constructor declaration. */ private static void parseConDecl(PsiBuilder builder, ConDeclTopType conDecl, Comment[] comments) { if (conDecl instanceof ConDecl) { parseName(builder, ((ConDecl) conDecl).name, comments); IElementType e = builder.getTokenType(); parseBangTypes(builder, conDecl == null ? null : ((ConDecl) conDecl).bangTypes, comments); } else if (conDecl instanceof InfixConDecl) { IElementType e = builder.getTokenType(); parseBangType(builder, ((InfixConDecl) conDecl).b1, comments); e = builder.getTokenType(); parseName(builder, ((InfixConDecl) conDecl).name, comments); parseBangType(builder, ((InfixConDecl) conDecl).b2, comments); } else if (conDecl instanceof RecDecl) { parseName(builder, ((RecDecl) conDecl).name, comments); boolean layouted = false; IElementType e = builder.getTokenType(); if (e == LBRACE) { consumeToken(builder, LBRACE); e = builder.getTokenType(); layouted = true; } parseFieldDecls(builder, ((RecDecl) conDecl).fields, comments); e = builder.getTokenType(); if (layouted) { consumeToken(builder, RBRACE); e = builder.getTokenType(); } } } /** * Parses the field declarations in a GADT-style declaration. */ private static void parseFieldDecls(PsiBuilder builder, FieldDecl[] fieldDecls, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (fieldDecls != null && i < fieldDecls.length) { parseFieldDecl(builder, fieldDecls[i], comments); i++; } e = builder.getTokenType(); } /** * Parses a field declaration. */ private static void parseFieldDecl(PsiBuilder builder, FieldDecl fieldDecl, Comment[] comments) { IElementType e = builder.getTokenType(); parseNames(builder, fieldDecl.names, comments); e = builder.getTokenType(); consumeToken(builder, DOUBLECOLON); e = builder.getTokenType(); parseBangType(builder, fieldDecl.bang, comments); e = builder.getTokenType(); } /** * Parses a list of bang types. */ private static void parseBangTypes(PsiBuilder builder, BangTypeTopType[] bangTypes, Comment[] comments) { int i = 0; while (bangTypes != null && i < bangTypes.length) { parseBangType(builder, bangTypes[i], comments); i++; } } /** * Parses one bang type. */ private static void parseBangType(PsiBuilder builder, BangTypeTopType bangType, Comment[] comments) { IElementType e = builder.getTokenType(); // TODO: Refine bangType. if (bangType instanceof UnBangedTy) { parseTypeTopType(builder, ((UnBangedTy) bangType).type, comments); } else if (bangType instanceof BangedTy) { consumeToken(builder, EXLAMATION); parseTypeTopType(builder, ((BangedTy) bangType).type, comments); e = builder.getTokenType(); } else if (bangType instanceof UnpackedTy) { parseGenericPragma(builder, null, comments); consumeToken(builder, EXLAMATION); e = builder.getTokenType(); parseTypeTopType(builder, ((UnpackedTy) bangType).type, comments); e = builder.getTokenType(); } } private static void parseMatchTop(PsiBuilder builder, MatchTopType matchTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (matchTopType instanceof Match) { parseMatch(builder, (Match) matchTopType, comments); } else if (matchTopType instanceof InfixMatch) { parseInfixMatch(builder, (InfixMatch) matchTopType, comments); } } /** * Parses a single match. */ private static void parseMatch(PsiBuilder builder, Match match, Comment[] comments) { IElementType e = builder.getTokenType(); parseName(builder, match.name, comments); int i = 0; while (match.pats != null && i < match.pats.length) { parsePatTopType(builder, match.pats[i], comments); i++; } parseRhsTopType(builder, match.rhs, comments); e = builder.getTokenType(); if (e == WHERE) { consumeToken(builder, WHERE); parseBindsTopType(builder, match.bindsMaybe, comments); e = builder.getTokenType(); } } /** * Parses a single infix declaration. */ private static void parseInfixDecl(PsiBuilder builder, InfixDecl decl, Comment[] comments) { IElementType e = builder.getTokenType(); builder.advanceLexer(); // TOOD: Parse infix/infixl/infixr e = builder.getTokenType(); if (e == INTEGERTOKEN) consumeToken(builder, INTEGERTOKEN); e = builder.getTokenType(); int i = 0; while (decl.ops != null && i < decl.ops.length) { parseOp(builder, decl.ops[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) { consumeToken(builder, COMMA); e = builder.getTokenType(); } } } /** * Parses a single default declaration. */ private static void parseDefaultDecl(PsiBuilder builder, DefaultDecl decl, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, DEFAULT); e = builder.getTokenType(); consumeToken(builder, LPAREN); e = builder.getTokenType(); parseTypeTopTypes(builder, decl.types, comments); e = builder.getTokenType(); consumeToken(builder, RPAREN); } /** * Parses a single infix match. */ private static void parseInfixMatch(PsiBuilder builder, InfixMatch match, Comment[] comments) { IElementType e = builder.getTokenType(); boolean startParen = e == LPAREN && !(match.pat instanceof PParen); if (startParen) consumeToken(builder, LPAREN); e = builder.getTokenType(); parsePatTopType(builder, match.pat, comments); e = builder.getTokenType(); parseName(builder, match.name, comments); int i = 0; while (match.pats != null && i < match.pats.length) { parsePatTopType(builder, match.pats[i], comments); if (startParen && i == 0) { consumeToken(builder, RPAREN); e = builder.getTokenType(); } i++; } parseRhsTopType(builder, match.rhs, comments); e = builder.getTokenType(); if (e == WHERE) { consumeToken(builder, WHERE); parseBindsTopType(builder, match.bindsMaybe, comments); e = builder.getTokenType(); } } /** * Parses one binding. */ private static void parseBindsTopType(PsiBuilder builder, BindsTopType bindsTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (bindsTopType instanceof BDecls) { parseDecls(builder, ((BDecls) bindsTopType).decls, comments); } else if (bindsTopType instanceof IPBinds) { throw new RuntimeException("TODO: Implement IPBinds:" + bindsTopType.toString()); } } /** * Parses several patterns. */ private static void parsePatTopTypes(PsiBuilder builder, PatTopType[] pats, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while(pats != null && i < pats.length) { parsePatTopType(builder, pats[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) { consumeToken(builder, COMMA); e = builder.getTokenType(); } } } /** * Parses one pattern. */ private static void parsePatTopType(PsiBuilder builder, PatTopType patTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (patTopType instanceof PVar) { parsePVar(builder, (PVar) patTopType, comments); } else if (patTopType instanceof PLit) { parseLiteralTop(builder, ((PLit) patTopType).lit, comments); e = builder.getTokenType(); } else if (patTopType instanceof PNeg) { e = builder.getTokenType(); consumeToken(builder, MINUS); e = builder.getTokenType(); parsePatTopType(builder, ((PNeg) patTopType).pat, comments); e = builder.getTokenType(); } else if (patTopType instanceof PNPlusK) { e = builder.getTokenType(); parseName(builder, ((PNPlusK) patTopType).name, comments); e = builder.getTokenType(); consumeToken(builder, PLUS); e = builder.getTokenType(); consumeToken(builder, INTEGERTOKEN); e = builder.getTokenType(); } else if (patTopType instanceof PApp) { e = builder.getTokenType(); parseQName(builder, ((PApp) patTopType).qName, comments); e = builder.getTokenType(); parsePatTopTypes(builder, ((PApp) patTopType).pats, comments); e = builder.getTokenType(); } else if (patTopType instanceof PInfixApp) { e = builder.getTokenType(); parsePatTopType(builder, ((PInfixApp) patTopType).p1, comments); e = builder.getTokenType(); parseQName(builder, ((PInfixApp) patTopType).qName, comments); e = builder.getTokenType(); parsePatTopType(builder, ((PInfixApp) patTopType).p1, comments); e = builder.getTokenType(); } else if (patTopType instanceof PTuple) { consumeToken(builder, LPAREN); e = builder.getTokenType(); boolean unboxed = parseBoxed(builder, ((PTuple) patTopType).boxed, comments); parsePatTopTypes(builder, ((PTuple) patTopType).pats, comments); e = builder.getTokenType(); if (unboxed) { consumeToken(builder, HASH); e = builder.getTokenType(); } consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (patTopType instanceof PList) { consumeToken(builder, LBRACKET); parsePatTopTypes(builder, ((PList) patTopType).pats, comments); e = builder.getTokenType(); consumeToken(builder, RBRACKET); e = builder.getTokenType(); } else if (patTopType instanceof PParen) { consumeToken(builder, LPAREN); e = builder.getTokenType(); parsePatTopType(builder, ((PParen) patTopType).pat, comments); consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (patTopType instanceof PRec) { parseQName(builder, ((PRec) patTopType).qName, comments); e = builder.getTokenType(); consumeToken(builder, LBRACE); parsePatFieldTopTypes(builder, ((PRec) patTopType).patFields, comments); e = builder.getTokenType(); consumeToken(builder, RBRACE); e = builder.getTokenType(); } else if (patTopType instanceof PAsPat) { parseName(builder, ((PAsPat) patTopType).name, comments); e = builder.getTokenType(); consumeToken(builder, AMPERSAT); parsePatTopType(builder, ((PAsPat) patTopType).pat, comments); e = builder.getTokenType(); } else if (patTopType instanceof PWildCard) { builder.advanceLexer(); // TODO: Token.UNDERSCORE? e = builder.getTokenType(); } else if (patTopType instanceof PIrrPat) { consumeToken(builder, TILDE); e = builder.getTokenType(); parsePatTopType(builder, ((PIrrPat) patTopType).pat, comments); e = builder.getTokenType(); } else if (patTopType instanceof PatTypeSig) { parsePatTopType(builder, ((PatTypeSig) patTopType).pat, comments); e = builder.getTokenType(); consumeToken(builder, DOUBLECOLON); parseTypeTopType(builder, ((PatTypeSig) patTopType).type, comments); e = builder.getTokenType(); } else if (patTopType instanceof PViewPat) { parseExpTopType(builder, ((PViewPat) patTopType).exp, comments); e = builder.getTokenType(); consumeToken(builder, RIGHTARROW); parsePatTopType(builder, ((PViewPat) patTopType).pat, comments); e = builder.getTokenType(); } else if (patTopType instanceof PBangPat) { consumeToken(builder, EXLAMATION); e = builder.getTokenType(); parsePatTopType(builder, ((PBangPat) patTopType).pat, comments); e = builder.getTokenType(); } else { throw new RuntimeException("parsePatTopType" + patTopType.toString()); } } private static void parseComment(IElementType start, PsiBuilder builder, Comment[] comments) { PsiBuilder.Marker startCom = builder.mark(); IElementType e = builder.getTokenType(); while (e == COMMENT || e == COMMENTTEXT || e == OPENCOM || e == CLOSECOM) { builder.advanceLexer(); e = builder.getTokenType(); } startCom.done(start); } /** * Parses a group of module pragmas. */ private static void parseModulePragmas(PsiBuilder builder, ModulePragmaTopType[] modulePragmas, Comment[] comments) { int i = 0; while(modulePragmas != null && i < modulePragmas.length) { parseModulePragma(builder, modulePragmas[i], comments); i++; } } /** * Parses a module pragma. */ private static void parseModulePragma(PsiBuilder builder, ModulePragmaTopType modulePragmaTopType, Comment[] comments) { int i = 0; if (modulePragmaTopType instanceof LanguagePragma) { LanguagePragma langPragma = (LanguagePragma) modulePragmaTopType; IElementType e = builder.getTokenType(); PsiBuilder.Marker pragmaMark = builder.mark(); consumeToken(builder, OPENPRAGMA); consumeToken(builder, PRAGMA); while (langPragma.names != null && i < langPragma.names.length) { // TODO: Improve precision of pragma lexing. // parseName(builder, langPragma.names[i], comments); i++; } consumeToken(builder, CLOSEPRAGMA); pragmaMark.done(e); } else if (modulePragmaTopType instanceof OptionsPragma) { // FIXME: Use optionsPragma information. OptionsPragma optionsPragma = (OptionsPragma) modulePragmaTopType; IElementType e = builder.getTokenType(); PsiBuilder.Marker pragmaMark = builder.mark(); chewPragma(builder); consumeToken(builder, CLOSEPRAGMA); pragmaMark.done(e); } else if (modulePragmaTopType instanceof AnnModulePragma) { // FIXME: Use annModulePragma information. AnnModulePragma annModulePragma = (AnnModulePragma) modulePragmaTopType; IElementType e = builder.getTokenType(); PsiBuilder.Marker pragmaMark = builder.mark(); chewPragma(builder); consumeToken(builder, CLOSEPRAGMA); pragmaMark.done(e); } } /** * Parses a pattern variable. */ private static void parsePVar(PsiBuilder builder, PVar pVar, Comment[] comments) { parseName(builder, pVar.name, comments); } /** * Parses a group of GuardedRhss. */ private static void parseGuardedRhss(PsiBuilder builder, GuardedRhs[] rhss, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while(rhss != null && i < rhss.length) { parseGuardedRhs(builder, rhss[i], comments); i++; e = builder.getTokenType(); } } /** * Parses one GuardedRhs. */ private static void parseGuardedRhs(PsiBuilder builder, GuardedRhs rhs, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, PIPE); e = builder.getTokenType(); parseStmtTopTypes(builder, rhs.stmts, comments); e = builder.getTokenType(); consumeToken(builder, EQUALS); parseExpTopType(builder, rhs.exp, comments); e = builder.getTokenType(); } /** * Parses one Rhs. */ private static void parseRhsTopType(PsiBuilder builder, RhsTopType rhsTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (rhsTopType instanceof UnGuardedRhs) { consumeToken(builder, EQUALS); parseExpTopType(builder, ((UnGuardedRhs) rhsTopType).exp, comments); } else if (rhsTopType instanceof GuardedRhss) { e = builder.getTokenType(); parseGuardedRhss(builder, ((GuardedRhss) rhsTopType).rhsses, comments); } } /** * Parses an unqualified op. */ private static void parseOp(PsiBuilder builder, OpTopType opTopType, Comment[] comments) { IElementType e = builder.getTokenType(); boolean backticked = e == BACKTICK; if (backticked) { consumeToken(builder, BACKTICK); e = builder.getTokenType(); } if (opTopType instanceof VarOp) { parseName(builder, ((VarOp) opTopType).name, comments); } else if (opTopType instanceof ConOp) { parseName(builder, ((ConOp) opTopType).name, comments); } if (backticked) consumeToken(builder, BACKTICK); e = builder.getTokenType(); } /** * Parses a qualified op. */ private static void parseQOp(PsiBuilder builder, QOpTopType qOpTopType, Comment[] comments) { IElementType e = builder.getTokenType(); boolean backticked = e == BACKTICK; if (backticked) { consumeToken(builder, BACKTICK); e = builder.getTokenType(); } if (qOpTopType instanceof QVarOp) { parseQName(builder, ((QVarOp) qOpTopType).qName, comments); } else if (qOpTopType instanceof QConOp) { parseQName(builder, ((QConOp) qOpTopType).qName, comments); } if (backticked) consumeToken(builder, BACKTICK); e = builder.getTokenType(); } /** * Parses a qualified name. */ private static void parseQName(PsiBuilder builder, QNameTopType qNameTopType, Comment[] comments) { if (qNameTopType instanceof Qual) { Qual name = (Qual) qNameTopType; parseModuleName(builder, name.moduleName, comments); parseName(builder, name.name, comments); } else if (qNameTopType instanceof UnQual) { parseName(builder, ((UnQual) qNameTopType).name, comments); } else if (qNameTopType instanceof Special) { parseSpecialConTopType(builder, ((Special) qNameTopType).specialCon, comments); } } /** * Parses a special constructor. */ private static void parseSpecialConTopType(PsiBuilder builder, SpecialConTopType specialConTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (specialConTopType instanceof UnitCon) { consumeToken(builder, LPAREN); e = builder.getTokenType(); consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (specialConTopType instanceof ListCon) { consumeToken(builder, LBRACKET); e = builder.getTokenType(); consumeToken(builder, RBRACKET); e = builder.getTokenType(); } else if (specialConTopType instanceof FunCon) { consumeToken(builder, LPAREN); e = builder.getTokenType(); consumeToken(builder, RIGHTARROW); e = builder.getTokenType(); consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (specialConTopType instanceof TupleCon) { consumeToken(builder, LPAREN); e = builder.getTokenType(); boolean unboxed = parseBoxed(builder, ((TupleCon) specialConTopType).boxed, comments); e = builder.getTokenType(); int i = 1; while (i < ((TupleCon) specialConTopType).i) { consumeToken(builder, COMMA); e = builder.getTokenType(); i++; } e = builder.getTokenType(); if (unboxed) { consumeToken(builder, HASH); e = builder.getTokenType(); } consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (specialConTopType instanceof Cons) { consumeToken(builder, COLON); e = builder.getTokenType(); } else if (specialConTopType instanceof UnboxedSingleCon) { consumeToken(builder, LPAREN); e = builder.getTokenType(); consumeToken(builder, HASH); e = builder.getTokenType(); consumeToken(builder, HASH); e = builder.getTokenType(); consumeToken(builder, RPAREN); } } /** * Parses a list of names. */ private static void parseNames(PsiBuilder builder, NameTopType[] names, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (names != null && i < names.length) { parseName(builder, names[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) consumeToken(builder, COMMA); } } /** * Parses a name. */ private static void parseName(PsiBuilder builder, NameTopType nameTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (nameTopType instanceof Ident) { int startPos = builder.getCurrentOffset(); while ((builder.getCurrentOffset() - startPos) < ((Ident) nameTopType).name.length()) { builder.remapCurrentToken(NAME); consumeToken(builder, NAME); e = builder.getTokenType(); } } else if (nameTopType instanceof Symbol) { boolean startParen = e == LPAREN; if (startParen) consumeToken(builder, LPAREN); e = builder.getTokenType(); int startPos = builder.getCurrentOffset(); while ((builder.getCurrentOffset() - startPos) < ((Symbol) nameTopType).symbol.length()) { builder.remapCurrentToken(SYMBOL); consumeToken(builder, SYMBOL); e = builder.getTokenType(); } e = builder.getTokenType(); if (startParen) { consumeToken(builder, RPAREN); e = builder.getTokenType(); } } } /** * Parses a literal */ private static void parseLiteralTop(PsiBuilder builder, LiteralTopType literalTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (literalTopType instanceof CharLit) { consumeToken(builder, CHARTOKEN); e = builder.getTokenType(); } else if (literalTopType instanceof StringLit) { parseStringLiteral(builder); } else if (literalTopType instanceof IntLit) { consumeToken(builder, INTEGERTOKEN); e = builder.getTokenType(); } else if (literalTopType instanceof FracLit) { consumeToken(builder, FLOATTOKEN); e = builder.getTokenType(); } else if (literalTopType instanceof PrimInt) { consumeToken(builder, INTEGERTOKEN); e = builder.getTokenType(); consumeToken(builder, HASH); e = builder.getTokenType(); } else if (literalTopType instanceof PrimWord) { consumeToken(builder, INTEGERTOKEN); e = builder.getTokenType(); consumeToken(builder, HASH); e = builder.getTokenType(); consumeToken(builder, HASH); e = builder.getTokenType(); } else if (literalTopType instanceof PrimFloat) { consumeToken(builder, FLOATTOKEN); e = builder.getTokenType(); consumeToken(builder, HASH); e = builder.getTokenType(); } else if (literalTopType instanceof PrimDouble) { consumeToken(builder, FLOATTOKEN); e = builder.getTokenType(); consumeToken(builder, HASH); e = builder.getTokenType(); consumeToken(builder, HASH); e = builder.getTokenType(); } else if (literalTopType instanceof PrimChar) { consumeToken(builder, CHARTOKEN); e = builder.getTokenType(); consumeToken(builder, HASH); e = builder.getTokenType(); } else if (literalTopType instanceof PrimString) { parseStringLiteral(builder); e = builder.getTokenType(); consumeToken(builder, HASH); e = builder.getTokenType(); } else { throw new RuntimeException("LiteralTop: " + literalTopType.toString()); } } /** * Parse a string literal. */ private static void parseStringLiteral(PsiBuilder builder) { IElementType e = builder.getTokenType(); PsiBuilder.Marker marker = builder.mark(); consumeToken(builder, DOUBLEQUOTE); IElementType e2 = builder.getTokenType(); while (e2 != DOUBLEQUOTE) { if (e2 == BADSTRINGTOKEN) { builder.error("Bad stringtoken"); builder.advanceLexer(); } else { consumeToken(builder, STRINGTOKEN); } e2 = builder.getTokenType(); } consumeToken(builder, DOUBLEQUOTE); marker.done(e); } /** * Parses a list of statements. */ private static void parseStmtTopTypes(PsiBuilder builder, StmtTopType[] stmtTopTypes, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (stmtTopTypes != null && i < stmtTopTypes.length) { parseStmtTopType(builder, stmtTopTypes[i], comments); i++; } } /** * Parses a statement. */ private static void parseStmtTopType(PsiBuilder builder, StmtTopType stmtTopType, Comment[] comments) { IElementType e = builder.getTokenType(); PsiBuilder.Marker stmtMark = builder.mark(); if (stmtTopType instanceof Generator) { parsePatTopType(builder, ((Generator) stmtTopType).pat, comments); consumeToken(builder, LEFTARROW); parseExpTopType(builder, ((Generator) stmtTopType).exp, comments); } else if (stmtTopType instanceof Qualifier) { parseExpTopType(builder, ((Qualifier) stmtTopType).exp, comments); } else if (stmtTopType instanceof LetStmt) { consumeToken(builder, LET); parseBindsTopType(builder, ((LetStmt) stmtTopType).binds, comments); } else if (stmtTopType instanceof RecStmt) { builder.advanceLexer(); IElementType e1 = builder.getTokenType(); parseStmtTopTypes(builder, ((RecStmt) stmtTopType).stmts, comments); e1 = builder.getTokenType(); } stmtMark.done(e); } /** * Parses a list of expressions. */ private static void parseExpTopTypes(PsiBuilder builder, ExpTopType[] expTopType, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (expTopType != null && i < expTopType.length) { parseExpTopType(builder, expTopType[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) consumeToken(builder, COMMA); } } /** * Parses an expression. */ private static void parseExpTopType(PsiBuilder builder, ExpTopType expTopType, Comment[] comments) { IElementType e1 = builder.getTokenType(); if (expTopType instanceof App) { parseExpTopType(builder, ((App) expTopType).e1, comments); parseExpTopType(builder, ((App) expTopType).e2, comments); } else if (expTopType instanceof Var) { parseQName(builder, ((Var) expTopType).qName, comments); } else if (expTopType instanceof Con) { parseQName(builder, ((Con) expTopType).qName, comments); } else if (expTopType instanceof Lit) { parseLiteralTop(builder, ((Lit) expTopType).literal, comments); } else if (expTopType instanceof InfixApp) { parseExpTopType(builder, ((InfixApp) expTopType).e1, comments); IElementType e = builder.getTokenType(); parseQOp(builder, ((InfixApp) expTopType).qop, comments); e = builder.getTokenType(); parseExpTopType(builder, ((InfixApp) expTopType).e2, comments); e = builder.getTokenType(); } else if (expTopType instanceof List) { builder.advanceLexer(); parseExpTopTypes(builder, ((List) expTopType).exps, comments); IElementType e = builder.getTokenType(); builder.advanceLexer(); } else if (expTopType instanceof NegApp) { consumeToken(builder, MINUS); parseExpTopType(builder, ((NegApp) expTopType).e1, comments); } else if (expTopType instanceof Case) { IElementType e = builder.getTokenType(); consumeToken(builder, CASE); e = builder.getTokenType(); parseExpTopType(builder, ((Case) expTopType).scrutinee, comments); e = builder.getTokenType(); consumeToken(builder, OF); e = builder.getTokenType(); parseAlts(builder, ((Case) expTopType).alts, comments); e = builder.getTokenType(); } else if (expTopType instanceof Do) { IElementType e = builder.getTokenType(); PsiBuilder.Marker doMark = builder.mark(); consumeToken(builder, DO); parseStmtTopTypes(builder, ((Do) expTopType).stmts, comments); doMark.done(e); } else if (expTopType instanceof Lambda) { consumeToken(builder, BACKSLASH); IElementType e = builder.getTokenType(); parsePatTopTypes(builder, ((Lambda) expTopType).pats, comments); e = builder.getTokenType(); consumeToken(builder, RIGHTARROW); parseExpTopType(builder, ((Lambda) expTopType).exp, comments); e = builder.getTokenType(); } else if (expTopType instanceof Tuple) { consumeToken(builder, LPAREN); IElementType e = builder.getTokenType(); boolean unboxed = parseBoxed(builder, ((Tuple) expTopType).boxed, comments); e = builder.getTokenType(); parseExpTopTypes(builder, ((Tuple) expTopType).exps, comments); e = builder.getTokenType(); if (unboxed) { consumeToken(builder, HASH); e = builder.getTokenType(); } consumeToken(builder, RPAREN); e1 = builder.getTokenType(); } else if (expTopType instanceof TupleSection) { TupleSection ts = (TupleSection) expTopType; consumeToken(builder, LPAREN); IElementType e = builder.getTokenType(); boolean unboxed = parseBoxed(builder, ((TupleSection) expTopType).boxed, comments); e = builder.getTokenType(); int i = 0; while (ts.expMaybes != null && i < ts.expMaybes.length) { if (ts.expMaybes[i] != null) parseExpTopType(builder, ts.expMaybes[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) consumeToken(builder, COMMA); } e = builder.getTokenType(); if (unboxed) { consumeToken(builder, HASH); e = builder.getTokenType(); } consumeToken(builder, RPAREN); e1 = builder.getTokenType(); } else if (expTopType instanceof Paren) { consumeToken(builder, LPAREN); e1 = builder.getTokenType(); parseExpTopType(builder, ((Paren) expTopType).exp, comments); e1 = builder.getTokenType(); consumeToken(builder, RPAREN); e1 = builder.getTokenType(); } else if (expTopType instanceof LeftSection) { e1 = builder.getTokenType(); consumeToken(builder, LPAREN); e1 = builder.getTokenType(); parseExpTopType(builder, ((LeftSection) expTopType).exp, comments); e1 = builder.getTokenType(); parseQOp(builder, ((LeftSection) expTopType).qop, comments); e1 = builder.getTokenType(); consumeToken(builder, RPAREN); e1 = builder.getTokenType(); } else if (expTopType instanceof RightSection) { e1 = builder.getTokenType(); consumeToken(builder, LPAREN); parseQOp(builder, ((RightSection) expTopType).qop, comments); parseExpTopType(builder, ((RightSection) expTopType).exp, comments); e1 = builder.getTokenType(); consumeToken(builder, RPAREN); e1 = builder.getTokenType(); } else if (expTopType instanceof RecConstr) { e1 = builder.getTokenType(); parseQName(builder, ((RecConstr) expTopType).qName, comments); e1 = builder.getTokenType(); consumeToken(builder, LBRACE); parseFieldUpdateTopTypes(builder, ((RecConstr) expTopType).fieldUpdates, comments); e1 = builder.getTokenType(); consumeToken(builder, RBRACE); e1 = builder.getTokenType(); } else if (expTopType instanceof RecUpdate) { e1 = builder.getTokenType(); parseExpTopType(builder, ((RecUpdate) expTopType).exp, comments); e1 = builder.getTokenType(); consumeToken(builder, LBRACE); parseFieldUpdateTopTypes(builder, ((RecUpdate) expTopType).fieldUpdates, comments); e1 = builder.getTokenType(); consumeToken(builder, RBRACE); e1 = builder.getTokenType(); } else if (expTopType instanceof EnumFrom) { consumeToken(builder, LBRACKET); e1 = builder.getTokenType(); parseExpTopType(builder, ((EnumFrom) expTopType).exp, comments); e1 = builder.getTokenType(); consumeToken(builder, DOUBLEPERIOD); e1 = builder.getTokenType(); consumeToken(builder, RBRACKET); e1 = builder.getTokenType(); } else if (expTopType instanceof EnumFromTo) { consumeToken(builder, LBRACKET); e1 = builder.getTokenType(); parseExpTopType(builder, ((EnumFromTo) expTopType).from, comments); e1 = builder.getTokenType(); consumeToken(builder, DOUBLEPERIOD); e1 = builder.getTokenType(); parseExpTopType(builder, ((EnumFromTo) expTopType).to, comments); consumeToken(builder, RBRACKET); e1 = builder.getTokenType(); } else if (expTopType instanceof EnumFromThen) { consumeToken(builder, LBRACKET); e1 = builder.getTokenType(); parseExpTopType(builder, ((EnumFromThen) expTopType).from, comments); e1 = builder.getTokenType(); consumeToken(builder, COMMA); e1 = builder.getTokenType(); parseExpTopType(builder, ((EnumFromThen) expTopType).step, comments); consumeToken(builder, DOUBLEPERIOD); e1 = builder.getTokenType(); consumeToken(builder, RBRACKET); e1 = builder.getTokenType(); } else if (expTopType instanceof EnumFromThenTo) { consumeToken(builder, LBRACKET); e1 = builder.getTokenType(); parseExpTopType(builder, ((EnumFromThenTo) expTopType).from, comments); e1 = builder.getTokenType(); consumeToken(builder, COMMA); e1 = builder.getTokenType(); parseExpTopType(builder, ((EnumFromThenTo) expTopType).step, comments); consumeToken(builder, DOUBLEPERIOD); e1 = builder.getTokenType(); parseExpTopType(builder, ((EnumFromThenTo) expTopType).to, comments); e1 = builder.getTokenType(); consumeToken(builder, RBRACKET); e1 = builder.getTokenType(); } else if (expTopType instanceof ListComp) { consumeToken(builder, LBRACKET); e1 = builder.getTokenType(); parseExpTopType(builder, ((ListComp) expTopType).exp, comments); e1 = builder.getTokenType(); consumeToken(builder, PIPE); e1 = builder.getTokenType(); parseQualStmtTopTypes(builder, ((ListComp) expTopType).qualStmts, comments); e1 = builder.getTokenType(); consumeToken(builder, RBRACKET); e1 = builder.getTokenType(); } else if (expTopType instanceof ParComp) { ParComp p = (ParComp) expTopType; consumeToken(builder, LBRACKET); e1 = builder.getTokenType(); parseExpTopType(builder, ((ParComp) expTopType).exp, comments); e1 = builder.getTokenType(); consumeToken(builder, PIPE); e1 = builder.getTokenType(); int i = 0; while (p.qualStmts != null && i < p.qualStmts.length) { parseQualStmtTopTypes(builder, p.qualStmts[i], comments); i++; e1 = builder.getTokenType(); if (e1 == PIPE) consumeToken(builder, PIPE); e1 = builder.getTokenType(); } consumeToken(builder, RBRACKET); e1 = builder.getTokenType(); } else if (expTopType instanceof ExpTypeSig) { IElementType e = builder.getTokenType(); parseExpTopType(builder, ((ExpTypeSig) expTopType).exp, comments); e = builder.getTokenType(); consumeToken(builder, DOUBLECOLON); e = builder.getTokenType(); parseTypeTopType(builder, ((ExpTypeSig) expTopType).type, comments); e = builder.getTokenType(); } else if (expTopType instanceof Let) { builder.advanceLexer(); IElementType e = builder.getTokenType(); parseBindsTopType(builder, ((Let) expTopType).binds, comments); e = builder.getTokenType(); consumeToken(builder, IN); e = builder.getTokenType(); parseExpTopType(builder, ((Let) expTopType).exp, comments); e = builder.getTokenType(); } else if (expTopType instanceof If) { consumeToken(builder, IF); IElementType e = builder.getTokenType(); parseExpTopType(builder, ((If) expTopType).cond, comments); e = builder.getTokenType(); consumeToken(builder, THEN); e = builder.getTokenType(); parseExpTopType(builder, ((If) expTopType).t, comments); e = builder.getTokenType(); consumeToken(builder, ELSE); e = builder.getTokenType(); parseExpTopType(builder, ((If) expTopType).f, comments); e = builder.getTokenType(); } else if (expTopType instanceof QuasiQuote) { IElementType e = builder.getTokenType(); consumeToken(builder, LBRACKET); builder.advanceLexer(); e = builder.getTokenType(); consumeToken(builder, PIPE); e = builder.getTokenType(); while (e != PIPE) { builder.advanceLexer(); e = builder.getTokenType(); } consumeToken(builder, PIPE); consumeToken(builder, RBRACKET); e = builder.getTokenType(); } else if (expTopType instanceof CorePragma) { parseGenericPragma(builder, null, comments); parseExpTopType(builder, ((CorePragma) expTopType).exp, comments); } else if (expTopType instanceof SCCPragma) { parseGenericPragma(builder, null, comments); parseExpTopType(builder, ((SCCPragma) expTopType).exp, comments); } else if (expTopType instanceof Proc) { e1 = builder.getTokenType(); builder.advanceLexer(); // TODO: consumeToken(builder, PROCTOKEN); e1 = builder.getTokenType(); parsePatTopType(builder, ((Proc) expTopType).pat, comments); consumeToken(builder, RIGHTARROW); parseExpTopType(builder, ((Proc) expTopType).exp, comments); } else if (expTopType instanceof LeftArrApp) { e1 = builder.getTokenType(); parseExpTopType(builder, ((LeftArrApp) expTopType).e1, comments); builder.advanceLexer(); // TODO: consumeToken(builder, LeftArrApp); e1 = builder.getTokenType(); builder.advanceLexer(); e1 = builder.getTokenType(); parseExpTopType(builder, ((LeftArrApp) expTopType).e2, comments); e1 = builder.getTokenType(); } else if (expTopType instanceof RightArrApp) { e1 = builder.getTokenType(); parseExpTopType(builder, ((RightArrApp) expTopType).e1, comments); builder.advanceLexer(); // TODO: consumeToken(builder, RightArrApp); e1 = builder.getTokenType(); builder.advanceLexer(); e1 = builder.getTokenType(); parseExpTopType(builder, ((RightArrApp) expTopType).e2, comments); e1 = builder.getTokenType(); } else if (expTopType instanceof LeftArrHighApp) { e1 = builder.getTokenType(); parseExpTopType(builder, ((LeftArrHighApp) expTopType).e1, comments); builder.advanceLexer(); // TODO: consumeToken(builder, LeftArrHighApp); e1 = builder.getTokenType(); builder.advanceLexer(); e1 = builder.getTokenType(); builder.advanceLexer(); e1 = builder.getTokenType(); parseExpTopType(builder, ((LeftArrHighApp) expTopType).e2, comments); e1 = builder.getTokenType(); } else if (expTopType instanceof RightArrHighApp) { e1 = builder.getTokenType(); parseExpTopType(builder, ((RightArrHighApp) expTopType).e1, comments); builder.advanceLexer(); // TODO: consumeToken(builder, RightArrHighApp); e1 = builder.getTokenType(); builder.advanceLexer(); e1 = builder.getTokenType(); builder.advanceLexer(); e1 = builder.getTokenType(); parseExpTopType(builder, ((RightArrHighApp) expTopType).e2, comments); e1 = builder.getTokenType(); } else { throw new RuntimeException("parseExpTopType: " + expTopType.toString()); } } /** * Parses a list of field patterns. */ private static void parsePatFieldTopTypes(PsiBuilder builder, PatFieldTopType[] fields, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (fields != null && i < fields.length) { parsePatFieldTopType(builder, fields[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) consumeToken(builder, COMMA); } } /** * Parses a field pattern. */ private static void parsePatFieldTopType(PsiBuilder builder, PatFieldTopType field, Comment[] comments) { IElementType e = builder.getTokenType(); if (field instanceof PFieldPat) { parseQName(builder, ((PFieldPat) field).qName, comments); e = builder.getTokenType(); consumeToken(builder, EQUALS); e = builder.getTokenType(); parsePatTopType(builder, ((PFieldPat) field).pat, comments); e = builder.getTokenType(); } else if (field instanceof PFieldPun) { consumeToken(builder, VARIDREGEXP); e = builder.getTokenType(); } else if (field instanceof PFieldWildcard) { builder.advanceLexer(); // TODO: Token.UNDERSCORE? e = builder.getTokenType(); } } /** * Parses a list of field updates. */ private static void parseFieldUpdateTopTypes(PsiBuilder builder, FieldUpdateTopType[] fieldUpdateTopTypes, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (fieldUpdateTopTypes != null && i < fieldUpdateTopTypes.length) { parseFieldUpdateTopType(builder, fieldUpdateTopTypes[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) consumeToken(builder, COMMA); } } /** * Parses a field update. */ private static void parseFieldUpdateTopType(PsiBuilder builder, FieldUpdateTopType fieldUpdate, Comment[] comments) { IElementType e = builder.getTokenType(); if (fieldUpdate instanceof FieldUpdate) { parseQName(builder, ((FieldUpdate) fieldUpdate).qName, comments); e = builder.getTokenType(); consumeToken(builder, EQUALS); e = builder.getTokenType(); parseExpTopType(builder, ((FieldUpdate) fieldUpdate).exp, comments); e = builder.getTokenType(); } else if (fieldUpdate instanceof FieldPun) { throw new RuntimeException("TODO: FieldPun not implemented"); } else if (fieldUpdate instanceof FieldWildcard) { throw new RuntimeException("TODO: FieldWildcard not implemented"); } } /** * Parses a list of alts. */ private static void parseAlts(PsiBuilder builder, Alt[] alts, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (alts != null && i < alts.length) { parseAlt(builder, alts[i], comments); i++; e = builder.getTokenType(); if (e == SEMICOLON) consumeToken(builder, SEMICOLON); } } /** * Parses a single alt. */ private static void parseAlt(PsiBuilder builder, Alt alt, Comment[] comments) { IElementType e = builder.getTokenType(); parsePatTopType(builder, alt.pat, comments); e = builder.getTokenType(); parseGuardedAltsTopType(builder, alt.guardedAlts, comments); e = builder.getTokenType(); parseBindsTopType(builder, alt.bindsMaybe, comments); e = builder.getTokenType(); } /** * Parses a single guarded alt. */ private static void parseGuardedAltsTopType(PsiBuilder builder, GuardedAltsTopType alt, Comment[] comments) { IElementType e = builder.getTokenType(); if (alt instanceof UnGuardedAlt) { consumeToken(builder, RIGHTARROW); e = builder.getTokenType(); parseExpTopType(builder, ((UnGuardedAlt) alt).exp, comments); e = builder.getTokenType(); } else if (alt instanceof GuardedAlts) { parseGuardedAlts(builder, ((GuardedAlts) alt).alts, comments); e = builder.getTokenType(); } } /** * Parses a list of guarded alts. */ private static void parseGuardedAlts(PsiBuilder builder, GuardedAlt[] alts, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (alts != null && i < alts.length) { parseGuardedAlt(builder, alts[i], comments); i++; e = builder.getTokenType(); if (e == SEMICOLON) consumeToken(builder, SEMICOLON); } } /** * Parses a single guarded alt. */ private static void parseGuardedAlt(PsiBuilder builder, GuardedAlt alt, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, PIPE); e = builder.getTokenType(); parseStmtTopTypes(builder, alt.stmts, comments); e = builder.getTokenType(); consumeToken(builder, RIGHTARROW); e = builder.getTokenType(); parseExpTopType(builder, alt.exp, comments); e = builder.getTokenType(); } /** * Parses a list of types. */ private static void parseTypeTopTypes(PsiBuilder builder, TypeTopType[] typeTopTypes, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (typeTopTypes != null && i < typeTopTypes.length) { parseTypeTopType(builder, typeTopTypes[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) consumeToken(builder, COMMA); } } /** * Parses a type. */ private static void parseTypeTopType(PsiBuilder builder, TypeTopType typeTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (typeTopType instanceof TyForall) { // FIXME: No forall lexeme. TyForall t = (TyForall) typeTopType; e = builder.getTokenType(); if (t.tyVarBinds != null) { // Implicit foralls for typeclasses. builder.advanceLexer(); e = builder.getTokenType(); parseTyVarBinds(builder, t.tyVarBinds, comments); e = builder.getTokenType(); consumeToken(builder, PERIOD); } parseContextTopType(builder, t.context, comments); e = builder.getTokenType(); if (e == DOUBLEARROW) consumeToken(builder, DOUBLEARROW); parseTypeTopType(builder, t.type, comments); e = builder.getTokenType(); } else if (typeTopType instanceof TyFun) { parseTypeTopType(builder, ((TyFun) typeTopType).t1, comments); consumeToken(builder, RIGHTARROW); parseTypeTopType(builder, ((TyFun) typeTopType).t2, comments); } else if (typeTopType instanceof TyTuple) { consumeToken(builder, LPAREN); e = builder.getTokenType(); boolean unboxed = parseBoxed(builder, ((TyTuple) typeTopType).boxed, comments); e = builder.getTokenType(); parseTypeTopTypes(builder, ((TyTuple) typeTopType).types, comments); e = builder.getTokenType(); if (unboxed) { consumeToken(builder, HASH); e = builder.getTokenType(); } consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (typeTopType instanceof TyList) { consumeToken(builder, LBRACKET); e = builder.getTokenType(); parseTypeTopType(builder, ((TyList) typeTopType).t, comments); e = builder.getTokenType(); consumeToken(builder, RBRACKET); e = builder.getTokenType(); } else if (typeTopType instanceof TyApp) { parseTypeTopType(builder, ((TyApp) typeTopType).t1, comments); e = builder.getTokenType(); parseTypeTopType(builder, ((TyApp) typeTopType).t2, comments); e = builder.getTokenType(); } else if (typeTopType instanceof TyVar) { parseName(builder, ((TyVar) typeTopType).name, comments); e = builder.getTokenType(); } else if (typeTopType instanceof TyCon) { parseQName(builder, ((TyCon) typeTopType).qName, comments); } else if (typeTopType instanceof TyParen) { consumeToken(builder, LPAREN); e = builder.getTokenType(); parseTypeTopType(builder, ((TyParen) typeTopType).type, comments); e = builder.getTokenType(); consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (typeTopType instanceof TyInfix) { e = builder.getTokenType(); parseTypeTopType(builder, ((TyInfix) typeTopType).t1, comments); e = builder.getTokenType(); parseQName(builder, ((TyInfix) typeTopType).qName, comments); e = builder.getTokenType(); parseTypeTopType(builder, ((TyInfix) typeTopType).t2, comments); e = builder.getTokenType(); } else if (typeTopType instanceof TyKind) { e = builder.getTokenType(); consumeToken(builder, LPAREN); e = builder.getTokenType(); parseTypeTopType(builder, ((TyKind) typeTopType).type, comments); e = builder.getTokenType(); consumeToken(builder, DOUBLECOLON); e = builder.getTokenType(); parseKindTopType(builder, ((TyKind) typeTopType).kind, comments); e = builder.getTokenType(); consumeToken(builder, RPAREN); e = builder.getTokenType(); } else { throw new RuntimeException("parseTypeTopType: " + typeTopType.toString()); } } /** * Parses a list of kinds. */ private static void parseKindTopTypes(PsiBuilder builder, KindTopType[] kinds, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (kinds != null && i < kinds.length) { parseKindTopType(builder, kinds[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) consumeToken(builder, COMMA); } } /** * Parses a kind. */ private static void parseKindTopType(PsiBuilder builder, KindTopType kind, Comment[] comments) { IElementType e = builder.getTokenType(); if (kind instanceof KindStar) { consumeToken(builder, ASTERISK); e = builder.getTokenType(); } else if (kind instanceof KindBang) { consumeToken(builder, EXLAMATION); e = builder.getTokenType(); } else if (kind instanceof KindFn) { parseKindTopType(builder, ((KindFn) kind).k1, comments); consumeToken(builder, RIGHTARROW); parseKindTopType(builder, ((KindFn) kind).k2, comments); } else if (kind instanceof KindParen) { consumeToken(builder, LPAREN); e = builder.getTokenType(); parseKindTopType(builder, ((KindParen) kind).kind, comments); e = builder.getTokenType(); consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (kind instanceof KindVar) { parseQName(builder, ((KindVar) kind).qName, comments); e = builder.getTokenType(); } else if (kind instanceof KindApp) { parseKindTopType(builder, ((KindApp) kind).k1, comments); e = builder.getTokenType(); parseKindTopType(builder, ((KindApp) kind).k2, comments); e = builder.getTokenType(); } else if (kind instanceof KindTuple) { consumeToken(builder, SINGLEQUOTE); e = builder.getTokenType(); consumeToken(builder, LPAREN); e = builder.getTokenType(); parseKindTopTypes(builder, ((KindTuple) kind).kinds, comments); consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (kind instanceof KindList) { consumeToken(builder, SINGLEQUOTE); e = builder.getTokenType(); consumeToken(builder, LBRACKET); e = builder.getTokenType(); parseKindTopTypes(builder, ((KindList) kind).kinds, comments); consumeToken(builder, RBRACKET); e = builder.getTokenType(); } } /** * Parses a list of qualified statements. */ private static void parseQualStmtTopTypes(PsiBuilder builder, QualStmtTopType[] qualStmtTopTypes, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (qualStmtTopTypes != null && i < qualStmtTopTypes.length) { parseQualStmtTopType(builder, qualStmtTopTypes[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) consumeToken(builder, COMMA); } } /** * Parses one qualified statement. */ private static void parseQualStmtTopType(PsiBuilder builder, QualStmtTopType qualStmtTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (qualStmtTopType instanceof QualStmt) { parseStmtTopType(builder, ((QualStmt) qualStmtTopType).stmt, comments); } else if (qualStmtTopType instanceof ThenTrans) { consumeToken(builder, THEN); e = builder.getTokenType(); parseExpTopType(builder, ((ThenTrans) qualStmtTopType).exp, comments); e = builder.getTokenType(); } else if (qualStmtTopType instanceof ThenBy) { consumeToken(builder, THEN); e = builder.getTokenType(); parseExpTopType(builder, ((ThenBy) qualStmtTopType).e1, comments); e = builder.getTokenType(); builder.advanceLexer(); // TODO: Add Token.BY e = builder.getTokenType(); parseExpTopType(builder, ((ThenBy) qualStmtTopType).e2, comments); e = builder.getTokenType(); } else if (qualStmtTopType instanceof GroupBy) { consumeToken(builder, THEN); e = builder.getTokenType(); builder.advanceLexer(); // TODO: Add Token.GROUP e = builder.getTokenType(); builder.advanceLexer(); // TODO: Add Token.USING e = builder.getTokenType(); parseExpTopType(builder, ((GroupBy) qualStmtTopType).exp, comments); e = builder.getTokenType(); } else if (qualStmtTopType instanceof GroupUsing) { consumeToken(builder, THEN); e = builder.getTokenType(); builder.advanceLexer(); // TODO: Add Token.GROUP e = builder.getTokenType(); builder.advanceLexer(); // TODO: Add Token.USING e = builder.getTokenType(); parseExpTopType(builder, ((GroupUsing) qualStmtTopType).exp, comments); e = builder.getTokenType(); } else if (qualStmtTopType instanceof GroupByUsing) { consumeToken(builder, THEN); e = builder.getTokenType(); builder.advanceLexer(); // TODO: Add Token.GROUP e = builder.getTokenType(); builder.advanceLexer(); // TODO: Add Token.BY e = builder.getTokenType(); parseExpTopType(builder, ((GroupByUsing) qualStmtTopType).e1, comments); e = builder.getTokenType(); builder.advanceLexer(); // TODO: Add Token.USING. parseExpTopType(builder, ((GroupByUsing) qualStmtTopType).e2, comments); e = builder.getTokenType(); } } /** * Parses contexts. */ private static void parseContextTopType(PsiBuilder builder, ContextTopType context, Comment[] comments) { IElementType e = builder.getTokenType(); if (context instanceof CxSingle) { parseAsstTopType(builder, ((CxSingle) context).asst, comments); } else if (context instanceof CxTuple) { consumeToken(builder, LPAREN); e = builder.getTokenType(); parseAsstTopTypes(builder, ((CxTuple) context).assts, comments); e = builder.getTokenType(); consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (context instanceof CxParen) { consumeToken(builder, LPAREN); parseContextTopType(builder, ((CxParen) context).context, comments); e = builder.getTokenType(); consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (context instanceof CxEmpty) { throw new RuntimeException("TODO: Implement CxEmpty"); } } /** * Parses a list of Assts. */ private static void parseAsstTopTypes(PsiBuilder builder, AsstTopType[] assts, Comment[] comments) { int i = 0; IElementType e = builder.getTokenType(); while (assts != null && i < assts.length) { parseAsstTopType(builder, assts[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) { consumeToken(builder, COMMA); e = builder.getTokenType(); } } } /** * Parses Assts. */ private static void parseAsstTopType(PsiBuilder builder, AsstTopType asst, Comment[] comments) { IElementType e = builder.getTokenType(); if (asst instanceof ClassA) { parseQName(builder, ((ClassA) asst).qName, comments); e = builder.getTokenType(); parseTypeTopTypes(builder, ((ClassA) asst).types, comments); e = builder.getTokenType(); } else if (asst instanceof InfixA) { parseTypeTopType(builder, ((InfixA) asst).t1, comments); e = builder.getTokenType(); parseQName(builder, ((InfixA) asst).qName, comments); e = builder.getTokenType(); parseTypeTopType(builder, ((InfixA) asst).t2, comments); e = builder.getTokenType(); } else if (asst instanceof IParam) { throw new RuntimeException("TODO: Parse IParam"); /* Preliminary untested implementation: parseContextTopType(builder, ((IParam) asst).ipName, comments); e = builder.getTokenType(); parseTypeTopType(builder, ((IParam) asst).type, comments); e = builder.getTokenType(); */ } else if (asst instanceof EqualP) { throw new RuntimeException("TODO: Parse EqualP"); /* Preliminary untested implementation: parseTypeTopType(builder, ((EqualP) asst).t1, comments); consumeToken(builder, TILDETOKENHERE); e = builder.getTokenType(); parseTypeTopType(builder,((EqualP) asst).t2, comments); e = builder.getTokenType(); */ } } /** * Parses box annotations. */ public static boolean parseBoxed(PsiBuilder builder, BoxedTopType boxedTopType, Comment[] comments) { // TODO: Improve granularity. IElementType e = builder.getTokenType(); if (boxedTopType instanceof Boxed) { return false; } else if (boxedTopType instanceof Unboxed) { consumeToken(builder, HASH); return true; } throw new RuntimeException("Unexpected boxing: " + boxedTopType.toString()); } /** * Parses a generic pragma. */ public static void parseGenericPragma(PsiBuilder builder, DeclTopType annPragma, Comment[] comments) { // TODO: Improve granularity. PsiBuilder.Marker pragmaMark = builder.mark(); IElementType e = builder.getTokenType(); chewPragma(builder); consumeToken(builder, CLOSEPRAGMA); pragmaMark.done(e); } /** * Eats a complete pragma and leaves the builder at CLOSEPRAGMA token. */ public static void chewPragma(PsiBuilder builder) { IElementType e = builder.getTokenType(); while (e != CLOSEPRAGMA) { builder.advanceLexer(); e = builder.getTokenType(); } } public static boolean consumeToken(PsiBuilder builder_, IElementType token) { if (nextTokenIsInner(builder_, token)) { builder_.advanceLexer(); return true; } return false; } public static boolean nextTokenIsInner(PsiBuilder builder_, IElementType expectedToken) { IElementType tokenType = builder_.getTokenType(); if (expectedToken != tokenType) { System.out.println("Found token: " + tokenType + " vs expected: " + expectedToken); } return expectedToken == tokenType; } }
package omnikryptec.postprocessing; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.GL11; import omnikryptec.postprocessing.FrameBufferObject.DepthbufferType; import omnikryptec.shader_files.DebugShader; import omnikryptec.util.RenderUtil; public class DebugRenderer extends PostProcessingStage { private List<Integer> disabled = new ArrayList<Integer>(); private DebugShader shader = new DebugShader(); private boolean tmp; private int notr; public DebugRenderer() { } public DebugRenderer(Integer... is) { disabled.addAll(Arrays.asList(is)); } public DebugRenderer disableIndex(int i) { disabled.add(i); return this; } public DebugRenderer enableIndex(int i) { disabled.remove((Integer) i); return this; } private int last=-1; private int side=0; @Override public void render(FrameBufferObject before, List<FrameBufferObject> beforelist, int stage) { notr = 0; shader.start(); if(last!=beforelist.size() + 1 - disabled.size()){ side = calcQuadratic(last = beforelist.size() + 1 - disabled.size()); } getFbo().bindFrameBuffer(); RenderUtil.clear(0, 0, 0, 0); if (tmp = !disabled.contains(0)) { beforelist.get(0).bindDepthTexture(0); shader.info.loadVec3(side, 0, 0); GL11.glDrawArrays(GL11.GL_TRIANGLE_STRIP, 0, 4); } for (int i = 0; i < beforelist.size(); i++) { if (disabled.contains(i + 1)) { notr++; continue; } beforelist.get(i).bindToUnit(0); shader.info.loadVec3(side, i + (tmp ? 1 : 0) - notr, (i + (tmp ? 1 : 0) - notr) % side); GL11.glDrawArrays(GL11.GL_TRIANGLE_STRIP, 0, 4); } getFbo().unbindFrameBuffer(); } private int calcQuadratic(int amount) { double sqrt = Math.sqrt(amount); return (int) Math.ceil(sqrt); } @Override protected FrameBufferObject createFbo() { return new FrameBufferObject(Display.getWidth(), Display.getHeight(), DepthbufferType.DEPTH_TEXTURE); } }
package com.lukekorth.httpebble; import android.accounts.Account; import android.accounts.AccountManager; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.text.method.LinkMovementMethod; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TableLayout; import android.widget.TextView; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import com.lukekorth.httpebble.billing.IabHelper; import com.lukekorth.httpebble.billing.IabResult; import com.lukekorth.httpebble.billing.Inventory; import com.lukekorth.httpebble.billing.Purchase; import static android.Manifest.permission.GET_ACCOUNTS; public class PebbleConnect extends AppCompatActivity { private IabHelper mIabHelper; private Button mSetup; private TableLayout mCredentials; private TextView mUsername; private TextView mToken; private Button mReset; private Button mDocumentation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Settings.upgradeVersion(this); ((TextView) findViewById(R.id.notifications)).setMovementMethod(LinkMovementMethod.getInstance()); ((TextView) findViewById(R.id.source)).setMovementMethod(LinkMovementMethod.getInstance()); mSetup = (Button) findViewById(R.id.setup); mCredentials = (TableLayout) findViewById(R.id.credentials); mUsername = (TextView) findViewById(R.id.username); mToken = (TextView) findViewById(R.id.token); mReset = (Button) findViewById(R.id.reset); mDocumentation = (Button) findViewById(R.id.documentation); if (!TextUtils.isEmpty(Settings.getEmail(this))) { showCredentials(); } } @Override protected void onResume() { super.onResume(); int resultCode = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.SUCCESS) { if (GoogleApiAvailability.getInstance().isUserResolvableError(resultCode)) { GoogleApiAvailability.getInstance().getErrorDialog(this, resultCode, 1).show(); } else { new AlertDialog.Builder(this) .setTitle(R.string.device_not_supported) .setMessage(R.string.device_not_supported_message) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); PebbleConnect.this.finish(); } }) .show(); } } if (Settings.needToRegister(this)) { startService(new Intent(this, RegistrationIntentService.class)); } } @Override protected void onDestroy() { super.onDestroy(); if (mIabHelper != null) { mIabHelper.dispose(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (ContextCompat.checkSelfPermission(this, GET_ACCOUNTS) == PackageManager.PERMISSION_GRANTED) { setup(null); } } private void showCredentials() { mSetup.setVisibility(View.GONE); mCredentials.setVisibility(View.VISIBLE); mUsername.setText(Settings.getEmail(this)); mToken.setText(Settings.getToken(this)); mReset.setVisibility(View.VISIBLE); mDocumentation.setVisibility(View.VISIBLE); } public void setup(View v) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ContextCompat.checkSelfPermission(this, GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[] { GET_ACCOUNTS }, 1); } else { Account[] accounts = AccountManager.get(this).getAccountsByType("com.google"); if (accounts.length == 0) { new AlertDialog.Builder(this) .setMessage(R.string.no_emails_found) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); } else { final String[] emails = new String[accounts.length]; for (int i = 0; i < accounts.length; i++) { emails[i] = accounts[i].name; } new AlertDialog.Builder(this) .setTitle(R.string.choose_email) .setSingleChoiceItems(emails, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Settings.setEmail(PebbleConnect.this, emails[which]); } }) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); if (!TextUtils.isEmpty(Settings.getEmail(PebbleConnect.this))) { showCredentials(); Settings.setNeedToRegister(PebbleConnect.this, true); startService(new Intent(PebbleConnect.this, RegistrationIntentService.class)); } } }) .show(); } } } public void reset(View v) { Settings.setEmail(this, null); Settings.clearToken(this); mCredentials.setVisibility(View.GONE); mReset.setVisibility(View.GONE); mDocumentation.setVisibility(View.GONE); mSetup.setVisibility(View.VISIBLE); } public void documentation(View v) { startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://lukekorth.com/blog/restful-pebble/"))); } @Override public boolean onCreateOptionsMenu(final Menu menu) { if (Settings.hasPurchased(this)) { return true; } mIabHelper = new IabHelper(this, getString(R.string.billing_public_key)); mIabHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { @Override public void onIabSetupFinished(IabResult result) { mIabHelper.queryInventoryAsync(new IabHelper.QueryInventoryFinishedListener() { @Override public void onQueryInventoryFinished(IabResult result, Inventory inv) { if (result.isSuccess()) { if (inv.hasPurchase("httpebble.unlock") || inv.hasPurchase("httpebble.donation.1") || inv.hasPurchase("httpebble.donation.2") || inv.hasPurchase("httpebble.donation.3") || inv.hasPurchase("httpebble.donation.5") || inv.hasPurchase("httpebble.donation.10")) { Settings.setPurchased(PebbleConnect.this, true); startService(new Intent(PebbleConnect.this, RegistrationIntentService.class)); } else { final MenuItem upgrade = menu.add(R.string.upgrade); upgrade.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { new AlertDialog.Builder(PebbleConnect.this) .setTitle(R.string.upgrade) .setMessage(R.string.upgrade_description) .setPositiveButton(R.string.purchase, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mIabHelper.launchPurchaseFlow(PebbleConnect.this, "httpebble.unlock", 1, new IabHelper.OnIabPurchaseFinishedListener() { @Override public void onIabPurchaseFinished(IabResult result, Purchase info) { upgrade.setVisible(false); PebbleConnect.this.invalidateOptionsMenu(); Settings.setPurchased(PebbleConnect.this, result.isSuccess()); startService(new Intent(PebbleConnect.this, RegistrationIntentService.class)); } }); dialog.dismiss(); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); return true; } }).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); } } } }); } }); return true; } }
package com.jawspeak.intellij; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.ScrollingModel; import com.intellij.openapi.editor.VisualPosition; import com.intellij.openapi.editor.event.EditorFactoryEvent; import com.intellij.openapi.editor.event.EditorFactoryListener; import com.intellij.openapi.editor.event.VisibleAreaEvent; import com.intellij.openapi.editor.event.VisibleAreaListener; import com.intellij.openapi.editor.impl.ScrollingModelImpl; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.FileEditorManagerEvent; import com.intellij.openapi.fileEditor.FileEditorManagerListener; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ReflectionUtil; import java.awt.Point; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import javax.swing.JComponent; import org.jetbrains.annotations.NotNull; /** * Listens for scroll change events in "interested editors" (the split ones), and then moves the * others to stay in sync. With inspiration from my buddy Mike's request. */ public class JoinedScroller implements FileEditorManagerListener, VisibleAreaListener, EditorFactoryListener { private final static Logger logger = Logger.getInstance(JoinedScroller.class.getName()); private final Set<Editor> openedEditors = new HashSet<>(); private final static AtomicInteger openCount = new AtomicInteger(); private final static AtomicInteger closedCount = new AtomicInteger(); private final static AtomicInteger editorCreatedCount = new AtomicInteger(); private final static AtomicInteger editorReleasedCount = new AtomicInteger(); private final Project project; public JoinedScroller(Project project) { this.project = project; } @Override public void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) { logger.info("fileOpened: opened file=" + file.getCanonicalPath() + " openedCount=" + openCount.incrementAndGet()); } @Override public void fileClosed(@NotNull FileEditorManager source, @NotNull VirtualFile file) { // no-op handle editors closing below. logger.info("fileClosed: closed file=" + file.getCanonicalPath() + " closedCount=" + closedCount.incrementAndGet()); } @Override public void editorCreated(@NotNull EditorFactoryEvent event) { Editor editor = event.getEditor(); if (!openedEditors.contains(editor)) { reflectivelyCheckCurrentListeners("editorCreated.before", editor); openedEditors.add(editor); editor.getScrollingModel().addVisibleAreaListener(this); logger.info("editorCreated: createdCount=" + editorCreatedCount.incrementAndGet() + " listening for editor=" + shortObjectString(editor) + " openedEditors=" + listShortObjects(openedEditors)); reflectivelyCheckCurrentListeners("editorCreated.after", editor); } else { logger.warn("editorCreated: createdCount=" + editorCreatedCount.incrementAndGet() + " (should not happen) already contains editor=" + shortObjectString(editor)); } } @Override public void editorReleased(@NotNull EditorFactoryEvent event) { Editor editor = event.getEditor(); if (openedEditors.contains(editor)) { logger.info("editorReleased: releasedCount=" + editorReleasedCount.incrementAndGet() + " removed listener for editor=" + shortObjectString(editor) + " openedEditors=" + listShortObjects(openedEditors)); reflectivelyCheckCurrentListeners("editorReleased.before", editor); editor.getScrollingModel().removeVisibleAreaListener(this); openedEditors.remove(editor); reflectivelyCheckCurrentListeners("editorReleased.after", editor); } else { logger.warn("editorReleased: releasedCount=" + editorReleasedCount.incrementAndGet() + " (should not happen) released editor we were not tracking editor=" + shortObjectString(editor)); } } @Override public void selectionChanged(@NotNull FileEditorManagerEvent event) { // Don't care, as we observe visible area changes instead. } @Override public void visibleAreaChanged(VisibleAreaEvent event) { Editor masterEditor = event.getEditor(); try { // Disable while we move things. Must remember to always add it back on. // Doing everything on this thread and not with SwingUtilities to ensure single threaded. masterEditor.getScrollingModel().removeVisibleAreaListener(this); VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(masterEditor.getDocument()); List<Editor> allTheseShowingEditors = new ArrayList<>(); for (Editor e : EditorFactory.getInstance().getEditors(masterEditor.getDocument())) { if (e.getComponent().isShowing()) { allTheseShowingEditors.add(e); } } if (allTheseShowingEditors.size() < 2) { logger.info("visibleAreaChanged: <2 showing editors for file=" + (virtualFile != null ? virtualFile.getCanonicalPath() : "<null>") + " editors=" + listShortObjects(allTheseShowingEditors)); return; } // sort all editors by their location on the screen Left to Right, Top to Bottom. Collections.sort(allTheseShowingEditors, (e1, e2) -> { if (!e1.getComponent().isShowing() || !e2.getComponent().isShowing()) { return 0; // don't try to look when not on the screen. } Point e1Location = e1.getComponent().getLocationOnScreen(); Point e2Location = e2.getComponent().getLocationOnScreen(); if (e1Location.getX() != e2Location.getX()) { return (int) (e1Location.getX() - e2Location.getX()); } return (int) (e1Location.getY() - e2Location.getY()); }); syncJoinedTabScrolling(virtualFile.getCanonicalPath(), masterEditor, allTheseShowingEditors); } finally { // Re-enable listener. masterEditor.getScrollingModel().addVisibleAreaListener(this); } } private static void syncJoinedTabScrolling(String filePathWeAreWorkingOn /*used for logging and debugging. hack hack hack.*/, Editor master, List<Editor> allTheseEditors) { int masterIndex = -1; // TODO later can make more efficient w/ a doubly linked list or something. for (int i = 0; i < allTheseEditors.size(); i++) { if (allTheseEditors.get(i) == master) { masterIndex = i; break; } } if (masterIndex < 0) { logger.error("Did not find masterIndex - a bug"); } // only scroll one to the left or right because events will cascade onward to others. if (masterIndex - 1 >= 0) { Editor slave = allTheseEditors.get(masterIndex - 1); scroll(master, slave, SlavePosition.SLAVE_LEFT_OF_MASTER); } if (masterIndex + 1 < allTheseEditors.size()) { Editor slave = allTheseEditors.get(masterIndex + 1); scroll(master, slave, SlavePosition.SLAVE_RIGHT_OF_MASTER); } } private enum SlavePosition { SLAVE_LEFT_OF_MASTER, SLAVE_RIGHT_OF_MASTER } private static class EditorTopBottom { final int column; final int topLine; final int bottomLine; final int verticalScrollOffset; final int linesVisible; final Editor editor; EditorTopBottom(Editor editor) { this.editor = editor; ScrollingModel scrolling = editor.getScrollingModel(); verticalScrollOffset = scrolling.getVerticalScrollOffset(); // convert to visual position (including folding) if this is logical (ignoring folding). VisualPosition vp = editor.xyToVisualPosition( new Point(scrolling.getVisibleArea().x, verticalScrollOffset)); topLine = vp.line; column = vp.column; bottomLine = editor.xyToVisualPosition( new Point(scrolling.getVisibleArea().x, verticalScrollOffset + scrolling.getVisibleArea().height)).line; linesVisible = bottomLine - topLine + 1; // inclusive of both lines, so add one. Preconditions.checkState(linesVisible >= 0, "Invalid lines visible calculation - bug!"); } public String toString() { return "EditorTopBottom{editor=" + shortObjectString(editor) + ", top=" + topLine + ", bottom=" + bottomLine + ", linesVisible=" + linesVisible + "}"; } } // With inspiration from SyncScrollSupport.java in intellij CE source. private static void scroll(Editor master, Editor slave, SlavePosition slavePosition) { EditorTopBottom masterTopBottom = new EditorTopBottom(master); EditorTopBottom slaveTopBottom = new EditorTopBottom(slave); // For slaves to the LEFT of master: their new top line // = convertFromVisualLinesToXY(master_top_line - (size_of_slave_in_lines -1)) // For slaves to the RIGHT of master: their new top line // = convertFromVisualLinesToXY(master_top_line + (size_of_master_in_lines - 1)) // (-1 to give overlap in the two editors so 1 line is the same continuing b/w the two). int slaveNewTopLine; switch (slavePosition) { case SLAVE_LEFT_OF_MASTER: slaveNewTopLine = masterTopBottom.topLine - (slaveTopBottom.linesVisible - 1); break; case SLAVE_RIGHT_OF_MASTER: slaveNewTopLine = masterTopBottom.topLine + (masterTopBottom.linesVisible - 1); break; default: throw new RuntimeException("Invalid state - should never happen"); } if (slaveNewTopLine == slaveTopBottom.topLine) { return; // already at the desired position. } slaveNewTopLine = Math.max(0, slaveNewTopLine); logger.info("scroll: masterTopBottom=" + masterTopBottom + " slaveTopBottom=" + slaveTopBottom + " slaveNewTopLine=" + slaveNewTopLine); int correction = (masterTopBottom.verticalScrollOffset) % master.getLineHeight(); Point point = slave.visualPositionToXY( new VisualPosition(slaveNewTopLine, masterTopBottom.column)); int offset = point.y + correction; int deltaHeaderOffset = getHeaderOffset(slave) - getHeaderOffset(master); doScrollVertically(slave.getScrollingModel(), offset + deltaHeaderOffset); } private static void doScrollVertically(@NotNull ScrollingModel model, int offset) { model.disableAnimation(); try { model.scrollVertically(offset); } finally { model.enableAnimation(); } } private static int getHeaderOffset(@NotNull final Editor editor) { final JComponent header = editor.getHeaderComponent(); return header == null ? 0 : header.getHeight(); } private static void reflectivelyCheckCurrentListeners(String logLabel, Editor editor) { // Works in developement. Not in prod. try { if (editor.getScrollingModel().getClass().equals(ScrollingModelImpl.class)) { List<VisibleAreaListener> listeners = ReflectionUtil.getField(ScrollingModelImpl.class, editor.getScrollingModel(), List.class, "myVisibleAreaListeners"); logger.info(logLabel + ": editor=" + shortObjectString(editor) + " currentListeners=" + listShortObjects(listeners)); } } catch (Exception e) { logger.error("reflectivelyCheckCurrentListeners: error trying.", e); } } private static String shortObjectString(Object o) { if (o == null) { return "<null>"; } if (!o.toString().contains(".")) { return o.toString(); } return o.toString().substring(o.toString().lastIndexOf('.') + 1); } private static String listShortObjects(Collection c) { if (c == null) { return "<unavailable>"; } List<String> collector = new ArrayList<>(); for (Object o : c) { collector.add(shortObjectString(o)); } return Joiner.on(",").join(collector); } }
package org.appwork.swing.components; import java.awt.Color; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.text.ParseException; import javax.swing.JFormattedTextField.AbstractFormatter; import javax.swing.JSpinner; import javax.swing.SpinnerModel; import javax.swing.SpinnerNumberModel; import javax.swing.Timer; import javax.swing.text.DefaultFormatterFactory; import org.appwork.utils.formatter.SizeFormatter; import org.appwork.utils.formatter.SizeFormatter.Unit; public class SizeSpinner extends ExtSpinner implements FocusListener, ActionListener { private static final long serialVersionUID = -3983659343629867162L; private SpinnerNumberModel nm; public SizeSpinner(final long min, final long max, final long steps) { this(new SpinnerNumberModel(min, min, max, steps)); } /** * @param model */ public SizeSpinner(final SpinnerNumberModel model) { super(model); // this.addFocusListener(this); this.nm = (SpinnerNumberModel) super.getModel(); final DefaultFormatterFactory factory = new DefaultFormatterFactory(new AbstractFormatter() { private static final long serialVersionUID = 7808117078307243989L; @Override public Object stringToValue(final String text) throws ParseException { return SizeSpinner.this.textToObject(text); } @Override public String valueToString(final Object value) throws ParseException { return SizeSpinner.this.longToText(((Number) value).longValue()); } }); ((JSpinner.DefaultEditor) this.getEditor()).getTextField().setFormatterFactory(factory); ((JSpinner.DefaultEditor) this.getEditor()).getTextField().addFocusListener(this); ((JSpinner.DefaultEditor) this.getEditor()).getTextField().addActionListener(this); } /* * (non-Javadoc) * * @see * java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ @Override public void actionPerformed(final ActionEvent e) { this.correct(); } private void beep() { Toolkit.getDefaultToolkit().beep(); final Color bg = ((JSpinner.DefaultEditor) this.getEditor()).getTextField().getForeground(); ((JSpinner.DefaultEditor) this.getEditor()).getTextField().setForeground(Color.RED); new Timer(100, new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { ((JSpinner.DefaultEditor) SizeSpinner.this.getEditor()).getTextField().setForeground(bg); } }).start(); } private void correct() { final long v = ((Number) this.getValue()).longValue(); long newValue = v; if (this.nm.getMinimum() != null) { newValue = Math.max(v, ((Number) this.nm.getMinimum()).longValue()); } if (this.nm.getMaximum() != null) { newValue = Math.min(((Number) this.nm.getMaximum()).longValue(), newValue); } if (newValue != v) { this.beep(); this.setValue(newValue); } } /* * (non-Javadoc) * * @see java.awt.event.FocusListener#focusGained(java.awt.event.FocusEvent) */ @Override public void focusGained(final FocusEvent e) { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see java.awt.event.FocusListener#focusLost(java.awt.event.FocusEvent) */ @Override public void focusLost(final FocusEvent e) { this.correct(); } /** * @return */ public long getBytes() { return ((Number) this.getValue()).longValue(); } @Override public Object getNextValue() { final Object ret = this.getValue(); final long num = ((Number) ret).longValue(); final Unit unit = SizeFormatter.getBestUnit(num); int c = (int) (num == 0 ? 0 : Math.log10(num / unit.getBytes())); c = Math.max(0, c - 1); long newV; if (this.nm.getMaximum() != null) { newV = (long) Math.min(((Number) this.nm.getMaximum()).longValue(), num + unit.getBytes() * Math.pow(10, c)); } else { newV = (long) (num + unit.getBytes() * Math.pow(10, c)); } final Unit newUnit = SizeFormatter.getBestUnit(newV); if (newUnit == unit) { if (newV == num) { this.beep(); } return newV; } newV = (int) (newV / newUnit.getBytes()) * newUnit.getBytes(); if (newV == num) { this.beep(); } return newV; } @Override public Object getPreviousValue() { final Object ret = this.getValue(); final long num = ((Number) ret).longValue(); final Unit unit = SizeFormatter.getBestUnit(num); int c = (int) (num == 0 ? 0 : Math.log10(num / unit.getBytes())); c = Math.max(0, c - 1); long nv; if (this.nm.getMinimum() != null) { nv = (long) Math.max(((Number) this.nm.getMinimum()).longValue(), num - unit.getBytes() * Math.pow(10, c)); } else { nv = (long) (num - unit.getBytes() * Math.pow(10, c)); } final Unit nunit = SizeFormatter.getBestUnit(nv); if (nunit == unit) { if (nv == num) { this.beep(); } return nv; } nv = Math.max(((Number) this.nm.getMinimum()).longValue(), num - unit.getBytes() / 1024); if (nv == num) { this.beep(); } return nv; } /** * @param longValue * @return */ protected String longToText(final long longValue) { return SizeFormatter.formatBytes(longValue); } @Override public void setModel(final SpinnerModel model) { throw new IllegalStateException("Not available"); } protected Object textToObject(final String text) { return SizeFormatter.getSize(text, true, true); } }
package org.voltdb; import org.voltdb.catalog.Catalog; import org.voltdb.catalog.CatalogMap; import org.voltdb.catalog.Cluster; import org.voltdb.catalog.Database; import org.voltdb.catalog.Procedure; import org.voltdb.catalog.Site; import org.voltdb.dtxn.SiteTracker; import org.voltdb.utils.JarClassLoader; public class CatalogContext { /** Pass this to constructor for catalog path in tests */ public static final String NO_PATH = "EMPTY_PATH"; // THE CATALOG! public final Catalog catalog; // PUBLIC IMMUTABLE CACHED INFORMATION public final Cluster cluster; public final Database database; public final CatalogMap<Procedure> procedures; public final CatalogMap<Site> sites; public final AuthSystem authSystem; public final int numberOfPartitions; public final int numberOfExecSites; public final int numberOfNodes; public final SiteTracker siteTracker; // PRIVATE private final String m_path; private final JarClassLoader m_catalogClassLoader; public CatalogContext(Catalog catalog, String pathToCatalogJar) { // check the heck out of the given params in this immutable class assert(catalog != null); assert(pathToCatalogJar != null); if (catalog == null) throw new RuntimeException("Can't create CatalogContext with null catalog."); if (pathToCatalogJar == null) throw new RuntimeException("Can't create CatalogContext with null jar path."); m_path = pathToCatalogJar; if (pathToCatalogJar.startsWith(NO_PATH) == false) m_catalogClassLoader = new JarClassLoader(pathToCatalogJar); else m_catalogClassLoader = null; this.catalog = catalog; cluster = catalog.getClusters().get("cluster"); database = cluster.getDatabases().get("database"); procedures = database.getProcedures(); authSystem = new AuthSystem(database, cluster.getSecurityenabled()); sites = cluster.getSites(); siteTracker = new SiteTracker(cluster.getSites()); // count nodes numberOfNodes = cluster.getHosts().size(); // count exec sites int execSiteCount = 0; for (Site site : sites) { if (site.getPartition() != null) { assert (site.getIsexec()); execSiteCount++; } } numberOfExecSites = execSiteCount; // count partitions numberOfPartitions = cluster.getPartitions().size(); } public CatalogContext deepCopy() { return new CatalogContext(catalog.deepCopy(), m_path); } public CatalogContext update(String pathToNewJar, String diffCommands) { Catalog newCatalog = catalog.deepCopy(); newCatalog.execute(diffCommands); CatalogContext retval = new CatalogContext(newCatalog, pathToNewJar); return retval; } /** * Given a class name in the catalog jar, loads it from the jar, even if the * jar is served from a url and isn't in the classpath. * * @param procedureClassName The name of the class to load. * @return A java Class variable assocated with the class. * @throws ClassNotFoundException if the class is not in the jar file. */ public Class<?> classForProcedure(String procedureClassName) throws ClassNotFoundException { //System.out.println("Loading class " + procedureClassName); // this is a safety mechanism to prevent catalog classes overriding voltdb stuff if (procedureClassName.startsWith("org.voltdb.")) return Class.forName(procedureClassName); // look in the catalog for the file return m_catalogClassLoader.loadClass(procedureClassName); } }
package com.opencms.file; import java.util.zip.*; import com.opencms.core.*; import com.opencms.template.*; import com.opencms.util.*; import java.util.*; import java.io.*; import org.w3c.dom.*; import com.opencms.file.genericSql.*; //import com.opencms.file.genericSql.linkmanagement.*; public class CmsResourceTypePage implements I_CmsResourceType, Serializable, I_CmsConstants, com.opencms.workplace.I_CmsWpConstants { /** Definition of the class */ private final static String C_CLASSNAME="com.opencms.template.CmsXmlTemplate"; private static final String C_DEFAULTBODY_START = "<?xml version=\"1.0\"?>\n<XMLTEMPLATE>\n<TEMPLATE>\n<![CDATA[\n"; private static final String C_DEFAULTBODY_END = "]]></TEMPLATE>\n</XMLTEMPLATE>"; /** * The id of resource type. */ private int m_resourceType; /** * The id of the launcher used by this resource. */ private int m_launcherType; /** * The resource type name. */ private String m_resourceTypeName; /** * The class name of the Java class launched by the launcher. */ private String m_launcherClass; /** * inits a new CmsResourceType object. * * @param resourceType The id of the resource type. * @param launcherType The id of the required launcher. * @param resourceTypeName The printable name of the resource type. * @param launcherClass The Java class that should be invoked by the launcher. * This value is <b> null </b> if the default invokation class should be used. */ public void init(int resourceType, int launcherType, String resourceTypeName, String launcherClass){ m_resourceType=resourceType; m_launcherType=launcherType; m_resourceTypeName=resourceTypeName; m_launcherClass=launcherClass; } /** * Returns the name of the Java class loaded by the launcher. * This method returns <b>null</b> if the default class for this type is used. * * @return the name of the Java class. */ public String getLauncherClass() { if ((m_launcherClass == null) || (m_launcherClass.length()<1)) { return C_UNKNOWN_LAUNCHER; } else { return m_launcherClass; } } /** * Returns the launcher type needed for this resource-type. * * @return the launcher type for this resource-type. */ public int getLauncherType() { return m_launcherType; } /** * Returns the name for this resource-type. * * @return the name for this resource-type. */ public String getResourceTypeName() { return m_resourceTypeName; } /** * Returns the type of this resource-type. * * @return the type of this resource-type. */ public int getResourceType() { return m_resourceType; } /** * Returns a string-representation for this object. * This can be used for debugging. * * @return string-representation for this object. */ public String toString() { StringBuffer output=new StringBuffer(); output.append("[ResourceType]:"); output.append(m_resourceTypeName); output.append(" , Id="); output.append(m_resourceType); output.append(" , launcherType="); output.append(m_launcherType); output.append(" , launcherClass="); output.append(m_launcherClass); return output.toString(); } /** * Changes the group of a resource. * <br> * Only the group of a resource in an offline project can be changed. The state * of the resource is set to CHANGED (1). * If the content of this resource is not existing in the offline project already, * it is read from the online project and written into the offline project. * <p> * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user is owner of the resource or is admin</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param filename the complete path to the resource. * @param newGroup the name of the new group for this resource. * @param chRekursive only used by folders. * * @exception CmsException if operation was not successful. */ public void chgrp(CmsObject cms, String filename, String newGroup, boolean chRekursive) throws CmsException{ CmsFile file = cms.readFile(filename); // check if the current user has the right to change the group of the // resource. Only the owner of a file and the admin are allowed to do this. if ((cms.getRequestContext().currentUser().equals(cms.readOwner(file))) || (cms.userInGroup(cms.getRequestContext().currentUser().getName(), C_GROUP_ADMIN))){ cms.doChgrp(filename, newGroup); //check if the file type name is page String bodyPath = checkBodyPath(cms, (CmsFile)file); if (bodyPath != null){ cms.doChgrp(bodyPath, newGroup); } } } /** * Changes the flags of a resource. * <br> * Only the flags of a resource in an offline project can be changed. The state * of the resource is set to CHANGED (1). * If the content of this resource is not existing in the offline project already, * it is read from the online project and written into the offline project. * The user may change the flags, if he is admin of the resource. * <p> * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param filename the complete path to the resource. * @param flags the new flags for the resource. * @param chRekursive only used by folders. * * @exception CmsException if operation was not successful. * for this resource. */ public void chmod(CmsObject cms, String filename, int flags, boolean chRekursive) throws CmsException{ CmsFile file = cms.readFile(filename); // check if the current user has the right to change the group of the // resource. Only the owner of a file and the admin are allowed to do this. if ((cms.getRequestContext().currentUser().equals(cms.readOwner(file))) || (cms.userInGroup(cms.getRequestContext().currentUser().getName(), C_GROUP_ADMIN))){ // modify the access flags cms.doChmod(filename, flags); String bodyPath = checkBodyPath(cms, (CmsFile)file); if (bodyPath != null){ // set the internal read flag if nescessary if ((flags & C_ACCESS_INTERNAL_READ) ==0 ) { flags += C_ACCESS_INTERNAL_READ; } cms.doChmod(bodyPath, flags); } } } /** * Changes the owner of a resource. * <br> * Only the owner of a resource in an offline project can be changed. The state * of the resource is set to CHANGED (1). * If the content of this resource is not existing in the offline project already, * it is read from the online project and written into the offline project. * The user may change this, if he is admin of the resource. * <p> * <B>Security:</B> * Access is cranted, if: * <ul> * <li>the user has access to the project</li> * <li>the user is owner of the resource or the user is admin</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param filename the complete path to the resource. * @param newOwner the name of the new owner for this resource. * @param chRekursive only used by folders. * * @exception CmsException if operation was not successful. */ public void chown(CmsObject cms, String filename, String newOwner, boolean chRekursive) throws CmsException{ CmsFile file = cms.readFile(filename); // check if the current user has the right to change the group of the // resource. Only the owner of a file and the admin are allowed to do this. if ((cms.getRequestContext().currentUser().equals(cms.readOwner(file))) || (cms.userInGroup(cms.getRequestContext().currentUser().getName(), C_GROUP_ADMIN))){ cms.doChown(filename, newOwner); //check if the file type name is page String bodyPath = checkBodyPath(cms, (CmsFile)file); if (bodyPath != null){ cms.doChown(bodyPath, newOwner); } } } /** * Changes the resourcetype of a resource. * <br> * Only the resourcetype of a resource in an offline project can be changed. The state * of the resource is set to CHANGED (1). * If the content of this resource is not exisiting in the offline project already, * it is read from the online project and written into the offline project. * The user may change this, if he is admin of the resource. * <p> * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user is owner of the resource or is admin</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param filename the complete path to the resource. * @param newType the name of the new resourcetype for this resource. * * @exception CmsException if operation was not successful. */ public void chtype(CmsObject cms, String filename, String newType) throws CmsException{ CmsFile file = cms.readFile(filename); // check if the current user has the right to change the group of the // resource. Only the owner of a file and the admin are allowed to do this. if ((cms.getRequestContext().currentUser().equals(cms.readOwner(file))) || (cms.userInGroup(cms.getRequestContext().currentUser().getName(), C_GROUP_ADMIN))){ cms.doChtype(filename, newType); //check if the file type name is page String bodyPath = checkBodyPath(cms, (CmsFile)file); if (bodyPath != null){ cms.doChtype(bodyPath, newType); } } } /** * Copies a Resource. * * @param source the complete path of the sourcefile. * @param destination the complete path of the destinationfolder. * @param keepFlags <code>true</code> if the copy should keep the source file's flags, * <code>false</code> if the copy should get the user's default flags. * * @exception CmsException if the file couldn't be copied, or the user * has not the appropriate rights to copy the file. */ public void copyResource(CmsObject cms, String source, String destination, boolean keepFlags) throws CmsException{ // Read and parse the source page file CmsFile file = cms.readFile(source); CmsXmlControlFile hXml=new CmsXmlControlFile(cms, file); // Check the path of the body file. // Don't use the checkBodyPath method here to avaoid overhead. String bodyPath=(C_CONTENTBODYPATH.substring(0, C_CONTENTBODYPATH.lastIndexOf("/")))+(source); if (bodyPath.equals(hXml.getElementTemplate("body"))){ // Evaluate some path information String destinationFolder = destination.substring(0,destination.lastIndexOf("/")+1); checkFolders(cms, destinationFolder); String newbodyPath=(C_CONTENTBODYPATH.substring(0, C_CONTENTBODYPATH.lastIndexOf("/")))+ destination; // we don't want to use the changeContent method here // to avoid overhead by copying, readig, parsing, setting XML and writing again. // Instead, we re-use the already parsed XML content of the source hXml.setElementTemplate("body", newbodyPath); cms.doCopyFile(source, destination); CmsFile newPageFile = cms.readFile(destination); newPageFile.setContents(hXml.getXmlText().getBytes()); cms.writeFile(newPageFile); // Now the new page file is created. Copy the body file cms.doCopyFile(bodyPath, newbodyPath); // set access flags, if neccessary } else { // The body part of the source was not found at // the default place. Leave it there, don't make // a copy and simply make a copy of the page file. // So the new page links to the old body. cms.doCopyFile(source, destination); // set access flags, if neccessary } if(!keepFlags) { setDefaultFlags(cms, destination); } } /** * Copies a resource from the online project to a new, specified project. * <br> * Copying a resource will copy the file header or folder into the specified * offline project and set its state to UNCHANGED. * * @param resource the name of the resource. * @exception CmsException if operation was not successful. */ public void copyResourceToProject(CmsObject cms, String resourceName) throws CmsException { //String resourceName = linkManager.getResourceName(resourceId); CmsFile file = cms.readFile(resourceName); cms.doCopyResourceToProject(resourceName); //check if the file type name is page String bodyPath = checkBodyPath(cms, (CmsFile)file); if (bodyPath != null){ cms.doCopyResourceToProject(bodyPath); } } /** * Creates a new resource * * @param cms The CmsObject * @param folder The name of the parent folder * @param name The name of the file * @param properties The properties of the file * @param contents The file content * * @exception CmsException if operation was not successful. */ public CmsResource createResource(CmsObject cms, String folder, String name, Hashtable properties, byte[] contents) throws CmsException{ // Scan for mastertemplates Vector allMasterTemplates = cms.getFilesInFolder(C_CONTENTTEMPLATEPATH); // Select the first mastertemplate as default String masterTemplate = ""; if(allMasterTemplates.size() > 0) { masterTemplate = ((CmsFile)allMasterTemplates.elementAt(0)).getAbsolutePath(); } // Evaluate the absolute path to the new body file String bodyFolder =(C_CONTENTBODYPATH.substring(0, C_CONTENTBODYPATH.lastIndexOf("/"))) + folder; // Create the new page file CmsFile file = cms.doCreateFile(folder, name, "".getBytes(), I_CmsConstants.C_TYPE_PAGE_NAME, properties); cms.doLockResource(folder + name, true); CmsXmlControlFile pageXml = new CmsXmlControlFile(cms, file); pageXml.setTemplateClass(C_CLASSNAME); pageXml.setMasterTemplate(masterTemplate); pageXml.setElementClass("body", C_CLASSNAME); pageXml.setElementTemplate("body", bodyFolder + name); pageXml.write(); // Check, if the body path exists and create missing folders, if neccessary checkFolders(cms, folder); // Create the new body file //CmsFile bodyFile = cms.doCreateFile(bodyFolder, name, (C_DEFAULTBODY_START + new String(contents) + C_DEFAULTBODY_END).getBytes(), I_CmsConstants.C_TYPE_BODY_NAME, new Hashtable()); CmsFile bodyFile = cms.doCreateFile(bodyFolder, name, (C_DEFAULTBODY_START + new String(contents) + C_DEFAULTBODY_END).getBytes(), I_CmsConstants.C_TYPE_PLAIN_NAME, new Hashtable()); cms.doLockResource(bodyFolder + name, true); cms.chmod(bodyFile.getAbsolutePath(), bodyFile.getAccessFlags() + C_ACCESS_INTERNAL_READ); return file; } public CmsResource createResource(CmsObject cms, String folder, String name, Hashtable properties, byte[] contents, String masterTemplate) throws CmsException{ CmsFile resource = (CmsFile)createResource(cms, folder, name, properties, contents); CmsXmlControlFile pageXml = new CmsXmlControlFile(cms, resource); pageXml.setMasterTemplate(masterTemplate); pageXml.write(); return resource; } /** * Deletes a resource. * * @param filename the complete path of the file. * * @exception CmsException if the file couldn't be deleted, or if the user * has not the appropriate rights to delete the file. */ public void deleteResource(CmsObject cms, String filename) throws CmsException{ CmsFile file = cms.readFile(filename); cms.doDeleteFile(filename); String bodyPath = checkBodyPath(cms, (CmsFile)file); if (bodyPath != null){ cms.doDeleteFile(bodyPath); } // The page file contains XML. // So there could be some data in the parser's cache. // Clear it! String currentProject = cms.getRequestContext().currentProject().getName(); CmsXmlControlFile.clearFileCache(currentProject + ":" + filename); } /** * Undeletes a resource. * * @param filename the complete path of the file. * * @exception CmsException if the file couldn't be undeleted, or if the user * has not the appropriate rights to undelete the file. */ public void undeleteResource(CmsObject cms, String filename) throws CmsException{ CmsFile file = cms.readFile(filename); cms.doUndeleteFile(filename); String bodyPath = checkBodyPath(cms, (CmsFile)file); if (bodyPath != null){ cms.doUndeleteFile(bodyPath); } // The page file contains XML. // So there could be some data in the parser's cache. // Clear it! String currentProject = cms.getRequestContext().currentProject().getName(); CmsXmlControlFile.clearFileCache(currentProject + ":" + filename); } /** * When a resource has to be exported, the IDs inside the * Linkmanagement-Tags have to be changed to the corresponding URLs * * @param file is the file that has to be changed */ public CmsFile exportResource(CmsObject cms, CmsFile file) throws CmsException { //nothing to do here, because there couldnt be any Linkmanagement-Tags in a page-file (control-file) return file; } /** * When a resource has to be imported, the URLs of the * Links inside the resources have to be saved and changed to the corresponding IDs * * @param file is the file that has to be changed */ public CmsResource importResource(CmsObject cms, String source, String destination, String type, String user, String group, String access, Hashtable properties, String launcherStartClass, byte[] content, String importPath) throws CmsException { CmsFile file = null; String path = importPath + destination.substring(0, destination.lastIndexOf("/") + 1); String name = destination.substring((destination.lastIndexOf("/") + 1), destination.length()); int state = C_STATE_NEW; // this is a file // first delete the file, so it can be overwritten try { lockResource(cms, path + name, true); deleteResource(cms, path + name); state = C_STATE_CHANGED; } catch (CmsException exc) { state = C_STATE_NEW; // ignore the exception, the file dosen't exist } // now create the file // do not use createResource because then there will the body-file be created too. // that would cause an exception while importing because of trying to // duplicate an entry file = (CmsFile)cms.doCreateFile(path, name, content, type, properties); String fullname = file.getAbsolutePath(); lockResource(cms, fullname, true); try{ cms.doChmod(fullname, Integer.parseInt(access)); }catch(CmsException e){ System.out.println("chmod(" + access + ") failed "); } try{ cms.doChgrp(fullname, group); }catch(CmsException e){ System.out.println("chgrp(" + group + ") failed "); } try{ cms.doChown(fullname, user); }catch(CmsException e){ System.out.println("chown((" + user + ") failed "); } if(launcherStartClass != null){ file.setLauncherClassname(launcherStartClass); cms.writeFile(file); } return file; } /** * Locks a given resource. * <br> * A user can lock a resource, so he is the only one who can write this * resource. * * @param resource the complete path to the resource to lock. * @param force if force is <code>true</code>, a existing locking will be overwritten. * * @exception CmsException if the user has not the rights to lock this resource. * It will also be thrown, if there is a existing lock and force was set to false. */ public void lockResource(CmsObject cms, String resource, boolean force) throws CmsException{ // First read the page file. CmsFile pageFile = cms.readFile(resource); CmsUser pageLocker = null; CmsUser bodyLocker = null; // Check any locks on th page file pageLocker = getLockedBy(cms, resource); CmsUser currentUser = cms.getRequestContext().currentUser(); boolean pageLockedAndSelf = pageLocker != null && currentUser.equals(pageLocker); CmsResource bodyFile = null; String bodyPath = null; // Try to fetch the body file. try { bodyPath = readBodyPath(cms, pageFile); bodyFile = cms.readFileHeader(bodyPath); } catch(Exception e) { bodyPath = null; bodyFile = null; } // first lock the page file cms.doLockResource(resource, force); if(bodyFile != null) { // Everything with the page file is ok. We have write access. XML is valid. // Body file could be determined and fetched. // Now check further body file details (is it locked already, WHO has locked it, etc.) bodyLocker = getLockedBy(cms, bodyPath); // Lock the body, if neccessary //if((bodyLocker == null && (pageLocker == null || pageLockedAndSelf || force)) // || (bodyLocker != null && !currentUser.equals(bodyLocker) // && !(pageLocker != null && !currentUser.equals(pageLocker) && !force))) { cms.doLockResource(bodyPath, force); } /* // Lock the page file, if neccessary if(!(pageLockedAndSelf && (bodyFile != null && ((bodyLocker == null) || !currentUser.equals(bodyLocker))))) { cms.doLockResource(resource, force); } */ } /** * Moves a resource to the given destination. * * @param source the complete path of the sourcefile. * @param destination the complete path of the destinationfile. * * @exception CmsException if the user has not the rights to move this resource, * or if the file couldn't be moved. */ public void moveResource(CmsObject cms, String source, String destination) throws CmsException{ CmsFile file = cms.readFile(source); //String bodyPath = readBodyPath(cms, source); String bodyPath = checkBodyPath(cms, file); //int help = C_CONTENTBODYPATH.lastIndexOf("/"); //String hbodyPath=(C_CONTENTBODYPATH.substring(0,help)) + source; //if(hbodyPath.equals(bodyPath)) { if(bodyPath != null) { //help=bodyPath.lastIndexOf("/") + 1; //hbodyPath = bodyPath.substring(0,help) + destination; //String hbodyPath = bodyPath.substring(0, bodyPath.lastIndexOf("/")) + destination; String hbodyPath = C_CONTENTBODYPATH.substring(0, C_CONTENTBODYPATH.lastIndexOf("/")) + destination; checkFolders(cms, destination.substring(0, destination.lastIndexOf("/"))); cms.doMoveFile(bodyPath, hbodyPath); changeContent(cms, source, hbodyPath); } cms.doMoveFile(source, destination); } /** * Renames the file to the new name. * * @param oldname the complete path to the file which will be renamed. * @param newname the new name of the file. * * @exception CmsException if the user has not the rights * to rename the file, or if the file couldn't be renamed. */ public void renameResource(CmsObject cms, String oldname, String newname) throws CmsException{ CmsFile file = cms.readFile(oldname); String bodyPath = readBodyPath(cms, file); int help = C_CONTENTBODYPATH.lastIndexOf("/"); String hbodyPath=(C_CONTENTBODYPATH.substring(0,help)) + oldname; if(hbodyPath.equals(bodyPath)) { cms.doRenameFile(bodyPath, newname); help=bodyPath.lastIndexOf("/") + 1; hbodyPath = bodyPath.substring(0,help) + newname; changeContent(cms, oldname, hbodyPath); } cms.doRenameFile(oldname,newname); } /** * Restores a file in the current project with a version in the backup * * @param cms The CmsObject * @param versionId The version id of the resource * @param filename The name of the file to restore * * @exception CmsException Throws CmsException if operation was not succesful. */ public void restoreResource(CmsObject cms, int versionId, String filename) throws CmsException{ if(!cms.accessWrite(filename)){ throw new CmsException(filename, CmsException.C_NO_ACCESS); } CmsFile file = cms.readFile(filename); cms.doRestoreResource(versionId, filename); String bodyPath = checkBodyPath(cms, (CmsFile)file); if (bodyPath != null){ cms.doRestoreResource(versionId, bodyPath); } } /** * Undo changes in a resource. * <br> * * @param resource the complete path to the resource to be restored. * * @exception CmsException if the user has not the rights * to write this resource. */ public void undoChanges(CmsObject cms, String resource) throws CmsException{ if(!cms.accessWrite(resource)){ throw new CmsException(resource, CmsException.C_NO_ACCESS); } CmsFile file = cms.readFile(resource); cms.doUndoChanges(resource); String bodyPath = checkBodyPath(cms, (CmsFile)file); if (bodyPath != null){ cms.doUndoChanges(bodyPath); } } /** * Unlocks a resource. * <br> * A user can unlock a resource, so other users may lock this file. * * @param resource the complete path to the resource to be unlocked. * * @exception CmsException if the user has not the rights * to unlock this resource. */ public void unlockResource(CmsObject cms, String resource) throws CmsException{ // First read the page file. CmsFile pageFile = cms.readFile(resource); CmsUser pageLocker = null; CmsUser bodyLocker = null; // Check any locks on th page file pageLocker = getLockedBy(cms, resource); CmsUser currentUser = cms.getRequestContext().currentUser(); CmsResource bodyFile = null; String bodyPath = null; // Try to fetch the body file. try { bodyPath = readBodyPath(cms, pageFile); bodyFile = cms.readFileHeader(bodyPath); } catch(Exception e) { bodyPath = null; bodyFile = null; } cms.doUnlockResource(resource); if(bodyFile != null) { // Everything with the page file is ok. We have write access. XML is valid. // Body file could be determined and fetched. // Now check further body file details (is it locked already, WHO has locked it, etc.) bodyLocker = getLockedBy(cms, bodyPath); // Unlock the body, if neccessary //if((pageLocker == null || pageLocker.equals(currentUser)) && (bodyLocker != null)) { cms.doUnlockResource(bodyPath); } // Unlock the page file, if neccessary //if(pageLocker != null || bodyLocker == null) { //cms.doUnlockResource(resource); } /** * method to check get the real body path from the content file * * @param cms The CmsObject, to access the XML read file. * @param file File in which the body path is stored. This should really * be a CmsFile object an not a file header. This won't be checked for * performance reasons. */ private String readBodyPath(CmsObject cms, CmsFile file) throws CmsException{ CmsXmlControlFile hXml=new CmsXmlControlFile(cms, file); String body = ""; try{ body = hXml.getElementTemplate("body"); } catch (CmsException exc){ // could not read body } return body; } /** * method to check get the real body path from the content file * * @param cms The CmsObject, to access the XML read file. * @param file File in which the body path is stored. */ private String checkBodyPath(CmsObject cms, CmsFile file) throws CmsException { String result =(C_CONTENTBODYPATH.substring(0, C_CONTENTBODYPATH.lastIndexOf("/")))+(file.getAbsolutePath()); if (!result.equals(readBodyPath(cms, (CmsFile)file))){ result = null; } return result; } private CmsUser getLockedBy(CmsObject cms, String filename) { CmsUser result = null; try { result = cms.lockedBy(filename); if(result.getId() == -1) { result = null; } } catch(Exception e) { result = null; } return result; } /** * This method changes the path of the body file in the xml conten file * if file type name is page * * @param cms The CmsObject * @param file The XML content file * @param bodypath the new XML content entry * @exception Exception if something goes wrong. */ private void changeContent(CmsObject cms, String filename, String bodypath) throws CmsException { CmsFile file=cms.readFile(filename); CmsXmlControlFile hXml=new CmsXmlControlFile(cms, file); hXml.setElementTemplate("body", bodypath); hXml.write(); } /** * This method checks if all nescessary folders are exisitng in the content body * folder and creates the missing ones. <br> * All page contents files are stored in the content body folder in a mirrored directory * structure of the OpenCms filesystem. Therefor it is nescessary to create the * missing folders when a new page document is createg. * @param cms The CmsObject * @param path The path in the CmsFilesystem where the new page should be created. * @exception CmsException if something goes wrong. */ private void checkFolders(CmsObject cms, String path) throws CmsException { String completePath=C_CONTENTBODYPATH; StringTokenizer t=new StringTokenizer(path,"/"); // check if all folders are there while (t.hasMoreTokens()) { String foldername=t.nextToken(); try { // try to read the folder. if this fails, an exception is thrown cms.readFolder(completePath+foldername+"/"); } catch (CmsException e) { // the folder could not be read, so create it. String orgFolder=completePath+foldername+"/"; orgFolder=orgFolder.substring(C_CONTENTBODYPATH.length()-1); CmsFolder newfolder=cms.doCreateFolder(completePath,foldername); CmsFolder folder=cms.readFolder(orgFolder); cms.doLockResource(newfolder.getAbsolutePath(),false); cms.doChgrp(newfolder.getAbsolutePath(),cms.readGroup(folder).getName()); cms.doChmod(newfolder.getAbsolutePath(),folder.getAccessFlags()); cms.doChown(newfolder.getAbsolutePath(),cms.readOwner(folder).getName()); cms.doUnlockResource(newfolder.getAbsolutePath()); } completePath+=foldername+"/"; } } /** * Set the access flags of the copied resource to the default values. * @param cms The CmsObject. * @param filename The name of the file. * @exception Throws CmsException if something goes wrong. */ private void setDefaultFlags(CmsObject cms, String filename) throws CmsException { Hashtable startSettings=null; Integer accessFlags=null; startSettings=(Hashtable)cms.getRequestContext().currentUser().getAdditionalInfo(C_ADDITIONAL_INFO_STARTSETTINGS); if (startSettings != null) { accessFlags=(Integer)startSettings.get(C_START_ACCESSFLAGS); } if (accessFlags == null) { accessFlags = new Integer(C_ACCESS_DEFAULT_FLAGS); } chmod(cms, filename, accessFlags.intValue(), false); } /** * Changes the project-id of the resource to the new project * for publishing the resource directly * * @param newProjectId The Id of the new project * @param resourcename The name of the resource to change */ public void changeLockedInProject(CmsObject cms, int newProjectId, String resourcename) throws CmsException{ CmsFile file = cms.readFile(resourcename); cms.doChangeLockedInProject(newProjectId, resourcename); String bodyPath = checkBodyPath(cms, (CmsFile)file); if (bodyPath != null){ cms.doChangeLockedInProject(newProjectId, bodyPath); } // The page file contains XML. // So there could be some data in the parser's cache. // Clear it! String currentProject = cms.getRequestContext().currentProject().getName(); CmsXmlControlFile.clearFileCache(currentProject + ":" + resourcename); } }
package org.bouncycastle.bcpg; import java.io.*; import java.util.Vector; /** * reader for Base64 armored objects - read the headers and then start returning * bytes when the data is reached. An IOException is thrown if the CRC check * fails. */ public class ArmoredInputStream extends InputStream { /* * set up the decoding table. */ private static final byte[] decodingTable; static { decodingTable = new byte[128]; for (int i = 'A'; i <= 'Z'; i++) { decodingTable[i] = (byte)(i - 'A'); } for (int i = 'a'; i <= 'z'; i++) { decodingTable[i] = (byte)(i - 'a' + 26); } for (int i = '0'; i <= '9'; i++) { decodingTable[i] = (byte)(i - '0' + 52); } decodingTable['+'] = 62; decodingTable['/'] = 63; } /** * decode the base 64 encoded input data. * * @return the offset the data starts in out. */ private int decode( int in0, int in1, int in2, int in3, int[] out) throws EOFException { int b1, b2, b3, b4; if (in3 < 0) { throw new EOFException("unexpected end of file in armored stream."); } if (in2 == '=') { b1 = decodingTable[in0] &0xff; b2 = decodingTable[in1] & 0xff; out[2] = ((b1 << 2) | (b2 >> 4)) & 0xff; return 2; } else if (in3 == '=') { b1 = decodingTable[in0]; b2 = decodingTable[in1]; b3 = decodingTable[in2]; out[1] = ((b1 << 2) | (b2 >> 4)) & 0xff; out[2] = ((b2 << 4) | (b3 >> 2)) & 0xff; return 1; } else { b1 = decodingTable[in0]; b2 = decodingTable[in1]; b3 = decodingTable[in2]; b4 = decodingTable[in3]; out[0] = ((b1 << 2) | (b2 >> 4)) & 0xff; out[1] = ((b2 << 4) | (b3 >> 2)) & 0xff; out[2] = ((b3 << 6) | b4) & 0xff; return 0; } } InputStream in; boolean start = true; int[] outBuf = new int[3]; int bufPtr = 3; CRC24 crc = new CRC24(); boolean crcFound = false; boolean hasHeaders = true; String header = null; boolean newLineFound = false; boolean clearText = false; boolean restart = false; Vector headerList= new Vector(); int lastC = 0; /** * Create a stream for reading a PGP armoured message, parsing up to a header * and then reading the data that follows. * * @param in */ public ArmoredInputStream( InputStream in) throws IOException { this(in, true); } /** * Create an armoured input stream which will assume the data starts * straight away, or parse for headers first depending on the value of * hasHeaders. * * @param in * @param hasHeaders true if headers are to be looked for, false otherwise. */ public ArmoredInputStream( InputStream in, boolean hasHeaders) throws IOException { this.in = in; this.hasHeaders = hasHeaders; if (hasHeaders) { parseHeaders(); } start = false; } public int available() throws IOException { return in.available(); } private boolean parseHeaders() throws IOException { header = null; int c; int last = 0; boolean headerFound = false; headerList = new Vector(); // if restart we already have a header if (restart) { headerFound = true; } else { while ((c = in.read()) >= 0) { if (c == '-' && (last == 0 || last == '\n' || last == '\r')) { headerFound = true; break; } last = c; } } if (headerFound) { StringBuffer buf = new StringBuffer("-"); boolean eolReached = false; boolean crLf = false; if (restart) // we've had to look ahead two '-' { buf.append('-'); } while ((c = in.read()) >= 0) { if (last == '\r' && c == '\n') { crLf = true; } if (eolReached && (last != '\r' && c == '\n')) { break; } if (eolReached && c == '\r') { break; } if (c == '\r' || (last != '\r' && c == '\n')) { headerList.addElement(buf.toString()); buf.setLength(0); } if (c != '\n' && c != '\r') { buf.append((char)c); eolReached = false; } else { if (c == '\r' || (last != '\r' && c == '\n')) { eolReached = true; } } last = c; } if (crLf) { in.read(); // skip last \n } } if (headerList.size() > 0) { header = (String)headerList.elementAt(0); } clearText = " newLineFound = true; return headerFound; } /** * @return true if we are inside the clear text section of a PGP * signed message. */ public boolean isClearText() { return clearText; } /** * Return the armor header line (if there is one) * @return the armor header line, null if none present. */ public String getArmorHeaderLine() { return header; } /** * Return the armor headers (the lines after the armor header line), * @return an array of armor headers, null if there aren't any. */ public String[] getArmorHeaders() { if (headerList.size() <= 1) { return null; } String[] hdrs = new String[headerList.size() - 1]; for (int i = 0; i != hdrs.length; i++) { hdrs[i] = (String)headerList.elementAt(i + 1); } return hdrs; } private int readIgnoreSpace() throws IOException { int c = in.read(); while (c == ' ' || c == '\t') { c = in.read(); } return c; } public int read() throws IOException { int c; if (start) { if (hasHeaders) { parseHeaders(); } crc.reset(); start = false; } if (clearText) { c = in.read(); if (c == '\r' || (c == '\n' && lastC != '\r')) { newLineFound = true; } else if (newLineFound && c == '-') { c = in.read(); if (c == '-') // a header, not dash escaped { clearText = false; start = true; restart = true; } else // a space - must be a dash escape { c = in.read(); } newLineFound = false; } else { if (c != '\n' && lastC != '\r') { newLineFound = false; } } lastC = c; return c; } if (bufPtr > 2 || crcFound) { c = readIgnoreSpace(); if (c == '\r' || c == '\n') { c = readIgnoreSpace(); while (c == '\n' || c == '\r') { c = readIgnoreSpace(); } if (c < 0) // EOF { return -1; } if (c == '=') // crc reached { bufPtr = decode(readIgnoreSpace(), readIgnoreSpace(), readIgnoreSpace(), readIgnoreSpace(), outBuf); if (bufPtr == 0) { int i = ((outBuf[0] & 0xff) << 16) | ((outBuf[1] & 0xff) << 8) | (outBuf[2] & 0xff); crcFound = true; if (i != crc.getValue()) { throw new IOException("crc check failed in armored message."); } return read(); } else { throw new IOException("no crc found in armored message."); } } else if (c == '-') // end of record reached { while ((c = in.read()) >= 0) { if (c == '\n' || c == '\r') { break; } } if (!crcFound) { throw new IOException("crc check not found."); } crcFound = false; start = true; bufPtr = 3; return -1; } else // data { bufPtr = decode(c, readIgnoreSpace(), readIgnoreSpace(), readIgnoreSpace(), outBuf); } } else { if (c >= 0) { bufPtr = decode(c, readIgnoreSpace(), readIgnoreSpace(), readIgnoreSpace(), outBuf); } else { return -1; } } } c = outBuf[bufPtr++]; crc.update(c); return c; } public void close() throws IOException { in.close(); } }
package com.opencms.template; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import org.w3c.dom.CDATASection; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import com.opencms.boot.I_CmsLogChannels; import com.opencms.core.A_OpenCms; import com.opencms.core.CmsException; import com.opencms.file.CmsFile; import com.opencms.file.CmsObject; public abstract class A_CmsXmlContent implements I_CmsXmlContent,I_CmsLogChannels { /** parameter types for XML node handling methods. */ public static final Class[] C_PARAMTYPES_HANDLING_METHODS = new Class[] { Element.class, Object.class, Object.class }; /** parameter types for user methods called by METHOD tags */ public static final Class[] C_PARAMTYPES_USER_METHODS = new Class[] { CmsObject.class, String.class, A_CmsXmlContent.class, Object.class }; /** The classname of the super XML content class */ public static final String C_MINIMUM_CLASSNAME = "com.opencms.template.A_CmsXmlContent"; /** Constant pathname, where to find templates */ public static final String C_TEMPLATEPATH = "/system/workplace/templates/"; /** Constant extension of the template-files. */ public static final String C_TEMPLATE_EXTENSION = ""; /** Error message for bad <code>&lt;PROCESS&gt;</code> tags */ public static final String C_ERR_NODATABLOCK = "? UNKNOWN DATABLOCK "; /** CmsObject Object for accessing resources */ protected CmsObject m_cms; /** All XML tags known by this class. */ protected Vector m_knownTags = new Vector(); /** * This Hashtable contains some XML tags as keys * and the corresponding methods as values. * Used to pass to processNode() to read in * include files and scan for datablocks. */ protected Hashtable m_firstRunTags = new Hashtable(); /** * This Hashtable contains some XML tags as keys * and the corresponding methods as values. * Used to pass to processNode() before generating * HTML output. */ protected Hashtable m_mainProcessTags = new Hashtable(); /** constant for registering handling tags */ protected final static int C_REGISTER_FIRST_RUN = 1; /** constant for registering handling tags */ protected final static int C_REGISTER_MAIN_RUN = 2; /** Boolean for additional debug output control */ private static final boolean C_DEBUG = false; /** DOM representaion of the template content. */ private Document m_content; /** Filename this template was read from */ private String m_filename; /** All datablocks in DOM format */ private Hashtable m_blocks = new Hashtable(); /** Reference All included A_CmsXmlContents */ private Vector m_includedTemplates = new Vector(); /** Cache for parsed documents */ static private Hashtable m_filecache = new Hashtable(); /** XML parser */ private static I_CmsXmlParser parser = new CmsXmlXercesParser(); private String m_newEncoding = null; // private static I_CmsXmlParser parser = new CmsXmlProjectXParser(); /** Constructor for creating a new instance of this class */ public A_CmsXmlContent() { registerAllTags(); } /** * Calls a user method in the object callingObject. * Every user method has to user the parameter types defined in * C_PARAMTYPES_USER_METHODS to be recognized by this method. * * @see #C_PARAMTYPES_USER_METHODS * @param methodName Name of the method to be called. * @param parameter Additional parameter passed to the method. * @param callingObject Reference to the object containing the called method. * @param userObj Customizable user object that will be passed through to the user method. * @param resolveMethods If true the methodtags will be resolved even if they have own CacheDirectives. * @throws CmsException */ protected Object callUserMethod(String methodName, String parameter, Object callingObject, Object userObj, boolean resolveMethods) throws CmsException { Object[] params = new Object[] { m_cms, parameter, this, userObj }; Object result = null; // Check if the user selected a object where to look for the user method. if(callingObject == null) { throwException("You are trying to call the user method \"" + methodName + "\" without giving an object containing this method. " + "Please select a callingObject in your getProcessedData or getProcessedDataValue call.", CmsException.C_XML_NO_USER_METHOD); } // check if the method has cachedirectives, if so we just return null // this way the methode tag stays in the Element and can be handled like // an normal element. We do this only if elementCache is active. if(m_cms.getRequestContext().isElementCacheEnabled() && !resolveMethods){ try{ if(callingObject.getClass().getMethod("getMethodCacheDirectives", new Class[] { CmsObject.class, String.class}).invoke(callingObject, new Object[] {m_cms, methodName}) != null){ return null; } }catch(NoSuchMethodException e){ throwException("Method getMethodeCacheDirectives was not found in class " + callingObject.getClass().getName() + ".", CmsException.C_XML_NO_USER_METHOD); }catch(InvocationTargetException targetEx) { // the method could be invoked, but throwed a exception // itself. Get this exception and throw it again. Throwable e = targetEx.getTargetException(); if(!(e instanceof CmsException)) { // Only print an error if this is NO CmsException throwException("Method getMethodeCacheDirectives throwed an exception. " + e, CmsException.C_UNKNOWN_EXCEPTION); }else { // This is a CmsException Error printing should be done previously. throw (CmsException)e; } }catch(Exception exc2) { throwException("Method getMethodeCacheDirectives was found but could not be invoked. " + exc2, CmsException.C_XML_NO_USER_METHOD); } } // OK. We have a calling object. Now try to invoke the method try { // try to invoke the method 'methodName' result = getUserMethod(methodName, callingObject).invoke(callingObject, params); }catch(NoSuchMethodException exc) { throwException("User method " + methodName + " was not found in class " + callingObject.getClass().getName() + ".", CmsException.C_XML_NO_USER_METHOD); }catch(InvocationTargetException targetEx) { // the method could be invoked, but throwed a exception // itself. Get this exception and throw it again. Throwable e = targetEx.getTargetException(); if(!(e instanceof CmsException)) { // Only print an error if this is NO CmsException throwException("User method " + methodName + " throwed an exception. " + e, CmsException.C_UNKNOWN_EXCEPTION); }else { // This is a CmsException // Error printing should be done previously. throw (CmsException)e; } }catch(Exception exc2) { throwException("User method " + methodName + " was found but could not be invoked. " + exc2, CmsException.C_XML_NO_USER_METHOD); } if((result != null) && (!(result instanceof String || result instanceof CmsProcessedString || result instanceof Integer || result instanceof NodeList || result instanceof byte[]))) { throwException("User method " + methodName + " in class " + callingObject.getClass().getName() + " returned an unsupported Object: " + result.getClass().getName(), CmsException.C_XML_PROCESS_ERROR); } return (result); } /** * Deletes all files from the file cache. */ public static void clearFileCache() { if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_CACHE, "[A_CmsXmlContent] clearing XML file cache."); } m_filecache.clear(); } /** * Deletes the file represented by the given A_CmsXmlContent from * the file cache. * @param doc A_CmsXmlContent representing the XML file to be deleted. */ public static void clearFileCache(A_CmsXmlContent doc) { if(doc != null) { String currentProject = doc.m_cms.getRequestContext().currentProject().getName(); m_filecache.remove(currentProject + ":" + doc.getAbsoluteFilename()); } } /** * Deletes the file with the given key from the file cache. * If no such file exists nothing happens. * @param key Key of the template file to be removed from the cache. */ public static void clearFileCache(String key) { m_filecache.remove(key); } /** * Creates a clone of this object. * @return cloned object. * @throws CloneNotSupportedException */ public Object clone() throws CloneNotSupportedException { try { A_CmsXmlContent newDoc = (A_CmsXmlContent)getClass().newInstance(); newDoc.init(m_cms, (Document)m_content.cloneNode(true), m_filename); return newDoc; } catch(Exception e) { if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + "Error while trying to clone object."); A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + e); } throw new CloneNotSupportedException(e.toString()); } } /** * Concats two datablock hashtables and returns the resulting one. * * @param data1 First datablock hashtable. * @param data2 Second datablock hashtable. * @return Concatenated data. */ private Hashtable concatData(Hashtable data1, Hashtable data2) { Hashtable retValue = (Hashtable)data1.clone(); Enumeration keys = data2.keys(); Object key; while(keys.hasMoreElements()) { key = keys.nextElement(); retValue.put(key, data2.get(key)); } return retValue; } /** * Create a new CmsFile object containing an empty XML file of the * current content type. * The String returned by <code>getXmlDocumentTagName()</code> * will be used to build the XML document element. * @param cms Current cms object used for accessing system resources. * @param filename Name of the file to be created. * @param documentType Document type of the new file. * @throws CmsException if no absolute filename is given or write access failed. */ public void createNewFile(CmsObject cms, String filename, String documentType) throws CmsException { if(!filename.startsWith("/")) { // this is no absolute filename. this.throwException("Cannot create new file. Bad name.", CmsException.C_BAD_NAME); } int slashIndex = filename.lastIndexOf("/") + 1; String folder = filename.substring(0, slashIndex); // CHECK: String file = filename.substring(slashIndex); cms.createResource(folder, filename, documentType, null, "".getBytes()); cms.lockResource(filename); m_cms = cms; m_filename = filename; try { m_content = parser.createEmptyDocument(getXmlDocumentTagName()); } catch(Exception e) { throwException("Cannot create empty XML document for file " + m_filename + ". ", CmsException.C_XML_PARSING_ERROR); } write(); } /** * Internal method for debugging purposes. * Dumps the content of the datablock hashtable to the logfile. */ private void dumpDatablocks() { if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { Enumeration hashKeys = m_blocks.keys(); String key = null; Element node = null; A_OpenCms.log(C_OPENCMS_DEBUG, "******** DUMP OF DATABLOCK HASHTABLE *********"); while(hashKeys.hasMoreElements()) { key = (String)hashKeys.nextElement(); node = (Element)m_blocks.get(key); A_OpenCms.log(C_OPENCMS_DEBUG, "* " + key + " --> " + node.getNodeName()); } A_OpenCms.log(C_OPENCMS_DEBUG, "**********************************************"); } } /** * Internal method for debugging purposes. * Dumpes the content of a given NodeList to the logfile. * * @param l NodeList to dump. */ private void dumpNodeList(NodeList l) { if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { if(l == null) { A_OpenCms.log(C_OPENCMS_DEBUG, "******* NODE LIST IS NULL ********"); } else { int len = l.getLength(); A_OpenCms.log(C_OPENCMS_DEBUG, "******** DUMP OF NODELIST ********"); A_OpenCms.log(C_OPENCMS_DEBUG, "* LEN: " + len); for(int i = 0;i < len;i++) { A_OpenCms.log(C_OPENCMS_DEBUG, "*" + l.item(i)); } A_OpenCms.log(C_OPENCMS_DEBUG, "**********************************"); } } } /** * Fast method to replace a datablock. * <P> * <b>USE WITH CARE!</b> * <P> * Using this method only if * <ul> * <li>The tag name is given in lowercase</li> * <li>The datablock already exists (it may be empty)</li> * <li>Neither tag nor data are <code>null</code></li> * <li>You are sure, there will occure no errors</li> * </ul> * * @param tag Key for this datablock. * @param data String to be put in the datablock. */ protected void fastSetData(String tag, String data) { // fastSetData could have been called with an upper case argument tag = tag.toLowerCase(); Element originalBlock = (Element)(m_blocks.get(tag)); while(originalBlock.hasChildNodes()) { originalBlock.removeChild(originalBlock.getFirstChild()); } originalBlock.appendChild(m_content.createTextNode(data)); } /** * Gets the absolute filename of the XML file represented by this content class * @return Absolute filename */ public String getAbsoluteFilename() { return m_filename; } /** * Gets all datablocks (the datablock hashtable). * @return Hashtable with all datablocks. */ protected Hashtable getAllData() { return m_blocks; } /** * Help method to print nice classnames in error messages * @return class name in [ClassName] format */ protected String getClassName() { String name = getClass().getName(); return "[" + name.substring(name.lastIndexOf(".") + 1) + "] "; } /** * This method should be implemented by every extending class. * It returns a short description of the content definition type * (e.g. "OpenCms news article"). * @return content description. */ abstract public String getContentDescription(); /** * Gets a complete datablock from the datablock hashtable. * * @param tag Key for the datablocks hashtable. * @return Complete DOM element of the datablock for the given key * or null if no datablock is found for this key. */ protected Element getData(String tag) throws CmsException { Object result = m_blocks.get(tag.toLowerCase()); if(result == null) { String errorMessage = "Unknown Datablock " + tag + " requested."; throwException(errorMessage, CmsException.C_XML_UNKNOWN_DATA); } else { if(!(result instanceof Element)) { String errorMessage = "Unexpected object returned as datablock. Requested Tagname: " + tag + ". Returned object: " + result.getClass().getName() + "."; throwException(errorMessage, CmsException.C_XML_CORRUPT_INTERNAL_STRUCTURE); } } return (Element)m_blocks.get(tag.toLowerCase()); } /** * Gets the text and CDATA content of a datablock from the * datablock hashtable. * * @param tag Key for the datablocks hashtable. * @return Datablock content for the given key or null if no datablock * is found for this key. */ protected String getDataValue(String tag) throws CmsException { Element dataElement = getData(tag); return getTagValue(dataElement); } /** * Gets a short filename (without path) of the XML file represented by this content class * of the template file. * @return filename */ public String getFilename() { return m_filename.substring(m_filename.lastIndexOf("/") + 1); } /** * Gets a processed datablock from the datablock hashtable. * * @param tag Key for the datablocks hashtable. * @return Processed datablock for the given key. * @throws CmsException */ protected Element getProcessedData(String tag) throws CmsException { return getProcessedData(tag, null, null); } /** * Gets a processed datablock from the datablock hashtable. * * @param tag Key for the datablocks hashtable. * @param callingObject Object that should be used to look up user methods. * @return Processed datablock for the given key. * @throws CmsException */ protected Element getProcessedData(String tag, Object callingObject) throws CmsException { return getProcessedData(tag, callingObject, null); } /** * Gets a processed datablock from the datablock hashtable. * <P> * The userObj Object is passed to all called user methods. * By using this, the initiating class can pass customized data to its methods. * * @param tag Key for the datablocks hashtable. * @param callingObject Object that should be used to look up user methods. * @param userObj any object that should be passed to user methods * @return Processed datablock for the given key. * @throws CmsException */ protected Element getProcessedData(String tag, Object callingObject, Object userObj) throws CmsException { Element dBlock = (Element)getData(tag).cloneNode(true); processNode(dBlock, m_mainProcessTags, null, callingObject, userObj); return dBlock; } /** * Gets a processed datablock from the datablock hashtable. * <P> * The userObj Object is passed to all called user methods. * By using this, the initiating class can pass customized data to its methods. * * @param tag Key for the datablocks hashtable. * @param callingObject Object that should be used to look up user methods. * @param userObj any object that should be passed to user methods * @param stream OutputStream that may be used for directly streaming the results or null. * @return Processed datablock for the given key. * @throws CmsException */ protected Element getProcessedData(String tag, Object callingObject, Object userObj, OutputStream stream) throws CmsException { Element dBlock = (Element)getData(tag).cloneNode(true); processNode(dBlock, m_mainProcessTags, null, callingObject, userObj, stream); return dBlock; } /** * Gets the text and CDATA content of a processed datablock from the * datablock hashtable. * * @param tag Key for the datablocks hashtable. * @return Processed datablock for the given key. * @throws CmsException */ protected String getProcessedDataValue(String tag) throws CmsException { return getProcessedDataValue(tag, null, null, null); } /** * Gets the text and CDATA content of a processed datablock from the * datablock hashtable. * * @param tag Key for the datablocks hashtable. * @param callingObject Object that should be used to look up user methods. * @return Processed datablock for the given key. * @throws CmsException */ protected String getProcessedDataValue(String tag, Object callingObject) throws CmsException { return getProcessedDataValue(tag, callingObject, null, null); } /** * Gets the text and CDATA content of a processed datablock from the * datablock hashtable. * <P> * The userObj Object is passed to all called user methods. * By using this, the initiating class can pass customized data to its methods. * * @param tag Key for the datablocks hashtable. * @param callingObject Object that should be used to look up user methods. * @param userObj any object that should be passed to user methods * @return Processed datablock for the given key. * @throws CmsException */ protected String getProcessedDataValue(String tag, Object callingObject, Object userObj) throws CmsException { return getProcessedDataValue(tag, callingObject, userObj, null); } /** * Gets the text and CDATA content of a processed datablock from the * datablock hashtable. An eventually given output stream is user for streaming * the generated result directly to the response output stream while processing. * <P> * The userObj Object is passed to all called user methods. * By using this, the initiating class can pass customized data to its methods. * * @param tag Key for the datablocks hashtable. * @param callingObject Object that should be used to look up user methods. * @param userObj any object that should be passed to user methods * @param stream OutputStream that may be used for directly streaming the results or null. * @return Processed datablock for the given key. * @throws CmsException */ protected String getProcessedDataValue(String tag, Object callingObject, Object userObj, OutputStream stream) throws CmsException { // we cant cache the methods here, so we use the other way registerTag("METHOD", A_CmsXmlContent.class, "handleMethodTagForSure", C_REGISTER_MAIN_RUN); Element data = getProcessedData(tag, callingObject, userObj, stream); registerTag("METHOD", A_CmsXmlContent.class, "handleMethodTag", C_REGISTER_MAIN_RUN); return getTagValue(data); } /** * Reads all text or CDATA values from the given XML element, * e.g. <code>&lt;ELEMENT&gt;foo blah &lt;![CDATA[&lt;H1&gt;Hello&lt;/H1&gt;]]&gt;&lt;/ELEMENT&gt;</code>. * * @param n Element that should be read out. * @return Concatenated string of all text and CDATA nodes or <code>null</code> * if no nodes were found. */ protected String getTagValue(Element n) { StringBuffer result = new StringBuffer(); if(n != null) { NodeList childNodes = n.getChildNodes(); Node child = null; if(childNodes != null) { int numchilds = childNodes.getLength(); for(int i = 0;i < numchilds;i++) { child = childNodes.item(i); String nodeValue = child.getNodeValue(); if(nodeValue != null) { //if(child.getNodeType() == n.TEXT_NODE || child.getNodeType() == n.CDATA_SECTION_NODE) { if(child.getNodeType() == Element.CDATA_SECTION_NODE) { //result.append(child.getNodeValue()); result.append(nodeValue); } else { if(child.getNodeType() == Element.TEXT_NODE) { //String s = child.getNodeValue().trim(); nodeValue = nodeValue.trim(); //if(!"".equals(s)) { if(!"".equals(nodeValue)) { //result.append(child.getNodeValue()); result.append(nodeValue); } } } } } } } return result.toString(); } /** * Looks up a user defined method requested by a "METHOD" tag. * The method is searched in the Object callingObject. * @param methodName Name of the user method * @param callingObject Object that requested the processing of the XML document * @return user method * @throws NoSuchMethodException */ private Method getUserMethod(String methodName, Object callingObject) throws NoSuchMethodException { if(methodName == null || "".equals(methodName)) { // no valid user method name throw (new NoSuchMethodException("method name is null or empty")); } return callingObject.getClass().getMethod(methodName, C_PARAMTYPES_USER_METHODS); } /** * Gets the XML parsed content of this template file as a DOM document. * <P> * <em>WARNING: The returned value is the original DOM document, not a clone. * Any changes will take effect to the behaviour of this class. * Especially datablocks are concerned by this!</em> * * @return the content of this template file. */ protected Document getXmlDocument() { return m_content; } /** * This method should be implemented by every extending class. * It returns the name of the XML document tag to scan for. * @return name of the XML document tag. */ abstract public String getXmlDocumentTagName(); /** * Gets the currently used XML Parser. * @return currently used parser. */ public static I_CmsXmlParser getXmlParser() { return parser; } /** * Prints the XML parsed content to a String * @return String with XML content */ public String getXmlText() { StringWriter writer = new StringWriter(); getXmlText(writer); return writer.toString(); } /** * Prints the XML parsed content of this template file * to the given Writer. * * @param out Writer to print to. */ public void getXmlText(Writer out) { parser.getXmlText(m_content, out); } /** * Prints the XML parsed content of the given Node and * its subnodes to the given Writer. * * @param out Writer to print to. * @param n Node that should be printed. */ public void getXmlText(Writer out, Node n) { Document tempDoc = (Document)m_content.cloneNode(false); tempDoc.appendChild(parser.importNode(tempDoc, n)); parser.getXmlText(tempDoc, out); } //[added by Gridnine AB, 2002-06-17] public void getXmlText(OutputStream out) { parser.getXmlText(m_content, out, m_newEncoding); } //[added by Gridnine AB, 2002-06-17] public void getXmlText(OutputStream out, Node n) { Document tempDoc = (Document)m_content.cloneNode(false); tempDoc.appendChild(parser.importNode(tempDoc, n)); parser.getXmlText(tempDoc, out, m_newEncoding); } /** * Prints the XML parsed content of a given node and * its subnodes to a String * @param n Node that should be printed. * @return String with XML content */ public String getXmlText(Node n) { StringWriter writer = new StringWriter(); getXmlText(writer, n); return writer.toString(); } /** * Handling of "DATA" tags and unknown tags. * A reference to each data tag ist stored in an internal hashtable with * the name of the datablock as key. * Nested datablocks are stored with names like outername.innername * * @param n XML element containing the <code>&lt;DATA&gt;</code> tag. * @param callingObject Reference to the object requesting the node processing. * @param userObj Customizable user object that will be passed through to handling and user methods. */ private void handleDataTag(Element n, Object callingObject, Object userObj) { String blockname; String bestFit = null; String parentname = null; Node parent = n.getParentNode(); while(parent != null && parent.getNodeType() == Node.ELEMENT_NODE) { // check if this datablock is part of a datablock // hierarchy like 'language.de.btn_yes' // look for the best fitting hierarchy name part, too if(parent.getNodeName().equals("DATA")) { blockname = ((Element)parent).getAttribute("name"); } else { blockname = parent.getNodeName(); String secondName = ((Element)parent).getAttribute("name"); if(!"".equals(secondName)) { blockname = blockname + "." + secondName; } } blockname = blockname.toLowerCase(); if(parentname == null) { parentname = blockname; } else { parentname = blockname + "." + parentname; } if(m_blocks.containsKey(parentname)) { bestFit = parentname; } parent = parent.getParentNode(); } // bestFit now contains the best fitting name part // next, look for the tag name (the part behind the last ".") if(n.getNodeName().equals("DATA")) { blockname = n.getAttribute("name"); } else { blockname = n.getNodeName(); String secondName = n.getAttribute("name"); if(!"".equals(secondName)) { blockname = blockname + "." + secondName; } } blockname = blockname.toLowerCase(); // now we can build the complete datablock name if(bestFit != null) { blockname = bestFit + "." + blockname; } if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() && C_DEBUG) { A_OpenCms.log(C_OPENCMS_DEBUG, "Reading datablock " + blockname); } // finally we cat put the new datablock into the hashtable m_blocks.put(blockname, n); //return null; } /** * Handling of "INCLUDE" tags. * @param n XML element containing the <code>&lt;INCLUDE&gt;</code> tag. * @param callingObject Reference to the object requesting the node processing. * @param userObj Customizable user object that will be passed through to handling and user methods. */ private Object handleIncludeTag(Element n, Object callingObject, Object userObj) throws CmsException { A_CmsXmlContent include = null; String tagcontent = getTagValue(n); include = readIncludeFile(tagcontent); return include.getXmlDocument().getDocumentElement().getChildNodes(); } /** * Handling of "LINK" tags. * @param n XML element containing the <code>&lt;LINK&gt;</code> tag. * @param callingObject Reference to the object requesting the node processing. * @param userObj Customizable user object that will be passed through to handling and user methods. */ private Object handleLinkTag(Element n, Object callingObject, Object userObj) throws CmsException { // get the string and call the getLinkSubstitution method Element dBlock = (Element)n.cloneNode(true); processNode(dBlock, m_mainProcessTags, null, callingObject, userObj, null); String link = getTagValue(dBlock); return m_cms.getLinkSubstitution(link); } /** * Handling of the "METHOD name=..." tags. * Name attribute and value of the element are read and the user method * 'name' is invoked with the element value as parameter. * * @param n XML element containing the <code>&lt;METHOD&gt;</code> tag. * @param callingObject Reference to the object requesting the node processing. * @param userObj Customizable user object that will be passed through to handling and user methods. * @return Object returned by the user method * @throws CmsException */ private Object handleMethodTag(Element n, Object callingObject, Object userObj) throws CmsException { processNode(n, m_mainProcessTags, null, callingObject, userObj); String tagcontent = getTagValue(n); String method = n.getAttribute("name"); Object result = null; try { result = callUserMethod(method, tagcontent, callingObject, userObj, false); } catch(Throwable e1) { if(e1 instanceof CmsException) { throw (CmsException)e1; } else { throwException("handleMethodTag() received an exception from callUserMethod() while calling \"" + method + "\" requested by class " + callingObject.getClass().getName() + ": " + e1); } } return result; } /** * Handling of the "METHOD name=..." tags. * In contrast to the method handleMethodTag this method resolves * every method even if it has it own CacheDirectives. It is used only for * getProcessedDataValue. * Name attribute and value of the element are read and the user method * 'name' is invoked with the element value as parameter. * * @param n XML element containing the <code>&lt;METHOD&gt;</code> tag. * @param callingObject Reference to the object requesting the node processing. * @param userObj Customizable user object that will be passed through to handling and user methods. * @return Object returned by the user method * @throws CmsException */ private Object handleMethodTagForSure(Element n, Object callingObject, Object userObj) throws CmsException { processNode(n, m_mainProcessTags, null, callingObject, userObj); String tagcontent = getTagValue(n); String method = n.getAttribute("name"); Object result = null; try { result = callUserMethod(method, tagcontent, callingObject, userObj, true); } catch(Throwable e1) { if(e1 instanceof CmsException) { throw (CmsException)e1; } else { throwException("handleMethodTagForSure() received an exception from callUserMethod() while calling \"" + method + "\" requested by class " + callingObject.getClass().getName() + ": " + e1); } } return result; } /** * Handling of the "PROCESS" tags. * Looks up the requested datablocks in the internal hashtable and * returns its subnodes. * * @param n XML element containing the <code>&lt;PROCESS&gt;</code> tag. * @param callingObject Reference to the object requesting the node processing. * @param userObj Customizable user object that will be passed through to handling and user methods. */ private Object handleProcessTag(Element n, Object callingObject, Object userObj) { String blockname = getTagValue(n).toLowerCase(); Element datablock = null; if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() && C_DEBUG) { A_OpenCms.log(C_OPENCMS_DEBUG, getClassName() + "handleProcessTag() started. Request for datablock \"" + blockname + "\"."); } datablock = (Element)((Element)m_blocks.get(blockname)); if(datablock == null) { if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { String logUri = ""; try{ logUri = " RequestUri is "+ m_cms.getRequestContext().getFolderUri() + m_cms.getRequestContext().getFileUri() + "."; }catch(Exception e){ } A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + "Requested datablock \"" + blockname + "\" not found in "+m_filename+"!" + logUri); } return C_ERR_NODATABLOCK + blockname; } else { return datablock.getChildNodes(); } } /** * Checks if this Template owns a datablock with the given key. * @param key Datablock key to be checked. * @return true if a datablock is found, false otherwise. */ protected boolean hasData(String key) { return m_blocks.containsKey(key.toLowerCase()); } /** * Initialize the XML content class. * Load and parse the content of the given CmsFile object. * @param cms CmsObject Object for accessing resources. * @param file CmsFile object of the file to be loaded and parsed. * @throws CmsException */ public void init(CmsObject cms, CmsFile file) throws CmsException { String filename = file.getAbsolutePath(); String currentProject = cms.getRequestContext().currentProject().getName(); Document parsedContent = null; m_cms = cms; m_filename = filename; parsedContent = loadCachedDocument(filename); if(parsedContent == null) { //[removed by Gridnine AB, 2002-06-13] String fileContent = new String(file.getContents()); byte[] fileContent = file.getContents(); //[removed by Gridnine AB, 2002-06-13] if(fileContent == null || "".equals(fileContent.trim())) { //[changed by ednfal, 2002-08-07] if you use Oracle the "empty" fileContent has a blank, so its length is 1 if(fileContent == null || fileContent.length <= 1) { // The file content is empty. Possibly the file object is only // a file header. Re-read the file object and try again file = cms.readFile(filename); //[removed by Gridnine AB, 2002-06-13] fileContent = new String(file.getContents()).trim(); fileContent = file.getContents(); } //[removed by Gridnine AB, 2002-06-13] if(fileContent == null || "".equals(fileContent.trim())) { //[changed by ednfal, 2002-08-07] if you use Oracle the "empty" fileContent has a blank, so its length is 1 if(fileContent == null || fileContent.length <= 1) { // The file content is still emtpy. // Start with an empty XML document. try { parsedContent = getXmlParser().createEmptyDocument(getXmlDocumentTagName()); } catch(Exception e) { throwException("Could not initialize now XML document " + filename + ". " + e, CmsException.C_XML_PARSING_ERROR); } } else { parsedContent = parse(fileContent); } m_filecache.put(currentProject + ":" + filename, parsedContent.cloneNode(true)); } init(cms, parsedContent, filename); } /** * Initialize the XML content class. * Load and parse the content of the given CmsFile object. * <P> * If a previously cached parsed content exists, it will be re-used. * <P> * If no absolute file name ist given, * template files will be searched a hierachical order using * <code>lookupAbsoluteFilename</code>. * * @param cms CmsObject Object for accessing resources. * @param file CmsFile object of the file to be loaded and parsed. * @throws CmsException */ public void init(CmsObject cms, String filename) throws CmsException { if(!filename.startsWith("/")) { throw new CmsException("A relative path has entered the A_CmsXmlContent class. filename="+filename+""); } String currentProject = cms.getRequestContext().currentProject().getName(); Document parsedContent = null; m_cms = cms; m_filename = filename; parsedContent = loadCachedDocument(filename); if(parsedContent == null) { CmsFile file = cms.readFile(filename); //[removed by Gridnine AB, 2002-06-13] parsedContent = parse(new String(file.getContents())); parsedContent = parse(file.getContents()); m_filecache.put(currentProject + ":" + filename, parsedContent.cloneNode(true)); } else { // File was found in cache. // We have to read the file header to check access rights. cms.readFileHeader(filename); } /* if (filename.indexOf(I_CmsWpConstants.C_VFS_DIR_LOCALES)!=-1) { System.err.println( "\n" + filename ); this.printNode(parsedContent,0, ""); } */ init(cms, parsedContent, filename); } private static final String badChars = "\n"; private static final String[] goodChars = { "\\n" }; /** * Prints all nodes of a XML locale file in depth first order split by "." * to STDOUT. This method is useful for backward compatibility: you can copy * the output of this method (which is written to $TOMCAT_HOME/logs/catalina. * out) to build Java resource bundles. This method is for internal use * only, should be commented out on production system! * * @param node the current node in the XML document that is examined * @param depth the current depth in the XML tree * @param path the current path of the XML nodes, eg. node1.node2.node3... */ private void printNode(Node node, int depth, String path) { int nodeType = node.getNodeType(); if (nodeType == Node.ELEMENT_NODE) { String nodeName = node.getNodeName(); if (!"".equals(nodeName)) { if (depth>2) { path += "."; } if (depth>1) { path += nodeName; } } } else if (nodeType == Node.TEXT_NODE) { String nodeValue = node.getNodeValue(); if (!"".equals(nodeValue)) { int nodeValueLength = nodeValue.length(); String nodeValueNoBadChars = ""; for (int i=0;i<nodeValueLength;i++) { int index = 0; if ((index=badChars.indexOf(nodeValue.charAt(i)))!=-1) { nodeValueNoBadChars += goodChars[index]; } else { nodeValueNoBadChars += nodeValue.charAt(i); } } if (node.getPreviousSibling()==null) { System.out.print(path + "="); } System.out.print(nodeValueNoBadChars); if (node.getNextSibling()==null) { System.out.print("\n"); } } } else if (nodeType == Node.CDATA_SECTION_NODE) { CDATASection cdata = (CDATASection)node; String nodeValue = cdata.getData(); if (!"".equals(nodeValue)) { int nodeValueLength = nodeValue.length(); String nodeValueNoBadChars = ""; for (int i=0;i<nodeValueLength;i++) { int index = 0; if ((index=badChars.indexOf(nodeValue.charAt(i)))!=-1) { nodeValueNoBadChars += goodChars[index]; } else { nodeValueNoBadChars += nodeValue.charAt(i); } } if (node.getPreviousSibling()==null) { System.out.print(path + "="); } System.out.print(nodeValueNoBadChars); if (node.getNextSibling()==null) { System.out.print("\n"); } } } NodeList nodeChildren = node.getChildNodes(); if (nodeChildren != null) { for (int i = 0; i < nodeChildren.getLength(); i++) { printNode(nodeChildren.item(i), depth+1, path); } } } /** * Initialize the class with the given parsed XML DOM document. * @param cms CmsObject Object for accessing system resources. * @param document DOM document object containing the parsed XML file. * @param filename OpenCms filename of the XML file. * @throws CmsException */ public void init(CmsObject cms, Document content, String filename) throws CmsException { m_cms = cms; m_content = content; m_filename = filename; // First check the document tag. Is this the right document type? Element docRootElement = m_content.getDocumentElement(); String docRootElementName = docRootElement.getNodeName().toLowerCase(); if(!docRootElementName.equals(getXmlDocumentTagName().toLowerCase())) { // Hey! This is a wrong XML document! // We will throw an execption and the document away :-) removeFromFileCache(); m_content = null; String errorMessage = "XML document " + getAbsoluteFilename() + " is not of the expected type. This document is \"" + docRootElementName + "\", but it should be \"" + getXmlDocumentTagName() + "\" (" + getContentDescription() + ")."; throwException(errorMessage, CmsException.C_XML_WRONG_CONTENT_TYPE); } // OK. Document tag is fine. Now get the DATA tags and collect them // in a Hashtable (still in DOM representation!) try { processNode(m_content, m_firstRunTags, A_CmsXmlContent.class.getDeclaredMethod("handleDataTag", C_PARAMTYPES_HANDLING_METHODS), null, null); } catch(CmsException e) { if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_INFO, "Error while scanning for DATA and INCLUDE tags in file " + getAbsoluteFilename() + "."); } throw e; } catch(NoSuchMethodException e2) { String errorMessage = "XML tag process method \"handleDataTag\" could not be found"; throwException(errorMessage, CmsException.C_XML_NO_PROCESS_METHOD); } } /** * Internal method for creating a new datablock. * <P> * This method is called by setData() if a new, not existing * datablock must be created. * <P> * <B>Functionality:</B> If a non-hierarchical datablock is given, * it is inserted at the end of the DOM document. * If a hierarchical datablock is given, all possible parent * names are checked in a backward oriented order. If a * datablock with a name that equals a part of the hierarchy is * found, the new datablock will be created as a (sub)child * of this datablock. * * @param tag Key for this datablock. * @param data DOM element node for this datablock. */ private void insertNewDatablock(String tag, Element data) { // First check, if this is an extended datablock // in <NAME1 name="name2>... format, that has to be inserted // as name1.name2 String nameAttr = data.getAttribute("name"); String workTag = null; if((!data.getNodeName().toLowerCase().equals("data")) && nameAttr != null && (!"".equals(nameAttr))) { // this is an extended datablock workTag = tag.substring(0, tag.lastIndexOf(".")); }else { workTag = tag; } // Import the node for later inserting Element importedNode = (Element)parser.importNode(m_content, data); // Check, if this is a simple datablock without hierarchy. if(workTag.indexOf(".") == -1) { // Fine. We can insert the new Datablock at the of the document m_content.getDocumentElement().appendChild(importedNode); m_blocks.put(tag, importedNode); }else { // This is a hierachical datablock tag. We have to search for // an appropriate place to insert first. boolean found = false; String match = "." + workTag; int dotIndex = match.lastIndexOf("."); Vector newBlocks = new Vector(); while((!found) && (dotIndex > 1)) { match = match.substring(0, dotIndex); if(hasData(match.substring(1))) { found = true; }else { dotIndex = match.lastIndexOf("."); newBlocks.addElement(match.substring(dotIndex + 1)); } } // newBlocks now contains a (backward oriented) list // of all datablocks that have to be created, before // the new datablock named "tag" can be inserted. String datablockPrefix = ""; if(found) { datablockPrefix = match.substring(1) + "."; } // number of new elements to be created int numNewBlocks = newBlocks.size(); // used to create the required new elements Element newElem = null; // Contains the last existing Element in the hierarchy. Element lastElem = null; // now create the new elements backwards for(int i = numNewBlocks - 1;i >= 0;i newElem = m_content.createElement("DATA"); newElem.setAttribute("name", (String)newBlocks.elementAt(i)); m_blocks.put(datablockPrefix + (String)newBlocks.elementAt(i), newElem); if(lastElem != null) { lastElem.appendChild(newElem); }else { lastElem = newElem; } } // Now all required parent datablocks are created. // Finally the given datablock can be inserted. if(lastElem != null) { lastElem.appendChild(importedNode); }else { lastElem = importedNode; } m_blocks.put(datablockPrefix + tag, importedNode); // lastElem now contains the hierarchical tree of all DATA tags to be // inserted. // If we have found an existing part of the hierarchy, get // this part and append the tree. If no part was found, append the // tree at the end of the document. if(found) { Element parent = (Element)m_blocks.get(match.substring(1)); parent.appendChild(lastElem); }else { m_content.getDocumentElement().appendChild(lastElem); } } } /** * Reloads a previously cached parsed content. * * @param filename Absolute pathname of the file to look for. * @return DOM parsed document or null if the cached content was not found. */ private Document loadCachedDocument(String filename) { Document cachedDoc = null; String currentProject = m_cms.getRequestContext().currentProject().getName(); Document lookup = (Document)m_filecache.get(currentProject + ":" + filename); if(lookup != null) { try { //cachedDoc = lookup.cloneNode(true).getOwnerDocument(); cachedDoc = (Document)lookup.cloneNode(true); }catch(Exception e) { lookup = null; cachedDoc = null; } } if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() && C_DEBUG && cachedDoc != null) { A_OpenCms.log(C_OPENCMS_DEBUG, getClassName() + "Re-used previously parsed XML file " + getFilename() + "."); } return cachedDoc; } /** * Utility method for putting a single Node to a new NodeList * consisting only of this Node. * @param n Node to put in NodeList * @return NodeList containing copy of the Node n */ private NodeList nodeToNodeList(Node n) { if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_DEBUG, "nodeToNodeList called with node " + n); } Element tempNode = m_content.createElement("TEMP"); tempNode.appendChild(n.cloneNode(true)); return tempNode.getChildNodes(); } //[added by Gridnine AB, 2002-06-13] protected Document parse(byte[] content) throws CmsException { return parse(new ByteArrayInputStream(content)); } /** * Starts the XML parser with the content of the given CmsFile object. * After parsing the document it is scanned for INCLUDE and DATA tags * by calling processNode with m_firstRunParameters. * * @param content String to be parsed * @return Parsed DOM document. * @see #processNode * @see #firstRunParameters */ //[removed by Gridnine AB, 2002-06-13] protected Document parse(String content) throws CmsException { protected Document parse(InputStream content) throws CmsException { Document parsedDoc = null; //[removed by Gridnine AB, 2002-06-13] StringReader reader = new StringReader(content); // First parse the String for XML Tags and // get a DOM representation of the document try { //[removed by Gridnine AB, 2002-06-13] parsedDoc = parser.parse(reader); parsedDoc = parser.parse(content); } catch(Exception e) { // Error while parsing the document. // there ist nothing to do, we cannot go on. // throws exception. String errorMessage = "Cannot parse XML file \"" + getAbsoluteFilename() + "\". " + e; throwException(errorMessage, CmsException.C_XML_PARSING_ERROR); } if(parsedDoc == null) { String errorMessage = "Unknown error. Parsed DOM document is null."; throwException(errorMessage, CmsException.C_XML_PARSING_ERROR); } /* Try to normalize the XML document. We should not call the normalize() method in the usual way here, since the DOM interface changed at this point between Level 1 and Level 2. It's better to lookup the normalize() method first using reflection API and call it then. So we will get the appropriate method for the currently used DOM level and avoid NoClassDefFound exceptions. */ try { Class elementClass = Class.forName("org.w3c.dom.Element"); Method normalizeMethod = elementClass.getMethod("normalize", new Class[]{}); normalizeMethod.invoke(parsedDoc.getDocumentElement(), new Object[]{}); } catch(Exception e) { // Sorry. The workaround using reflection API failed. // We have to throw an exception. throwException("Normalizing the XML document failed. Possibly you are using concurrent versions of " + "the XML parser with different DOM levels. ", e, CmsException.C_XML_PARSING_ERROR); } // Delete all unnecessary text nodes from the tree. // These nodes could cause errors when serializing this document otherwise Node loop = parsedDoc.getDocumentElement(); while(loop != null) { Node next = treeWalker(parsedDoc.getDocumentElement(), loop); if(loop.getNodeType() == Node.TEXT_NODE) { Node leftSibling = loop.getPreviousSibling(); Node rightSibling = loop.getNextSibling(); if(leftSibling == null || rightSibling == null || (leftSibling.getNodeType() == Node.ELEMENT_NODE && rightSibling.getNodeType() == Node.ELEMENT_NODE)) { if("".equals(loop.getNodeValue().trim())) { loop.getParentNode().removeChild(loop); } } } loop = next; } return parsedDoc; } /** * Main processing funtion for the whole XML document. * * @see #processNode * @param keys Hashtable with XML tags to look for and corresponding methods. * @param defaultMethod Method to be called if the tag is unknown. * @param callingObject Reference to the object requesting the node processing. * @param userObj Customizable user object that will be passed through to handling and user methods. * @throws CmsException */ protected void processDocument(Hashtable keys, Method defaultMethod, Object callingObject, Object userObj) throws CmsException { processNode(m_content.getDocumentElement(), keys, defaultMethod, callingObject, userObj); } /** * Universal main processing function for parsed XML templates. * The given node is processed by a tree walk. * <P> * Every XML tag will be looked up in the Hashtable "keys". * If a corresponding entry is found, the tag will be handled * by the corresponding function returned from the Hashtable. * <P> * If an unknown tag is detected the method defaultMethod is called * instead. Is defaultMethod == null nothing will be done with unknown tags. * <P> * The invoked handling methods are allowed to return null or objects * of the type String, Node, Integer or byte[]. * If the return value is null, nothing happens. In all other cases * the handled node in the tree will be replaced by a new node. * The value of this new node depends on the type of the returned value. * * @param n Node with its subnodes to process * @param keys Hashtable with XML tags to look for and corresponding methods. * @param defaultMethod Method to be called if the tag is unknown. * @param callingObject Reference to the Object that requested the node processing. * @param userObj Customizable user object that will be passed to handling and user methods. * @throws CmsException */ protected void processNode(Node n, Hashtable keys, Method defaultMethod, Object callingObject, Object userObj) throws CmsException { processNode(n, keys, defaultMethod, callingObject, userObj, null); } protected void processNode(Node n, Hashtable keys, Method defaultMethod, Object callingObject, Object userObj, OutputStream stream) throws CmsException { // Node currently processed Node child = null; // Name of the currently processed child String childName = null; // Node nextchild needed for the walk through the tree Node nextchild = null; // List of new Nodes the current node should be replaced with NodeList newnodes = null; // single new Node from newnodes Node insert = null; // tag processing method to be called for the current Node Method callMethod = null; // Object returned by the tag processing methods Object methodResult = null; // Used for streaming mode. Indicates, if the replaced results for the current node are already written to the stream. boolean newnodesAreAlreadyProcessed = false; // We should remember the starting node for walking through the tree. Node startingNode = n; // only start if there is something to process if(n != null && n.hasChildNodes()) { child = n.getFirstChild(); while(child != null) { childName = child.getNodeName().toLowerCase(); // Get the next node in the tree first nextchild = treeWalker(startingNode, child); // Only look for element nodes // all other nodes are not very interesting if(child.getNodeType() == Node.ELEMENT_NODE) { newnodes = null; callMethod = null; newnodesAreAlreadyProcessed = false; if(keys.containsKey(childName)) { // name of this element found in keys Hashtable callMethod = (Method)keys.get(childName); } else { if(!m_knownTags.contains(childName)) { // name was not found // and even name is not known as tag callMethod = defaultMethod; } } if(callMethod != null) { methodResult = null; try { if(C_DEBUG && I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_DEBUG, "<" + childName + "> tag found. Value: " + child.getNodeValue()); A_OpenCms.log(C_OPENCMS_DEBUG, "Tag will be handled by method [" + callMethod.getName() + "]. Invoking method NOW."); } // now invoke the tag processing method. methodResult = callMethod.invoke(this, new Object[] { child, callingObject, userObj }); } catch(Exception e) { if(e instanceof InvocationTargetException) { Throwable thrown = ((InvocationTargetException)e).getTargetException(); // if the method has thrown a cms exception then // throw it again if(thrown instanceof CmsException) { throw (CmsException)thrown; } else { throwException("processNode received an exception while handling XML tag \"" + childName + "\" by \"" + callMethod.getName() + "\" for file " + getFilename() + ": " + e, CmsException.C_XML_PROCESS_ERROR); } } else { throwException("processNode could not invoke the XML tag handling method " + callMethod.getName() + "\" for file " + getFilename() + ": " + e, CmsException.C_XML_PROCESS_ERROR); } } // Inspect the type of the method return value // Currently NodeList, String and Integer are // recognized. All other types will be ignored. if(methodResult == null) { newnodes = null; } else { if(methodResult instanceof NodeList) { newnodes = (NodeList)methodResult; } else { if(methodResult instanceof String) { newnodes = stringToNodeList((String)methodResult); } else { if(methodResult instanceof CmsProcessedString) { newnodes = stringToNodeList(((CmsProcessedString)methodResult).toString()); newnodesAreAlreadyProcessed = true; } else { if(methodResult instanceof Integer) { newnodes = stringToNodeList(((Integer)methodResult).toString()); } else { if(methodResult instanceof byte[]) { newnodes = stringToNodeList(new String((byte[])methodResult)); } else { // Type not recognized. if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_CRITICAL, "Return type of method " + callMethod.getName() + " not recognized. Cannot insert value."); } newnodes = null; } } } } } } // the list of nodes to be inserted could be printed out here. // uncomment the following to activate this feature. // printNodeList(newnodes); if(newnodes != null) { // the called method returned a valid result. // we have do remove the old element from the tree // and replace it by the new nodes. // WARNING! Do not remove any subchilds from the old // element. There could be links to the subchilds // in our Hashtables (e.g. for datablocks). // Only remove the child itself from the tree! int numNewChilds = newnodes.getLength(); if(numNewChilds > 0) { // there are new childs. // so we can replace the old element for(int j = 0;j < numNewChilds;j++) { //insert = parser.importNode(m_content, newnodes.item(j)); insert = parser.importNode(child.getOwnerDocument(), newnodes.item(j)); if(j == 0 && !newnodesAreAlreadyProcessed) { nextchild = insert; } //A_OpenCms.log(c_OPENCMS_DEBUG, "trying to add node " + newnodes.item(j)); child.getParentNode().insertBefore(insert, child); //A_OpenCms.log(c_OPENCMS_DEBUG, "Node " + newnodes.item(j) + " added."); } if(newnodesAreAlreadyProcessed) { // We just have inserted new nodes that were processed prviously. // So we hav to recalculate the next child. nextchild = treeWalkerWidth(startingNode, child); } } else { // the list of the new childs is empty. // so we have to re-calculate the next node // in the tree since the old nextchild will be deleted // been deleted. nextchild = treeWalkerWidth(startingNode, child); } // now delete the old child and get the next one. child.getParentNode().removeChild(child); } } } else if(stream != null){ /* We are in HTTP streaming mode. So we can put the content of the current node directly into the output stream. */ String streamResults = null; if(child.getNodeType() == Node.CDATA_SECTION_NODE) { streamResults = child.getNodeValue(); } else { if(child.getNodeType() == Node.TEXT_NODE) { String s = child.getNodeValue().trim(); if(!"".equals(s)) { streamResults = child.getNodeValue(); } } } if(streamResults != null) { try { stream.write(streamResults.getBytes(m_cms.getRequestContext().getEncoding())); } catch (Exception e) { throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, e); } } } child = nextchild; } } } /** * Read the datablocks of the given content file and include them * into the own Hashtable of datablocks. * * @param include completely initialized A_CmsXmlObject to be included * @throws CmsExeption */ public void readIncludeFile(A_CmsXmlContent include) throws CmsException { m_includedTemplates.addElement(include); m_blocks = concatData(m_blocks, include.getAllData()); } /** * Parses the given file and stores it in the internal list of included files and * appends the relevant data structures of the new file to its own structures. * * @param include Filename of the XML file to be included * @throws CmsException */ public A_CmsXmlContent readIncludeFile(String filename) throws CmsException { A_CmsXmlContent include = null; if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() && C_DEBUG) { A_OpenCms.log(C_OPENCMS_DEBUG, getClassName() + "Including File: " + filename); } try { include = (A_CmsXmlContent)getClass().newInstance(); include.init(m_cms, filename); } catch(Exception e) { if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + "while include file: " + e); } } readIncludeFile(include); return include; } /** * Internal method registering all special tags relevant for the basic functionality of * this abstract class. * <P> * OpenCms special tags are: * <UL> * <LI><CODE>INCLUDE: </CODE> used to include other XML files</LI> * <LI><CODE>DATA: </CODE> used to define a datablock that can be handled * by getData or processed by getProcessedData or <code>PROCESS</CODE></LI> * <LI><CODE>PROCESS: </CODE> used to insert earlier or external defined datablocks</LI> * <LI><CODE>METHOD: </CODE> used to call customized methods in the initiating user object</LI> * </UL> * All unknown tags will be treated as a shortcut for <code>&lt;DATA name="..."&gt;</code>. */ private void registerAllTags() { // register tags for scanning "INCLUDE" and "DATA" registerTag("INCLUDE", A_CmsXmlContent.class, "handleIncludeTag", C_REGISTER_FIRST_RUN); registerTag("DATA", A_CmsXmlContent.class, "handleDataTag", C_REGISTER_FIRST_RUN); // register tags for preparing HTML output registerTag("METHOD", A_CmsXmlContent.class, "handleMethodTag", C_REGISTER_MAIN_RUN); registerTag("PROCESS", A_CmsXmlContent.class, "handleProcessTag", C_REGISTER_MAIN_RUN); registerTag("LINK", A_CmsXmlContent.class, "handleLinkTag", C_REGISTER_MAIN_RUN); registerTag("INCLUDE", A_CmsXmlContent.class, "replaceTagByComment", C_REGISTER_MAIN_RUN); registerTag("DATA", A_CmsXmlContent.class, "replaceTagByComment", C_REGISTER_MAIN_RUN); registerTag(getXmlDocumentTagName()); } /** * Registers the given tag to be "known" by the system. * So this tag will not be handled by the default method of processNode. * Under normal circumstances this feature will only be used for * the XML document tag. * @param tagname Tag name to register. */ public void registerTag(String tagname) { if(!(m_knownTags.contains(tagname.toLowerCase()))) { m_knownTags.addElement(tagname.toLowerCase()); } } /** * Registeres a tagname together with a corresponding method for processing * with processNode. Tags can be registered for two different runs of the processNode * method. This can be selected by the runSelector. * <P> * C_REGISTER_FIRST_RUN registeres the given tag for the first * run of processNode, just after parsing a XML document. The basic functionality * of this class uses this run to scan for INCLUDE and DATA tags. * <P> * C_REGISTER_MAIN_RUN registeres the given tag for the main run of processNode. * This will be initiated by getProcessedData(), processDocument() or any * PROCESS tag. * * @param tagname Tag name to register. * @param c Class containing the handling method. * @param methodName Name of the method that should handle a occurance of tag "tagname". * @param runSelector see description above. */ public void registerTag(String tagname, Class c, String methodName, int runSelector) { Hashtable selectedRun = null; switch(runSelector) { case C_REGISTER_FIRST_RUN: selectedRun = m_firstRunTags; break; case C_REGISTER_MAIN_RUN: selectedRun = m_mainProcessTags; break; } try { selectedRun.put(tagname.toLowerCase(), c.getDeclaredMethod(methodName, C_PARAMTYPES_HANDLING_METHODS)); } catch(Exception e) { if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_CACHE, "[A_CmsXmlContent] Exception in register tag: " + e.getMessage()); } } registerTag(tagname); } /** * Remove a datablock from the internal hashtable and * from the XML document * @param tag Key of the datablock to delete. */ protected void removeData(String tag) { Element e = (Element)m_blocks.get(tag.toLowerCase()); if(e != null) { m_blocks.remove(tag.toLowerCase()); Element parent = (Element)e.getParentNode(); if(parent != null) { parent.removeChild(e); } } } /** * Deletes this object from the internal XML file cache */ public void removeFromFileCache() { String currentProject = m_cms.getRequestContext().currentProject().getName(); m_filecache.remove(currentProject + ":" + getAbsoluteFilename()); } /** * Generates a XML comment. * It's used to replace no longer needed DOM elements by a short XML comment * * @param n XML element containing the tag to be replaced <em>(unused)</em>. * @param callingObject Reference to the object requesting the node processing <em>(unused)</em>. * @param userObj Customizable user object that will be passed through to handling and user methods <em>(unused)</em>. * @return the generated XML comment. */ private NodeList replaceTagByComment(Element n, Object callingObject, Object userObj) { Element tempNode = (Element)n.cloneNode(false); while(tempNode.hasChildNodes()) { tempNode.removeChild(tempNode.getFirstChild()); } tempNode.appendChild(m_content.createComment("removed " + n.getNodeName())); return tempNode.getChildNodes(); } /** * Creates a datablock consisting of a single TextNode containing * data and stores this block into the datablock-hashtable. * * @param tag Key for this datablock. * @param data String to be put in the datablock. */ protected void setData(String tag, String data) { // create new XML Element to store the data //Element newElement = m_content.createElement("DATA"); String attribute = tag; int dotIndex = tag.lastIndexOf("."); if(dotIndex != -1) { attribute = attribute.substring(dotIndex + 1); } //newElement.setAttribute("name", attribute); Element newElement = m_content.createElement(attribute); if(data == null || "".equals(data)) { // empty string or null are given. // put an empty datablock without any text nodes. setData(tag, newElement); }else { // Fine. String is not empty. // So we can add a new text node containig the string data. // Leading spaces are removed before creating the text node. newElement.appendChild(m_content.createTextNode(data.trim())); setData(tag, newElement); } } /** * Stores a given datablock element in the datablock hashtable. * * @param tag Key for this datablock. * @param data DOM element node for this datablock. */ protected void setData(String tag, Element data) { // If we got a null data, give this request to setData(Strig, String) // to create a new text node. if(data == null) { setData(tag, ""); }else { // Now we can be sure to have a correct Element tag = tag.toLowerCase(); Element newElement = (Element)data.cloneNode(true); if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() && C_DEBUG) { A_OpenCms.log(C_OPENCMS_DEBUG, getClassName() + "Putting datablock " + tag + " into internal Hashtable."); } if(!(m_blocks.containsKey(tag))) { // This is a brand new datablock. It can be inserted directly. //m_blocks.put(tag, newElement); insertNewDatablock(tag, newElement); }else { // datablock existed before, so the childs of the old // one can be replaced. if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() && C_DEBUG) { A_OpenCms.log(C_OPENCMS_DEBUG, getClassName() + "Datablock existed before. Replacing."); } // Look up the old datablock and remove all its childs. Element originalBlock = (Element)(m_blocks.get(tag)); while(originalBlock.hasChildNodes()) { originalBlock.removeChild(originalBlock.getFirstChild()); } // And now add all childs of the new node NodeList newNodes = data.getChildNodes(); int len = newNodes.getLength(); for(int i = 0;i < len;i++) { Node newElement2 = (Node)newNodes.item(i).cloneNode(true); originalBlock.appendChild(parser.importNode(originalBlock.getOwnerDocument(), newElement2)); } } } } /** * Creates a datablock element by parsing the data string * and stores this block into the datablock-hashtable. * * @param tag Key for this datablock. * @param data String to be put in the datablock. */ public void setParsedData(String tag, String data) throws CmsException{ StringBuffer tempXmlString = new StringBuffer(); tempXmlString.append("<?xml version=\"1.0\"?>\n"); tempXmlString.append("<" + getXmlDocumentTagName() + ">"); tempXmlString.append("<"+ tag +">\n"); tempXmlString.append("<![CDATA["); tempXmlString.append(data); tempXmlString.append("]]>"); tempXmlString.append("</"+ tag +">\n"); tempXmlString.append("</" + getXmlDocumentTagName() + ">\n"); I_CmsXmlParser parser = getXmlParser(); StringReader parserReader = new StringReader(tempXmlString.toString()); Document tempDoc = null; try { tempDoc = parser.parse(parserReader); }catch(Exception e) { throwException("PARSING ERROR! "+e.toString(), CmsException.C_XML_PARSING_ERROR); } Element templateNode = (Element)tempDoc.getDocumentElement().getFirstChild(); setData(tag, templateNode); } /** * Utility method for converting a String to a NodeList containing * a single TextNode. * @param s String to convert * @return NodeList containing a TextNode with s */ private NodeList stringToNodeList(String s) { Element tempNode = m_content.createElement("TEMP"); Text text = m_content.createTextNode(s); tempNode.appendChild(text); return tempNode.getChildNodes(); } /** * Help method that handles any occuring exception by writing * an error message to the OpenCms logfile and throwing a * CmsException of the type "unknown". * @param errorMessage String with the error message to be printed. * @throws CmsException */ protected void throwException(String errorMessage) throws CmsException { throwException(errorMessage, CmsException.C_UNKNOWN_EXCEPTION); } /** * Help method that handles any occuring exception by writing * an error message to the OpenCms logfile and throwing a * CmsException of the given type. * @param errorMessage String with the error message to be printed. * @param type Type of the exception to be thrown. * @throws CmsException */ protected void throwException(String errorMessage, int type) throws CmsException { if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + errorMessage); } throw new CmsException(errorMessage, type); } /** * Help method that handles any occuring exception by writing * an error message to the OpenCms logfile and throwing a * CmsException of the type "unknown". * @param errorMessage String with the error message to be printed. * @param e Original exception. * @throws CmsException */ protected void throwException(String errorMessage, Exception e) throws CmsException { throwException(errorMessage, e, CmsException.C_UNKNOWN_EXCEPTION); } /** * Help method that handles any occuring exception by writing * an error message to the OpenCms logfile and throwing a * CmsException of the type "unknown". * @param errorMessage String with the error message to be printed. * @param e Original exception. * @param type Type of the exception to be thrown. * @throws CmsException */ protected void throwException(String errorMessage, Exception e, int type) throws CmsException { if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) { A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + errorMessage); } if(e instanceof CmsException) { throw (CmsException)e; } else { throw new CmsException(errorMessage, type, e); } } /** * Gets a string representation of this object. * @return String representation of this object. */ public String toString() { StringBuffer output = new StringBuffer(); output.append("[XML file]: "); output.append(getFilename()); output.append(", content type: "); output.append(getContentDescription()); return output.toString(); } /** * Help method to walk through the DOM document tree. * First it will be looked for children of the given node. * If there are no children, the siblings and the siblings of our parents * are examined. This will be done by calling treeWalkerWidth. * @param n Node representing the actual position in the tree * @return next node */ protected Node treeWalker(Node root, Node n) { Node nextnode = null; if(n.hasChildNodes()) { // child has child notes itself // process these first in the next loop nextnode = n.getFirstChild(); }else { // child has no subchild. // so we take the next sibling nextnode = treeWalkerWidth(root, n); } return nextnode; } /** * Help method to walk through the DOM document tree by a * width-first-order. * @param n Node representing the actual position in the tree * @return next node */ protected Node treeWalkerWidth(Node root, Node n) { if(n == root) { return null; } Node nextnode = null; Node parent = null; nextnode = n.getNextSibling(); parent = n.getParentNode(); while(nextnode == null && parent != null && parent != root) { // child has sibling // last chance: we take our parent's sibling // (or our grandparent's sibling...) nextnode = parent.getNextSibling(); parent = parent.getParentNode(); } return nextnode; } /** * Writes the XML document back to the OpenCms system. * @throws CmsException */ public void write() throws CmsException { /* // Get the XML content as String StringWriter writer = new StringWriter(); getXmlText(writer); byte[] xmlContent = writer.toString().getBytes(); */ ByteArrayOutputStream os = new ByteArrayOutputStream(); getXmlText(os); byte[] xmlContent = os.toByteArray(); // Get the CmsFile object to write to String filename = getAbsoluteFilename(); CmsFile file = m_cms.readFile(filename); // Set the new content and write the file file.setContents(xmlContent); m_cms.writeFile(file); // update the internal parsed content cache with the new file data. String currentProject = m_cms.getRequestContext().currentProject().getName(); m_filecache.put(currentProject + ":" + filename, m_content.cloneNode(true)); } /** * Returns current XML document encoding. * @return String encoding of XML document */ //Gridnine AB Aug 9, 2002 public String getEncoding() { return parser.getOriginalEncoding(m_content); } /** * Sets new encoding for XML document. * @param encoding */ public void setEncoding(String encoding) { m_newEncoding = encoding; } }
package org.buzzrobotics.subsystems; import edu.wpi.first.wpilibj.AnalogChannel; import edu.wpi.first.wpilibj.Jaguar; import edu.wpi.first.wpilibj.SpeedController; import edu.wpi.first.wpilibj.command.PIDSubsystem; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj.smartdashboard.SendablePIDController; import org.buzzrobotics.RobotMap; import org.buzzrobotics.commands.CommandBase; import org.buzzrobotics.commands.ShooterAngle_Set; /** * Shooter Angle * Uses screw (Controlled by Moter and POT) to limit how far the shooter catapult can go. * @author Kyle Deane */ public class ShooterAngle extends PIDSubsystem { private static final double Kp = 5; private static final double Ki = 0.0; private static final double Kd = 0.0; AnalogChannel ShooterPot; SpeedController ShooterAngleMotor; public ShooterAngle() { super("ShooterAngle", Kp, Ki, Kd); ShooterAngleMotor = new Jaguar(RobotMap.ShooterAngleMotor); ShooterPot = new AnalogChannel(RobotMap.ShooterPot); setSetpointRange(1.09, 3.79); double startpos = returnPot(); setSetpoint(startpos); enable(); //possibly might need to be removed. i can set it to enable on the first run. // Use these to get going: // setSetpoint() - Sets where the PID controller should move the system // enable() - Enables the PID controller. } public void initDefaultCommand() { // Set the default command for a subsystem here. // setDefaultCommand(new Shooter_Angle(3)); setDefaultCommand(new ShooterAngle_Set()); } protected double returnPIDInput() { // Return your input value for the PID loop // e.g. a sensor, like a potentiometer: // yourPot.getAverageVoltage() / kYourMaxVoltage; return ShooterPot.getVoltage(); } protected void usePIDOutput(double output) { ShooterAngleMotor.set(-output); } public double returnPot(){ return ShooterPot.getVoltage(); } public void jogUp() { setSetpointRelative(-.1); } public void jogDown() { setSetpointRelative(.1); } public void shot1() { setSetpoint(1.84); } public void shot2() { setSetpoint(1.11); } public boolean atSetpoint() { return Math.abs(getPosition() - getSetpoint()) < .1; } }
package org.chrisle.githubrepoviewer.hosts; import java.util.List; /** * * @author chrl */ public interface IHost { public List<String> getRepositories(); public List<String> getBranches(); public List<String> getTags(); public Boolean isPrivate(); public String getHostName(); public String getHostIcon(); }
package com.teamdev.jxmaps.demo; interface MenuListener { void sampleSelected(SampleDescriptor descriptor); }
package org.elevenfifty.smoothie; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import org.apache.commons.io.IOUtils; import org.elevenfifty.smoothie.beans.AbstractIngredient; import org.elevenfifty.smoothie.beans.Additive; import org.elevenfifty.smoothie.beans.Base; import org.elevenfifty.smoothie.beans.Ingredient; import org.elevenfifty.smoothie.beans.Produce; import org.elevenfifty.smoothie.beans.Recipe; import org.elevenfifty.smoothie.beans.RecipeIngredient; import org.elevenfifty.smoothie.beans.RecipeIngredient.Unit; public class SmoothieMachine { private static enum Size { SMALL(1), MEDIUM(1.5), LARGE(2); double scale = 0; Size(double scale) { this.scale = scale; } public double getScale() { return scale; } }; public static void main(String[] args) { // Gather user input for smoothie construction // TODO VALIDATE USER INPUT PROPERLY Size s = Size.valueOf(args[0]); int recipeId = Integer.valueOf(args[1]); // Load Ingredients Map<Integer, Ingredient> ingredients = getIngredients(); System.out.println(ingredients); // Bring in recipes // TODO Replace with Map<Integer, Recipe> Map<Integer, Recipe> recipes = getRecipes(ingredients); System.out.println(recipes); // TODO does recipe id exist in map? If not return fancy english error // message // TODO Makes the smoothies from a recipe and parameters // TODO Print out smoothie information to enjoy } private static Map<Integer, Ingredient> getIngredients() { // Open the File Map<Integer, Ingredient> ingredients = new HashMap<Integer, Ingredient>(); BufferedReader reader = null; try { // Used BufferedReader, See Files.java in javadoc reader = new BufferedReader(new InputStreamReader(SmoothieMachine.class.getClassLoader().getResourceAsStream("produce.csv"))); // Read the file String line = null; boolean firstLine = true; while ((line = reader.readLine()) != null) { if (firstLine) { firstLine = false; // Skip the header row continue; } System.out.println(line); // Parse the data String[] columns = line.split(","); int pluCode = Integer.parseInt(columns[1]); int weight = Integer.parseInt(columns[4]); int calories = Integer.parseInt(columns[5]); double price = Double.parseDouble(columns[3].trim().substring(1)); // Translate parsed data to object AbstractIngredient ai; if ("Produce".equalsIgnoreCase(columns[0])) { ai = new Produce(); } else if ("Base".equalsIgnoreCase(columns[0])) { ai = new Base(); } else if ("Additive".equalsIgnoreCase(columns[0])) { ai = new Additive(); } else { // Ignore unknown types System.out.println("Unknown Ingredient [" + columns[0] + "]"); continue; } ai.setPluCode(pluCode); ai.setPrice(price); ai.setName(columns[2]); ai.setWeight(weight); ai.setCalories(calories); ingredients.put(pluCode, ai); } } catch (Exception e) { e.printStackTrace(); } finally { // Finally close the file IOUtils.closeQuietly(reader); } // Return Ingredients return ingredients; } private static Map<Integer, Recipe> getRecipes(Map<Integer, Ingredient> ingredients) { // Open the File Map<Integer, Recipe> recipes = new HashMap<Integer, Recipe>(); BufferedReader reader = null; try { // Used BufferedReader, See Files.java in javadoc reader = new BufferedReader(new InputStreamReader(SmoothieMachine.class.getClassLoader().getResourceAsStream("recipe.csv"))); // Read the file String line = null; Recipe r = null; while ((line = reader.readLine()) != null) { System.out.println(line); // Parse the data String[] columns = line.split(","); int Id = 0; int numColumns = columns.length; if (numColumns == 2) { Id = Integer.valueOf(columns[0]); r = new Recipe(columns[1], Id); } else if (numColumns == 3) { int pluCode = Integer.parseInt(columns[2]); Ingredient ing = ingredients.get(pluCode); r.addRecipeIngredient(new RecipeIngredient(ing, Integer.valueOf(columns[0]), Unit.valueOf(columns[1]))); } else if (numColumns <= 1) { recipes.put(Id, r); } } } catch (Exception e) { e.printStackTrace(); } finally { // Finally close the file IOUtils.closeQuietly(reader); } // Return Ingredients return recipes; } }
package com.tzapps.tzpalette.ui; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import android.app.ActionBar; import android.app.ActionBar.Tab; import android.app.Activity; import android.app.AlertDialog; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.v13.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnFocusChangeListener; import android.view.WindowManager; import android.widget.EditText; import android.widget.ShareActionProvider; import android.widget.Toast; import com.tzapps.common.ui.OnFragmentStatusChangedListener; import com.tzapps.common.utils.ActivityUtils; import com.tzapps.common.utils.BitmapUtils; import com.tzapps.tzpalette.R; import com.tzapps.tzpalette.data.PaletteData; import com.tzapps.tzpalette.data.PaletteDataHelper; import com.tzapps.tzpalette.ui.PaletteItemOptionsDialogFragment.OnClickPaletteItemOptionListener; import com.tzapps.tzpalette.ui.PaletteListFragment.OnClickPaletteItemListener; public class MainActivity extends Activity implements OnFragmentStatusChangedListener, OnClickPaletteItemOptionListener, OnClickPaletteItemListener { private final static String TAG = "MainActivity"; public final static String PALETTE_DATA_ID = "com.tzapps.tzpalette.PaletteDataId"; public final static String PALETTE_DATA_ADDNEW = "com.tzapps.tzpalette.PaletteDataAddNew"; private final static String FOLDER_HOME = "tzpalette"; /** Called when the user clicks the TakePicture button */ private static final int TAKE_PHOTE_RESULT = 1; /** Called when the user clicks the LoadPicture button */ private static final int LOAD_PICTURE_RESULT = 2; /** Called when the user opens the Palette Edit view */ private static final int PALETTE_EDIT_RESULT = 3; private static final String TZPALETTE_FILE_PREFIX = "MyPalette"; private static final int PAGE_CAPTURE_VIEW_POSITION = 0; private static final int PAGE_PALETTE_LIST_POSITION = 1; private static final int PAGE_ABOUT_VIEW_POSITION = 2; private ViewPager mViewPager; private TabsAdapter mTabsAdapter; private String mCurrentPhotoPath; private PaletteDataHelper mDataHelper; private ShareActionProvider mShareActionProvider; private PaletteListFragment mPaletteListFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityUtils.forceToShowOverflowOptionsOnActoinBar(this); mDataHelper = PaletteDataHelper.getInstance(this); mViewPager = new ViewPager(this); mViewPager.setId(R.id.main_pager); setContentView(mViewPager); final ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); mTabsAdapter = new TabsAdapter(this, mViewPager); mTabsAdapter.addTab(actionBar.newTab().setText("Capture"), CaptureFragment.class, null); mTabsAdapter.addTab(actionBar.newTab().setText("My Palettes"), PaletteListFragment.class,null); // mTabsAdapter.addTab(actionBar.newTab().setText("About"), CaptureFragment.class, null); // Open palette list view directly if there has been already record in database if (mDataHelper.getDataCount() > 0) mTabsAdapter.setSelectedPage(PAGE_PALETTE_LIST_POSITION); // Get intent, action and MIME type Intent intent = getIntent(); String action = intent.getAction(); String type = intent.getType(); if (Intent.ACTION_SEND.equals(action) && type != null) { if (type.startsWith("image/")) handleSendImage(intent); } } private void handleSendImage(Intent intent) { Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); if (imageUri != null) openEditView(imageUri); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("tab", mTabsAdapter.getSelectedNavigationIndex()); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mTabsAdapter.setSelectedTab(savedInstanceState.getInt("tab", 0)); } @Override public boolean onPrepareOptionsMenu(Menu menu) { //menu.clear(); return super.onPrepareOptionsMenu(menu); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. MenuInflater inflater = getMenuInflater(); int position = mViewPager.getCurrentItem(); switch (position) { case PAGE_CAPTURE_VIEW_POSITION: inflater.inflate(R.menu.capture_view_actions, menu); break; case PAGE_PALETTE_LIST_POSITION: inflater.inflate(R.menu.palette_list_view_actions, menu); break; case PAGE_ABOUT_VIEW_POSITION: inflater.inflate(R.menu.about_view_actions, menu); break; } return super.onCreateOptionsMenu(menu); } // Call to update the share intent private void setShareIntent(Intent shareIntent) { if (mShareActionProvider != null) { mShareActionProvider.setShareIntent(shareIntent); } } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on the action bar items switch (item.getItemId()) { case R.id.action_share: sharePalette(); return true; case R.id.action_export: exportPalette(); return true; case R.id.action_takePhoto: takePhoto(); return true; case R.id.action_loadPicture: loadPicture(); return true; case R.id.action_settings: openSettings(); return true; case R.id.action_about: //mTabsAdapter.setSelectedTab(TAB_ABOUT_VIEW_POSITION); return true; default: return super.onOptionsItemSelected(item); } } private void openSettings() { Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); } @Override public void onPaletteItemOptionClicked(int position, long dataId, PaletteItemOption option) { assert (mPaletteListFragment != null); PaletteData data = mPaletteListFragment.getItem(position); if (data == null) return; switch (option) { case Rename: Log.d(TAG, "Rename palatte item(position=" + position + " , id=" + dataId + ")"); showRenameDialog(position, dataId); break; case Delete: Log.d(TAG, "Delete palatte item(position=" + position + " , id=" + dataId + ")"); mPaletteListFragment.remove(data); mDataHelper.delete(data); break; case View: Log.d(TAG, "View palette item (position=" + position + " , id=" + dataId + ")"); openPaletteCardView(dataId); break; case Edit: Log.d(TAG, "Edit palette item (position=" + position + " , id=" + dataId + ")"); openEditView(dataId); break; } } public void onClick(View view) { switch (view.getId()) { case R.id.palette_item_options: long dataId = (Long) view.getTag(R.id.TAG_PALETTE_DATA_ID); int itemPosition = (Integer) view.getTag(R.id.TAG_PALETTE_ITEM_POSITION); PaletteData data = mPaletteListFragment.getItem(itemPosition); Log.d(TAG, "Show options on palette data + " + data); PaletteItemOptionsDialogFragment optionDialogFrag = PaletteItemOptionsDialogFragment.newInstance(data.getTitle(), itemPosition, dataId); optionDialogFrag.show(getFragmentManager(), "dialog"); break; case R.id.btn_loadPicture: loadPicture(); break; case R.id.btn_takePhoto: takePhoto(); break; } } @Override public void onPaletteItemClick(int position, long dataId, PaletteData data) { // TODO view the palette data Log.i(TAG, "palette data " + data.getId() + " clicked"); openPaletteCardView(dataId); } private void openPaletteCardView(long dataId) { Intent intent = new Intent(this, PaletteCardActivity.class); intent.putExtra(PALETTE_DATA_ID, dataId); startActivity(intent); } @Override public void onPaletteItemLongClick(int position, long dataId, PaletteData data) { Log.i(TAG, "palette data " + data.getId() + " long clicked"); PaletteItemOptionsDialogFragment optionDialogFrag = PaletteItemOptionsDialogFragment.newInstance(data.getTitle(), position, dataId); optionDialogFrag.show(getFragmentManager(), "dialog"); } private void updatePaletteDataTitle(int position, long dataId, String title) { assert (mPaletteListFragment != null); PaletteData data = mPaletteListFragment.getItem(position); if (data == null) return; data.setTitle(title); mDataHelper.update(data, /* updateThumb */false); mPaletteListFragment.refresh(); } private void showRenameDialog(final int position, final long dataId) { assert (mPaletteListFragment != null); PaletteData data = mPaletteListFragment.getItem(position); if (data == null) return; final AlertDialog.Builder alert = new AlertDialog.Builder(this); final EditText input = new EditText(this); input.setText(data.getTitle()); input.setSingleLine(true); input.setSelectAllOnFocus(true); alert.setTitle(R.string.action_rename) .setView(input) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String text = input.getText().toString(); updatePaletteDataTitle(position, dataId, text); } }) .setNegativeButton("Cancel", null); final AlertDialog dialog = alert.create(); input.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { dialog.getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); } } } ); dialog.show(); } private void sharePalette() { View paletteCard = null; //(View) findViewById(R.id.capture_view_frame); Bitmap bitmap = BitmapUtils.getBitmapFromView(paletteCard); assert (bitmap != null); // TODO make the share function work rather than just a trial version String name = FOLDER_HOME + File.separator + "share"; File file = BitmapUtils.saveBitmapToSDCard(bitmap, name); Intent sendIntent = new Intent(Intent.ACTION_SEND); sendIntent.setType("image/jpeg"); sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); sendIntent.putExtra(Intent.EXTRA_TEXT, "My Palette"); startActivity(Intent.createChooser(sendIntent, "share")); } private void exportPalette() { View paletteCard = null; //(View) findViewById(R.id.capture_view_bottom_bar); Bitmap bitmap = BitmapUtils.getBitmapFromView(paletteCard); assert (bitmap != null); String title = null; //mCurrentPalette.getTitle(); if (title == null) title = getResources().getString(R.string.palette_title_default); BitmapUtils.saveBitmapToSDCard(bitmap, FOLDER_HOME + File.separator + title); Toast.makeText(this, "Palette <" + title + "> has been exported", Toast.LENGTH_SHORT) .show(); } @Override public void onFragmentViewCreated(Fragment fragment) { if (fragment instanceof PaletteListFragment) { mPaletteListFragment = (PaletteListFragment) fragment; mPaletteListFragment.addAll(mDataHelper.getAllData()); } } private File getAlbumDir() { File storageDir = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), FOLDER_HOME); if (!storageDir.isDirectory()) storageDir.mkdirs(); return storageDir; } private File createImageFile() throws IOException { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = TZPALETTE_FILE_PREFIX + "_" + timeStamp; File image = File.createTempFile(imageFileName, ".jpg", getAlbumDir()); mCurrentPhotoPath = image.getAbsolutePath(); return image; } /** Called when the user performs the Take Photo action */ private void takePhoto() { Log.d(TAG, "take a photo"); if (ActivityUtils.isIntentAvailable(getBaseContext(), MediaStore.ACTION_IMAGE_CAPTURE)) { try { File file = createImageFile(); Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); startActivityForResult(takePictureIntent, TAKE_PHOTE_RESULT); } catch (IOException e) { Log.e(TAG, "take a photo failed"); } } else { Log.e(TAG, "no camera found"); } } /** Called when the user performs the Load Picture action */ private void loadPicture() { Log.d(TAG, "load a picture"); Intent photoPickerIntent = new Intent(Intent.ACTION_PICK); /* invoke the system's media scanner to add the photo to * the Media Provider's database */ Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); mediaScanIntent.setData(selectedImage); sendBroadcast(mediaScanIntent); openEditView(selectedImage); } } break; case LOAD_PICTURE_RESULT: if (resultCode == RESULT_OK) { Uri selectedImage = intent.getData(); if (selectedImage != null) openEditView(selectedImage); } break; case PALETTE_EDIT_RESULT: if (resultCode == RESULT_OK) { long dataId = intent.getLongExtra(PALETTE_DATA_ID, Long.valueOf(-1)); boolean addNew = intent.getBooleanExtra(PALETTE_DATA_ADDNEW, false); PaletteData data = mDataHelper.get(dataId); if (data != null) { if (addNew) mPaletteListFragment.add(data); else mPaletteListFragment.update(data); } // navigate to the palette list view after saving/updating a palette data mTabsAdapter.setSelectedPage(PAGE_PALETTE_LIST_POSITION); } break; } } private void openEditView(long dataId) { Intent intent = new Intent(this, PaletteEditActivity.class); intent.putExtra(PALETTE_DATA_ID, dataId); startActivityForResult(intent, PALETTE_EDIT_RESULT); } private void openEditView(Uri selectedImage) { Intent intent = new Intent(this, PaletteEditActivity.class); intent.putExtra(PALETTE_DATA_ID, Long.valueOf(-1)); intent.setData(selectedImage); startActivityForResult(intent, PALETTE_EDIT_RESULT); } private void updateOptionMenu() { invalidateOptionsMenu(); } /** * This is a helper class that implements the management of tabs and all details of connecting a * ViewPager with associated TabHost. It relies on a trick. Normally a tab host has a simple API * for supplying a View or Intent that each tab will show. This is not sufficient for switching * between pages. So instead we make the content part of the tab host 0dp high (it is not shown) * and the TabsAdapter supplies its own dummy view to show as the tab content. It listens to * changes in tabs, and takes care of switch to the correct paged in the ViewPager whenever the * selected tab changes. */ public class TabsAdapter extends FragmentPagerAdapter implements ActionBar.TabListener, ViewPager.OnPageChangeListener { private final Context mContext; private final ActionBar mActionBar; private final ViewPager mViewPager; private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>(); final class TabInfo { private final Class<?> clss; private final Bundle args; TabInfo(Class<?> _class, Bundle _args) { clss = _class; args = _args; } } public TabsAdapter(Activity activity, ViewPager pager) { super(activity.getFragmentManager()); mContext = activity; mActionBar = activity.getActionBar(); mViewPager = pager; mViewPager.setAdapter(this); mViewPager.setOnPageChangeListener(this); } public int getSelectedNavigationIndex() { return mActionBar.getSelectedNavigationIndex(); } public void setSelectedTab(int position) { mActionBar.setSelectedNavigationItem(position); } public void setSelectedPage(int position) { mViewPager.setCurrentItem(position); } public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) { TabInfo info = new TabInfo(clss, args); tab.setTag(info); tab.setTabListener(this); mTabs.add(info); mActionBar.addTab(tab); notifyDataSetChanged(); } @Override public int getCount() { return mTabs.size(); } @Override public Fragment getItem(int position) { TabInfo info = mTabs.get(position); return Fragment.instantiate(mContext, info.clss.getName(), info.args); } @Override public void onPageSelected(int position) { mActionBar.setSelectedNavigationItem(position); //Invalidate the options menu to re-create them updateOptionMenu(); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {} @Override public void onPageScrollStateChanged(int state) {} @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) {} @Override public void onTabReselected(Tab tab, FragmentTransaction ft) {} } }
package org.griphyn.vdl.mapping; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.griphyn.vdl.type.Field; import org.griphyn.vdl.type.Type; import org.griphyn.vdl.type.Types; public abstract class AbstractDataNode implements DSHandle { public static final Logger logger = Logger.getLogger(AbstractDataNode.class); public static final MappingParam PARAM_PREFIX = new MappingParam("prefix", null); private Field field; private Map handles; private Object value; private boolean closed; private List listeners; protected AbstractDataNode(Field field) { this.field = field; handles = new HashMap(); } public void init(Map params) { } public Type getType() { return field.getType(); } public boolean isPrimitive() { return field.getType().isPrimitive(); } protected Field getField() { return field; } /** * create a String representation of this node. If the node has a value, * then uses the String representation of that value. Otherwise, generates a * text description. */ public String toString() { if (this.value != null && !(this.value instanceof Exception)) { // special handling for ints... if (this.getType().equals(Types.INT)) { try { Number n = (Number) this.getValue(); return String.valueOf(n.intValue()); } catch (ClassCastException e) { throw new RuntimeException("Internal type error. Value is not a Number for " + getDisplayableName() + getPathFromRoot()); } } else { return this.value.toString(); } } String prefix = this.getClass().getName() + " with no value at dataset="; prefix = prefix + getDisplayableName(); if (!Path.EMPTY_PATH.equals(getPathFromRoot())) { prefix = prefix + " path="+ getPathFromRoot().toString(); } return prefix; } protected String getDisplayableName() { String prefix = getRoot().getParam("dbgname"); if (prefix == null) { prefix = getRoot().getParam("prefix"); } if (prefix == null) { prefix = "unnamed SwiftScript value"; } return prefix; } public DSHandle getField(Path path) throws InvalidPathException { if (path.isEmpty()) { return this; } try { DSHandle handle = getField(path.getFirst()); if (path.size() > 1) { return handle.getField(path.butFirst()); } else { return handle; } } catch (NoSuchFieldException e) { throw new InvalidPathException(path, this); } } public Collection getFields(Path path) throws InvalidPathException, HandleOpenException { List fields = new ArrayList(); getFields(fields, path); return fields; } private void getFields(List fields, Path path) throws InvalidPathException, HandleOpenException { if (path.isEmpty()) { fields.add(this); } else { Path rest = path.butFirst(); if (path.isWildcard(0)) { if (isArray() && !closed) { throw new HandleOpenException(this); } Iterator i = this.handles.entrySet().iterator(); while (i.hasNext()) { Map.Entry e = (Map.Entry) i.next(); ((AbstractDataNode) e.getValue()).getFields(fields, rest); } } else { try { ((AbstractDataNode) getField(path.getFirst())).getFields(fields, rest); } catch (NoSuchFieldException e) { throw new InvalidPathException(path, this); } } } } public void set(DSHandle handle) { // TODO check type if (closed) { throw new IllegalArgumentException(this.getDisplayableName() + " is already assigned"); } if (getParent() == null) { /* * AbstractDataNode node = (AbstractDataNode)handle; field = * node.getField(); handles = node.getHandles(); closed = * node.isClosed(); value = node.getValue(); */ throw new RuntimeException("Can't set root data node!"); } else { ((AbstractDataNode) getParent()).setField(field.getName(), handle); } } protected void setField(String name, DSHandle handle) { synchronized (handles) { handles.put(name, handle); } } protected synchronized DSHandle getField(String name) throws NoSuchFieldException { DSHandle handle = getHandle(name); if (handle == null) { if (closed) { throw new NoSuchFieldException(name); } else { handle = createDSHandle(name); } } return handle; } protected DSHandle getHandle(String name) { synchronized (handles) { return (DSHandle) handles.get(name); } } protected boolean isHandlesEmpty() { synchronized (handles) { return handles.isEmpty(); } } public DSHandle createDSHandle(String fieldName) throws NoSuchFieldException { if (closed) { throw new RuntimeException("Cannot write to closed handle: " + this + " (" + fieldName + ")"); } AbstractDataNode child; Field childField = getChildField(fieldName); if (childField.getType().isArray()) { child = new ArrayDataNode(getChildField(fieldName), getRoot(), this); } else { child = new DataNode(getChildField(fieldName), getRoot(), this); } synchronized (handles) { Object o = handles.put(fieldName, child); if (o != null) { throw new RuntimeException("Trying to create a handle that already exists (" + fieldName + ") in " + this); } } return child; } protected Field getChildField(String fieldName) throws NoSuchFieldException { return Field.Factory.createField(fieldName, field.getType().getField(fieldName).getType()); } protected void checkDataException() { if (value instanceof DependentException) { throw (DependentException) value; } } protected void checkMappingException() { if (value instanceof MappingDependentException) { throw (MappingDependentException) value; } } public Object getValue() { checkDataException(); if (field.getType().isArray()) { return handles; } else { return value; } } public Map getArrayValue() { checkDataException(); if (!field.getType().isArray()) { throw new RuntimeException("getArrayValue called on a struct: " + this); } return handles; } public boolean isArray() { return false; } public void setValue(Object value) { if (this.value != null) { throw new IllegalArgumentException(this.getDisplayableName() + " is already assigned with a value of " + this.value); } this.value = value; } public Collection getFringePaths() throws HandleOpenException { ArrayList list = new ArrayList(); getFringePaths(list, Path.EMPTY_PATH); return list; } public void getFringePaths(List list, Path parentPath) throws HandleOpenException { checkMappingException(); if (getField().getType().getBaseType() != null) { list.add(Path.EMPTY_PATH.toString()); } else { Iterator i = getField().getType().getFields().iterator(); while (i.hasNext()) { Field field = (Field) i.next(); AbstractDataNode mapper; try { mapper = (AbstractDataNode) this.getField(field.getName()); } catch (NoSuchFieldException e) { throw new RuntimeException( "Inconsistency between type declaration and handle for field '" + field.getName() + "'"); } //[m] Hmm. Should there be a difference between field and mapper.getField()? //Path fullPath = parentPath.addLast(mapper.getField().getName()); Path fullPath = parentPath.addLast(field.getName()); if (!mapper.field.getType().isPrimitive() && !mapper.isArray()) { list.add(fullPath); } else { mapper.getFringePaths(list, fullPath); } } } } public synchronized void closeShallow() { this.closed = true; notifyListeners(); } public boolean isClosed() { return closed; } public void closeDeep() { if (!this.closed) { setValue(Boolean.TRUE); closeShallow(); } synchronized (handles) { Iterator i = handles.entrySet().iterator(); while (i.hasNext()) { Map.Entry e = (Map.Entry) i.next(); AbstractDataNode mapper = (AbstractDataNode) e.getValue(); mapper.closeDeep(); } } } public Path getPathFromRoot() { AbstractDataNode parent = (AbstractDataNode) this.getParent(); Path myPath; if (parent != null) { myPath = parent.getPathFromRoot(); return myPath.addLast(getField().getName(), parent.getField().getType().isArray()); } else { return Path.EMPTY_PATH; } } public Mapper getMapper() { return ((AbstractDataNode) getRoot()).getMapper(); } protected Map getHandles() { return handles; } public synchronized void addListener(DSHandleListener listener) { if (logger.isInfoEnabled()) { logger.info("Adding handle listener \"" + listener + "\" to \"" + this + "\""); } if (listeners == null) { listeners = new LinkedList(); } listeners.add(listener); if (closed) { notifyListeners(); } } protected synchronized void notifyListeners() { if (listeners != null) { Iterator i = listeners.iterator(); while (i.hasNext()) { DSHandleListener listener = (DSHandleListener) i.next(); i.remove(); if (logger.isInfoEnabled()) { logger.info("Notifying listener \"" + listener + "\" about \"" + this + "\""); } listener.handleClosed(this); } listeners = null; } } }
package com.virtualfactory.engine; import com.virtualfactory.utils.InvisibleWall; import com.virtualfactory.screen.layer.*; import com.virtualfactory.screen.other.Popups; import com.virtualfactory.screen.intro.IntroScreen; import com.virtualfactory.screen.menu.*; import com.virtualfactory.data.GameData; import com.jme3.animation.AnimChannel; import com.jme3.post.filters.FadeFilter; import com.jme3.animation.AnimControl; import com.jme3.animation.AnimEventListener; import com.jme3.app.Application; import com.jme3.app.SimpleApplication; import com.jme3.app.state.AbstractAppState; import com.jme3.app.state.AppStateManager; import com.jme3.asset.AssetManager; import com.jme3.audio.AudioNode; import com.jme3.bullet.BulletAppState; import com.jme3.bullet.collision.shapes.*; import com.jme3.bullet.control.*; import com.jme3.collision.CollisionResult; import com.jme3.collision.CollisionResults; import com.jme3.cursors.plugins.JmeCursor; import com.jme3.input.*; import com.jme3.input.controls.*; import com.jme3.light.*; import com.jme3.material.Material; import com.jme3.math.*; import com.jme3.niftygui.NiftyJmeDisplay; import com.jme3.post.FilterPostProcessor; import com.jme3.renderer.Camera; import com.jme3.renderer.ViewPort; import com.jme3.scene.*; import com.jme3.scene.debug.Grid; import com.jme3.scene.shape.*; import com.jme3.scene.shape.Line; import com.jme3.system.AppSettings; import com.jme3.texture.Texture; import com.jme3.util.SkyFactory; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.elements.Element; import com.virtualfactory.entity.*; import com.virtualfactory.narrator.Narrator; import com.virtualfactory.screen.layer.components.*; import com.virtualfactory.pathfinding.Path; import com.virtualfactory.pathfinding.Path.Step; import com.virtualfactory.screen.other.Credits; import com.virtualfactory.simpack.*; import com.virtualfactory.strategy.ManageEvents; import com.virtualfactory.threads.*; import com.virtualfactory.utils.*; import de.lessvoid.nifty.tools.SizeValue; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; public class GameEngine extends AbstractAppState implements AnimEventListener { protected BulletAppState bulletAppState; /* Terrain */ RigidBodyControl terrainPhysicsNode; /* Materials */ Material matTerrain; Material matWire; Material matCharacter; /* Character */ ArrayList<CharacterControl> arrCharacter; ArrayList<CharacterControl> arrCharacter2; ArrayList<CharacterControl> arrCharacter3; ArrayList<CharacterControl> arrCharacter4; Node model; float angle; /* Camera */ boolean left = false, right = false, up = false, down = false; ChaseCamera chaseCam; /* Animation */ AnimControl animationControl; ArrayList<AnimControl> arrAnimationControl; float cont = 0; AnimChannel animationChannel_Disp; CharacterControl character_Disp; private GameData gameData; private ManageEvents manageEvents; private boolean isLevelStarted; private MenuScreenController menuScreenC; private LayerScreenController layerScreenC; private Node world; private RigidBodyControl worldRigid; private RigidBodyControl bucketRigid; private Box bucketBox; private Material bucketMaterial; private RigidBodyControl stationRigid; private Box stationBox; private Material stationMaterial; private RigidBodyControl partRigid; private Box partBox; private Material partMaterial; private ArrayList<DispOperatorWalksTo> arrOperatorsWalksTo; private ArrayList<DispOperatorMachineMovingTo> arrOperatorsMachinesMovingTo; private ArrayList<StationAnimation> arrStationAnimations; private TerrainMap terrainMap; private Nifty niftyGUI; private Status currentSystemStatus; private double currentSystemTime; private long currentTempSystemTime; private long initialRealSystemTime; private long currentIdleSystemTime; private long currentWindowRefreshSystemTime; private int timeToUpdateSlots; private Node shootables; private int initialGameId; private ArrayList<JmeCursor> cursors; private CloseGame closeGame; private Geometry showSpotObject; private GameSounds gameSounds; private ArrayList<Pair<GameSounds, Sounds>> arrGameSounds; private boolean isDashboardVisible = false; public SimpleApplication jmonkeyApp; private AppStateManager stateManager; private AssetManager assetManager; private Node guiNode; private Node rootNode; private InputManager inputManager; private FlyByCamera flyCam; private Camera cam; private ViewPort viewPort; private ViewPort guiViewPort; private CharacterControl player; private GhostControl topStairsSensor; private boolean forward = false; private boolean backward = false; private boolean moveLeft = false; private boolean moveRight = false; private boolean lookUp = false; private boolean lookDown = false; private boolean lookLeft = false; private boolean lookRight = false; private boolean topViewEnabled = false; private boolean isDebugCamEnabled = false; private int viewNumber = 0; private float playerSpeed = 1.3f; private Vector3f camDir; private Vector3f camLeft; private Vector3f walkDirection = new Vector3f(0, 0, 0); private PointLight lamp1; private PointLight lamp2; private boolean isLightingEnabled; private FadeFilter fadeFilter; private FilterPostProcessor fpp; private GhostControl bottomStairsSensor; private Narrator gameNarrator; private boolean isPlayerUpstairs = true; @Override public void initialize(AppStateManager manager, Application application) { Params.screenHeight = application.getContext().getSettings().getHeight(); jmonkeyApp = (SimpleApplication) application; loadJmonkeyAppResources(); loadGameData(); loadGameSounds(); loadGameControls(); NiftyJmeDisplay niftyDisplay = new NiftyJmeDisplay(assetManager, inputManager, jmonkeyApp.getAudioRenderer(), guiViewPort); guiViewPort.addProcessor(niftyDisplay); niftyGUI = niftyDisplay.getNifty(); buildGameScreens(); if (Params.DEBUG_ON) niftyGUI.gotoScreen("initialMenu"); else niftyGUI.gotoScreen("start"); gameNarrator = new Narrator(stateManager, assetManager, guiNode); } private void loadJmonkeyAppResources() { if (jmonkeyApp == null) throw new IllegalStateException("jmonkeyApp has not been initialized."); stateManager = jmonkeyApp.getStateManager(); assetManager = jmonkeyApp.getAssetManager(); inputManager = jmonkeyApp.getInputManager(); flyCam = jmonkeyApp.getFlyByCamera(); cam = jmonkeyApp.getCamera(); viewPort = jmonkeyApp.getViewPort(); guiViewPort = jmonkeyApp.getGuiViewPort(); guiNode = jmonkeyApp.getGuiNode(); rootNode = jmonkeyApp.getRootNode(); } private void loadGameData() { gameData = GameData.getInstance(); gameData.setGameEngine(this); } private void loadGameSounds() { gameSounds = new GameSounds(assetManager); arrGameSounds = new ArrayList<>(); } private void loadGameControls() { loadAvailableCursors(); updateCursorIcon(0); deleteDefaultControls(); String[] mappings = {"Forward", "Backward", "Move Left", "Move Right", "Look Up", "Look Down", "Look Left", "Look Right", "Jump", "Picking", "Toggle Dashboard", "Toggle Top View", "Toggle Full Screen", "Debug Position", "Debug Cam", "Mouse Picking"}; Trigger[] triggers = {new KeyTrigger(KeyInput.KEY_W), new KeyTrigger(KeyInput.KEY_S), new KeyTrigger(KeyInput.KEY_A), new KeyTrigger(KeyInput.KEY_D), new KeyTrigger(KeyInput.KEY_UP), new KeyTrigger(KeyInput.KEY_DOWN), new KeyTrigger(KeyInput.KEY_LEFT), new KeyTrigger(KeyInput.KEY_RIGHT), new KeyTrigger(KeyInput.KEY_SPACE), new KeyTrigger(KeyInput.KEY_LSHIFT), new KeyTrigger(KeyInput.KEY_RSHIFT), new KeyTrigger(KeyInput.KEY_T), new KeyTrigger(KeyInput.KEY_F1), new KeyTrigger(KeyInput.KEY_P), new KeyTrigger(KeyInput.KEY_0), new MouseButtonTrigger(MouseInput.BUTTON_LEFT)}; for (int i = 0; i < mappings.length; i++) { inputManager.addMapping(mappings[i], triggers[i]); inputManager.addListener(actionListener, mappings[i]); } } private void loadAvailableCursors() { cursors = new ArrayList<>(); cursors.add((JmeCursor) assetManager.loadAsset("Interface/Cursor/cursorWood.ico")); cursors.add((JmeCursor) assetManager.loadAsset("Interface/Cursor/busy.ani")); inputManager.setCursorVisible(true); } public void updateCursorIcon(int newCursorValue) { inputManager.setMouseCursor(cursors.get(newCursorValue)); } private void deleteDefaultControls() { inputManager.deleteMapping(SimpleApplication.INPUT_MAPPING_EXIT); inputManager.deleteMapping("FLYCAM_ZoomIn"); inputManager.deleteMapping("FLYCAM_ZoomOut"); inputManager.deleteMapping("FLYCAM_Up"); inputManager.deleteMapping("FLYCAM_Down"); inputManager.deleteMapping("FLYCAM_Left"); inputManager.deleteMapping("FLYCAM_Right"); inputManager.deleteTrigger("FLYCAM_RotateDrag", new MouseButtonTrigger(MouseInput.BUTTON_LEFT)); } private ActionListener actionListener = new ActionListener() { @Override public void onAction(String name, boolean keyPressed, float tpf) { if (name.equals("Toggle Full Screen") && !keyPressed) changeScreenSize(); if (!isLevelStarted) return; switch (name) { case "Forward": forward = keyPressed; break; case "Backward": backward = keyPressed; break; case "Move Left": moveLeft = keyPressed; break; case "Move Right": moveRight = keyPressed; break; case "Look Up": lookUp = keyPressed; break; case "Look Down": lookDown = keyPressed; break; case "Look Left": lookLeft = keyPressed; break; case "Look Right": lookRight = keyPressed; break; case "Jump": if (!keyPressed) player.jump(); break; case "Picking": case "Mouse Picking": if (!keyPressed) handlePickedObject(name); break; case "Toggle Dashboard": if (!keyPressed) toggleDashBoard(); break; case "Toggle Top View": if (!keyPressed && isPlayerUpstairs) toggleTopView(); break; case "Debug Position": if (!keyPressed) System.out.println("" + "\n\nlocation: " + cam.getLocation() + "\nleft: " + cam.getLeft() + "\nup: " + cam.getUp() + "\ndirection: " + cam.getDirection()); break; case "Debug Cam": if (!keyPressed) isDebugCamEnabled = !isDebugCamEnabled; break; default: break; } } }; private void buildGameScreens() { if (niftyGUI == null) throw new IllegalStateException("Cannot build game screens. Nifty GUI was not initialized."); niftyGUI.loadStyleFile("Interface/NiftyJars/nifty-style-black/nifty-default-styles.xml"); niftyGUI.loadControlFile("nifty-default-controls.xml"); niftyGUI.registerSound("intro", "Interface/sound/19546__tobi123__Gong_mf2.wav"); niftyGUI.registerMusic("credits", "Interface/sound/Loveshadow_-_Almost_Given_Up.ogg"); IntroScreen.build(niftyGUI); MenuScreen.build(niftyGUI); LayerScreen.build(niftyGUI); Credits.register(niftyGUI); Popups.register(niftyGUI); menuScreenC = (MenuScreenController) niftyGUI.getScreen("initialMenu").getScreenController(); menuScreenC.setGameEngine(this); layerScreenC = (LayerScreenController) niftyGUI.getScreen("layerScreen").getScreenController(); layerScreenC.setGameEngine(this); } public void playGame(E_Game tempGame, boolean newGame) { initialGameId = tempGame.getIdGame(); updateCursorIcon(1); flushPreviousGame(); if (newGame) { this.getArrGameSounds().clear(); this.gameSounds.stopSound(Sounds.Background); gameData.createGame(tempGame); } else { gameData.loadGame(tempGame); } manageEvents = new ManageEvents(this, gameData); gameData.updateTimeOrders(); resetLayerScreen(); initSimPack(); loadElementsToDisplay(newGame ? GameType.New : GameType.Load); enableLayerScreen(); updateCursorIcon(0); isLevelStarted = true; gameNarrator.talk("Welcome to Virtual Factory!\nPress 'T' for a top view of the factory.", 5); } private void flushPreviousGame() { rootNode.detachAllChildren(); resetPhysicsEngine(); System.gc(); terrainMap = new TerrainMap(); shootables = new Node("Shootables"); rootNode.attachChild(shootables); } private void resetPhysicsEngine() { if (bulletAppState == null) { bulletAppState = new BulletAppState(); bulletAppState.setThreadingType(BulletAppState.ThreadingType.PARALLEL); stateManager.attach(bulletAppState); } else { bulletAppState.getPhysicsSpace().destroy(); bulletAppState.getPhysicsSpace().create(); } } private void resetLayerScreen() { getLayerScreenController().updateStartScreen(); getLayerScreenController().setTimeFactor((float) gameData.getCurrentGame().getTimeFactor()); getLayerScreenController().setGameNamePrincipal(gameData.getCurrentGame().getGameName()); getLayerScreenController().setNextDueDate("-"); getLayerScreenController().setNextPurchaseDueDate("-"); } private void initSimPack() { currentSystemStatus = Status.Busy; currentSystemTime = gameData.getCurrentGame().getCurrentTime(); currentTempSystemTime = System.currentTimeMillis(); Sim.init(currentSystemTime, new LinkedListFutureEventList()); Sim.schedule(new SimEvent(Sim.time() + getLayerScreenController().getTimeFactor(), Params.startEvent)); } private void loadElementsToDisplay(GameType gameType) { createTerrain(); arrOperatorsWalksTo = new ArrayList<>(); arrOperatorsMachinesMovingTo = new ArrayList<>(); arrStationAnimations = new ArrayList<>(); Iterable<E_Station> tempStation = gameData.getMapUserStation().values(); for (E_Station station : tempStation) { createStations(station); } Iterable<E_Operator> tempOperator = gameData.getMapUserOperator().values(); for (E_Operator operator : tempOperator) { createOperators(operator, gameType); operator.updateInactiveBrokenOperator(); if (operator.getState().equals(ObjectState.Inactive)) { operator.showHideInactiveOperator(true); } } Iterable<E_Machine> tempMachine = gameData.getMapUserMachine().values(); for (E_Machine machine : tempMachine) { createMachines(machine, gameType); machine.updateInactiveBrokenMachine(); if (machine.getMachineState().equals(ObjectState.Inactive)) { machine.showHideInactiveMachine(true); } } createShowSpotObject(); if (topViewEnabled) { topViewEnabled = false; viewNumber = 0; cam.setAxes(Params.camAxesLeft, Params.camAxesUp, Params.camAxesDir); flyCam.setMoveSpeed(100); Params.camMaxX = Params.playerMaxX; Params.camMinX = Params.playerMinX; Params.camMaxY = Params.playerMaxY; Params.camMinY = Params.playerMinY; Params.camMaxZ = Params.playerMaxZ; Params.camMinZ = Params.playerMinZ; } } private void createTerrain() { fpp = new FilterPostProcessor(assetManager); fadeFilter = new FadeFilter(1.5f); fpp.addFilter(fadeFilter); viewPort.addProcessor(fpp); E_Terrain tempTerrain = gameData.getMapTerrain(); flyCam.setMoveSpeed(100); /* Factory */ world = (Node) assetManager.loadModel("Models/factory.j3o"); world.setLocalScale(250.0f, 250.0f, 250.0f); world.setLocalTranslation(-9.0f, 0.0f, 82.0f); rootNode.attachChild(world); RigidBodyControl rigidBody = new RigidBodyControl(0); world.addControl(rigidBody); bulletAppState.getPhysicsSpace().add(rigidBody); Node grass = (Node) assetManager.loadModel("Models/grass.j3o"); grass.setLocalScale(250.0f, 250.0f, 250.0f); grass.setLocalTranslation(-9.0f, 0.0f, 82.0f); rootNode.attachChild(grass); createSkyBox(); createLighting(); createInvisibleWalls(); topStairsSensor = new GhostControl(new BoxCollisionShape(new Vector3f(15, 10, 5))); Vector3f sensorLocation = new Vector3f(134.05f, 59.06f, -285.02f); enableSensor(topStairsSensor, sensorLocation); bottomStairsSensor = new GhostControl(new BoxCollisionShape(new Vector3f(15, 10, 5))); sensorLocation = new Vector3f(107.42f, 12.67f, -284.9f); enableSensor(bottomStairsSensor, sensorLocation); /* First-person Player */ player = new CharacterControl(new CapsuleCollisionShape(0.4f, 24.5f, 1), 0.05f); player.setJumpSpeed(45); player.setFallSpeed(120); player.setGravity(Params.playerGravity); player.setPhysicsLocation(new Vector3f(51.68367f, 59.064148f, -292.67755f)); cam.setRotation(new Quaternion(0.07086334f, -0.01954512f, 0.0019515193f, 0.99729264f)); flyCam.setRotationSpeed(1.9499999f); player.setViewDirection(new Vector3f(0, 0, 1)); bulletAppState.getPhysicsSpace().add(player); //blocked zones Map<Integer, E_TerrainReserved> tempBlockedZones = tempTerrain.getArrZones(); for (E_TerrainReserved tempBlockedZone : tempBlockedZones.values()) { setTerrainMap(tempBlockedZone.getLocationX(), tempBlockedZone.getLocationZ(), tempBlockedZone.getWidth(), tempBlockedZone.getLength(), true); } } private void createInvisibleWalls() { String[] wallNames = {"bottom right wall", "bottom left wall", "bottom front wall", "bottom back wall", "upper right wall", "upper left wall", "upper front wall", "upper back wall"}; Vector3f[] sizes = {new Vector3f(0.6f, 0.6f, 23.600018f), new Vector3f(1.4000001f, 0.6f, 23.600018f), new Vector3f(9.399996f, 1.0f, 1.0f), new Vector3f(9.399996f, 1.0f, 0.6f), new Vector3f(0.40000004f, 1.0f, 3.4000006f), new Vector3f(0.40000004f, 1.0f, 3.0000005f), new Vector3f(7.599997f, 1.0f, 0.20000003f), new Vector3f(9.599996f, 1.0f, 0.40000004f)}; Vector3f[] locations = {new Vector3f(-37.600044f, 5.850006f, -117.43932f), new Vector3f(137.1993f, 5.850006f, -117.43932f), new Vector3f(50.80012f, 9.999995f, 106.9995f), new Vector3f(50.60012f, 9.999995f, -346.80283f), new Vector3f(-40.543167f, 56.8007f, -318.2905f), new Vector3f(140.85591f, 56.8007f, -322.69077f), new Vector3f(31.656963f, 56.8007f, -289.88876f), new Vector3f(50.433777f, 56.38947f, -350.81924f)}; for (int i = 0; i < wallNames.length; i++) { Geometry invisibleWall = new InvisibleWall(bulletAppState, sizes[i], locations[i]); invisibleWall.setName(wallNames[i]); rootNode.attachChild(invisibleWall); } } private void createSkyBox() { String path = "Textures/Skybox/"; Texture west = assetManager.loadTexture(path + "skyLeft.jpg"); Texture east = assetManager.loadTexture(path + "skyRight.jpg"); Texture north = assetManager.loadTexture(path + "skyFront.jpg"); Texture south = assetManager.loadTexture(path + "skyBack.jpg"); Texture top = assetManager.loadTexture(path + "skyTop.jpg"); Texture bottom = assetManager.loadTexture(path + "skyDown.jpg"); Spatial skyBox = SkyFactory.createSky(assetManager, west, east, north, south, top, bottom); rootNode.attachChild(skyBox); } private void createLighting() { if (isLightingEnabled) return; isLightingEnabled = true; ColorRGBA color = ColorRGBA.White; lamp1 = new PointLight(); lamp1.setPosition(new Vector3f(40, 200, 150)); lamp1.setColor(color); lamp1.setRadius(lamp1.getRadius()/20); rootNode.addLight(lamp1); lamp2 = new PointLight(); lamp2.setPosition(new Vector3f(43.50383f, 80.081642f, -310.90753f)); lamp2.setColor(color); lamp2.setRadius(lamp1.getRadius()); rootNode.addLight(lamp2); } private void enableSensor(GhostControl sensor, Vector3f location) { Box b = new Box(1, 1, 1); Geometry boxGeometry = new Geometry("sensor box", b); boxGeometry.setLocalTranslation(location); Material boxMat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); boxMat.setColor("Color", ColorRGBA.Yellow); boxGeometry.setMaterial(boxMat); boxGeometry.addControl(sensor); bulletAppState.getPhysicsSpace().add(sensor); } private void enableLayerScreen() { //show static windows niftyGUI.getScreen("layerScreen").findElementByName("winOvC_Element").getControl(OverallScreenController.class).loadWindowControl(this, 0, null); niftyGUI.getScreen("layerScreen").findElementByName("winOrC_Element").getControl(OrderScreenController.class).loadWindowControl(this, 0, null); niftyGUI.getScreen("layerScreen").findElementByName("winGLC_Element").getControl(GameLogScreenController.class).loadWindowControl(this, 0, null); niftyGUI.getScreen("layerScreen").findElementByName("winGSC_Element").getControl(GameSetupScreenController.class).loadWindowControl(this, -1, null); // -1 because we dont want it to be visible niftyGUI.getScreen("layerScreen").findElementByName("winFCC_Element").getControl(FlowChartScreenController.class).loadWindowControl(this, -1, null); niftyGUI.getScreen("layerScreen").findElementByName("winDashboard_Element").getControl(DashboardScreenController.class).loadWindowControl(this, 0, null); //clean lists niftyGUI.getScreen("layerScreen").findElementByName("winOrC_Element").getControl(OrderScreenController.class).cleanOrders(); niftyGUI.getScreen("layerScreen").findElementByName("winGLC_Element").getControl(GameLogScreenController.class).cleanMessages(); niftyGUI.getScreen("layerScreen").findElementByName("winGSC_Element").getControl(GameSetupScreenController.class).updateAllStepStatus(false); getLayerScreenController().updateQuantityCurrentMoney(gameData.getCurrentMoney()); getLayerScreenController().forcePauseGame(); initialRealSystemTime = System.currentTimeMillis() / 1000; currentIdleSystemTime = System.currentTimeMillis() / 1000; currentWindowRefreshSystemTime = System.currentTimeMillis() / 1000; timeToUpdateSlots = gameData.getCurrentTimeWithFactor(); getLayerScreenController().hideCurrentControlsWindow(); getLayerScreenController().showHideDynamicButtons(0); getLayerScreenController().showHideDynamicSubLevelButtons(0); niftyGUI.getScreen("layerScreen").findElementByName("winOvC_Element").getControl(OverallScreenController.class).HideWindow(); niftyGUI.getScreen("layerScreen").findElementByName("winOrC_Element").getControl(OrderScreenController.class).HideWindow(); niftyGUI.getScreen("layerScreen").findElementByName("winGLC_Element").getControl(GameLogScreenController.class).showHide(); } /** * Engine's main game loop. It runs every frame. * @param tpf time per frame (elapsed time since the last frame) */ @Override public void update(float tpf) { updatePlayerPosition(); updateGameDataAndLogic(); } public void updatePlayerPosition() { if (!isLevelStarted) return; if (topStairsSensor.getOverlappingCount() > 1 || bottomStairsSensor.getOverlappingCount() > 1) handleTransition(); if (lookUp) rotateCamera(-Params.rotationSpeed, cam.getLeft()); if (lookDown) rotateCamera(Params.rotationSpeed, cam.getLeft()); if (lookLeft) rotateCamera(Params.rotationSpeed, new Vector3f(0,1,0)); if (lookRight) rotateCamera(-Params.rotationSpeed, new Vector3f(0,1,0)); if (topViewEnabled || isDebugCamEnabled) return; camDir = cam.getDirection().clone().multLocal(playerSpeed); camLeft = cam.getLeft().clone().multLocal(playerSpeed); walkDirection.set(0, 0, 0); // reset walkDirection vector if (forward) walkDirection.addLocal(camDir); if (backward) walkDirection.addLocal(camDir.negate()); if (moveLeft) walkDirection.addLocal(camLeft); if (moveRight) walkDirection.addLocal(camLeft.negate()); player.setWalkDirection(walkDirection); // walk! cam.setLocation(player.getPhysicsLocation()); if (isPlayerUpstairs && player.getPhysicsLocation().getY() < 58.0f) player.warp(new Vector3f(player.getPhysicsLocation().getX(), 58.0f, player.getPhysicsLocation().getZ())); else if (player.getPhysicsLocation().getY() < 12.65f) player.warp(new Vector3f(player.getPhysicsLocation().getX(), 12.65f, player.getPhysicsLocation().getZ())); } private void handleTransition() { isPlayerUpstairs = topStairsSensor.getOverlappingCount() > 1; boolean isFadeEffectStarted = fadeFilter.getValue() < 1; if (!isFadeEffectStarted) { playerSpeed = 0; fadeFilter.fadeOut(); AudioNode footsteps; footsteps = new AudioNode(assetManager, isPlayerUpstairs ? "Sounds/footsteps1.wav" : "Sounds/footsteps2.wav", false); footsteps.setPositional(false); footsteps.play(); } boolean isFadeEffectFinished = fadeFilter.getValue() <= 0; if (isFadeEffectFinished) { if (isPlayerUpstairs) { player.warp(new Vector3f(121.2937f, 12.65f, -309.41315f)); cam.setRotation(new Quaternion(0.04508071f, -0.4710204f, 0.02474963f, 0.8806219f)); isPlayerUpstairs = false; } else { player.setPhysicsLocation(new Vector3f(51.68367f, 59.064148f, -292.67755f)); cam.setRotation(new Quaternion(0.07086334f, -0.01954512f, 0.0019515193f, 0.99729264f)); gameNarrator.talk("Second Floor.\nPress 'T' for a top view of the factory.", "Sounds/Narrator/instructions.wav"); isPlayerUpstairs = true; } fadeFilter.fadeIn(); playerSpeed = 1.3f; } } private void rotateCamera(float value, Vector3f axis){ Matrix3f mat = new Matrix3f(); if (topViewEnabled) value = value*0.3f; mat.fromAngleNormalAxis(flyCam.getRotationSpeed() * value, axis); Vector3f tempUp = cam.getUp(); Vector3f tempLeft = cam.getLeft(); Vector3f tempDir = cam.getDirection(); mat.mult(tempUp, tempUp); mat.mult(tempLeft, tempLeft); mat.mult(tempDir, tempDir); if (tempDir.getX() > Params.camMaxX || tempDir.getX() < Params.camMinX || tempDir.getY() > Params.camMaxY || tempDir.getY() < Params.camMinY || tempDir.getZ() > Params.camMaxZ || tempDir.getZ() < Params.camMinZ) return; Quaternion q = new Quaternion(); q.fromAxes(tempLeft, tempUp, tempDir); q.normalizeLocal(); cam.setAxes(q); } public void updateGameDataAndLogic() { //Added by Chris if (!this.getLayerScreenController().getPauseStatus() && gameSounds.machineSoundPlaying()) this.gameSounds.pauseSound(Sounds.MachineWorking); if (!isLevelStarted) return; if (currentSystemStatus.equals(Status.Busy)) currentSystemTime += (double) ((System.currentTimeMillis() - currentTempSystemTime) / 1000.0); updateGraphicElementsArray(); if (gameData.getCurrentTimeWithFactor() - timeToUpdateSlots >= Params.timeToUpdateSlotsMinutes) { timeToUpdateSlots = gameData.getCurrentTimeWithFactor(); executeThreadToUpdateSlots(); } if ((System.currentTimeMillis() / 1000) - initialRealSystemTime >= Params.timeToSaveLogSeconds) { gameData.updatePlayerLog(); initialRealSystemTime = System.currentTimeMillis() / 1000; } if ((System.currentTimeMillis() / 1000) - currentIdleSystemTime >= Params.timeToCloseGameSeconds) { showPopupAttemptingToCloseGame(); updateLastActivitySystemTime(); } if ((System.currentTimeMillis() / 1000) - currentWindowRefreshSystemTime >= gameData.getCurrentGame().getTimeFactor() * Params.timeUnitsToRefresh) { gameData.updateControlsWindows(); currentWindowRefreshSystemTime = System.currentTimeMillis() / 1000; } // Update dashboard data niftyGUI.getScreen("layerScreen").findElementByName("winDashboard_Element").getControl(DashboardScreenController.class).updateData(); currentTempSystemTime = System.currentTimeMillis(); gameData.getCurrentGame().setCurrentTime(currentSystemTime); getLayerScreenController().setCurrentGameTime(gameData.getCurrentTimeGame()); SimEvent nextEvent = Sim.next_event(currentSystemTime, Sim.Mode.SYNC); while (nextEvent != null) { if (nextEvent.getId() == Params.startEvent) { gameData.manageMachineStates(); manageEvents.executeEvent(); //it happens each TIME-UNIT Sim.schedule(new SimEvent(Sim.time() + getLayerScreenController().getTimeFactor(), Params.startEvent)); niftyGUI.getScreen("layerScreen").findElementByName("winDashboard_Element").getControl(DashboardScreenController.class).updateQuantityPeopleStatus(gameData.getNoUserOperator(Status.Busy), gameData.getNoUserOperator(Status.Idle)); } else { manageEvents.setStrategy(nextEvent.getToken()); manageEvents.releaseResourcesEvent(); } nextEvent = Sim.next_event(currentSystemTime, Sim.Mode.SYNC); getLayerScreenController().updateQuantityCurrentMoney(gameData.getCurrentMoney()); } } private void toggleDashBoard() { if (isDashboardVisible) { niftyGUI.getScreen("layerScreen").findElementByName("winDashboard_Element").hide(); isDashboardVisible = false; } else { niftyGUI.getScreen("layerScreen").findElementByName("winDashboard_Element").show(); isDashboardVisible = true; } } public GameSounds getGameSounds() { return gameSounds; } private void executeThreadToUpdateSlots() { UpdateSlotsStorage updateSlotsStorage = new UpdateSlotsStorage(); updateSlotsStorage.setMapUserStorageStation(gameData.getMapUserStorageStation()); updateSlotsStorage.setGameEngine(this); updateSlotsStorage.start(); } public void updateLastActivitySystemTime() { currentIdleSystemTime = System.currentTimeMillis() / 1000; } private void showPopupAttemptingToCloseGame() { getLayerScreenController().pauseGame(); Element exitPopup = niftyGUI.createPopup("gameClosing"); niftyGUI.showPopup(niftyGUI.getCurrentScreen(), exitPopup.getId(), null); niftyGUI.getCurrentScreen().processAddAndRemoveLayerElements(); closeGame = new CloseGame(); closeGame.setGameEngine(this); closeGame.setScreen(niftyGUI.getCurrentScreen()); closeGame.setNifty(niftyGUI); closeGame.setExitPopup(exitPopup); closeGame.start(); } public void stopClosingGame() { closeGame.setContinueGame(true); } public void updateEventsTime() { if (Sim.getFutureEventList() == null) { return; } Iterator<SimEvent> arrEvents = (Iterator) Sim.getFutureEventList().getQueue().iterator(); while (arrEvents.hasNext()) { SimEvent tempEvent = arrEvents.next(); TOKEN tempToken = tempEvent.getToken(); double oldTime = tempEvent.getTime(); if (tempToken.getAttribute(1) != 0) { tempEvent.setTime((oldTime - currentSystemTime) * getLayerScreenController().getTimeFactor() / tempToken.getAttribute(1) + currentSystemTime); // System.out.println("CHANGED TIME - attritube0:" + tempToken.getAttribute(0) + " - Time:" + currentSystemTime + " - EndTime:" + tempEvent.getTime() + " - OldEndTime:" + oldTime + " - OldFactorTime:" + tempToken.getAttribute(1) + " - NewFactorTime:" + getLayerScreenController().getTimeFactor()); if (tempToken.getAttribute(2) == Params.simpackPurchase && tempToken.getAttribute(0) == gameData.getCurrentPurchaseId()) { gameData.setNextPurchaseDueDate((int) ((tempEvent.getTime() - currentSystemTime) * getLayerScreenController().getTimeFactorForSpeed())); getLayerScreenController().setNextPurchaseDueDate(gameData.convertTimeUnistToHourMinute(gameData.getNextPurchaseDueDate())); //System.out.println("PURCHASE MISSING REAL_TIME:" + (tempEvent.getTime()-currentSystemTime) + " - GAME_TIME:" + (tempEvent.getTime()-currentSystemTime)*getLayerScreenController().getTimeFactorForSpeed() + " - CLOCK_TIME:" + gameData.getNextPurchaseDueDate()); } tempToken.setAttribute(1, getLayerScreenController().getTimeFactor()); } } } private void updateGraphicElementsArray() { Iterator<DispOperatorWalksTo> tempElements = arrOperatorsWalksTo.iterator(); while (tempElements.hasNext()) { if (tempElements.next().isToBeRemoved()) { tempElements.remove(); } } Iterator<DispOperatorMachineMovingTo> tempElements2 = arrOperatorsMachinesMovingTo.iterator(); while (tempElements2.hasNext()) { if (tempElements2.next().isToBeRemoved()) { tempElements2.remove(); } } //System.out.println("SystemTime:" + currentSystemTime + " - UPDATE GRAPHIC ELEMENT ARRAY"); } @Override public void onAnimCycleDone(AnimControl control, AnimChannel channel, String animName) { // if (channel == shootingChannel) { // channel.setAnim("Walk"); } private void createGrid(int iniX, int iniZ, int sizeW, int sizeL) { Line line; Geometry lineGeo; Material lineMat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); lineMat.setColor("Color", ColorRGBA.Black); int noMatrixWidth = (int) sizeW / Params.standardBucketWidthLength; int noMatrixLength = (int) sizeL / Params.standardBucketWidthLength; for (int i = 0; i <= noMatrixLength; i++) { line = new Line(new Vector3f(iniX, 1f, iniZ + i * Params.standardBucketWidthLength), new Vector3f(iniX + sizeW, 1f, iniZ + i * Params.standardBucketWidthLength)); lineGeo = new Geometry(); lineGeo.setMesh(line); lineGeo.setMaterial(lineMat); rootNode.attachChild(lineGeo); } for (int i = 0; i <= noMatrixWidth; i++) { line = new Line(new Vector3f(iniX + i * Params.standardBucketWidthLength, 1f, iniZ), new Vector3f(iniX + i * Params.standardBucketWidthLength, 1f, iniZ + sizeL)); lineGeo = new Geometry(); lineGeo.setMesh(line); lineGeo.setMaterial(lineMat); rootNode.attachChild(lineGeo); } } private void createPartsInStation(int idStation, int iniX, int iniZ, int sizeW, int sizeL) { int noMatrixWidth = (int) sizeW / Params.standardBucketWidthLength; int noMatrixLength = (int) sizeL / Params.standardBucketWidthLength; Geometry part; for (int i = 0; i < noMatrixWidth; i++) { for (int j = 0; j < noMatrixLength; j++) { partMaterial = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); partMaterial.setColor("Color", ColorRGBA.White); partBox = new Box(Vector3f.ZERO, (float) Params.standardPartWidthLength / 2.0f, 0.0f, (float) Params.standardPartWidthLength / 2.0f); part = new Geometry(TypeElements.STATION.toString() + idStation + "_" + TypeElements.PART.toString() + i + "_" + j, partBox); part.setMaterial(partMaterial); rootNode.attachChild(part); shootables.attachChild(part); part.setLocalTranslation(new Vector3f(iniX + (float) Params.standardBucketWidthLength / 2.0f + Params.standardBucketWidthLength * i, 0.5f, iniZ + (float) Params.standardBucketWidthLength / 2.0f + Params.standardBucketWidthLength * j)); } } } private void createStations(E_Station station) { stationBox = new Box(Vector3f.ZERO, (float) station.getSizeW() / 2, .5f, (float) station.getSizeL() / 2); Geometry stationGeo = new Geometry(TypeElements.STATION + String.valueOf(station.getIdStation()), stationBox); stationMaterial = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); if (station.getStationType().toString().toUpperCase().equals(StationType.StaffZone.toString().toUpperCase())) { stationMaterial.setTexture("ColorMap", assetManager.loadTexture("Models/Stations/staffZone.png")); } else if (station.getStationType().toString().toUpperCase().equals(StationType.MachineZone.toString().toUpperCase())) { stationMaterial.setTexture("ColorMap", assetManager.loadTexture("Models/Stations/machineZone.png")); } else { station.reserveParkingZone(); if (station.getStationType().toString().toUpperCase().equals(StationType.AssembleZone.toString().toUpperCase())) { stationMaterial.setTexture("ColorMap", assetManager.loadTexture(station.getStationDesign())); } else if (station.getStationType().toString().toUpperCase().equals(StationType.PurchaseZone.toString().toUpperCase())) { stationMaterial.setTexture("ColorMap", assetManager.loadTexture("Models/Stations/purchaseZone.png")); } else if (station.getStationType().toString().toUpperCase().equals(StationType.ShippingZone.toString().toUpperCase())) { stationMaterial.setTexture("ColorMap", assetManager.loadTexture("Models/Stations/shippingZone.png")); } else if (station.getStationType().toString().toUpperCase().equals(StationType.StorageIG.toString().toUpperCase())) { stationMaterial.setTexture("ColorMap", assetManager.loadTexture("Models/Stations/storageIGZone.png")); } else if (station.getStationType().toString().toUpperCase().equals(StationType.StorageFG.toString().toUpperCase())) { stationMaterial.setTexture("ColorMap", assetManager.loadTexture("Models/Stations/storageFGZone.png")); } else if (station.getStationType().toString().toUpperCase().equals(StationType.StorageRM.toString().toUpperCase())) { stationMaterial.setTexture("ColorMap", assetManager.loadTexture("Models/Stations/storageRMZone.png")); } if (station.getStationType().toString().toUpperCase().equals(StationType.StorageIG.toString().toUpperCase()) || station.getStationType().toString().toUpperCase().equals(StationType.StorageFG.toString().toUpperCase()) || station.getStationType().toString().toUpperCase().equals(StationType.StorageRM.toString().toUpperCase())) { station.initializeSlots(); } } stationGeo.setMaterial(stationMaterial); rootNode.attachChild(stationGeo); stationGeo.setLocalTranslation(new Vector3f(station.getStationLocationX(), 0.5f, station.getStationLocationY())); stationRigid = new RigidBodyControl(new MeshCollisionShape(stationBox), 0); stationGeo.addControl(stationRigid); bulletAppState.getPhysicsSpace().add(stationRigid); //to be shootable shootables.attachChild(stationGeo); if (station.getStationType().toString().toUpperCase().contains("Storage".toUpperCase())) { //create grid, only in Storages createGrid(station.getStationLocationX() - (int) station.getSizeW() / 2, station.getStationLocationY() - (int) station.getSizeL() / 2, (int) station.getSizeW(), (int) station.getSizeL()); createPartsInStation(station.getIdStation(), station.getStationLocationX() - (int) station.getSizeW() / 2, station.getStationLocationY() - (int) station.getSizeL() / 2, (int) station.getSizeW(), (int) station.getSizeL()); setTerrainMap(station.getStationLocationX() - Params.standardBucketWidthLength / 2, station.getStationLocationY(), (int) station.getSizeW() - Params.standardBucketWidthLength, (int) station.getSizeL(), true); } else { //add buckets!!!! and/or machines station.updateBucketsPosition(); Iterable<E_Bucket> tempBucket = station.getArrBuckets(); for (E_Bucket bucket : tempBucket) { createBuckets(bucket); updatePartsInBucket(bucket); } } } private void createBuckets(E_Bucket bucket) { bucketBox = new Box(Vector3f.ZERO, (float) Params.standardBucketWidthLength / 2.0f, .5f, (float) Params.standardBucketWidthLength / 2.0f); Geometry bucketGeo = new Geometry(TypeElements.STATION + String.valueOf(bucket.getIdStation()) + "_" + TypeElements.BUCKET + String.valueOf(bucket.getIdBucket()), bucketBox); bucketMaterial = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); bucketMaterial.setColor("Color", ColorRGBA.Yellow); bucketGeo.setMaterial(bucketMaterial); rootNode.attachChild(bucketGeo); bucketGeo.setLocalTranslation(new Vector3f((float) bucket.getCurrentLocationX(), 1.0f, (float) bucket.getCurrentLocationZ())); bucketRigid = new RigidBodyControl(new MeshCollisionShape(bucketBox), 0); bucketGeo.addControl(bucketRigid); bulletAppState.getPhysicsSpace().add(bucketRigid); setTerrainMap(bucket.getCurrentLocationX(), bucket.getCurrentLocationZ(), Params.standardBucketWidthLength + 3, Params.standardBucketWidthLength + 3, true); shootables.attachChild(bucketGeo); } public void updatePartsInBucket(E_Bucket bucket) { Geometry part; part = (Geometry) rootNode.getChild(TypeElements.STATION + String.valueOf(bucket.getIdStation()) + "_" + TypeElements.BUCKET + String.valueOf(bucket.getIdBucket() + "_" + TypeElements.PART + String.valueOf(bucket.getIdPart()))); partBox = new Box(Vector3f.ZERO, (float) Params.standardPartWidthLength / 2.0f, (float) bucket.getSize() / 2.0f, (float) Params.standardPartWidthLength / 2.0f); if (part == null) { part = new Geometry(TypeElements.STATION + String.valueOf(bucket.getIdStation()) + "_" + TypeElements.BUCKET + String.valueOf(bucket.getIdBucket()) + "_" + TypeElements.PART + String.valueOf(bucket.getIdPart()), partBox); partMaterial = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); partMaterial.setColor("Color", Colors.getColorRGBA(gameData.getMapUserPart().get(bucket.getIdPart()).getPartDesignColor())); part.setMaterial(partMaterial); rootNode.attachChild(part); shootables.attachChild(part); } else { part.setMesh(partBox); } part.setLocalTranslation(new Vector3f((float) bucket.getCurrentLocationX(), 1.5f + (float) bucket.getSize() / 2.0f, (float) bucket.getCurrentLocationZ())); //System.out.println("Part loc:" + part.getLocalTranslation() + " - station:" + bucket.getIdStation() + " " + bucket.getCurrentLocationX() + "," + bucket.getCurrentLocationZ()); } public void operatorWalksTo(E_Operator operator, int posX, int posZ) { arrOperatorsWalksTo.add(new DispOperatorWalksTo(this, operator, posX, posZ, getLayerScreenController().getTimeFactorForSpeed())); } public void operatorWalksToStaffZone(E_Operator operator, int posX, int posZ) { arrOperatorsWalksTo.add(new DispOperatorWalksTo(this, operator, posX, posZ, getLayerScreenController().getTimeFactorForSpeed(), true)); } public void operatorWalksToSpecificMachine(E_Operator operator, E_Machine machine, int posX, int posZ) { arrOperatorsWalksTo.add(new DispOperatorWalksTo(this, operator, machine, posX, posZ, getLayerScreenController().getTimeFactorForSpeed())); } public void operatorAndMachineMovingTo(E_Operator operator, E_Machine machine, int posX, int posZ) { arrOperatorsMachinesMovingTo.add(new DispOperatorMachineMovingTo(this, rootNode, operator, machine, posX, posZ, getLayerScreenController().getTimeFactorForSpeed())); } public void operatorAndMachineMovingToMachineZone(E_Operator operator, E_Machine machine, int posX, int posZ) { arrOperatorsMachinesMovingTo.add(new DispOperatorMachineMovingTo(this, rootNode, operator, machine, posX, posZ, getLayerScreenController().getTimeFactorForSpeed(), true)); } private void createMachines(E_Machine machine, GameType gameType) { Pair<Pair<Pair<Integer, Integer>, Pair<Integer, Integer>>, Pair<Integer, Integer>> machineLocation = null; if (gameType.equals(GameType.New)) { E_Station station = gameData.getUserStation_MachineZone(); machineLocation = station.getLocationInMatrix(machine.getSizeW(), machine.getSizeL()); if (machineLocation != null) { machine.setVirtualMatrixIniI(machineLocation.getFirst().getFirst().getFirst()); machine.setVirtualMatrixIniJ(machineLocation.getFirst().getFirst().getSecond()); machine.setVirtualMatrixEndI(machineLocation.getFirst().getSecond().getFirst()); machine.setVirtualMatrixEndJ(machineLocation.getFirst().getSecond().getSecond()); machine.setCurrentLocationX(machineLocation.getSecond().getFirst()); machine.setCurrentLocationZ(machineLocation.getSecond().getSecond()); machine.setVirtualIdLocation_MachineZone(TypeElements.STATION + String.valueOf(station.getIdStation())); machine.setVirtualIdLocation(TypeElements.STATION + String.valueOf(station.getIdStation())); } } model = (Node) assetManager.loadModel(machine.getMachineDesign()); if (!machine.getMachineMaterial().equals("")) { model.setMaterial(assetManager.loadMaterial(machine.getMachineMaterial())); } //model.setMaterial(assetManager.loadMaterial("Models/Machine/machine1.material")); model.setLocalScale(0.2f); model.setName(TypeElements.MACHINE + String.valueOf(machine.getIdMachine())); model.setLocalTranslation(new Vector3f(machine.getCurrentLocationX(), 0.5f, machine.getCurrentLocationZ())); rootNode.attachChild(model); // I cannot add an animation because my MACHINES do not support animation!!! machine.setModelCharacter(model); machine.setAssetManager(assetManager); machine.setRootNode(rootNode); machine.setBulletAppState(bulletAppState); shootables.attachChild(model); } private void createOperators(E_Operator operator, GameType gameType) { Pair<Pair<Pair<Integer, Integer>, Pair<Integer, Integer>>, Pair<Integer, Integer>> operatorLocation = null; if (gameType.equals(GameType.New)) { E_Station station = gameData.getUserStation_StaffZone(); operatorLocation = station.getLocationInMatrix(Params.standardOperatorWidthLength, Params.standardOperatorWidthLength); if (operatorLocation != null) { operator.setVirtualMatrixI(operatorLocation.getFirst().getFirst().getFirst()); operator.setVirtualMatrixJ(operatorLocation.getFirst().getFirst().getSecond()); operator.setCurrentLocationX(operatorLocation.getSecond().getFirst()); operator.setCurrentLocationZ(operatorLocation.getSecond().getSecond()); operator.setVirtualIdLocation_StaffZone(TypeElements.STATION + String.valueOf(station.getIdStation())); operator.setVirtualIdLocation(TypeElements.STATION + String.valueOf(station.getIdStation())); } } //FIX ME: it consider 'operator' has always a location in the matrix, it means a location X/Z CapsuleCollisionShape capsule = new CapsuleCollisionShape(1.5f, 6f, 1); character_Disp = new CharacterControl(capsule, 0.05f); model = (Node) assetManager.loadModel("Models/Operator/Oto.mesh.j3o"); model.setMaterial(assetManager.loadMaterial("Models/Operator/operatorNone.j3m")); model.addControl(character_Disp); model.setName(TypeElements.OPERATOR + String.valueOf(operator.getIdOperator())); Geometry base = new Geometry(TypeElements.CUBE.toString(), new Grid(8, 8, 1f)); base.setName(TypeElements.OPERATOR + String.valueOf(operator.getIdOperator())); base.setMaterial(matCharacter); base.setLocalTranslation(model.getLocalTranslation().getX() - 4, model.getLocalTranslation().getY() - 4.9f, model.getLocalTranslation().getZ() - 4); character_Disp.setPhysicsLocation(new Vector3f(operator.getCurrentLocationX(), Params.standardLocationY, operator.getCurrentLocationZ())); rootNode.attachChild(model); bulletAppState.getPhysicsSpace().add(character_Disp); model.getControl(AnimControl.class).addListener(this); operator.setCharacter(character_Disp); operator.setAnimationChannel(model.getControl(AnimControl.class).createChannel()); operator.setModelCharacter(model); operator.setAssetManager(assetManager); operator.setRootNode(rootNode); operator.setBaseCharacter(base); operator.updateOperatorCategory(); shootables.attachChild(model); } public void setTerrainMap(int locX, int locZ, int width, int length, boolean blocked) { int realLocX = locX + Params.terrainWidthLoc - width / 2; int realLocZ = locZ + Params.terrainHeightLoc - length / 2; int valuePixel = (blocked == true ? 1 : 0); for (int i = 0; i < width; i++) { for (int j = 0; j < length; j++) { terrainMap.setUnit(i + realLocX, j + realLocZ, valuePixel); } } } public void setTerrainMap(Path path, int locX, int locZ, boolean blocked) { int valuePixel = (blocked == true ? 1 : 0); if (path != null) { for (Step s : path.getSteps()) { terrainMap.setUnit(s.getX(), s.getY(), valuePixel); } } else { terrainMap.setUnit(locX, locZ, valuePixel); } } public void changeScreenSize() { AppSettings settings = ScreenSettings.generate(); if (jmonkeyApp.getContext().getSettings().isFullscreen()) { settings.setFullscreen(false); settings.setResolution(1280, 720); Params.screenHeight = 720; } else { Params.screenHeight = settings.getHeight(); } updateInterfacePosition(); jmonkeyApp.setSettings(settings); jmonkeyApp.restart(); } private void updateInterfacePosition() { int yPos = Params.screenHeight - (720 - 700); niftyGUI.getScreen("layerScreen").findElementByName("OrderLabel").setConstraintY(new SizeValue(yPos + "px")); niftyGUI.getScreen("layerScreen").findElementByName("OverallLabel").setConstraintY(new SizeValue(yPos + "px")); niftyGUI.getScreen("layerScreen").findElementByName("LogLabel").setConstraintY(new SizeValue(yPos + "px")); yPos = Params.screenHeight - (720 - 488); niftyGUI.getScreen("layerScreen").findElementByName("winOrderControl").setConstraintY(new SizeValue(yPos + "px")); niftyGUI.getScreen("layerScreen").findElementByName("winGameLogControl").setConstraintY(new SizeValue(yPos + "px")); niftyGUI.getScreen("layerScreen").findElementByName("winOvC_Element").getControl(OverallScreenController.class).refresh(isLevelStarted); } private void toggleTopView() { if (Params.topViewAvailable && viewNumber != 5) { topViewEnabled = true; switch(viewNumber) { case 0: Params.camAxesLeft = cam.getLeft(); Params.camAxesUp = cam.getUp(); Params.camAxesDir = cam.getDirection(); Params.flyCamRotationSpeed = flyCam.getRotationSpeed(); cam.setLocation(new Vector3f(210.75597f, 191.22467f, -111.45984f)); cam.setAxes(new Vector3f(0.006238699f, 0.0011283755f, 0.9999799f), new Vector3f(-0.7573153f, 0.6530373f, 0.0039878786f), new Vector3f(-0.6530197f, -0.75732493f, 0.004928589f)); break; case 1: Params.camMaxY = Params.securityCamsMaxY; Params.camMinY = Params.securityCamsMinY; Params.camMaxX = Params.cam1MaxX; Params.camMinX = Params.cam1MinX; // Params.camMaxZ = Params.cam1MaxX; // Params.camMinZ = Params.cam1MinX; cam.setLocation(new Vector3f(138.94714f, 74.204185f, -118.346085f)); cam.setAxes(new Vector3f(-0.004745364f, 0.0011234581f, 0.99998814f), new Vector3f(-0.69315696f, 0.720775f, -0.0040991306f), new Vector3f(-0.720771f, -0.69316816f, -0.0026416779f)); break; case 2: Params.camMaxX = Params.playerMaxX; Params.camMinX = Params.playerMinX; Params.camMaxZ = 0; Params.camMinZ = -100; cam.setLocation(new Vector3f(50.173473f, 78.43454f, 112.47995f)); cam.setAxes(new Vector3f(-0.9999976f, 0.0011224343f, 0.0018219932f), new Vector3f(0f, 0.8618528f, -0.5071584f), new Vector3f(-0.002139542f, -0.5071572f, -0.86185086f)); break; case 3: Params.camMaxX = 100f; Params.camMinX = 0f; Params.camMaxZ = Params.playerMaxZ; Params.camMinZ = Params.playerMinZ; cam.setLocation(new Vector3f(-37.94872f, 71.8763f, -118.55907f)); cam.setAxes(new Vector3f(-0.0045000315f, 0.0011213869f, -0.9999892f), new Vector3f(0.4902432f, 0.8715848f, -0.0012287796f), new Vector3f(0.871574f, -0.49024346f, -0.004471898f)); break; case 4: Params.camMaxX = Params.playerMaxX; Params.camMinX = Params.playerMinX; Params.camMaxZ = 100f; Params.camMinZ = 0f; cam.setLocation(new Vector3f(54.01033f, 79.31754f, -347.24677f)); cam.setAxes(new Vector3f(0.99922884f, 0.0011243783f, 0.039248988f), new Vector3f(-0.019561216f, 0.8809709f, 0.47276595f), new Vector3f(-0.034045644f, -0.47316912f, 0.8803135f)); break; } viewNumber = (viewNumber + 1)%6; flyCam.setMoveSpeed(0); // flyCam.setRotationSpeed(0); world.getChild("Beams-Metal").setCullHint(Spatial.CullHint.Always); } else if (Params.topViewAvailable && topViewEnabled) { topViewEnabled = false; cam.setAxes(Params.camAxesLeft, Params.camAxesUp, Params.camAxesDir); flyCam.setMoveSpeed(100); flyCam.setRotationSpeed(Params.flyCamRotationSpeed); world.getChild("Beams-Metal").setCullHint(Spatial.CullHint.Never); viewNumber = (viewNumber + 1)%6; Params.camMaxX = Params.playerMaxX; Params.camMinX = Params.playerMinX; Params.camMaxY = Params.playerMaxY; Params.camMinY = Params.playerMinY; Params.camMaxZ = Params.playerMaxZ; Params.camMinZ = Params.playerMinZ; } } private void handlePickedObject(String pickingType) { CollisionResults results = new CollisionResults(); Ray ray; if (pickingType.equals("Picking")) { //Picking with the SHIFT Button ray = new Ray(cam.getLocation(), cam.getDirection()); getLayerScreenController().hideCurrentControlsWindow(); } else { //Picking with mouse Vector3f origin = cam.getWorldCoordinates(inputManager.getCursorPosition(), 0.0f); Vector3f direction = cam.getWorldCoordinates(inputManager.getCursorPosition(), 0.3f); direction.subtractLocal(origin).normalizeLocal(); ray = new Ray(origin, direction); } shootables.collideWith(ray, results); if (results.size() > 0) { CollisionResult closest = results.getClosestCollision(); if (Params.DEBUG_ON) { System.out.println(closest.getDistance()); } if (closest.getDistance() > 60f && !topViewEnabled) { return; } String shootableObject; if (closest.getGeometry().getParent().getName().equals("Shootables")) { shootableObject = closest.getGeometry().getName(); } else { Node tempGeometry = closest.getGeometry().getParent(); while (!tempGeometry.getParent().getName().equals("Shootables")) { tempGeometry = tempGeometry.getParent(); } shootableObject = tempGeometry.getName(); } loadWindowControl(shootableObject); System.out.println(" } } private void loadWindowControl(String winControl) { Pair<Integer, Integer> positionWC = new Pair((int) inputManager.getCursorPosition().getX(), guiViewPort.getCamera().getHeight() - (int) inputManager.getCursorPosition().getY()); getLayerScreenController().hideCurrentControlsWindow(); getLayerScreenController().showHideDynamicButtons(0); getLayerScreenController().showHideDynamicSubLevelButtons(0); if (winControl.contains(TypeElements.OPERATOR.toString())) { niftyGUI.getScreen("layerScreen").findElementByName("winOC_Element").getControl(OperatorScreenController.class).loadWindowControl(this, Integer.valueOf(winControl.replace(TypeElements.OPERATOR.toString(), "")), positionWC); getLayerScreenController().setCurrentOptionselected("windowOperator"); } else if (winControl.contains(TypeElements.PART.toString())) { niftyGUI.getScreen("layerScreen").findElementByName("winPC_Element").getControl(PartScreenController.class).loadWindowControl(this, Integer.valueOf(winControl.split("_")[winControl.split("_").length - 1].replace(TypeElements.PART.toString(), "")), positionWC); getLayerScreenController().setCurrentOptionselected("windowPart"); } else if (winControl.contains(TypeElements.STATION.toString()) && !winControl.contains(TypeElements.BUCKET.toString())) { E_Station tempStation = getGameData().getMapUserStation().get(Integer.valueOf(winControl.replace(TypeElements.STATION.toString(), ""))); if (!tempStation.getStationType().equals(StationType.MachineZone) && !tempStation.getStationType().equals(StationType.StaffZone)) { niftyGUI.getScreen("layerScreen").findElementByName("winSSC_Element").getControl(StorageStationScreenController.class).loadWindowControl(this, Integer.valueOf(winControl.replace(TypeElements.STATION.toString(), "")), positionWC); getLayerScreenController().setCurrentOptionselected("windowStorageStation"); } } else if (winControl.contains(TypeElements.MACHINE.toString())) { niftyGUI.getScreen("layerScreen").findElementByName("winMC_Element").getControl(MachineScreenController.class).loadWindowControl(this, Integer.valueOf(winControl.replace(TypeElements.MACHINE.toString(), "")), positionWC); getLayerScreenController().setCurrentOptionselected("windowMachine"); } } @Override public void onAnimChange(AnimControl control, AnimChannel channel, String animName) { //throw new UnsupportedOperationException("Not supported yet."); } public void updateAnimations() { if (arrStationAnimations.size() > 0) { for (StationAnimation tempStationAnim : arrStationAnimations) { StationAnimation stationAnimation = new StationAnimation(); stationAnimation = new StationAnimation(); stationAnimation.setGameEngine(this); stationAnimation.setPartBox(tempStationAnim.getPartBox()); stationAnimation.setTimeToFinish(tempStationAnim.getTimeToFinish()); stationAnimation.setAddItems(tempStationAnim.isAddItems()); stationAnimation.setIsZeroItems(tempStationAnim.isIsZeroItems()); stationAnimation.setQuantity(tempStationAnim.getQuantity()); stationAnimation.setIdStrategy(tempStationAnim.getIdStrategy()); // if (tempStationAnim.getIdStrategy() != -1) // ((TransportStrategy)getManageEvents().getEvent(tempStationAnim.getIdStrategy())).getArrStationAnimation().add(stationAnimation); stationAnimation.start(); } } arrStationAnimations.clear(); } private void createShowSpotObject() { //showSpotObject Sphere sphere = new Sphere(20, 20, (float) Params.standardPartWidthLength / 2); showSpotObject = new Geometry("SPOT_OBJECT", sphere); Material materialForSpotObject = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); materialForSpotObject.setColor("Color", ColorRGBA.Blue); showSpotObject.setMaterial(materialForSpotObject); rootNode.attachChild(showSpotObject); showSpotObject.setLocalTranslation(new Vector3f(0, -(float) Params.standardPartWidthLength * 4, 0)); } public Geometry getShowSpotObject() { return showSpotObject; } public void setShowSpotObject(Geometry showSpotObject) { this.showSpotObject = showSpotObject; } public void updateGameSounds(boolean isPlaying) { if (isPlaying) { for (Pair<GameSounds, Sounds> gs : arrGameSounds) gs.getFirst().playSound(gs.getSecond()); } else { for (Pair<GameSounds, Sounds> gs : arrGameSounds) gs.getFirst().pauseSound(gs.getSecond()); } } public ArrayList<Pair<GameSounds, Sounds>> getArrGameSounds() { return arrGameSounds; } public void setArrGameSounds(ArrayList<Pair<GameSounds, Sounds>> arrGameSounds) { this.arrGameSounds = arrGameSounds; } public Node getShootables() { return shootables; } public boolean isExecuteGame() { return isLevelStarted; } public void setExecuteGame(boolean isLevelStarted) { this.isLevelStarted = isLevelStarted; } public ManageEvents getManageEvents() { return manageEvents; } public void setManageEvents(ManageEvents manageEvents) { this.manageEvents = manageEvents; } public GameData getGameData() { return gameData; } public void setGameData(GameData gameData) { this.gameData = gameData; } public LayerScreenController getLayerScreenController() { return layerScreenC; } public TerrainMap getTerrainMap() { return terrainMap; } public Status getCurrentSystemStatus() { return currentSystemStatus; } public void setCurrentSystemStatus(Status currentSystemStatus) { this.currentSystemStatus = currentSystemStatus; } public long getCurrentTempSystemTime() { return currentTempSystemTime; } public void setCurrentTempSystemTime(long currentTempSystemTime) { this.currentTempSystemTime = currentTempSystemTime; } public double getCurrentSystemTime() { return currentSystemTime; } public void setCurrentSystemTime(double currentSystemTime) { this.currentSystemTime = currentSystemTime; } public ArrayList<StationAnimation> getArrStationAnimations() { return arrStationAnimations; } public void setArrStationAnimations(ArrayList<StationAnimation> arrStationAnimations) { this.arrStationAnimations = arrStationAnimations; } public Nifty getNifty() { return niftyGUI; } public void setNifty(Nifty nifty) { this.niftyGUI = nifty; } public int getInitialGameId() { return initialGameId; } public void setInitialGameId(int initialGameId) { this.initialGameId = initialGameId; } }
package com.intellij.openapi.editor.impl; import com.intellij.ide.DataManager; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ActionButtonLook; import com.intellij.openapi.actionSystem.ex.ActionManagerEx; import com.intellij.openapi.actionSystem.impl.ActionButton; import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl; import com.intellij.openapi.editor.event.EditorMouseAdapter; import com.intellij.openapi.editor.event.EditorMouseEvent; import com.intellij.openapi.editor.event.EditorMouseMotionAdapter; import com.intellij.openapi.keymap.ex.KeymapManagerEx; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; /** * @author spleaner */ public class ContextMenuImpl extends JPanel implements Disposable { @NonNls public static final String ACTION_GROUP = "EditorContextBarMenu"; private ActionGroup myActionGroup; private JComponent myComponent; private boolean myShowing = false; private int myCurrentOpacity; private Timer myShowTimer; private Timer myHideTimer; private EditorImpl myEditor; private ContextMenuPanel myContextMenuPanel; public ContextMenuImpl(@NotNull final JScrollPane container, @NotNull final EditorImpl editor) { setLayout(new BorderLayout(0, 0)); final ActionManager actionManager = ActionManager.getInstance(); editor.addEditorMouseListener(new EditorMouseAdapter() { @Override public void mouseExited(final EditorMouseEvent e) { if (!isInsideActivationArea(container, e)) { toggleContextToolbar(false); } } }); editor.addEditorMouseMotionListener(new EditorMouseMotionAdapter() { @Override public void mouseMoved(final EditorMouseEvent e) { toggleContextToolbar(isInsideActivationArea(container, e)); } }); AnAction action = actionManager.getAction("EditorContextBarMenu"); if (action == null) { action = new DefaultActionGroup(); actionManager.registerAction(ACTION_GROUP, action); } if (action instanceof ActionGroup) { myActionGroup = (ActionGroup)action; } myEditor = editor; myComponent = createComponent(); add(myComponent); setVisible(false); setOpaque(false); } private static boolean isInsideActivationArea(JScrollPane container, EditorMouseEvent e) { final JViewport viewport = container.getViewport(); final Rectangle r = viewport.getBounds(); final Point viewPosition = viewport.getViewPosition(); final Rectangle activationArea = new Rectangle(0, 0, r.width, 150); final MouseEvent event = e.getMouseEvent(); final Point p = event.getPoint(); return activationArea.contains(p.x, p.y - viewPosition.y); } private void toggleContextToolbar(final boolean show) { if (show) { show(); } else { hide(); } } public void dispose() { myEditor = null; } @SuppressWarnings({"deprecation"}) @Override public void show() { final Component toolbar = myComponent.getComponent(0); final int count = ((Container)toolbar).getComponentCount(); if (count == 0) { return; } if (!myShowing) { myCurrentOpacity = 0; if (myHideTimer != null && myHideTimer.isRunning()) myHideTimer.stop(); super.show(); setOpaque(false); if (myShowTimer == null || !myShowTimer.isRunning()) { myShowing = true; myShowTimer = new Timer(1500, new ActionListener() { public void actionPerformed(final ActionEvent e) { myShowTimer.stop(); myShowTimer = new Timer(50, new ActionListener() { public void actionPerformed(final ActionEvent e) { myCurrentOpacity += 20; if (myCurrentOpacity > 100) { myCurrentOpacity = 100; myShowTimer.stop(); } repaint(); } }); myShowTimer.setRepeats(true); myShowTimer.start(); } }); myShowTimer.setRepeats(false); myShowTimer.start(); } } else { super.show(); } } @SuppressWarnings({"deprecation"}) @Override public void hide() { if (myShowing) { if (myShowTimer != null && myShowTimer.isRunning()) myShowTimer.stop(); if (myHideTimer == null || !myHideTimer.isRunning()) { myShowing = false; myHideTimer = new Timer(700, new ActionListener() { public void actionPerformed(final ActionEvent e) { myHideTimer.stop(); myHideTimer = new Timer(50, new ActionListener() { public void actionPerformed(final ActionEvent e) { myCurrentOpacity -= 20; if (myCurrentOpacity < 0) { myCurrentOpacity = 0; myHideTimer.stop(); //ContextMenuImpl.super.hide(); } repaint(); } }); myHideTimer.setRepeats(true); myHideTimer.start(); } }); myHideTimer.setRepeats(false); myHideTimer.start(); } } else { //super.hide(); } } private ActionToolbar createToolbar(final ActionGroup group) { final ActionToolbarImpl actionToolbar = new ActionToolbarImpl(ActionPlaces.CONTEXT_TOOLBAR, group, true, DataManager.getInstance(), ActionManagerEx.getInstanceEx(), KeymapManagerEx.getInstanceEx()) { @Override public void paint(final Graphics g) { if (myContextMenuPanel.isPaintChildren()) { paintChildren(g); } } @Override protected void paintChildren(final Graphics g) { if (myContextMenuPanel.isPaintChildren()) { super.paintChildren(g); } } @Override public boolean isOpaque() { return myContextMenuPanel.isPaintChildren(); } @Override public ActionButton createToolbarButton(final AnAction action, final ActionButtonLook look, final String place, final Presentation presentation, final Dimension minimumSize) { final ActionButton result = new ActionButton(action, presentation, place, minimumSize) { @Override public void paintComponent(final Graphics g) { if (myContextMenuPanel.isPaintChildren()) { final ActionButtonLook look = getButtonLook(); look.paintIcon(g, this, getIcon()); } if (getPopState() == ActionButton.POPPED) { final ActionButtonLook look = getButtonLook(); look.paintBackground(g, this); look.paintIcon(g, this, getIcon()); } } @Override public boolean isOpaque() { return myContextMenuPanel.isPaintChildren() || getPopState() == ActionButton.POPPED; } @Override public void paint(final Graphics g) { final Graphics2D g2 = (Graphics2D)g; paintComponent(g2); } }; result.setLook(look); return result; } }; actionToolbar.setTargetComponent(myEditor.getContentComponent()); return actionToolbar; } private JComponent createComponent() { final ActionToolbar toolbar = createToolbar(myActionGroup); toolbar.setMinimumButtonSize(new Dimension(20, 20)); toolbar.setReservePlaceAutoPopupIcon(false); myContextMenuPanel = new ContextMenuPanel(this); myContextMenuPanel.setLayout(new BorderLayout(0, 0)); myContextMenuPanel.add(toolbar.getComponent()); return myContextMenuPanel; } private static class ContextMenuPanel extends JPanel { private ContextMenuImpl myContextMenu; private BufferedImage myBufferedImage; private boolean myPaintChildren = false; private ContextMenuPanel(final ContextMenuImpl contextMenu) { myContextMenu = contextMenu; setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); setOpaque(false); } @Override public void invalidate() { super.invalidate(); myBufferedImage = null; } @Override public void revalidate() { super.revalidate(); myBufferedImage = null; } @Override protected void paintChildren(final Graphics g) { if (myPaintChildren) { super.paintChildren(g); } } public boolean isPaintChildren() { return myPaintChildren; } @Override public void paint(final Graphics g) { final Rectangle r = getBounds(); if (myBufferedImage == null) { myBufferedImage = new BufferedImage(r.width, r.height, BufferedImage.TYPE_INT_ARGB); final Graphics graphics = myBufferedImage.getGraphics(); final Graphics2D g2d2 = (Graphics2D)graphics; final Composite old = g2d2.getComposite(); g2d2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.2f)); g2d2.setColor(Color.GRAY); g2d2.fillRoundRect(0, 0, r.width - 1, r.height - 1, 6, 6); g2d2.setComposite(old); myPaintChildren = true; paintChildren(g2d2); myPaintChildren = false; } final Graphics2D g2 = (Graphics2D)g; final Composite old = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, myContextMenu.myCurrentOpacity / 100.0f)); g2.drawImage(myBufferedImage, 0, 0, myBufferedImage.getWidth(null), myBufferedImage.getHeight(null), null); g2.setComposite(old); } } }
package org.opencms.ui.apps.lists; import org.opencms.acacia.shared.I_CmsSerialDateValue; import org.opencms.ade.containerpage.shared.CmsDialogOptions; import org.opencms.file.CmsFile; import org.opencms.file.CmsObject; import org.opencms.file.CmsPropertyDefinition; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.file.types.CmsResourceTypeXmlContent; import org.opencms.file.types.I_CmsResourceType; import org.opencms.gwt.shared.CmsResourceStatusTabId; import org.opencms.i18n.CmsLocaleManager; import org.opencms.jsp.search.config.CmsSearchConfiguration; import org.opencms.jsp.search.config.CmsSearchConfigurationPagination; import org.opencms.jsp.search.config.I_CmsSearchConfigurationPagination; import org.opencms.jsp.search.config.parser.CmsSimpleSearchConfigurationParser; import org.opencms.jsp.search.config.parser.CmsSimpleSearchConfigurationParser.SortOption; import org.opencms.jsp.search.controller.CmsSearchController; import org.opencms.jsp.search.controller.I_CmsSearchControllerFacetField; import org.opencms.jsp.search.controller.I_CmsSearchControllerFacetRange; import org.opencms.jsp.search.result.CmsSearchResultWrapper; import org.opencms.jsp.search.state.I_CmsSearchStateFacet; import org.opencms.loader.CmsLoaderException; import org.opencms.lock.CmsLockActionRecord; import org.opencms.lock.CmsLockActionRecord.LockChange; import org.opencms.lock.CmsLockUtil; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.main.OpenCms; import org.opencms.relations.CmsLink; import org.opencms.search.CmsSearchException; import org.opencms.search.CmsSearchResource; import org.opencms.search.fields.CmsSearchField; import org.opencms.search.solr.CmsSolrIndex; import org.opencms.search.solr.CmsSolrQuery; import org.opencms.search.solr.CmsSolrResultList; import org.opencms.ui.A_CmsUI; import org.opencms.ui.CmsVaadinUtils; import org.opencms.ui.FontOpenCms; import org.opencms.ui.I_CmsDialogContext; import org.opencms.ui.I_CmsDialogContext.ContextType; import org.opencms.ui.I_CmsUpdateListener; import org.opencms.ui.actions.A_CmsWorkplaceAction; import org.opencms.ui.actions.CmsContextMenuActionItem; import org.opencms.ui.actions.CmsDeleteDialogAction; import org.opencms.ui.actions.CmsEditDialogAction; import org.opencms.ui.actions.CmsResourceInfoAction; import org.opencms.ui.apps.A_CmsWorkplaceApp; import org.opencms.ui.apps.CmsAppWorkplaceUi; import org.opencms.ui.apps.CmsEditor; import org.opencms.ui.apps.CmsFileExplorer; import org.opencms.ui.apps.I_CmsAppUIContext; import org.opencms.ui.apps.I_CmsContextProvider; import org.opencms.ui.apps.Messages; import org.opencms.ui.apps.lists.CmsOptionDialog.I_OptionHandler; import org.opencms.ui.apps.lists.daterestrictions.CmsDateRestrictionParser; import org.opencms.ui.apps.lists.daterestrictions.I_CmsListDateRestriction; import org.opencms.ui.apps.projects.CmsProjectManagerConfiguration; import org.opencms.ui.components.CmsBasicDialog; import org.opencms.ui.components.CmsErrorDialog; import org.opencms.ui.components.CmsFileTable; import org.opencms.ui.components.CmsFileTableDialogContext; import org.opencms.ui.components.CmsResourceTable; import org.opencms.ui.components.CmsResourceTable.I_ResourcePropertyProvider; import org.opencms.ui.components.CmsResourceTableProperty; import org.opencms.ui.components.CmsToolBar; import org.opencms.ui.components.I_CmsWindowCloseListener; import org.opencms.ui.components.OpenCmsTheme; import org.opencms.ui.components.extensions.CmsGwtDialogExtension; import org.opencms.ui.contextmenu.CmsResourceContextMenuBuilder; import org.opencms.ui.contextmenu.I_CmsContextMenuItem; import org.opencms.ui.contextmenu.I_CmsContextMenuItemProvider; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import org.opencms.workplace.editors.directedit.CmsDateSeriesEditHandler; import org.opencms.workplace.editors.directedit.I_CmsEditHandler; import org.opencms.workplace.explorer.CmsResourceUtil; import org.opencms.workplace.explorer.menu.CmsMenuItemVisibilityMode; import org.opencms.xml.containerpage.CmsContainerElementBean; import org.opencms.xml.content.CmsXmlContent; import org.opencms.xml.content.CmsXmlContentFactory; import org.opencms.xml.content.CmsXmlContentValueLocation; import org.opencms.xml.types.CmsXmlDisplayFormatterValue; import org.opencms.xml.types.CmsXmlVfsFileValue; import org.opencms.xml.types.I_CmsXmlContentValue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import com.vaadin.data.Item; import com.vaadin.data.Property.ValueChangeEvent; import com.vaadin.data.Property.ValueChangeListener; import com.vaadin.event.FieldEvents.TextChangeEvent; import com.vaadin.event.FieldEvents.TextChangeListener; import com.vaadin.navigator.ViewChangeListener; import com.vaadin.server.Sizeable.Unit; import com.vaadin.ui.AbstractSelect.ItemDescriptionGenerator; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.ComboBox; import com.vaadin.ui.Component; import com.vaadin.ui.HorizontalSplitPanel; import com.vaadin.ui.Table; import com.vaadin.ui.Table.CellStyleGenerator; import com.vaadin.ui.TextField; import com.vaadin.ui.UI; import com.vaadin.ui.Window; import com.vaadin.ui.themes.ValoTheme; /** * Manager for list configuration files.<p> */ public class CmsListManager extends A_CmsWorkplaceApp implements I_ResourcePropertyProvider, I_CmsContextProvider, ViewChangeListener, I_CmsWindowCloseListener { /** * Enum representing how selected categories should be combined in a search.<p> */ public static enum CategoryMode { /** Combine categories with AND. */ AND, /** Combine categories with OR. */ OR; } /** * The list configuration data.<p> */ public static class ListConfigurationBean { /** The additional content parameters. */ private Map<String, String> m_additionalParameters; /** The resource blacklist. */ private List<CmsUUID> m_blacklist; /** The categories. */ private List<String> m_categories; /** The display types. */ private List<String> m_dislayTypes; /** The folders. */ private List<String> m_folders; /** Search parameters by configuration node name. */ private Map<String, String> m_parameterFields; /** The category mode. */ private CategoryMode m_categoryMode; /** The date restriction. */ private I_CmsListDateRestriction m_dateRestriction; /** * Constructor.<p> */ public ListConfigurationBean() { m_parameterFields = new HashMap<String, String>(); } /** * Returns the additional content parameters.<p> * * @return the additional content parameters */ public Map<String, String> getAdditionalParameters() { return m_additionalParameters; } /** * Returns the black list.<p> * * @return the black list */ public List<CmsUUID> getBlacklist() { return m_blacklist; } /** * Returns the categories.<p> * * @return the categories */ public List<String> getCategories() { return m_categories; } /** * Gets the category conjunction setting.<p> * * @return the category conjunction setting */ public boolean getCategoryConjunction() { return Boolean.parseBoolean(getParameterValue(N_CATEGORY_CONJUNCTION)); } /** * Gets the category mode.<p> * * @return the category mode */ public CategoryMode getCategoryMode() { return m_categoryMode; } /** * Gets the date restriction.<p> * * @return the date restriction */ public I_CmsListDateRestriction getDateRestriction() { return m_dateRestriction; } /** * Returns the display types.<p> * * @return the display types */ public List<String> getDisplayTypes() { return m_dislayTypes; } /** * Gets the filter query.<p> * * @return the filter query */ public String getFilterQuery() { return m_parameterFields.get(N_FILTER_QUERY); } /** * Returns the folders.<p> * * @return the folders */ public List<String> getFolders() { return m_folders; } /** * Returns the parameter map.<p> * * @return the parameters */ public Map<String, String> getParameters() { return m_parameterFields; } /** * Returns the parameter by name.<p> * * @param key the parameter name * * @return the parameter value */ public String getParameterValue(String key) { return m_parameterFields.get(key); } /** * Gets the sort order.<p> * * @return the sort order */ public String getSortOrder() { return getParameterValue(N_SORT_ORDER); } /** * Returns the search types.<p> * * @return the search types */ public List<String> getTypes() { List<String> result = new ArrayList<String>(); if (m_dislayTypes != null) { for (String displayType : m_dislayTypes) { String type = displayType; if (type.contains(CmsXmlDisplayFormatterValue.SEPARATOR)) { type = type.substring(0, type.indexOf(CmsXmlDisplayFormatterValue.SEPARATOR)); } if (!result.contains(type)) { result.add(type); } } } return result; } /** * Returns the 'show expired' setting.<p> * * @return the 'show expired' setting */ public boolean isShowExpired() { return Boolean.parseBoolean(m_parameterFields.get(N_SHOW_EXPIRED)); } /** * Sets the additional content parameters.<p> * * @param additionalParameters the additional content parameters to set */ public void setAdditionalParameters(Map<String, String> additionalParameters) { m_additionalParameters = additionalParameters; } /** * Sets the blacklist.<p> * * @param blacklist the blacklist */ public void setBlacklist(List<CmsUUID> blacklist) { m_blacklist = blacklist; } /** * Sets the categories.<p> * * @param categories the categories */ public void setCategories(List<String> categories) { m_categories = categories; } /** * Sets the category mode.<p> * * @param categoryMode the category mode to set */ public void setCategoryMode(CategoryMode categoryMode) { m_categoryMode = categoryMode; } /** * Sets the date restrictions.<p> * * @param restriction the date restrictions */ public void setDateRestriction(I_CmsListDateRestriction restriction) { m_dateRestriction = restriction; } /** * Sets the display types.<p> * * @param displayTypes the display types */ public void setDisplayTypes(List<String> displayTypes) { m_dislayTypes = displayTypes; } /** * Sets the folders.<p> * * @param folders the folders */ public void setFolders(List<String> folders) { m_folders = folders; } /** * Sets the parameter by name.<p> * * @param name the parameter name * @param value the parameter value */ public void setParameterValue(String name, String value) { m_parameterFields.put(name, value); } } /** * Extended dialog context.<p> */ protected class DialogContext extends CmsFileTableDialogContext { /** The selected table items. */ private List<Item> m_selectedItems; /** * Constructor.<p> * * @param appId the app id * @param contextType the context type * @param fileTable the file table instance * @param resources the list of selected resources */ public DialogContext( String appId, ContextType contextType, CmsFileTable fileTable, List<CmsResource> resources) { super(appId, contextType, fileTable, resources); } /** * @see org.opencms.ui.components.CmsFileTableDialogContext#finish(java.util.Collection) */ @Override public void finish(Collection<CmsUUID> ids) { if (m_selectedItems == null) { super.finish(ids); } else { refreshResult(); } } /** * Returns the selected table items.<p> * * @return the selected table items */ public List<Item> getSelectedItems() { return m_selectedItems; } /** * Sets the table items.<p> * * @param items the table items */ public void setSelectedItems(List<Item> items) { m_selectedItems = items; } } /** * Overrides the standard delete action to enable use of edit handlers.<p> */ class DeleteAction extends CmsDeleteDialogAction { /** * @see org.opencms.ui.actions.CmsDeleteDialogAction#executeAction(org.opencms.ui.I_CmsDialogContext) */ @Override public void executeAction(final I_CmsDialogContext context) { final CmsResource resource = context.getResources().get(0); I_CmsResourceType resourceType = OpenCms.getResourceManager().getResourceType(resource); if ((resourceType instanceof CmsResourceTypeXmlContent) && (((CmsResourceTypeXmlContent)resourceType).getEditHandler(context.getCms()) != null)) { final I_CmsEditHandler handler = ((CmsResourceTypeXmlContent)resourceType).getEditHandler( context.getCms()); final CmsContainerElementBean elementBean = getElementForEditHandler((DialogContext)context); CmsDialogOptions options = handler.getDeleteOptions( context.getCms(), elementBean, null, Collections.<String, String[]> emptyMap()); if (options == null) { super.executeAction(context); } else if (options.getOptions().size() == 1) { deleteForOption(resource, elementBean, options.getOptions().get(0).getValue(), handler, context); } else { Window window = CmsBasicDialog.prepareWindow(); window.setCaption(options.getTitle()); CmsOptionDialog dialog = new CmsOptionDialog(resource, options, new I_OptionHandler() { public void handleOption(String option) { deleteForOption(resource, elementBean, option, handler, context); } }, null, window); window.setContent(dialog); CmsAppWorkplaceUi.get().addWindow(window); dialog.initActionHandler(window); } } else { super.executeAction(context); } } /** * Deletes with the given option.<p> * * @param resource the resource to delete * @param elementBean the element bean * @param deleteOption the delete option * @param editHandler edit handler * @param context the dialog context */ void deleteForOption( CmsResource resource, CmsContainerElementBean elementBean, String deleteOption, I_CmsEditHandler editHandler, I_CmsDialogContext context) { try { editHandler.handleDelete(context.getCms(), elementBean, deleteOption, null, null); } catch (CmsException e) { CmsErrorDialog.showErrorDialog(e); } } } /** * Overrides the standard delete action to enable use of edit handlers.<p> */ class EditAction extends CmsEditDialogAction { /** * @see org.opencms.ui.actions.CmsEditDialogAction#executeAction(org.opencms.ui.I_CmsDialogContext) */ @Override public void executeAction(final I_CmsDialogContext context) { final CmsResource resource = context.getResources().get(0); I_CmsResourceType resourceType = OpenCms.getResourceManager().getResourceType(resource); if ((resourceType instanceof CmsResourceTypeXmlContent) && (((CmsResourceTypeXmlContent)resourceType).getEditHandler(context.getCms()) != null)) { final I_CmsEditHandler handler = ((CmsResourceTypeXmlContent)resourceType).getEditHandler( context.getCms()); final CmsContainerElementBean elementBean = getElementForEditHandler((DialogContext)context); CmsDialogOptions options = handler.getEditOptions( context.getCms(), elementBean, null, Collections.<String, String[]> emptyMap(), true); if (options == null) { super.executeAction(context); } else if (options.getOptions().size() == 1) { editForOption(resource, elementBean, options.getOptions().get(0).getValue(), handler, context); } else { Window window = CmsBasicDialog.prepareWindow(); window.setCaption(options.getTitle()); CmsOptionDialog dialog = new CmsOptionDialog(resource, options, new I_OptionHandler() { public void handleOption(String option) { editForOption(resource, elementBean, option, handler, context); } }, null, window); window.setContent(dialog); CmsAppWorkplaceUi.get().addWindow(window); dialog.initActionHandler(window); } } else { super.executeAction(context); } } /** * Calls the editor with the given option.<p> * * @param resource the resource to delete * @param elementBean the element bean * @param editOption the edit option * @param editHandler edit handler * @param context the dialog context */ void editForOption( CmsResource resource, CmsContainerElementBean elementBean, String editOption, I_CmsEditHandler editHandler, I_CmsDialogContext context) { try { CmsUUID id = editHandler.prepareForEdit( context.getCms(), elementBean, editOption, null, Collections.<String, String[]> emptyMap()); if (resource.getStructureId().equals(id)) { super.executeAction(context); } else if (id != null) { CmsFileTableDialogContext changedContext = new CmsFileTableDialogContext( CmsProjectManagerConfiguration.APP_ID, ContextType.fileTable, m_resultTable, Collections.singletonList(context.getCms().readResource(id))); super.executeAction(changedContext); } } catch (CmsException e) { CmsErrorDialog.showErrorDialog(e); } } } /** XML content node name. */ public static final String N_DATE_RESTRICTION = "DateRestriction"; /** Default backend pagination. */ private static final I_CmsSearchConfigurationPagination PAGINATION = new CmsSearchConfigurationPagination( null, Integer.valueOf(10000), Integer.valueOf(1)); /** SOLR field name. */ public static final String FIELD_CATEGORIES = "category_exact"; /** SOLR field name. */ public static final String FIELD_DATE = "instancedate_%s_dt"; /** SOLR field name. */ public static final String FIELD_DATE_FACET_NAME = "instancedate"; /** SOLR field name. */ public static final String FIELD_PARENT_FOLDERS = "parent-folders"; /** List configuration node name and field key. */ public static final String N_BLACKLIST = "Blacklist"; /** List configuration node name and field key. */ public static final String N_CATEGORY = "Category"; /** List configuration node name for the category mode. */ public static final String N_CATEGORY_MODE = "CategoryMode"; /** List configuration node name and field key. */ public static final String N_CATEGORY_CONJUNCTION = "CategoryConjunction"; /** List configuration node name and field key. */ public static final String N_DISPLAY_TYPE = "TypesToCollect"; /** List configuration node name and field key. */ public static final String N_FILTER_QUERY = "FilterQuery"; /** List configuration node name and field key. */ public static final String N_KEY = "Key"; /** List configuration node name and field key. */ public static final String N_PARAMETER = "Parameter"; /** List configuration node name and field key. */ public static final String N_SEARCH_FOLDER = "SearchFolder"; /** List configuration node name and field key. */ public static final String N_SHOW_EXPIRED = "ShowExpired"; /** List configuration node name and field key. */ public static final String N_SORT_ORDER = "SortOrder"; /** List configuration node name and field key. */ public static final String N_TITLE = "Title"; /** List configuration node name and field key. */ public static final String N_VALUE = "Value"; /** List configuration node name and field key. */ public static final String PARAM_LOCALE = "locale"; /** The parameter fields. */ public static final String[] PARAMETER_FIELDS = new String[] { N_TITLE, N_CATEGORY, N_FILTER_QUERY, N_SORT_ORDER, N_SHOW_EXPIRED, N_CATEGORY_CONJUNCTION}; /** The view content list path name. */ public static final String PATH_NAME_VIEW = "view"; /** The list configuration resource type name. */ public static final String RES_TYPE_LIST_CONFIG = "listconfig"; /** The blacklisted table column property id. */ protected static final CmsResourceTableProperty BLACKLISTED_PROPERTY = new CmsResourceTableProperty( "BLACKLISTED", Boolean.class, Boolean.FALSE, Messages.GUI_LISTMANAGER_COLUMN_BLACKLISTED_0, true, 0, 110); /** The date series info table column property id. */ protected static final CmsResourceTableProperty INFO_PROPERTY = new CmsResourceTableProperty( "INFO_PROPERTY", String.class, null, null, true, 1, 0); /** The date series info label table column property id. */ protected static final CmsResourceTableProperty INFO_PROPERTY_LABEL = new CmsResourceTableProperty( "INFO_PROPERTY_LABEL", String.class, null, Messages.GUI_LISTMANAGER_COLUMN_INFO_0, true, 0, 110); /** The blacklisted table column property id. */ protected static final CmsResourceTableProperty INSTANCEDATE_PROPERTY = new CmsResourceTableProperty( "INSTANCEDATE_PROPERTY", Date.class, null, Messages.GUI_LISTMANAGER_COLUMN_INSTANCEDATE_0, true, 0, 145); /** The available sort options. */ protected static final String[][] SORT_OPTIONS = new String[][] { { SortOption.DATE_ASC.toString(), SortOption.DATE_DESC.toString(), SortOption.TITLE_ASC.toString(), SortOption.TITLE_DESC.toString(), SortOption.ORDER_ASC.toString(), SortOption.ORDER_DESC.toString()}, { Messages.GUI_LISTMANAGER_SORT_DATE_ASC_0, Messages.GUI_LISTMANAGER_SORT_DATE_DESC_0, Messages.GUI_LISTMANAGER_SORT_TITLE_ASC_0, Messages.GUI_LISTMANAGER_SORT_TITLE_DESC_0, Messages.GUI_LISTMANAGER_SORT_ORDER_ASC_0, Messages.GUI_LISTMANAGER_SORT_ORDER_DESC_0}}; /** The logger for this class. */ private static final Log LOG = CmsLog.getLog(CmsListManager.class.getName()); /** The month name abbreviations. */ static final String[] MONTHS = new String[] { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"}; /** The serial version id. */ private static final long serialVersionUID = -25954374225590319L; /** The current list configuration data. */ ListConfigurationBean m_currentConfig; /** The current list configuration resource. */ CmsResource m_currentResource; /** The result table. */ CmsResultTable m_resultTable; /** The create new button. */ private Button m_createNewButton; /** The current search parser. */ private CmsSimpleSearchConfigurationParser m_currentConfigParser; /** The current edit dialog window. */ private Window m_dialogWindow; /** The edit current configuration button. */ private Button m_editCurrentButton; /** Indicates multiple instances of a series are present in the current search result. */ private boolean m_hasSeriesInstances; /** Indicates series types are present in the current search result. */ private boolean m_hasSeriesType; /** Flag indicating individual instances of a date series should be hidden. */ private boolean m_hideSeriesInstances; /** The info button. */ private Button m_infoButton; /** Indicates if the overview list is shown. */ private boolean m_isOverView; /** The locale select. */ private ComboBox m_localeSelect; /** The current lock action. */ private CmsLockActionRecord m_lockAction; /** The list configurations overview table. */ private CmsFileTable m_overviewTable; /** The publish button. */ private Button m_publishButton; /** The resetting flag. */ private boolean m_resetting; /** The facet result display. */ private CmsResultFacets m_resultFacets; /** The mail layout. */ private HorizontalSplitPanel m_resultLayout; /** The sort select. */ private ComboBox m_resultSorter; /** The table filter input. */ private TextField m_tableFilter; /** The text search input. */ private TextField m_textSearch; /** The toggle date series display. */ private Button m_toggleSeriesButton; /** * Parses the list configuration resource.<p> * * @param cms the CMS context to use * @param res the list configuration resource * * @return the configuration data bean */ public static ListConfigurationBean parseListConfiguration(CmsObject cms, CmsResource res) { ListConfigurationBean result = new ListConfigurationBean(); try { CmsFile configFile = cms.readFile(res); CmsXmlContent content = CmsXmlContentFactory.unmarshal(cms, configFile); Locale locale = CmsLocaleManager.MASTER_LOCALE; if (!content.hasLocale(locale)) { locale = content.getLocales().get(0); } for (String field : PARAMETER_FIELDS) { String val = content.getStringValue(cms, field, locale); if (N_CATEGORY.equals(field)) { if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(val)) { result.setCategories(Arrays.asList(val.split(","))); } else { result.setCategories(Collections.<String> emptyList()); } } else { result.setParameterValue(field, val); } } I_CmsXmlContentValue restrictValue = content.getValue(N_DATE_RESTRICTION, locale); if (restrictValue != null) { CmsDateRestrictionParser parser = new CmsDateRestrictionParser(cms); I_CmsListDateRestriction restriction = parser.parse(new CmsXmlContentValueLocation(restrictValue)); if (restriction == null) { LOG.warn( "Improper date restriction configuration in content " + content.getFile().getRootPath() + ", online=" + cms.getRequestContext().getCurrentProject().isOnlineProject()); } result.setDateRestriction(restriction); } I_CmsXmlContentValue categoryModeVal = content.getValue(N_CATEGORY_MODE, locale); CategoryMode categoryMode = CategoryMode.OR; if (categoryModeVal != null) { try { categoryMode = CategoryMode.valueOf(categoryModeVal.getStringValue(cms)); } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); } } result.setCategoryMode(categoryMode); LinkedHashMap<String, String> parameters = new LinkedHashMap<String, String>(); for (I_CmsXmlContentValue parameter : content.getValues(N_PARAMETER, locale)) { I_CmsXmlContentValue keyVal = content.getValue(parameter.getPath() + "/" + N_KEY, locale); I_CmsXmlContentValue valueVal = content.getValue(parameter.getPath() + "/" + N_VALUE, locale); if ((keyVal != null) && CmsStringUtil.isNotEmptyOrWhitespaceOnly(keyVal.getStringValue(cms)) && (valueVal != null)) { parameters.put(keyVal.getStringValue(cms), valueVal.getStringValue(cms)); } } result.setAdditionalParameters(parameters); List<String> displayTypes = new ArrayList<String>(); List<I_CmsXmlContentValue> typeValues = content.getValues(N_DISPLAY_TYPE, locale); if (!typeValues.isEmpty()) { for (I_CmsXmlContentValue value : typeValues) { displayTypes.add(value.getStringValue(cms)); } } result.setDisplayTypes(displayTypes); List<String> folders = new ArrayList<String>(); List<I_CmsXmlContentValue> folderValues = content.getValues(N_SEARCH_FOLDER, locale); if (!folderValues.isEmpty()) { for (I_CmsXmlContentValue value : folderValues) { CmsLink val = ((CmsXmlVfsFileValue)value).getLink(cms); if (val != null) { // we are using root paths folders.add(val.getTarget()); } } } result.setFolders(folders); List<CmsUUID> blackList = new ArrayList<CmsUUID>(); List<I_CmsXmlContentValue> blacklistValues = content.getValues(N_BLACKLIST, locale); if (!blacklistValues.isEmpty()) { for (I_CmsXmlContentValue value : blacklistValues) { CmsLink link = ((CmsXmlVfsFileValue)value).getLink(cms); if (link != null) { blackList.add(link.getStructureId()); } } } result.setBlacklist(blackList); } catch (CmsException e) { e.printStackTrace(); } return result; } /** * @see org.opencms.ui.components.CmsResourceTable.I_ResourcePropertyProvider#addItemProperties(com.vaadin.data.Item, org.opencms.file.CmsObject, org.opencms.file.CmsResource, java.util.Locale) */ @Override public void addItemProperties(Item resourceItem, CmsObject cms, CmsResource resource, Locale locale) { if ((m_currentConfig != null) && (resourceItem.getItemProperty(CmsListManager.BLACKLISTED_PROPERTY) != null)) { resourceItem.getItemProperty(CmsListManager.BLACKLISTED_PROPERTY).setValue( Boolean.valueOf(m_currentConfig.getBlacklist().contains(resource.getStructureId()))); } if ((m_currentConfig != null) && (resourceItem.getItemProperty(CmsResourceTableProperty.PROPERTY_TITLE) != null)) { CmsResourceUtil resUtil = new CmsResourceUtil(cms, resource); String title = resUtil.getGalleryTitle((Locale)m_localeSelect.getValue()); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(title)) { resourceItem.getItemProperty(CmsResourceTableProperty.PROPERTY_TITLE).setValue(title); } } if ((resource instanceof CmsSearchResource) && (resourceItem.getItemProperty(CmsListManager.INFO_PROPERTY_LABEL) != null)) { String seriesType = ((CmsSearchResource)resource).getField(CmsSearchField.FIELD_SERIESDATES_TYPE); resourceItem.getItemProperty(CmsListManager.INFO_PROPERTY_LABEL).setValue( CmsVaadinUtils.getMessageText( "GUI_LISTMANAGER_SERIES_TYPE_" + (seriesType == null ? "DEFAULT" : seriesType) + "_0")); resourceItem.getItemProperty(CmsListManager.INFO_PROPERTY).setValue(seriesType); } if ((resource instanceof CmsSearchResource) && (resourceItem.getItemProperty(CmsListManager.INSTANCEDATE_PROPERTY) != null)) { Date date = ((CmsSearchResource)resource).getDateField(m_resultTable.getDateFieldKey()); resourceItem.getItemProperty(CmsListManager.INSTANCEDATE_PROPERTY).setValue(date); } } /** * @see com.vaadin.navigator.ViewChangeListener#afterViewChange(com.vaadin.navigator.ViewChangeListener.ViewChangeEvent) */ @Override public void afterViewChange(ViewChangeEvent event) { // nothing to do } /** * @see com.vaadin.navigator.ViewChangeListener#beforeViewChange(com.vaadin.navigator.ViewChangeListener.ViewChangeEvent) */ @Override public boolean beforeViewChange(ViewChangeEvent event) { unlockCurrent(); return true; } /** * @see org.opencms.ui.apps.I_CmsContextProvider#getDialogContext() */ @Override public I_CmsDialogContext getDialogContext() { CmsFileTable table = isOverView() ? m_overviewTable : m_resultTable; DialogContext context = new DialogContext( CmsProjectManagerConfiguration.APP_ID, ContextType.fileTable, table, table.getSelectedResources()); if (!isOverView()) { context.setSelectedItems(m_resultTable.getSelectedItems()); } return context; } /** * @see org.opencms.ui.apps.A_CmsWorkplaceApp#initUI(org.opencms.ui.apps.I_CmsAppUIContext) */ @Override public void initUI(I_CmsAppUIContext uiContext) { super.initUI(uiContext); m_publishButton = CmsToolBar.createButton( FontOpenCms.PUBLISH, CmsVaadinUtils.getMessageText(Messages.GUI_PUBLISH_BUTTON_TITLE_0)); if (CmsAppWorkplaceUi.isOnlineProject()) { // disable publishing in online project m_publishButton.setEnabled(false); m_publishButton.setDescription(CmsVaadinUtils.getMessageText(Messages.GUI_TOOLBAR_NOT_AVAILABLE_ONLINE_0)); } m_publishButton.addClickListener(new ClickListener() { /** Serial version id. */ private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { publish(); } }); uiContext.addToolbarButton(m_publishButton); m_editCurrentButton = CmsToolBar.createButton( FontOpenCms.PEN, CmsVaadinUtils.getMessageText(Messages.GUI_LISTMANAGER_EDIT_CONFIG_0)); m_editCurrentButton.addClickListener(new ClickListener() { /** Serial version id. */ private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { editListConfiguration(m_currentResource); } }); uiContext.addToolbarButton(m_editCurrentButton); m_infoButton = CmsToolBar.createButton( FontOpenCms.INFO, CmsVaadinUtils.getMessageText(org.opencms.ui.Messages.GUI_RESOURCE_INFO_0)); m_infoButton.addClickListener(new ClickListener() { /** Serial version id. */ private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { DialogContext context = new DialogContext( CmsProjectManagerConfiguration.APP_ID, ContextType.fileTable, m_resultTable, Collections.singletonList(m_currentResource)); CmsResourceInfoAction action = new CmsResourceInfoAction(); action.openDialog(context, CmsResourceStatusTabId.tabRelationsTo.name()); } }); uiContext.addToolbarButton(m_infoButton); m_toggleSeriesButton = CmsToolBar.createButton( FontOpenCms.LIST, CmsVaadinUtils.getMessageText(Messages.GUI_LISTMANAGER_TOGGLE_SERIES_BUTTON_0)); m_toggleSeriesButton.addClickListener(new ClickListener() { /** Serial version id. */ private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { toggleDateSeries(); } }); uiContext.addToolbarButton(m_toggleSeriesButton); m_createNewButton = CmsToolBar.createButton( FontOpenCms.WAND, CmsVaadinUtils.getMessageText(Messages.GUI_LISTMANAGER_CREATE_NEW_0)); m_createNewButton.addClickListener(new ClickListener() { /** Serial version id. */ private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { createNew(); } }); uiContext.addToolbarButton(m_createNewButton); m_rootLayout.setMainHeightFull(true); m_resultLayout = new HorizontalSplitPanel(); m_resultLayout.setSizeFull(); m_resultFacets = new CmsResultFacets(this); m_resultFacets.setWidth("100%"); m_resultLayout.setFirstComponent(m_resultFacets); LinkedHashMap<CmsResourceTableProperty, Integer> tableColumns = new LinkedHashMap<CmsResourceTableProperty, Integer>(); // insert columns a specific positions for (Map.Entry<CmsResourceTableProperty, Integer> columnsEntry : CmsFileTable.DEFAULT_TABLE_PROPERTIES.entrySet()) { if (columnsEntry.getKey().equals(CmsResourceTableProperty.PROPERTY_RESOURCE_NAME)) { tableColumns.put(INFO_PROPERTY_LABEL, Integer.valueOf(0)); } else if (columnsEntry.getKey().equals(CmsResourceTableProperty.PROPERTY_RESOURCE_TYPE)) { tableColumns.put(INSTANCEDATE_PROPERTY, Integer.valueOf(0)); } tableColumns.put(columnsEntry.getKey(), columnsEntry.getValue()); } tableColumns.put(BLACKLISTED_PROPERTY, Integer.valueOf(CmsResourceTable.INVISIBLE)); tableColumns.put(INFO_PROPERTY, Integer.valueOf(CmsResourceTable.INVISIBLE)); m_resultTable = new CmsResultTable(null, tableColumns); m_resultTable.applyWorkplaceAppSettings(); CmsResourceContextMenuBuilder menuBuilderOverView = new CmsResourceContextMenuBuilder(); menuBuilderOverView.addMenuItemProvider(OpenCms.getWorkplaceAppManager().getMenuItemProvider()); menuBuilderOverView.addMenuItemProvider(new I_CmsContextMenuItemProvider() { @Override public List<I_CmsContextMenuItem> getMenuItems() { return Arrays.<I_CmsContextMenuItem> asList(new CmsContextMenuActionItem(new CmsEditDialogAction() { @Override public void executeAction(I_CmsDialogContext context) { editListConfiguration(context.getResources().get(0)); } }, null, 10, 1000)); } }); CmsResourceContextMenuBuilder menuBuilder = new CmsResourceContextMenuBuilder(); menuBuilder.addMenuItemProvider(OpenCms.getWorkplaceAppManager().getMenuItemProvider()); menuBuilder.addMenuItemProvider(new I_CmsContextMenuItemProvider() { @Override public List<I_CmsContextMenuItem> getMenuItems() { return Arrays.<I_CmsContextMenuItem> asList( new CmsContextMenuActionItem(new A_CmsWorkplaceAction() { @Override public void executeAction(I_CmsDialogContext context) { CmsUUID structureId = context.getResources().get(0).getStructureId(); m_currentConfig.getBlacklist().add(structureId); saveBlacklist(m_currentConfig); context.finish(Collections.singletonList(structureId)); } @Override public String getId() { return "hideresource"; } @Override public String getTitleKey() { return Messages.GUI_LISTMANAGER_BLACKLIST_MENU_ENTRY_0; } @Override public CmsMenuItemVisibilityMode getVisibility(CmsObject cms, List<CmsResource> resources) { if ((m_currentConfig != null) && (resources != null) && (resources.size() == 1) && !m_currentConfig.getBlacklist().contains(resources.get(0).getStructureId())) { return CmsEditDialogAction.VISIBILITY.getVisibility( cms, Collections.singletonList(m_currentResource)); } else { return CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE; } } }, null, 10, 0), new CmsContextMenuActionItem(new A_CmsWorkplaceAction() { @Override public void executeAction(I_CmsDialogContext context) { CmsUUID structureId = context.getResources().get(0).getStructureId(); m_currentConfig.getBlacklist().remove(structureId); saveBlacklist(m_currentConfig); context.finish(Collections.singletonList(structureId)); } @Override public String getId() { return "showresource"; } @Override public String getTitleKey() { return Messages.GUI_LISTMANAGER_REMOVE_FROM_BLACKLIST_MENU_ENTRY_0; } @Override public CmsMenuItemVisibilityMode getVisibility(CmsObject cms, List<CmsResource> resources) { if ((m_currentConfig != null) && (resources != null) && (resources.size() == 1) && m_currentConfig.getBlacklist().contains(resources.get(0).getStructureId())) { return CmsEditDialogAction.VISIBILITY.getVisibility( cms, Collections.singletonList(m_currentResource)); } else { return CmsMenuItemVisibilityMode.VISIBILITY_INVISIBLE; } } }, null, 10, 0), new CmsContextMenuActionItem(new EditAction(), null, 10, 1000), new CmsContextMenuActionItem(new DeleteAction(), null, 10, 1000)); } }); m_resultTable.setMenuBuilder(menuBuilder); m_resultTable.addAdditionalStyleGenerator(new CellStyleGenerator() { private static final long serialVersionUID = 1L; @Override public String getStyle(Table source, Object itemId, Object propertyId) { String style = ""; Item item = source.getItem(itemId); Boolean blacklisted = (Boolean)item.getItemProperty(BLACKLISTED_PROPERTY).getValue(); if (blacklisted.booleanValue()) { style += OpenCmsTheme.PROJECT_OTHER + " "; } else if (CmsResourceTableProperty.PROPERTY_TITLE.equals(propertyId) && ((item.getItemProperty(CmsResourceTableProperty.PROPERTY_RELEASED_NOT_EXPIRED) == null) || ((Boolean)item.getItemProperty( CmsResourceTableProperty.PROPERTY_RELEASED_NOT_EXPIRED).getValue()).booleanValue())) { style += OpenCmsTheme.IN_NAVIGATION + " "; } if (INFO_PROPERTY_LABEL.equals(propertyId)) { if (blacklisted.booleanValue()) { style += OpenCmsTheme.TABLE_COLUMN_BOX_BLACK; } else { Object value = item.getItemProperty(INFO_PROPERTY).getValue(); if (value == null) { style += OpenCmsTheme.TABLE_COLUMN_BOX_GRAY; } else { I_CmsSerialDateValue.DateType type = I_CmsSerialDateValue.DateType.valueOf((String)value); switch (type) { case SERIES: style += OpenCmsTheme.TABLE_COLUMN_BOX_BLUE_LIGHT; break; case SINGLE: style += OpenCmsTheme.TABLE_COLUMN_BOX_GRAY; break; case EXTRACTED: style += OpenCmsTheme.TABLE_COLUMN_BOX_ORANGE; break; default: break; } } } } return style; } }); m_resultTable.setsetItemDescriptionGenerator(new ItemDescriptionGenerator() { private static final long serialVersionUID = 1L; public String generateDescription(Component source, Object itemId, Object propertyId) { Item item = ((Table)source).getItem(itemId); if (INFO_PROPERTY_LABEL.equals(propertyId) && ((Boolean)item.getItemProperty(BLACKLISTED_PROPERTY).getValue()).booleanValue()) { return CmsVaadinUtils.getMessageText(Messages.GUI_LISTMANAGER_COLUMN_BLACKLISTED_0); } return null; } }); m_resultTable.setContextProvider(this); m_resultTable.addPropertyProvider(this); m_resultTable.setSizeFull(); m_resultLayout.setSecondComponent(m_resultTable); m_overviewTable = new CmsFileTable(this); m_overviewTable.applyWorkplaceAppSettings(); m_overviewTable.setMenuBuilder(menuBuilderOverView); m_overviewTable.setSizeFull(); m_tableFilter = new TextField(); m_tableFilter.setIcon(FontOpenCms.FILTER); m_tableFilter.setInputPrompt( Messages.get().getBundle(UI.getCurrent().getLocale()).key(Messages.GUI_EXPLORER_FILTER_0)); m_tableFilter.addStyleName(ValoTheme.TEXTFIELD_INLINE_ICON); m_tableFilter.setWidth("200px"); m_tableFilter.addTextChangeListener(new TextChangeListener() { private static final long serialVersionUID = 1L; @Override public void textChange(TextChangeEvent event) { filterTable(event.getText()); } }); m_infoLayout.addComponent(m_tableFilter); m_localeSelect = new ComboBox(); m_localeSelect.setNullSelectionAllowed(false); m_localeSelect.setWidth("100px"); m_localeSelect.addValueChangeListener(new ValueChangeListener() { /** Serial version id. */ private static final long serialVersionUID = 1L; @Override public void valueChange(ValueChangeEvent event) { changeContentLocale((Locale)event.getProperty().getValue()); } }); m_infoLayout.addComponent(m_localeSelect); m_resultSorter = new ComboBox(); m_resultSorter.setNullSelectionAllowed(false); m_resultSorter.setWidth("200px"); for (int i = 0; i < SORT_OPTIONS[0].length; i++) { m_resultSorter.addItem(SORT_OPTIONS[0][i]); m_resultSorter.setItemCaption(SORT_OPTIONS[0][i], CmsVaadinUtils.getMessageText(SORT_OPTIONS[1][i])); } m_resultSorter.addValueChangeListener(new ValueChangeListener() { /** Serial version id. */ private static final long serialVersionUID = 1L; @Override public void valueChange(ValueChangeEvent event) { sortResult(); } }); m_infoLayout.addComponent(m_resultSorter); m_textSearch = new TextField(); m_textSearch.setIcon(FontOpenCms.SEARCH); m_textSearch.setInputPrompt(CmsVaadinUtils.getMessageText(Messages.GUI_LISTMANAGER_SEARCH_0)); m_textSearch.addStyleName(ValoTheme.TEXTFIELD_INLINE_ICON); m_textSearch.setWidth("200px"); m_textSearch.addValueChangeListener(new ValueChangeListener() { /** Serial version id. */ private static final long serialVersionUID = 1L; @Override public void valueChange(ValueChangeEvent event) { search((String)event.getProperty().getValue()); } }); m_infoLayout.addComponent(m_textSearch); m_resultLayout.setSecondComponent(m_resultTable); m_resultLayout.setSplitPosition(CmsFileExplorer.LAYOUT_SPLIT_POSITION, Unit.PIXELS); } /** * @see org.opencms.ui.components.I_CmsWindowCloseListener#onWindowClose() */ @Override public void onWindowClose() { unlockCurrent(); } /** * Saves the blacklist from the bean in the current list configuration.<p> * * @param configBean the bean whose blacklist should be saved */ public void saveBlacklist(ListConfigurationBean configBean) { if (m_dialogWindow != null) { m_dialogWindow.close(); m_dialogWindow = null; } CmsObject cms = A_CmsUI.getCmsObject(); try { m_lockAction = CmsLockUtil.ensureLock(cms, m_currentResource); } catch (CmsException e) { CmsErrorDialog.showErrorDialog(e); return; } try { CmsFile configFile = cms.readFile(m_currentResource); CmsXmlContent content = CmsXmlContentFactory.unmarshal(cms, configFile); // list configurations are single locale contents Locale locale = CmsLocaleManager.MASTER_LOCALE; int count = 0; while (content.hasValue(N_BLACKLIST, locale)) { content.removeValue(N_BLACKLIST, locale, 0); } for (CmsUUID hiddenId : configBean.getBlacklist()) { CmsXmlVfsFileValue contentVal; contentVal = (CmsXmlVfsFileValue)content.addValue(cms, N_BLACKLIST, locale, count); contentVal.setIdValue(cms, hiddenId); count++; } configFile.setContents(content.marshal()); cms.writeFile(configFile); if (m_lockAction.getChange().equals(LockChange.locked)) { CmsLockUtil.tryUnlock(cms, configFile); } } catch (CmsException e) { e.printStackTrace(); } m_currentConfig = configBean; } /** * Execute a search with the given search configuration parser.<p> * * @param configParser the search configuration parser * @param resource the current configuration resource */ public void search(CmsSimpleSearchConfigurationParser configParser, CmsResource resource) { m_currentResource = resource; m_currentConfigParser = configParser; resetContentLocale(configParser.getSearchLocale()); m_resetting = true; m_resultSorter.setValue(m_currentConfig.getParameterValue(N_SORT_ORDER)); m_resetting = false; search(null, null, null); } /** * Updates the search result.<p> * * @param fieldFacets the field facets * @param rangeFacets the range facets */ public void search(Map<String, List<String>> fieldFacets, Map<String, List<String>> rangeFacets) { search(fieldFacets, rangeFacets, null); } /** * Updates the search result.<p> * * @param fieldFacets the field facets * @param rangeFacets the range facets * @param additionalQuery the additional query */ public void search( Map<String, List<String>> fieldFacets, Map<String, List<String>> rangeFacets, String additionalQuery) { if (CmsStringUtil.isNotEmptyOrWhitespaceOnly((String)m_resultSorter.getValue())) { m_currentConfigParser.setSortOption((String)m_resultSorter.getValue()); } CmsSolrQuery query = m_currentConfigParser.getInitialQuery(); CmsSearchController controller = new CmsSearchController(new CmsSearchConfiguration(m_currentConfigParser)); controller.getPagination().getState().setCurrentPage(1); if (fieldFacets != null) { Map<String, I_CmsSearchControllerFacetField> fieldFacetControllers = controller.getFieldFacets().getFieldFacetController(); for (Map.Entry<String, List<String>> facetEntry : fieldFacets.entrySet()) { I_CmsSearchStateFacet state = fieldFacetControllers.get(facetEntry.getKey()).getState(); state.clearChecked(); for (String check : facetEntry.getValue()) { state.addChecked(check); } } } if (rangeFacets != null) { Map<String, I_CmsSearchControllerFacetRange> rangeFacetControllers = controller.getRangeFacets().getRangeFacetController(); for (Map.Entry<String, List<String>> facetEntry : rangeFacets.entrySet()) { I_CmsSearchStateFacet state = rangeFacetControllers.get(facetEntry.getKey()).getState(); state.clearChecked(); for (String check : facetEntry.getValue()) { state.addChecked(check); } } } if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(additionalQuery)) { controller.getCommon().getState().setQuery(additionalQuery); } else { resetTextSearch(); } controller.addQueryParts(query); executeSearch(controller, query); } /** * @see org.opencms.ui.apps.A_CmsWorkplaceApp#getBreadCrumbForState(java.lang.String) */ @Override protected LinkedHashMap<String, String> getBreadCrumbForState(String state) { LinkedHashMap<String, String> crumbs = new LinkedHashMap<String, String>(); if (CmsStringUtil.isEmptyOrWhitespaceOnly(state)) { crumbs.put("", CmsVaadinUtils.getMessageText(Messages.GUI_LISTMANAGER_TITLE_0)); } else if (CmsStringUtil.isNotEmptyOrWhitespaceOnly( A_CmsWorkplaceApp.getParamFromState(state, CmsEditor.RESOURCE_ID_PREFIX))) { crumbs.put( CmsListManagerConfiguration.APP_ID, CmsVaadinUtils.getMessageText(Messages.GUI_LISTMANAGER_TITLE_0)); String title = ""; try { title = A_CmsUI.getCmsObject().readPropertyObject( m_currentResource, CmsPropertyDefinition.PROPERTY_TITLE, false).getValue(); } catch (Exception e) { // ignore } if ((m_currentResource != null) && CmsStringUtil.isEmptyOrWhitespaceOnly(title)) { title = m_currentResource.getName(); } crumbs.put("", CmsVaadinUtils.getMessageText(Messages.GUI_LISTMANAGER_VIEW_1, title)); } return crumbs; } /** * @see org.opencms.ui.apps.A_CmsWorkplaceApp#getComponentForState(java.lang.String) */ @Override protected Component getComponentForState(String state) { CmsObject cms = A_CmsUI.getCmsObject(); boolean showOverview = true; if (CmsStringUtil.isNotEmptyOrWhitespaceOnly( A_CmsWorkplaceApp.getParamFromState(state, CmsEditor.RESOURCE_ID_PREFIX))) { try { CmsUUID id = new CmsUUID(A_CmsWorkplaceApp.getParamFromState(state, CmsEditor.RESOURCE_ID_PREFIX)); CmsResource res = cms.readResource(id, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED); m_currentConfig = parseListConfiguration(A_CmsUI.getCmsObject(), res); String localeString = A_CmsWorkplaceApp.getParamFromState(state, PARAM_LOCALE); Locale locale; if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(localeString)) { locale = CmsLocaleManager.getLocale(localeString); } else { locale = getContentLocale(m_currentConfig); } //SearchConfigParser configParser = new SearchConfigParser(m_currentConfig, m_collapseItemSeries, locale); CmsSimpleSearchConfigurationParser configParser = new CmsSimpleSearchConfigurationParser( cms, m_currentConfig, null); setBackendSpecificOptions(configParser, locale); search(configParser, res); showOverview = false; } catch (Exception e) { CmsErrorDialog.showErrorDialog(e); LOG.error(e.getLocalizedMessage(), e); } } if (showOverview) { unlockCurrent(); m_lockAction = null; displayListConfigs(); } // m_searchForm.resetFormValues(); enableOverviewMode(showOverview); return showOverview ? m_overviewTable : m_resultLayout; } /** * @see org.opencms.ui.apps.A_CmsWorkplaceApp#getSubNavEntries(java.lang.String) */ @Override protected List<NavEntry> getSubNavEntries(String state) { return null; } /** * Changes the search content locale, reissuing a search.<p> * * @param contentLocale the content locale to set */ void changeContentLocale(Locale contentLocale) { if (!m_resetting) { m_currentConfigParser.setSearchLocale(contentLocale); } m_resultTable.setContentLocale(contentLocale); search(null, null, null); } /** * Closes the edit dialog window.<p> */ void closeEditDialog() { if (m_dialogWindow != null) { m_dialogWindow.close(); m_dialogWindow = null; } if (m_isOverView) { unlockCurrent(); m_currentResource = null; } } /** * Opens the create new dialog.<p> */ void createNew() { if (m_isOverView) { editListConfiguration(null); } } /** * Displays the search result in the result table.<p> * * @param resultList the search result */ void displayResult(CmsSolrResultList resultList) { List<CmsResource> resources; evalSeries(resultList); if (m_hideSeriesInstances) { Set<CmsUUID> instanceIds = new HashSet<CmsUUID>(); resources = new ArrayList<CmsResource>(); for (CmsSearchResource res : resultList) { if (!instanceIds.contains(res.getStructureId())) { instanceIds.add(res.getStructureId()); resources.add(res); } } } else { resources = new ArrayList<CmsResource>(resultList); } m_resultTable.fillTable(A_CmsUI.getCmsObject(), resources, true, false); String state = A_CmsWorkplaceApp.addParamToState( "", CmsEditor.RESOURCE_ID_PREFIX, m_currentResource.getStructureId().toString()); state = A_CmsWorkplaceApp.addParamToState( state, PARAM_LOCALE, m_currentConfigParser.getSearchLocale().toString()); CmsAppWorkplaceUi.get().changeCurrentAppState(state); if (m_isOverView) { enableOverviewMode(false); updateBreadCrumb(getBreadCrumbForState(state)); } } /** * Edits the given list configuration resource.<p> * * @param resource the cofiguration resource */ void editListConfiguration(CmsResource resource) { try { CmsObject cms = A_CmsUI.getCmsObject(); String editState; if (resource == null) { editState = CmsEditor.getEditStateForNew( cms, OpenCms.getResourceManager().getResourceType(RES_TYPE_LIST_CONFIG), "/", null, false, UI.getCurrent().getPage().getLocation().toString()); } else { editState = CmsEditor.getEditState( resource.getStructureId(), false, UI.getCurrent().getPage().getLocation().toString()); } CmsAppWorkplaceUi.get().showApp(OpenCms.getWorkplaceAppManager().getAppConfiguration("editor"), editState); } catch (CmsLoaderException e) { CmsErrorDialog.showErrorDialog(e); } } /** * Enables the overview mode.<p> * * @param enabled <code>true</code> to enable the mode */ void enableOverviewMode(boolean enabled) { boolean isOffline = !A_CmsUI.getCmsObject().getRequestContext().getCurrentProject().isOnlineProject(); m_publishButton.setVisible(!enabled); m_publishButton.setEnabled(isOffline); m_infoButton.setVisible(!enabled); m_tableFilter.setVisible(enabled); m_textSearch.setVisible(!enabled); m_editCurrentButton.setVisible(!enabled); m_editCurrentButton.setEnabled(isOffline); m_createNewButton.setVisible(enabled); m_createNewButton.setEnabled(isOffline); m_toggleSeriesButton.setVisible(m_hasSeriesType && !enabled); m_resultSorter.setVisible(!enabled); m_localeSelect.setVisible(!enabled); m_isOverView = enabled; m_rootLayout.setMainContent(enabled ? m_overviewTable : m_resultLayout); } /** * Evaluates if date series types are present and if more than one instance of a series is in the search result.<p> * * @param resultList the search result list */ void evalSeries(CmsSolrResultList resultList) { m_hasSeriesType = false; m_hasSeriesInstances = false; Set<CmsUUID> instanceIds = new HashSet<CmsUUID>(); for (CmsSearchResource res : resultList) { String seriesType = res.getField(CmsSearchField.FIELD_SERIESDATES_TYPE); m_hasSeriesType = m_hasSeriesType || CmsStringUtil.isNotEmptyOrWhitespaceOnly(seriesType); if (m_hasSeriesType && I_CmsSerialDateValue.DateType.SERIES.name().equals(seriesType)) { if (instanceIds.contains(res.getStructureId())) { m_hasSeriesInstances = true; break; } else { instanceIds.add(res.getStructureId()); } } } if (!m_hasSeriesInstances) { setsDateSeriesHiddenFlag(false); } m_toggleSeriesButton.setEnabled(m_hasSeriesInstances); m_toggleSeriesButton.setVisible(m_hasSeriesType); } /** * Filters the result table.<p> * * @param filter the filter string */ void filterTable(String filter) { if (!m_resetting) { m_overviewTable.filterTable(filter); } } /** * Creates an element bean of the selected table item to be used with edit handlers.<p> * * @param context the dialog context * * @return the element bean */ CmsContainerElementBean getElementForEditHandler(DialogContext context) { List<Item> selected = context.getSelectedItems(); if (selected.size() == 1) { Item item = selected.get(0); Date instanceDate = (Date)item.getItemProperty(INSTANCEDATE_PROPERTY).getValue(); CmsResource resource = context.getResources().get(0); return new CmsContainerElementBean( resource.getStructureId(), null, Collections.singletonMap( CmsDateSeriesEditHandler.PARAM_INSTANCEDATE, String.valueOf(instanceDate.getTime())), false); } return null; } /** * Returns the resources to publish for the current list.<p> * * @return the publish resources */ List<CmsResource> getPublishResources() { List<CmsResource> result = new ArrayList<CmsResource>(); if (m_currentResource != null) { result.add(m_currentResource); CmsObject cms = A_CmsUI.getCmsObject(); CmsSolrQuery query = m_currentConfigParser.getInitialQuery(); CmsSearchController controller = new CmsSearchController(new CmsSearchConfiguration(m_currentConfigParser)); controller.getPagination().getState().setCurrentPage(1); controller.addQueryParts(query); CmsSolrIndex index = OpenCms.getSearchManager().getIndexSolr(CmsSolrIndex.DEFAULT_INDEX_NAME_OFFLINE); try { CmsSolrResultList solrResultList = index.search(cms, query, true, CmsResourceFilter.IGNORE_EXPIRATION); result.addAll(solrResultList); } catch (CmsSearchException e) { LOG.error("Error reading resources for publish.", e); } } return result; } /** * Returns whether the overview mode is active.<p> * * @return <code>true</code> in case the overview mode is active */ boolean isOverView() { return m_isOverView; } /** * Opens the publish dialog to publish all resources related to the current search configuration.<p> */ void publish() { I_CmsUpdateListener<String> updateListener = new I_CmsUpdateListener<String>() { @Override public void onUpdate(List<String> updatedItems) { updateItems(updatedItems); } }; CmsAppWorkplaceUi.get().disableGlobalShortcuts(); CmsGwtDialogExtension extension = new CmsGwtDialogExtension(A_CmsUI.get(), updateListener); extension.openPublishDialog(getPublishResources()); } /** * Refreshes the search result maintaining the current scroll position.<p> */ void refreshResult() { String itemId = m_resultTable.getCurrentPageFirstItemId(); search( m_resultFacets.getSelectedFieldFacets(), m_resultFacets.getSelectedRangeFactes(), m_textSearch.getValue()); m_resultTable.setCurrentPageFirstItemId(itemId); } /** * Searches within the current list.<p> * * @param query the query string */ void search(String query) { if (!m_resetting) { search(null, null, query); } } /** * Sets the date series hidden flag.<p> * * @param hide the date series hidden flag */ void setsDateSeriesHiddenFlag(boolean hide) { m_hideSeriesInstances = hide; if (m_hideSeriesInstances) { m_toggleSeriesButton.addStyleName(OpenCmsTheme.BUTTON_PRESSED); } else { m_toggleSeriesButton.removeStyleName(OpenCmsTheme.BUTTON_PRESSED); } } /** * Sorts the search result.<p> */ void sortResult() { if (!m_resetting) { search( m_resultFacets.getSelectedFieldFacets(), m_resultFacets.getSelectedRangeFactes(), m_textSearch.getValue()); } } /** * Toggles the date series filter.<p> */ void toggleDateSeries() { setsDateSeriesHiddenFlag(!m_hideSeriesInstances); refreshResult(); } /** * Tries to unlocks the current resource if available.<p> */ void tryUnlockCurrent() { if ((m_lockAction != null) && m_lockAction.getChange().equals(CmsLockActionRecord.LockChange.locked)) { try { A_CmsUI.getCmsObject().unlockResource(m_currentResource); } catch (CmsException e) { e.printStackTrace(); } } } /** * Unlocks the current resource in case it has been locked by previous actions.<p> */ void unlockCurrent() { if (m_currentResource != null) { if ((m_lockAction != null) && m_lockAction.getChange().equals(LockChange.locked)) { CmsLockUtil.tryUnlock(A_CmsUI.getCmsObject(), m_currentResource); } } m_lockAction = null; } /** * Updates the given items in the result table.<p> * * @param updatedItems the items to update */ void updateItems(List<String> updatedItems) { Set<CmsUUID> ids = new HashSet<CmsUUID>(); for (String id : updatedItems) { ids.add(new CmsUUID(id)); } m_resultTable.update(ids, false); } /** * Displays the list config resources.<p> */ private void displayListConfigs() { CmsObject cms = A_CmsUI.getCmsObject(); resetTableFilter(); try { // display the search configuration overview List<CmsResource> resources = cms.readResources( "/", CmsResourceFilter.ONLY_VISIBLE_NO_DELETED.addRequireType( OpenCms.getResourceManager().getResourceType(RES_TYPE_LIST_CONFIG))); m_overviewTable.fillTable(cms, resources); } catch (Exception e) { CmsErrorDialog.showErrorDialog(e); LOG.error(e.getLocalizedMessage(), e); } } /** * Executes a search.<p> * * @param controller the search controller * @param query the SOLR query */ private void executeSearch(CmsSearchController controller, CmsSolrQuery query) { CmsObject cms = A_CmsUI.getCmsObject(); CmsSolrIndex index = OpenCms.getSearchManager().getIndexSolr( cms.getRequestContext().getCurrentProject().isOnlineProject() ? CmsSolrIndex.DEFAULT_INDEX_NAME_ONLINE : CmsSolrIndex.DEFAULT_INDEX_NAME_OFFLINE); try { CmsSolrResultList solrResultList = index.search(cms, query, true, CmsResourceFilter.IGNORE_EXPIRATION); displayResult(solrResultList); m_resultFacets.displayFacetResult( solrResultList, new CmsSearchResultWrapper(controller, solrResultList, query, cms, null)); } catch (CmsSearchException e) { CmsErrorDialog.showErrorDialog(e); LOG.error("Error executing search.", e); } } /** * Returns the content locale configured for the first search root folder of the search configuration.<p> * * @param bean the search configuration data * * @return the locale */ private Locale getContentLocale(ListConfigurationBean bean) { CmsObject cms = A_CmsUI.getCmsObject(); if (bean.getFolders().isEmpty()) { return OpenCms.getLocaleManager().getDefaultLocale(cms, "/"); } else { return OpenCms.getLocaleManager().getDefaultLocale( cms, cms.getRequestContext().removeSiteRoot(m_currentConfig.getFolders().get(0))); } } /** * Resets the locale select according to the current configuration data.<p> * * @param defaultLocale the default content locale */ private void resetContentLocale(Locale defaultLocale) { m_resetting = true; m_localeSelect.removeAllItems(); if (m_currentConfig.getFolders().isEmpty()) { m_localeSelect.addItem(defaultLocale); m_localeSelect.setItemCaption(defaultLocale, defaultLocale.getDisplayLanguage(UI.getCurrent().getLocale())); } else { for (String folder : m_currentConfig.getFolders()) { for (Locale locale : OpenCms.getLocaleManager().getAvailableLocales(A_CmsUI.getCmsObject(), folder)) { if (!m_localeSelect.containsId(locale)) { m_localeSelect.addItem(locale); m_localeSelect.setItemCaption(locale, locale.getDisplayLanguage(UI.getCurrent().getLocale())); } } } } m_localeSelect.setValue(defaultLocale); m_localeSelect.setEnabled(m_localeSelect.getItemIds().size() > 1); m_resetting = false; } /** * Resets the table filter.<p> */ private void resetTableFilter() { m_resetting = true; m_tableFilter.clear(); m_resetting = false; } /** * Resets the text search input.<p> */ private void resetTextSearch() { m_resetting = true; m_textSearch.clear(); m_resetting = false; } /** * Sets options which are specific to the backend list manager on the cnofiguration parser.<p> * * @param configParser the configuration parser * @param locale the search locale */ private void setBackendSpecificOptions(CmsSimpleSearchConfigurationParser configParser, Locale locale) { configParser.setSearchLocale(locale); configParser.setIgnoreBlacklist(true); configParser.setPagination(PAGINATION); } }
package org.simpleim.server.server; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import java.util.logging.Level; import java.util.logging.Logger; import org.simpleim.common.message.*; import org.simpleim.server.database.DataBase; import org.simpleim.server.util.AccountGenerator; import com.lambdaworks.crypto.SCryptUtil; public class ServerHandler extends ChannelHandlerAdapter { private static final Logger logger = Logger.getLogger(ServerHandler.class.getName()); @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { boolean closeNow = true; Response response = null; String id; String password; if(msg instanceof NewAccountRequest) { closeNow = true; id=AccountGenerator.nextId(); password=AccountGenerator.generatePassword(); response = new NewAccountOkResponse() .setId(id) .setPassword(password); String hashedPassword = SCryptUtil.scrypt(password, 1 << 15, 8, 1); DataBase.InsertNumberRow(id, hashedPassword); } else { closeNow = true; response = new FailureResponse(); } ChannelFuture f = ctx.write(response); if(closeNow) f.addListener(ChannelFutureListener.CLOSE); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // Close the connection when an exception is raised. logger.log(Level.WARNING, "Unexpected exception from downstream.", cause); ctx.close(); } }
package com.intellij.ui; import com.intellij.codeInsight.lookup.LookupArranger; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.codeInsight.lookup.impl.LookupImpl; import com.intellij.lang.Language; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.IdeActions; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.PlainTextLanguage; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileFactory; import com.intellij.psi.codeStyle.NameUtil; import com.intellij.util.Function; import com.intellij.util.LocalTimeCounter; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * @author Roman Chernyatchik * * It is text field with autocompletion from list of values. * * Autocompletion is implemented via LookupManager. * Use setVariants(..) set list of values for autocompletion. * For variants you can use not only instances of PresentableLookupValue, but * also instances of LookupValueWithPriority and LookupValueWithUIHint */ public class TextFieldWithAutoCompletion extends EditorTextField { private List<LookupElement> myVariants; private String myAdText; public TextFieldWithAutoCompletion() { super(); } public TextFieldWithAutoCompletion(final Project project) { super(createDocument(project), project, PlainTextLanguage.INSTANCE.getAssociatedFileType()); new VariantsCompletionAction(); } private static Document createDocument(@Nullable final Project project) { if (project == null) { return EditorFactory.getInstance().createDocument(""); } final Language language = PlainTextLanguage.INSTANCE; final PsiFileFactory factory = PsiFileFactory.getInstance(project); final FileType fileType = language.getAssociatedFileType(); assert fileType != null; final long stamp = LocalTimeCounter.currentTime(); final PsiFile psiFile = factory.createFileFromText("Dummy." + fileType.getDefaultExtension(), fileType, "", stamp, true, false); final Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile); assert document != null; return document; } private class VariantsCompletionAction extends AnAction { private VariantsCompletionAction() { final AnAction action = ActionManager.getInstance().getAction(IdeActions.ACTION_CODE_COMPLETION); if (action != null) { registerCustomShortcutSet(action.getShortcutSet(), TextFieldWithAutoCompletion.this); } } public void actionPerformed(final AnActionEvent e) { final Editor editor = getEditor(); assert editor != null; editor.getSelectionModel().removeSelection(); final String lookupPrefix = getCurrentLookupPrefix(getCurrentTextPrefix()); final LookupImpl lookup = (LookupImpl)LookupManager.getInstance(getProject()).createLookup(editor, calcLookupItems(lookupPrefix), lookupPrefix != null ? lookupPrefix : "", LookupArranger.DEFAULT); final String advertisementText = getAdvertisementText(); if (!StringUtil.isEmpty(advertisementText)) { lookup.setAdvertisementText(advertisementText); lookup.refreshUi(); } lookup.show(); } } public void setAdvertisementText(@Nullable String text) { myAdText = text; } public String getAdvertisementText() { return myAdText; } public void setVariants(@Nullable final List<LookupElement> variants) { myVariants = (variants != null) ? variants : Collections.<LookupElement>emptyList(); } public void setVariants(@Nullable final String[] variants) { myVariants = (variants == null) ? Collections.<LookupElement>emptyList() : ContainerUtil.map(variants, new Function<String, LookupElement>() { public LookupElement fun(final String s) { return LookupElementBuilder.create(s); } }); } private LookupElement[] calcLookupItems(@Nullable final String lookupPrefix) { if (lookupPrefix == null) { return new LookupElement[0]; } final List<LookupElement> items = new ArrayList<LookupElement>(); if (lookupPrefix.length() == 0) { items.addAll(myVariants); } else { final NameUtil.Matcher matcher = NameUtil.buildMatcher(lookupPrefix, 0, true, true); for (LookupElement variant : myVariants) { if (matcher.matches(variant.getLookupString())) { items.add(variant); } } } Collections.sort(items, new Comparator<LookupElement>() { public int compare(final LookupElement item1, final LookupElement item2) { return item1.getLookupString().compareTo(item2.getLookupString()); } }); return items.toArray(new LookupElement[items.size()]); } /** * Returns prefix for autocompletion and lookup items matching. */ @Nullable protected String getCurrentLookupPrefix(final String currentTextPrefix) { return currentTextPrefix; } private String getCurrentTextPrefix() { return getText().substring(0, getCaretModel().getOffset()); } }
package com.intellij.diagnostic; import com.intellij.icons.AllIcons; import com.intellij.notification.Notification; import com.intellij.notification.NotificationAction; import com.intellij.notification.NotificationType; import com.intellij.notification.impl.NotificationsManagerImpl; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Ref; import com.intellij.openapi.wm.IconLikeCustomStatusBarWidget; import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.StatusBar; import com.intellij.ui.BalloonLayout; import com.intellij.ui.BalloonLayoutData; import com.intellij.ui.JBColor; import com.intellij.util.concurrency.EdtExecutorService; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.util.List; import java.util.concurrent.TimeUnit; public class IdeMessagePanel extends JPanel implements MessagePoolListener, IconLikeCustomStatusBarWidget { public static final String FATAL_ERROR = "FatalError"; private final IdeErrorsIcon myIdeFatal; private final IdeFrame myFrame; private final MessagePool myMessagePool; private Balloon myBalloon; private IdeErrorsDialog myDialog; private boolean myOpeningInProgress; private boolean myNotificationPopupAlreadyShown; public IdeMessagePanel(@Nullable IdeFrame frame, @NotNull MessagePool messagePool) { super(new BorderLayout()); myIdeFatal = new IdeErrorsIcon(e -> openErrorsDialog(null), frame != null); myIdeFatal.setVerticalAlignment(SwingConstants.CENTER); add(myIdeFatal, BorderLayout.CENTER); myFrame = frame; myMessagePool = messagePool; messagePool.addListener(this); updateFatalErrorsIcon(); setOpaque(false); } @Override @NotNull public String ID() { return FATAL_ERROR; } @Override public WidgetPresentation getPresentation(@NotNull PlatformType type) { return null; } @Override public void dispose() { myMessagePool.removeListener(this); } @Override public void install(@NotNull StatusBar statusBar) { } @Override public JComponent getComponent() { return this; } /** @deprecated use {@link #openErrorsDialog(LogMessage)} (to be removed in IDEA 2019) */ @SuppressWarnings("SpellCheckingInspection") public void openFatals(@Nullable LogMessage message) { openErrorsDialog(message); } public void openErrorsDialog(@Nullable LogMessage message) { if (myDialog != null) return; if (myOpeningInProgress) return; myOpeningInProgress = true; new Runnable() { @Override public void run() { if (!isOtherModalWindowActive()) { try { doOpenErrorsDialog(message); } finally { myOpeningInProgress = false; } } else if (myDialog == null) { EdtExecutorService.getScheduledExecutorInstance().schedule(this, 300L, TimeUnit.MILLISECONDS); } } }.run(); } private void doOpenErrorsDialog(@Nullable LogMessage message) { if (isOtherModalWindowActive()) { return; } Project project = myFrame != null ? myFrame.getProject() : null; myDialog = new IdeErrorsDialog(myMessagePool, project, message) { @Override protected void dispose() { super.dispose(); myDialog = null; updateFatalErrorsIcon(); } @Override protected void updateOnSubmit() { super.updateOnSubmit(); updateState(computeState()); } }; if (myBalloon != null) { myBalloon.hide(); } myDialog.show(); } private void updateState(IdeErrorsIcon.State state) { myIdeFatal.setState(state); UIUtil.invokeLaterIfNeeded(() -> setVisible(state != IdeErrorsIcon.State.NoErrors)); } @Override public void newEntryAdded() { updateFatalErrorsIcon(); } @Override public void poolCleared() { updateFatalErrorsIcon(); } @Override public void entryWasRead() { updateFatalErrorsIcon(); } private boolean isOtherModalWindowActive() { Window activeWindow = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow(); return activeWindow instanceof JDialog && ((JDialog)activeWindow).isModal() && (myDialog == null || myDialog.getWindow() != activeWindow); } private IdeErrorsIcon.State computeState() { List<AbstractMessage> unsent = myMessagePool.getFatalErrors(true, false); if (unsent.isEmpty()) return IdeErrorsIcon.State.NoErrors; if (unsent.stream().allMatch(AbstractMessage::isRead)) return IdeErrorsIcon.State.ReadErrors; return IdeErrorsIcon.State.UnreadErrors; } private void updateFatalErrorsIcon() { IdeErrorsIcon.State state = computeState(); updateState(state); if (state == IdeErrorsIcon.State.NoErrors) { myNotificationPopupAlreadyShown = false; } else if (state == IdeErrorsIcon.State.UnreadErrors && !myNotificationPopupAlreadyShown) { Project project = myFrame == null ? null : myFrame.getProject(); if (project != null) { ApplicationManager.getApplication().invokeLater(() -> showErrorNotification(project), project.getDisposed()); myNotificationPopupAlreadyShown = true; } } } private void showErrorNotification(@NotNull Project project) { String title = DiagnosticBundle.message("error.new.notification.title"); String linkText = DiagnosticBundle.message("error.new.notification.link"); Notification notification = new Notification("", AllIcons.Ide.FatalError, title, null, null, NotificationType.ERROR, null); notification.addAction(new NotificationAction(linkText) { @Override public void actionPerformed(@NotNull AnActionEvent e, @NotNull Notification notification) { notification.expire(); doOpenErrorsDialog(null); } }); BalloonLayout layout = myFrame.getBalloonLayout(); assert layout != null; BalloonLayoutData layoutData = BalloonLayoutData.createEmpty(); layoutData.fadeoutTime = 5000; layoutData.fillColor = new JBColor(0XF5E6E7, 0X593D41); layoutData.borderColor = new JBColor(0XE0A8A9, 0X73454B); assert myBalloon == null; myBalloon = NotificationsManagerImpl.createBalloon(myFrame, notification, false, false, new Ref<>(layoutData), project); Disposer.register(myBalloon, () -> myBalloon = null); layout.add(myBalloon); } }
package com.intellij.ide.actions; import com.intellij.ide.IdeBundle; import com.intellij.ide.util.EditorGotoLineNumberDialog; import com.intellij.ide.util.GotoLineNumberDialog; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; public class GotoLineAction extends AnAction implements DumbAware { public GotoLineAction() { setEnabledInModalContext(true); } @Override public void actionPerformed(@NotNull AnActionEvent e) { Project project = e.getData(CommonDataKeys.PROJECT); assert project != null; Editor editor = e.getData(CommonDataKeys.EDITOR_EVEN_IF_INACTIVE); if (Boolean.TRUE.equals(e.getData(PlatformDataKeys.IS_MODAL_CONTEXT))) { GotoLineNumberDialog dialog = new EditorGotoLineNumberDialog(project, editor); dialog.show(); } else { CommandProcessor processor = CommandProcessor.getInstance(); processor.executeCommand( project, () -> { GotoLineNumberDialog dialog = new EditorGotoLineNumberDialog(project, editor); dialog.show(); IdeDocumentHistory.getInstance(project).includeCurrentCommandAsNavigation(); }, IdeBundle.message("command.go.to.line"), null ); } } @Override public void update(@NotNull AnActionEvent event) { Presentation presentation = event.getPresentation(); Project project = event.getData(CommonDataKeys.PROJECT); if (project == null) { presentation.setEnabledAndVisible(false); return; } Editor editor = event.getData(CommonDataKeys.EDITOR_EVEN_IF_INACTIVE); presentation.setEnabledAndVisible(editor != null); } }
package com.kaltura.playersdk; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Point; import android.media.AudioManager; import android.net.Uri; import android.os.Build; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.Log; import android.view.Display; import android.view.View; import android.view.ViewGroup; import android.view.animation.BounceInterpolator; import android.widget.FrameLayout; import android.widget.RelativeLayout; import com.google.android.gms.cast.CastDevice; import com.google.android.gms.common.api.GoogleApiClient; import com.kaltura.playersdk.cast.KRouterManager; import com.kaltura.playersdk.casting.KCastRouterManager; import com.kaltura.playersdk.casting.KRouterInfo; import com.kaltura.playersdk.events.KPEventListener; import com.kaltura.playersdk.events.KPlayerState; import com.kaltura.playersdk.helpers.CacheManager; import com.kaltura.playersdk.helpers.KStringUtilities; import com.kaltura.playersdk.players.KPlayerController; import com.kaltura.playersdk.players.KPlayerListener; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.Method; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Set; public class PlayerViewController extends RelativeLayout implements KControlsView.KControlsViewClient, KRouterManager.KRouterManagerListener, KPlayerListener { public static String TAG = "PlayerViewController"; private KPlayerController playerController; public KControlsView mWebView = null; private double mCurSec; private Activity mActivity; // private OnShareListener mShareListener; private JSONObject nativeActionParams; private KPPlayerConfig mConfig; private String mIframeUrl = null; private boolean mWvMinimized = false; private int newWidth, newHeight; private boolean mIsJsCallReadyRegistration = false; private Set<ReadyEventListener> mCallBackReadyRegistrations; private HashMap<String, ArrayList<HashMap<String, EventListener>>> mPlayerEventsHash; private HashMap<String, EvaluateListener> mPlayerEvaluatedHash; private Set<KPEventListener> eventListeners; private SourceURLProvider mCustomSourceURLProvider; private boolean isFullScreen = false; private KRouterManager routerManager; /// KCastKalturaChannel Listener @Override public void onDeviceSelected(CastDevice castDeviceSelected) { if (castDeviceSelected == null) { mWebView.triggerEvent("chromecastDeviceDisConnected", null); playerController.removeCastPlayer(); } else { // playerController.startCasting(mActivity); mWebView.triggerEvent("onNativeRequestSessionSuccess", null); } } @Override public void onRouteAdded(boolean isAdded, KRouterInfo route) { if (getRouterManager().getAppListener() != null) { if (isAdded) { getRouterManager().getAppListener().addedCastDevice(route); } else { getRouterManager().getAppListener().removedCastDevice(route); } } } @Override public void onFoundDevices(final boolean didFound) { if (getRouterManager().shouldEnableKalturaCastButton()) { registerReadyEvent(new ReadyEventListener() { @Override public void handler() { mWebView.setKDPAttribute("chromecast", "visible", didFound ? "true" : "false"); } }); } if (getRouterManager().getAppListener() != null) { getRouterManager().getAppListener().didDetectCastDevices(didFound); } } @Override public void onShouldDisconnectCastDevice() { playerController.stopCasting(); mWebView.triggerEvent("chromecastDeviceDisConnected", null); if (getRouterManager().getAppListener() != null) { getRouterManager().getAppListener().castDeviceConnectionState(false); } } @Override public void onConnecting() { mWebView.triggerEvent("showConnectingMessage", null); } @Override public void onStartCasting(GoogleApiClient apiClient, CastDevice selectedDevice) { if (getRouterManager().getAppListener() != null) { getRouterManager().getAppListener().castDeviceConnectionState(true); } playerController.startCasting(apiClient); } // trigger timeupdate events public interface EventListener { void handler(String eventName, String params); } public interface ReadyEventListener { void handler(); } public interface EvaluateListener { void handler(String evaluateResponse); } public interface SourceURLProvider { String getURL(String entryId, String currentURL); } public PlayerViewController(Context context) { super(context); } public KCastRouterManager getKCastRouterManager() { if (routerManager == null) { routerManager = new KRouterManager(mActivity, this); } return routerManager; } private KRouterManager getRouterManager() { return (KRouterManager)getKCastRouterManager(); } public PlayerViewController(Context context, AttributeSet attrs) { super(context, attrs); } public PlayerViewController(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void initWithConfiguration(KPPlayerConfig configuration) { mConfig = configuration; setComponents(mConfig.getVideoURL()); } public void loadPlayerIntoActivity(Activity activity) { registerReadyEvent(new ReadyEventListener() { @Override public void handler() { if (eventListeners != null) { for (KPEventListener listener: eventListeners) { listener.onKPlayerStateChanged(PlayerViewController.this, KPlayerState.LOADED); } } } }); mActivity = activity; } public void addEventListener(KPEventListener listener) { if (listener != null) { if (eventListeners == null) { eventListeners = new HashSet<>(); } eventListeners.add(listener); } } public void removeEventListener(KPEventListener listener) { if (listener != null && eventListeners != null && eventListeners.contains(listener)) { eventListeners.remove(listener); } } public void setCustomSourceURLProvider(SourceURLProvider provider) { mCustomSourceURLProvider = provider; } private String getOverrideURL(String entryId, String currentURL) { if (mCustomSourceURLProvider != null) { String overrideURL = mCustomSourceURLProvider.getURL(entryId, currentURL); if (overrideURL != null) { return overrideURL; } } return currentURL; } /** * Release player's instance and save its last position for resuming later on. * This method should be called when the main activity is paused. */ public void releaseAndSavePosition() { playerController.removePlayer(); } /** * Recover from "releaseAndSavePosition", reload the player from previous position. * This method should be called when the main activity is resumed. */ public void resumePlayer() { if (playerController != null) { playerController.recoverPlayer(); } } public void removePlayer() { if (playerController != null) { playerController.destroy(); } if (eventListeners != null) { eventListeners = null; } } public void setActivity( Activity activity ) { mActivity = activity; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); } // public void setOnShareListener(OnShareListener listener) { // mShareListener = listener; private void setVolumeLevel(double percent) {//Itay AudioManager mgr = (AudioManager) mActivity.getSystemService(Context.AUDIO_SERVICE); if (percent > 0.01) { while (percent < 1.0) { percent *= 10; } } mgr.setStreamVolume(AudioManager.STREAM_MUSIC, (int) percent, 0); } @SuppressLint("NewApi") private Point getRealScreenSize(){ Display display = mActivity.getWindowManager().getDefaultDisplay(); int realWidth = 0; int realHeight = 0; if (Build.VERSION.SDK_INT >= 17){ //new pleasant way to get real metrics DisplayMetrics realMetrics = new DisplayMetrics(); display.getRealMetrics(realMetrics); realWidth = realMetrics.widthPixels; realHeight = realMetrics.heightPixels; } else { try { Method mGetRawH = Display.class.getMethod("getRawHeight"); Method mGetRawW = Display.class.getMethod("getRawWidth"); realWidth = (Integer) mGetRawW.invoke(display); realHeight = (Integer) mGetRawH.invoke(display); } catch (Exception e) { realWidth = display.getWidth(); realHeight = display.getHeight(); Log.e("Display Info", "Couldn't use reflection to get the real display metrics."); } } return new Point(realWidth,realHeight); } /** * Sets the player's dimensions. Should be called for any player redraw * (for example, in screen rotation, if supported by the main activity) * @param width player's width * @param height player's height * @param xPadding player's X position * @param yPadding player's Y position */ public void setPlayerViewDimensions(int width, int height, int xPadding, int yPadding) { setPadding(xPadding, yPadding, 0, 0); newWidth = width + xPadding; newHeight = height + yPadding; ViewGroup.LayoutParams lp = getLayoutParams(); if ( lp == null ) { lp = new ViewGroup.LayoutParams( newWidth, newHeight ); } else { lp.width = newWidth; lp.height = newHeight; } this.setLayoutParams(lp); for ( int i = 0; i < this.getChildCount(); i++ ) { View v = getChildAt(i); if( v == playerController.getPlayer() ) { continue; } ViewGroup.LayoutParams vlp = v.getLayoutParams(); vlp.width = newWidth; if ( (!mWvMinimized || !v.equals( mWebView)) ) { vlp.height = newHeight; } updateViewLayout(v, vlp); } if(mWebView != null) { // mWebView.loadUrl("javascript:android.onData(NativeBridge.videoPlayer.getControlBarHeight())"); mWebView.fetchControlsBarHeight(new KControlsView.ControlsBarHeightFetcher() { @Override public void fetchHeight(int controlBarHeight) { if ( playerController.getPlayer() != null && playerController.getPlayer() instanceof FrameLayout && ((FrameLayout)playerController.getPlayer()).getParent() == PlayerViewController.this ) { LayoutParams wvLp = (LayoutParams) ((View) playerController.getPlayer()).getLayoutParams(); if (getPaddingLeft() == 0 && getPaddingTop() == 0) { wvLp.addRule(CENTER_IN_PARENT); } else { wvLp.addRule(CENTER_IN_PARENT, 0); } float scale = mActivity.getResources().getDisplayMetrics().density; controlBarHeight = (int) (controlBarHeight * scale + 0.5f); wvLp.height = newHeight - controlBarHeight; wvLp.width = newWidth; wvLp.addRule(RelativeLayout.ALIGN_PARENT_TOP); final LayoutParams lp = wvLp; mActivity.runOnUiThread(new Runnable() { @Override public void run() { updateViewLayout((View) playerController.getPlayer(), lp); invalidate(); } }); } } }); } invalidate(); } /** * Sets the player's dimensions. Should be called for any player redraw * (for example, in screen rotation, if supported by the main activity) * Player's X and Y position will be 0 * @param width player's width * @param height player's height */ public void setPlayerViewDimensions(int width, int height) { setPlayerViewDimensions(width, height, 0, 0); } private void setChromecastVisiblity() { // mWebView.setKDPAttribute("chromecast", "visible", ChromecastHandler.routeInfos.size() > 0 ? "true" : "false"); } /* * Build player URL and load it to player view * @param requestDataSource - RequestDataSource object */ /** * Build player URL and load it to player view * param iFrameUrl- String url */ public void setComponents(String iframeUrl) { if(mWebView == null) { mWebView = new KControlsView(getContext().getApplicationContext()); mWebView.setKControlsViewClient(this); mCurSec = 0; ViewGroup.LayoutParams currLP = getLayoutParams(); LayoutParams wvLp = new LayoutParams(currLP.width, currLP.height); this.playerController = new KPlayerController(this); this.addView(mWebView, wvLp); } if( mIframeUrl == null || !mIframeUrl.equals(iframeUrl) ) { mIframeUrl = iframeUrl; Uri uri = Uri.parse(iframeUrl); if (mConfig.getCacheSize() > 0) { CacheManager.getInstance().setHost(uri.getHost()); CacheManager.getInstance().setCacheSize(mConfig.getCacheSize()); mWebView.setCacheManager(CacheManager.getInstance()); } mWebView.loadUrl(iframeUrl); } } /** * create PlayerView / CastPlayer instance according to cast status */ private void replacePlayerViewChild( View newChild, View oldChild ) { if ( oldChild.getParent().equals( this ) ) { this.removeView( oldChild ); } if ( this.getChildCount() > 1 ) { //last child is the controls webview this.addView( newChild , this.getChildCount() -1, oldChild.getLayoutParams() ); } } /** * slides with animation according the given values * * @param x * x offset to slide * @param duration * animation time in milliseconds */ public void slideView(int x, int duration) { this.animate().xBy(x).setDuration(duration) .setInterpolator(new BounceInterpolator()); } // VideoPlayerInterface methods // public boolean isPlaying() { // return (playerController.getPlayer() != null && playerController.getPlayer().isPlaying()); /** * * @return duration in seconds */ public double getDurationSec() { double duration = 0; if (playerController != null) { duration = playerController.getDuration(); } return duration; } public String getVideoUrl() { String url = null; if (playerController != null) url = playerController.getSrc(); return url; } public double getCurrentPlaybackTime() { if (playerController != null) { return playerController.getCurrentPlaybackTime(); } return 0.0; } // Kaltura Player external API public void sendNotification(String noteName, JSONObject noteBody) { notifyKPlayer("sendNotification", new String[]{noteName, noteBody.toString()}); } public void setKDPAttribute(String hostName, String propName, Object value) { notifyKPlayer("setKDPAttribute", new Object[]{hostName, propName, value}); } /** * call js function on NativeBridge.videoPlayer * * @param action * function name * @param eventValues * function arguments */ private void notifyKPlayer(final String action, final Object[] eventValues) { mActivity.runOnUiThread(new Runnable() { @Override public void run() { String values = ""; if (eventValues != null) { for (int i = 0; i < eventValues.length; i++) { if (eventValues[i] instanceof String) { values += "'" + eventValues[i] + "'"; } else { values += eventValues[i].toString(); } if (i < eventValues.length - 1) { values += ", "; } } // values = TextUtils.join("', '", eventValues); } if (mWebView != null) { Log.d(TAG, "NotifyKplayer: " + values); mWebView.loadUrl("javascript:NativeBridge.videoPlayer." + action + "(" + values + ");"); } } }); } @Override public void handleHtml5LibCall(String functionName, int callbackId, String args) { Method bridgeMethod = KStringUtilities.isMethodImplemented(this, functionName); Object object = this; if (bridgeMethod == null) { KPlayerController.KPlayer player = this.playerController.getPlayer(); bridgeMethod = KStringUtilities.isMethodImplemented(player, functionName); object = player; } if (bridgeMethod != null) { try { if (args == null) { bridgeMethod.invoke(object); } else { bridgeMethod.invoke(object, args); } } catch (Exception e) { e.printStackTrace(); } } } @Override public void openURL(String url) { } @Override public void eventWithValue(KPlayerController.KPlayer player, String eventName, String eventValue) { KStringUtilities event = new KStringUtilities(eventName); if (eventListeners != null) { for (KPEventListener listener : eventListeners) { if (KPlayerState.getStateForEventName(eventName) != null) { listener.onKPlayerStateChanged(this, KPlayerState.getStateForEventName(eventName)); } else if (event.isTimeUpdate()) { listener.onKPlayerPlayheadUpdate(this, Float.parseFloat(eventValue)); } } } this.mWebView.triggerEvent(eventName, eventValue); } @Override public void eventWithJSON(KPlayerController.KPlayer player, String eventName, String jsonValue) { this.mWebView.triggerEventWithJSON(eventName, jsonValue); } @Override public void contentCompleted(KPlayerController.KPlayer currentPlayer) { if (eventListeners != null) { for (KPEventListener listener: eventListeners) { listener.onKPlayerStateChanged(this, KPlayerState.ENDED); } } } private void play() { playerController.play(); } private void pause() { playerController.pause(); } public void registerReadyEvent(ReadyEventListener listener) { if (mIsJsCallReadyRegistration) { listener.handler(); } else { if (mCallBackReadyRegistrations == null && listener != null) { mCallBackReadyRegistrations = new HashSet<>(); } mCallBackReadyRegistrations.add(listener); } } public void addKPlayerEventListener(final String event, final String eventID, final EventListener listener) { this.registerReadyEvent(new ReadyEventListener() { @Override public void handler() { if (mPlayerEventsHash == null) { mPlayerEventsHash = new HashMap<String, ArrayList<HashMap<String,EventListener>>>(); } ArrayList<HashMap<String, EventListener>> listenerArr = (ArrayList<HashMap<String, EventListener>>)mPlayerEventsHash.get(event); if (listenerArr == null) { listenerArr = new ArrayList<HashMap<String, EventListener>>(); } HashMap<String, EventListener> addedEvent = new HashMap<String, EventListener>(); addedEvent.put(eventID, listener); listenerArr.add(addedEvent); mPlayerEventsHash.put(event, listenerArr); if (listenerArr.size() == 1 && !KStringUtilities.isToggleFullScreen(event)) { mWebView.addEventListener(event); } } }); } public void removeKPlayerEventListener(String event,String eventID) { ArrayList<HashMap<String, EventListener>> listenerArr = mPlayerEventsHash.get(event); if (listenerArr == null || listenerArr.size() == 0) { return; } ArrayList<HashMap<String, EventListener>> temp = new ArrayList<HashMap<String, EventListener>>(listenerArr); for (HashMap<String, EventListener> hash: temp) { if (hash.keySet().toArray()[hash.keySet().size() - 1].equals(eventID)) { listenerArr.remove(hash); } } if (listenerArr.size() == 0) { listenerArr = null; if (!KStringUtilities.isToggleFullScreen(event)) { mWebView.removeEventListener(event); } } } public void asyncEvaluate(String expression, String expressionID, EvaluateListener evaluateListener) { if (mPlayerEvaluatedHash == null) { mPlayerEvaluatedHash = new HashMap<String, EvaluateListener>(); } mPlayerEvaluatedHash.put(expressionID, evaluateListener); mWebView.evaluate(expression, expressionID); } public void sendNotification(String notificationName, String params) { if (notificationName == null) { notificationName = "null"; } mWebView.sendNotification(notificationName, params); } public void setKDPAttribute(String pluginName, String propertyName, String value) { mWebView.setKDPAttribute(pluginName, propertyName, value); } public void triggerEvent(String event, String value) { mWebView.triggerEvent(event, value); } /// Bridge methods private void setAttribute(String argsString) { String[] args = KStringUtilities.fetchArgs(argsString); if (args != null && args.length == 2) { String attributeName = args[0]; String attributeValue = args[1]; KStringUtilities.Attribute attribute = KStringUtilities.attributeEnumFromString(attributeName); if (attribute == null) { return; } switch (attribute) { case src: // attributeValue is the selected source -- allow override. attributeValue = getOverrideURL(mConfig.getEntryId(), attributeValue); this.playerController.setSrc(attributeValue); break; case currentTime: if (eventListeners != null) { for (KPEventListener listener: eventListeners) { listener.onKPlayerStateChanged(this, KPlayerState.SEEKING); } } this.playerController.setCurrentPlaybackTime(Float.parseFloat(attributeValue)); break; case visible: this.triggerEvent("visible", attributeValue); break; case licenseUri: this.playerController.setLicenseUri(attributeValue); break; case nativeAction: try { this.nativeActionParams = new JSONObject(attributeValue); } catch (JSONException e) { e.printStackTrace(); } break; case language: this.playerController.setLocale(attributeValue); break; case doubleClickRequestAds: playerController.initIMA(attributeValue, mActivity); break; case goLive: ((LiveStreamInterface)playerController.getPlayer()).switchToLive(); break; case chromecastAppId: // getRouterManager().initialize(attributeValue, mActivity); getRouterManager().initialize(attributeValue); Log.d("chromecast.initialize", attributeValue); break; } } } private void switchFlavor(String index) { int flavorIndex = -1; try { flavorIndex = Integer.parseInt(index); } catch (NumberFormatException e) { Log.e(TAG, "switchFlavor failed parsing index, ignoring request" + index); return; } KPlayerController.KPlayer player = playerController.getPlayer(); if (player instanceof QualityTracksInterface) { QualityTracksInterface adaptivePlayer = (QualityTracksInterface) player; adaptivePlayer.switchQualityTrack(flavorIndex); } } private void notifyJsReady() { mIsJsCallReadyRegistration = true; if (mCallBackReadyRegistrations != null) { ArrayList<ReadyEventListener> temp = new ArrayList<ReadyEventListener>(mCallBackReadyRegistrations); for (ReadyEventListener listener: temp) { listener.handler(); mCallBackReadyRegistrations.remove(listener); } temp = null; mCallBackReadyRegistrations = null; } } private void notifyKPlayerEvent(String args) { String[] arguments = KStringUtilities.fetchArgs(args); if (arguments.length == 2) { String eventName = arguments[0]; String params = arguments[1]; ArrayList<HashMap<String, EventListener>> listenerArr = mPlayerEventsHash.get(eventName); if (listenerArr != null) { for (HashMap<String, EventListener> hash: listenerArr) { ((EventListener)hash.values().toArray()[hash.values().size() - 1]).handler(eventName, params); } } } } private void notifyKPlayerEvaluated(String args) { String[] arguments = KStringUtilities.fetchArgs(args); if (arguments.length == 2) { EvaluateListener listener = mPlayerEvaluatedHash.get(arguments[0]); if (listener != null) { listener.handler(arguments[1]); } } else { Log.d("AsyncEvaluate Error", "Missing evaluate params"); } } private void notifyLayoutReady() { setChromecastVisiblity(); } private void toggleFullscreen() { isFullScreen = !isFullScreen; if (eventListeners != null) { for (KPEventListener listener : eventListeners) { listener.onKPlayerFullScreenToggeled(this, isFullScreen); } } } private void showChromecastDeviceList() { if(!mActivity.isFinishing() && getRouterManager().getAppListener() != null) { getRouterManager().getAppListener().castButtonClicked(); } } private void sendCCRecieverMessage(String args) { String decodeArgs = null; JSONArray jsonArgs = null; try { decodeArgs = URLDecoder.decode(args, "UTF-8"); Log.d(getClass().getSimpleName(), "sendCCRecieverMessage : " + decodeArgs); jsonArgs = new JSONArray(decodeArgs); getRouterManager().sendMessage(jsonArgs.getString(0), jsonArgs.getString(1)); } catch (Exception e) { e.printStackTrace(); } } private void loadCCMedia() { // getRouterManager().sendMessage(jsonArgs.getString(0), jsonArgs.getString(1)); } private void bindPlayerEvents() { } private void doNativeAction(String params) { Log.d("NativeAction", params); try { JSONObject actionObj = new JSONObject(params); if (actionObj.get("actionType").equals("share")) { share(actionObj); } } catch (JSONException e) { e.printStackTrace(); } } // Native actions private void share(JSONObject shareParams) { // if(mShareListener != null){ // try { // String videoUrl = (String)shareParams.get("sharedLink"); // String videoName = (String)shareParams.get("videoName"); // ShareManager.SharingType type = ShareStrategyFactory.getType(shareParams); // if (!mShareListener.onShare(videoUrl, type, videoName)){ // ShareManager.share(shareParams, mActivity); // } catch (JSONException e) { // e.printStackTrace(); // }else { // ShareManager.share(shareParams, mActivity); } }
package org.mwdb.math.matrix.operation; public class Gaussian1D { public static double getCovariance(double sum, double sumSq, int total){ return (sumSq-(sum*sum)/total)/(total-1); } public static double getDensity(double sum, double sumSq, int total, double feature){ if(total<2){ return 0; } double avg=sum/total; double cov=getCovariance(sum,sumSq,total); return 1/Math.sqrt(2*Math.PI*cov)*Math.exp(-(feature-avg)*(feature-avg)/(2*cov)); } public static double[] getDensity(double sum, double sumSq, int total, double[] feature){ if(total<2){ return null; } double avg=sum/total; double cov=getCovariance(sum,sumSq,total); double exp=1/Math.sqrt(2*Math.PI*cov); double[] proba= new double[feature.length]; for(int i=0;i<feature.length;i++){ proba[i]=exp*Math.exp(-(feature[i]-avg)*(feature[i]-avg)/(2*cov)); } return proba; } }
package SeSim; import java.util.*; import java.util.concurrent.*; import SeSim.Order.OrderStatus; public class Exchange extends Thread { // Class to describe an executed order public class Quote { double bid; double bid_size; double ask; double ask_size; public double price; public long size; public long time; } // QuoteReceiver has to be implemented by objects that wants // to receive quote updates public interface QuoteReceiver { void UpdateQuote(Quote q); } // Here we store the list of quote receivers TreeSet<QuoteReceiver> qrlist = new TreeSet<>(); public void AddQuoteReceiver(QuoteReceiver qr) { qrlist.add(qr); } // send updated quotes to all quote receivers void UpdateQuoteReceivers(Quote q) { Iterator<QuoteReceiver> i = qrlist.iterator(); while (i.hasNext()) { i.next().UpdateQuote(q); } } public ArrayList<Quote> quoteHistory = new ArrayList<>(); // long time = 0; double price = 12.9; long orderid = 1; double lastprice = 300.0; long lastsize; // Order orderlist[]; TreeSet<BuyOrder> bid = new TreeSet<>(); TreeSet<SellOrder> ask = new TreeSet<>(); private final Semaphore available = new Semaphore(1, true); private void Lock() { try { available.acquire(); } catch (InterruptedException e) { System.out.println("Interrupted"); } } private void Unlock() { available.release(); } public void print_current() { BuyOrder b; SellOrder a; //String bid; if (bid.isEmpty()) { b = new BuyOrder(); b.limit = -1; b.size = 0; } else { b = bid.first(); } if (ask.isEmpty()) { a = new SellOrder(); a.limit = -1; a.size = 0; } else { a = ask.first(); } Logger.info( String.format("BID: %s(%s) LAST: %.2f(%d) ASK: %s(%s)\n", b.format_limit(), b.format_size(), lastprice, lastsize, a.format_limit(), a.format_size()) ); } public void TransferMoney(Account src, Account dst, double money) { src.money -= money; dst.money += money; } public void CancelOrder(Order o) { Lock(); // System.out.println("Cancel BuyOrder"); bid.remove(o); ask.remove(o); o.status = OrderStatus.canceled; Unlock(); } public void OrderMatching() { while (true) { if (bid.isEmpty() || ask.isEmpty()) { // nothing to do return; } BuyOrder b = bid.first(); SellOrder a = ask.first(); if (a.size == 0) { // This order is fully executed, remove a.account.orderpending = false; a.status = OrderStatus.executed; ask.pollFirst(); continue; } if (b.size == 0) { b.account.orderpending = false; b.status = OrderStatus.executed; bid.pollFirst(); continue; } if (b.limit < a.limit) { // no match, nothing to do return; } if (b.limit >= a.limit) { double price; if (b.id < a.id) { price = b.limit; } else { price = a.limit; } long size = 0; if (b.size >= a.size) { size = a.size; } else { size = b.size; } b.account.Buy(a.account, size, price); b.size -= size; a.size -= size; lastprice = price; lastsize = size; Quote q = new Quote(); q.size = size; q.price = price; q.time = System.currentTimeMillis(); this.UpdateQuoteReceivers(q); //quoteHistory.add(q); continue; } return; } } public void ExecuteOrder(BuyOrder o) { // SellOrder op = ask.peek(); } public void SendOrder(SellOrder o) { // System.out.println("EX Sellorder"); Lock(); o.timestamp = System.currentTimeMillis(); o.id = orderid++; ask.add(o); Unlock(); Lock(); OrderMatching(); Unlock(); } public void SendOrder(BuyOrder o) { //System.out.println("EX Buyorder"); Lock(); o.timestamp = System.currentTimeMillis(); o.id = orderid++; bid.add(o); Unlock(); Lock(); OrderMatching(); Unlock(); } /* * public void SendOrder(Order o){ * * * if ( o.getClass() == BuyOrder.class){ bid.add((BuyOrder)o); } * * if ( o.getClass() == SellOrder.class){ ask.add((SellOrder)o); } * * } */ public double getlastprice() { /* * SellOrder so = new SellOrder(); so.limit=1000.0; so.size=500; * SendOrder(so); * * BuyOrder bo = new BuyOrder(); bo.limit=1001.0; bo.size=300; * SendOrder(bo); */ return price; } public double sendOrder(Account o) { return 0.7; } public void run() { while (true) { try { sleep(1500); } catch (InterruptedException e) { System.out.println("Interrupted"); } print_current(); } } }
package quadratischeFunktionen; import java.awt.geom.Point2D; /** * @author Thomas Kirz, Sebastian Vogt * @version 1.0 22.12.2015 */ public class QuadraticFunction { // Test //Suggestion for x-values: //private int xquantity; (result of user input) //private double[] fx = new double[xquantity]; //private double xstep (result of user input) //privte double xstart (result of user input) //private double x = xstart //for(int i = 0; i <= xquantity; i++){ // fx[i] = a * (Math.pow(x, 2)) + b * x + c (the values of the array fx are the program's output) // x = x + xstep private double a, b, c, d, e; /** * The vertex of the function */ Point2D.Double vertex; public QuadraticFunction(double a, double b, double c) throws IllegalArgumentException { if (a == 0) { throw new IllegalArgumentException("a must not be 0!"); } this.a = a; this.b = b; this.c = c; generateVertex(); } /** * @return the parameter a of the function */ public double getA() { return a; } /** * @return the parameter b of the function */ public double getB() { return b; } /** * @return the parameter c of the function */ public double getC() { return c; } /** * @return the parameter d of the function */ public double getD() { return d; } /** * @return the parameter e of the function */ public double getE() { return e; } /** * Calculates y of the function for a given x * * @return y */ public double getImageOf(double x) { return a * x * x + b * x + c; } /** * Gets the vertex of the function as a Point2D * * @return the vertex */ public Point2D.Double getVertex() { return vertex; } private void generateVertex() { d = b / (2 * a); e = (4 * a * c - b * b) / (4 * a); vertex = new Point2D.Double(-d, e); } public String toNormalString() { String part1, part2, part3; part1 = a + "x²"; if (b > 0) { part2 = " + " + b + "x"; } else if (b < 0) { part2 = " - " + -b + "x"; } else { part2 = ""; } if (c > 0) { part3 = " + " + c; } else if (c < 0) { part3 = " - " + -c; } else { part3 = ""; } return part1 + part2 + part3; } public String toVertexString() { String part1, part2; if (d > 0) { part1 = a + "(x + " + d + ")²"; } else if (d < 0) { part1 = a + "(x - " + -d + ")²"; } else { part1 = a + "x²"; } if (e > 0) { part2 = " + " + e; } else if (e < 0) { part2 = " - " + -e; } else { part2 = ""; } return part1 + part2; } }
package info.tregmine.commands; import java.util.Date; import org.bukkit.ChatColor; import org.bukkit.Server; import info.tregmine.Tregmine; import info.tregmine.api.TregminePlayer; import info.tregmine.api.UUIDFetcher; import info.tregmine.database.DAOException; import info.tregmine.database.IContext; import info.tregmine.database.ILogDAO; import net.md_5.bungee.api.chat.TextComponent; public class SeenCommand extends AbstractCommand { public SeenCommand(Tregmine tregmine) { super(tregmine, "seen"); } @Override public boolean handleOther(Server server, String[] args) { if (args.length != 1) { return false; } TregminePlayer target = tregmine.getPlayerOffline(UUIDFetcher.getUUIDOf(args[0])); if (target == null) { server.getConsoleSender().sendMessage("Could not find player: " + args[0]); return true; } try (IContext ctx = tregmine.createContext()) { ILogDAO logDAO = ctx.getLogDAO(); Date seen = logDAO.getLastSeen(target); server.getConsoleSender().sendMessage(args[0] + " was last seen on: " + seen); } catch (DAOException e) { throw new RuntimeException(e); } return true; } @Override public boolean handlePlayer(TregminePlayer player, String[] args) { if (args.length != 1) { return false; } TregminePlayer target = null;; try{ target = tregmine.getPlayerOffline(UUIDFetcher.getUUIDOf(args[0])); }catch(NullPointerException e){ player.sendSpigotMessage(new TextComponent(ChatColor.RED + "That player was not found, check the spelling and try again.")); return true; } if (target == null) { player.sendStringMessage(ChatColor.RED + "Could not find player: " + ChatColor.YELLOW + args[0]); return true; } try (IContext ctx = tregmine.createContext()) { ILogDAO logDAO = ctx.getLogDAO(); Date seen = logDAO.getLastSeen(target); if (seen != null) { player.sendSpigotMessage(new TextComponent(ChatColor.GREEN + ""), target.getChatName(), new TextComponent(ChatColor.YELLOW + " was last seen on: " + ChatColor.AQUA + seen)); } else { player.sendSpigotMessage(new TextComponent(ChatColor.GREEN + ""), target.getChatName(), new TextComponent(ChatColor.YELLOW + " hasn't been seen for a while.")); } } catch (DAOException e) { throw new RuntimeException(e); } return true; } }
package io.loaders.json; import java.util.ArrayList; import java.util.List; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import db.MonomersDB; import db.PolymersDB; import model.Monomer; import model.Polymer; import model.graph.MonomerGraph; import model.graph.MonomerGraph.MonomerLinks; public class PolymersJsonLoader extends AbstractJsonLoader<PolymersDB, Polymer> { private MonomersDB monos; public PolymersJsonLoader(MonomersDB monos) { this.monos = monos; } public PolymersJsonLoader(MonomersDB monos, boolean coordinates) { this.monos = monos; Polymer.setComputeCoordinates(true); } @Override protected PolymersDB createDB() { return new PolymersDB(); } @SuppressWarnings("unchecked") @Override protected Polymer objectFromJson(JSONObject obj) { if ("".equals((String)obj.get("smiles"))) { System.err.println("No smiles for " + ((String)obj.get("name"))); return null; } else if (((String)obj.get("smiles")).contains(".")) { System.err.println("The smiles for " + ((String)obj.get("name")) + " contains character '.'"); System.err.println("The '.' means that the smiles is composed of more than one molecule."); System.err.println("Please split the smiles in two distinct smiles."); return null; } JSONArray verticies; JSONArray edges; if (obj.containsKey("graph")) { JSONObject graph = (JSONObject)obj.get("graph"); // Parse the s2m graph format verticies = (JSONArray)graph.get("V"); edges = (JSONArray)graph.get("E"); } else if (obj.containsKey("structure")) { verticies = new JSONArray(); edges = new JSONArray(); // Parse the Norine graph format String text = (String) ((JSONObject)obj.get("structure")).get("graph"); String[] split = text.split("@"); // The verticies verticies = new JSONArray(); for (String val : split[0].split(",")) verticies.add(val); // The edges edges = new JSONArray(); for (int idx=1 ; idx<split.length ; idx++) { String[] links = split[idx].split(","); for (String val : links) { int link_to = new Integer(val); if (idx-1 < link_to) { JSONArray edge = new JSONArray(); edge.add(idx-1); edge.add(link_to); edges.add(edge); } } } } else { verticies = new JSONArray(); edges = new JSONArray(); } Monomer[] monomers = new Monomer[verticies.size()]; for (int i=0 ; i<monomers.length ; i++) { String name = (String) verticies.get(i); try { monomers[i] = this.monos.contains(name) ? this.monos.getObject(name) : new Monomer(name, "", ""); } catch (NullPointerException e) { e.printStackTrace(); } } // Create the graph in memory MonomerGraph g = new MonomerGraph(monomers); for (Object o : edges) { JSONArray link = (JSONArray)o; g.createLink ( ((Number)link.get(0)).intValue(), ((Number)link.get(1)).intValue() ); } int id = 0; if (obj.get("id") instanceof String) { String sid = (String) obj.get("id"); id = sid.startsWith("NOR") ? new Integer(sid.substring(3)) : sid.hashCode(); } else id = ((Number)obj.get("id")).intValue(); Polymer pep = new Polymer( id, (String)obj.get("name"), (String)obj.get("smiles"), monomers ); pep.setGraph(g); return pep; } @SuppressWarnings("unchecked") public JSONObject graphToJson(MonomerGraph g) { JSONObject jso = new JSONObject(); JSONArray nodes = new JSONArray(); for (Monomer m : g.nodes) { nodes.add(m.getCode()); } jso.put("V", nodes); JSONArray edges = new JSONArray(); List<MonomerLinks> added = new ArrayList<>(g.links.size()); for (MonomerLinks ml : g.links) { boolean contains = false; for (MonomerLinks old : added) if ((old.mono1 == ml.mono1 && old.mono2 == ml.mono2) || (old.mono2 == ml.mono1 && old.mono1 == ml.mono2)) { contains = true; break; } if (!contains) { added.add(ml); JSONArray edge = new JSONArray(); edge.add(ml.mono1); edge.add(ml.mono2); edges.add(edge); } } jso.put("E", edges); return jso; } @SuppressWarnings("unchecked") @Override protected JSONArray getArrayOfElements(Polymer pep) { JSONObject jso = new JSONObject(); jso.put("id", new Integer(pep.getId())); jso.put("name", pep.getName()); jso.put("smiles", pep.getSmiles()); jso.put("graph", this.graphToJson(pep.getGraph())); JSONArray array = new JSONArray(); array.add(jso); return array; } @Override protected String getObjectId(Polymer tObj) { return tObj.getId(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jade.imtp.leap.nio; //#J2ME_EXCLUDE_FILE import jade.imtp.leap.ICPException; import jade.imtp.leap.SSLHelper; import java.io.IOException; import java.nio.ByteBuffer; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLEngineResult.HandshakeStatus; import javax.net.ssl.SSLEngineResult.Status; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; /** * helper class that holds the ByteBuffers, SSLEngine and other Objects that deal with the non static part of the * ssl/nio handshaking/input/output. The contained SSLEngine is hidden to apps, because this helper takes on the responsibility * of dealing with concurrency issues * * @author eduard */ public final class SSLEngineHelper implements BufferTransformer { public static final ByteBuffer EMPTY_BUFFER = NIOHelper.EMPTY_BUFFER; /** * todo why 5k?? configurable? */ public static final int INCREASE_SIZE = 5120; private SSLEngine ssle = null; private ByteBuffer wrapData; private ByteBuffer unwrapData; private ByteBuffer sendData; private NIOJICPConnection connection = null; private static Logger log = Logger.getLogger(SSLEngineHelper.class.getName()); /** * Creates and initializes ByteBuffers and SSLEngine necessary for ssl/nio. * @see NIOHelper * @see SSLHelper * @param host provides a hint for optimization * @param port provides a hint for optimization * @param connection the connection that will use this helper * @throws ICPException */ public SSLEngineHelper(String host, int port, NIOJICPConnection connection) throws ICPException { SSLContext context = SSLHelper.createContext(); // get a SSLEngine, use host and port for optimization ssle = context.createSSLEngine(host, port); ssle.setUseClientMode(false); ssle.setNeedClientAuth(SSLHelper.needAuth()); if (!SSLHelper.needAuth()) { // if we don't do authentication we restrict our ssl connection to use specific cipher suites ssle.setEnabledCipherSuites(SSLHelper.getSupportedKeys()); } SSLSession session = ssle.getSession(); // TODO prevent buffer overflow, why *2? unwrapData = ByteBuffer.allocateDirect(session.getApplicationBufferSize() + 1500); wrapData = ByteBuffer.allocateDirect(session.getPacketBufferSize()); sendData = ByteBuffer.allocateDirect(wrapData.capacity());; this.connection = connection; } /** * executes a wrap on the SSLEngine, prevents threads from calling this method concurrently * @param source * @return * @throws SSLException */ private SSLEngineResult encode(ByteBuffer source) throws SSLException { return ssle.wrap(source, wrapData); } /** * runs all background handshaking tasks, blocks until these are finished * @return the new handshake status after finishing the background tasks */ private SSLEngineResult.HandshakeStatus runHandshakeTasks() { Runnable task = null; while ((task = ssle.getDelegatedTask()) != null) { task.run(); } // re evaluate handshake status return ssle.getHandshakeStatus(); } /** * closes the SSLEngine, tries to send a ssl close message * @throws IOException */ public void close() throws IOException { /* * try to nicely terminate ssl connection * 1 closeoutbound * 2 send ssl close message * 3 wait for client to also send close message * 4 close inbound * 5 don't let all this frustrate the channel closing */ ssle.closeOutbound(); sendSSLClose(); ssle.closeInbound(); } private void sendSSLClose() { try { // try to send close message while (!ssle.isOutboundDone()) { wrapAndSend(); } } catch (IOException e) { log.log(Level.FINE, "unable to send ssl close packet", e); } } private final int writeToChannel(ByteBuffer b) throws IOException { int m = b.remaining(); int n = connection.writeToChannel(b); if (n != m) { throw new IOException("should write " + m + ", written " + n); } return n; } private String getRemoteHost() { return connection.getRemoteHost(); } private SSLEngineResult unwrapData(ByteBuffer socketData) throws SSLException { SSLEngineResult result = null; do { try { // Unwrap (decode) the next SSL block. Unwrapped application data (if any) are put into the unwrapData buffer result = ssle.unwrap(socketData, unwrapData); if (log.isLoggable(Level.FINE)) log.fine("Decoded " + result.bytesConsumed() + " bytes; Produced "+result.bytesProduced()+" application-data bytes ["+getRemoteHost()+"]"); } catch (SSLException e) { // send close message to the client and re-throw the exception log.log(Level.WARNING, "Unwrap failure ["+getRemoteHost()+"]", e); try { close(); } catch(IOException ex) {} throw e; } } while (result.getStatus().equals(Status.OK) && result.getHandshakeStatus().equals(HandshakeStatus.NEED_UNWRAP)); return result; } private void checkStatusAfterHandshakeTasks(SSLEngineResult.HandshakeStatus handshakeStatus) throws SSLException, IOException { if (handshakeStatus.equals(HandshakeStatus.FINISHED)) { log.warning("Unexpected FINISHED SSL handshake status after execution of handshake tasks ["+getRemoteHost()+"]"); } else if (handshakeStatus.equals(HandshakeStatus.NEED_TASK)) { log.warning("Unexpected NEED_TASK SSL handshake status after execution of handshake tasks ["+getRemoteHost()+"]"); } else if (handshakeStatus.equals(HandshakeStatus.NEED_UNWRAP)) { if (log.isLoggable(Level.FINE)) log.fine("Need more data to proceed with Handshake ["+getRemoteHost()+"]"); } else if (handshakeStatus.equals(HandshakeStatus.NEED_WRAP)) { if (log.isLoggable(Level.FINE)) log.fine("Send back Handshake data after task execution ["+getRemoteHost()+"]"); wrapAndSend(); } else if (handshakeStatus.equals(HandshakeStatus.NOT_HANDSHAKING)) { log.warning("Unexpected NOT_HANDSHAKING SSL handshake status after execution of handshake tasks ["+getRemoteHost()+"]"); } } /** * First initialize your {@link SSLEngineHelper} by clearing its buffers and filling {@link SSLEngineHelper#getSocketData() } * with data from a connection. After this this method possibly recursively deals with handshaking and unwrapping * application data. The supplied appBuffer argument will be filled remaining unwrapped data will stay in the * {@link SSLEngineHelper#getUnwrapData() }. * @return the number of bytes available in the unwrapBuffer * @throws IOException */ /** * @return the number of bytes available in the unwrapBuffer * @throws IOException */ private synchronized int decrypt(ByteBuffer socketData) throws SSLException, IOException { if (log.isLoggable(Level.FINE)) { log.fine("Decrypt incoming data: remaining = " + socketData.remaining() + ", position = " + socketData.position() + ", limit = " + socketData.limit() + " [" + getRemoteHost() + "]"); } SSLEngineResult result = unwrapData(socketData); if (log.isLoggable(Level.FINE)) { log.fine("Checking handshake result [" + getRemoteHost() + "]"); } int n = 0; SSLEngineResult.Status status = result.getStatus(); SSLEngineResult.HandshakeStatus handshakeStatus = result.getHandshakeStatus(); boolean recurse = true; if (status.equals(Status.OK)) { if (handshakeStatus.equals(HandshakeStatus.NOT_HANDSHAKING)) { // Application data n = result.bytesProduced(); } else if (handshakeStatus.equals(HandshakeStatus.FINISHED)) { // Handshake completed if (log.isLoggable(Level.FINE)) { log.fine("Handshake finished [" + getRemoteHost() + "]"); } } else if (handshakeStatus.equals(HandshakeStatus.NEED_TASK)) { // The SSLEngine requires one or more "tasks" to be executed before the handshake can proceed --> // Run them and then go on taking into account the new handshake-status if (log.isLoggable(Level.FINE)) { log.fine("Activate Handshake task [" + getRemoteHost() + "]"); } handshakeStatus = runHandshakeTasks(); checkStatusAfterHandshakeTasks(handshakeStatus); } else if (handshakeStatus.equals(HandshakeStatus.NEED_UNWRAP)) { // This should never happen since we cannot exit the unwrapData() method with status == OK and handshakeStatus == NEED_UNWRAP throw new SSLException("Unexpected NEED_UNWRAP SSL handshake status! [" + getRemoteHost() + "]"); } else if (handshakeStatus.equals(HandshakeStatus.NEED_WRAP)) { // We must send data to the remote side for the handshake to continue if (log.isLoggable(Level.FINE)) { log.fine("Send back Handshake data [" + getRemoteHost() + "]"); } wrapAndSend(); } } else if (status.equals(Status.CLOSED)) { if (log.isLoggable(Level.FINE)) { log.fine(" sslengine closed [" + getRemoteHost() + "]"); } // send ssl close, don't recurse recurse = false; close(); } else if (status.equals(Status.BUFFER_UNDERFLOW)) { // There is not enough data in the socketData buffer to unwrap a meaningful SSL block --> // Wait for next data from the socket if (log.isLoggable(Level.FINE)) { log.fine("Not enough data to decode a meaningful SSL block. " + socketData.remaining() + " unprocessed bytes. [" + getRemoteHost() + "]"); } // Avoid entering an infinite recursion trying to continuously decode bytes still present in socketData (that are // not sufficient to unwrap a meaningful SSL block) return n; } else if (status.equals(Status.BUFFER_OVERFLOW)) { // The unwrapData buffer is too small to hold all unwrapped data --> Repeat with a larger buffer if (log.isLoggable(Level.FINE)) { NIOHelper.logBuffer(socketData, "socketData"); NIOHelper.logBuffer(unwrapData, "overflow unwrapData"); log.fine("enlarging unwrap buffer with" + INCREASE_SIZE); } log.info("Buffer overflow. Enlarge buffer and retry [" + getRemoteHost() + "]"); unwrapData.flip(); unwrapData = NIOHelper.enlargeAndFillBuffer(unwrapData, INCREASE_SIZE); return decrypt(socketData); } // If the socketData buffer contains unprocessed data, manage them if (socketData.hasRemaining() && recurse) { n += decrypt(socketData); } // Return the number of valid application data return n; } /** * generates handshake data and calls {@link NIOJICPConnection#writeToChannel(java.nio.ByteBuffer) }, possibly * recursive when required by handshaking * @return the amount of bytes written to the connection * @throws SSLException * @throws IOException */ private int wrapAndSend() throws SSLException, IOException { wrapData.clear(); int n = 0; SSLEngineResult result = encode(EMPTY_BUFFER); if (log.isLoggable(Level.FINE)) { log.fine("wrapped " + result); } if (result.bytesProduced() > 0) { wrapData.flip(); n = writeToChannel(wrapData); if (result.getHandshakeStatus().equals(HandshakeStatus.NEED_WRAP)) { n += wrapAndSend(); } return n; } else { log.warning("wrap produced no data " + getRemoteHost()); } return n; } /** * encrypt application data, does not write data to socket. After this method call the data to be * send can be retrieved through {@link SSLEngineHelper#getWrapData() }, the data will be ready for usage. * @param b the appData to wrap * @return the status object for the wrap or null * @throws SSLException * @throws IOException */ private SSLEngineResult wrapAppData(ByteBuffer b) throws SSLException, IOException { wrapData.clear(); SSLEngineResult result = encode(b); if (log.isLoggable(Level.FINE)) { log.fine("wrapped " + result); } if (result.bytesProduced() > 0) { wrapData.flip(); return result; } else { throw new IOException("wrap produced no data " + getRemoteHost()); } } public synchronized ByteBuffer preprocessBufferToWrite(ByteBuffer dataToSend) throws IOException { sendData.clear(); while (dataToSend.hasRemaining()) { SSLEngineResult res = wrapAppData(dataToSend); if (wrapData.remaining() > sendData.remaining()) { int extra = wrapData.remaining() - sendData.remaining(); sendData.flip(); sendData = NIOHelper.enlargeAndFillBuffer(sendData, extra); } NIOHelper.copyAsMuchAsFits(sendData, wrapData); } sendData.flip(); return sendData; } public synchronized ByteBuffer postprocessBufferRead(ByteBuffer socketData) throws PacketIncompleteException, IOException { //needMoreSocketData = false; unwrapData.clear(); int n = decrypt(socketData); if (n > 0) { unwrapData.flip(); return unwrapData; } else { return EMPTY_BUFFER; } } public boolean needSocketData() { return false; } }
package net.spy.digg; /** * Base class for paging parameters. */ public abstract class PagingParameters { /** * The minimum value for a count. */ public static final int MIN_COUNT = 0; /** * The maximum value for a count. */ public static final int MAX_COUNT = 100; private String sort = null; private Integer count = null; private Integer offset = null; public PagingParameters() { super(); } public Integer getCount() { return count; } /** * Set the number of results to return. * @param to an integer between MIN_COUNT and MAX_COUNT (inclusive). */ public void setCount(int to) { if(to < MIN_COUNT || to > MAX_COUNT) { throw new IllegalArgumentException("Count out of range."); } count = to; } /** * Get the result offset. */ public Integer getOffset() { return offset; } /** * Set the result offset. * @param to a positive integer */ public void setOffset(int to) { if(to < 0) { throw new IllegalArgumentException("Offset must be positive"); } offset = to; } /** * Get the sort type. */ public String getSort() { return sort; } /** * Set the sort type. */ public void setSort(String to) { sort = to; } }
//This library is free software; you can redistribute it and/or //modify it under the terms of the GNU Lesser General Public //This library is distributed in the hope that it will be useful, //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //You should have received a copy of the GNU Lesser General Public //Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. package opennlp.tools.util; import java.util.*; import opennlp.maxent.MaxentModel; import opennlp.tools.util.Cache; /** Performs k-best search over sequence. This is besed on the description in * Ratnaparkhi (1998), PhD diss, Univ. of Pennsylvania. */ public class BeamSearch { protected MaxentModel model; protected BeamSearchContextGenerator cg; protected int size; private static final Object[] EMPTY_ADDITIONAL_CONTEXT = new Object[0]; private double[] probs; private String out; private Cache contextsCache; private static final int zeroLog = -100000; /** Creates new search object. * @param size The size of the beam (k). * @param cg the context generator for the model. * @param model the model for assigning probabilities to the sequence outcomes. */ public BeamSearch(int size, BeamSearchContextGenerator cg, MaxentModel model) { this(size,cg,model,0); } public BeamSearch(int size, BeamSearchContextGenerator cg, MaxentModel model, int cacheSize) { this.size = size; this.cg = cg; this.model = model; this.probs = new double[model.getNumOutcomes()]; if (cacheSize > 0) { contextsCache = new Cache(cacheSize); } } public Sequence[] bestSequences(int numSequences, Object[] sequence, Object[] additionalContext) { return bestSequences(numSequences, sequence, additionalContext, zeroLog); } /** Returns the best sequence of outcomes based on model for this object. * @param numSequences The maximum number of sequences to be returned. * @param sequence The input sequence. * @param additionalContext An Object[] of additional context. This is passed to the context generator blindly with the assumption that the context are appropiate. * @param minSequenceScore A lower bound on the score of a returned sequence. * @return An array of the top ranked sequences of outcomes. */ public Sequence[] bestSequences(int numSequences, Object[] sequence, Object[] additionalContext, double minSequenceScore) { int n = sequence.length; Heap prev = new TreeHeap(size); Heap next = new TreeHeap(size); Heap tmp; if (contextsCache != null) { //contextsCache.clear(); } prev.add(new Sequence()); if (additionalContext == null) { additionalContext = EMPTY_ADDITIONAL_CONTEXT; } for (int i = 0; i < n; i++) { int sz = Math.min(size, prev.size()); int sc = 0; for (; prev.size() > 0 && sc < sz; sc++) { Sequence top = (Sequence) prev.extract(); List tmpOutcomes = top.getOutcomes(); String[] outcomes = (String[]) tmpOutcomes.toArray(new String[tmpOutcomes.size()]); String[] contexts = cg.getContext(i, sequence, outcomes, additionalContext); double[] scores; if (contextsCache != null) { scores = (double[]) contextsCache.get(contexts); if (scores == null) { scores = model.eval(contexts, probs); contextsCache.put(contexts,scores); } } else { scores = model.eval(contexts, probs); } double[] temp_scores = new double[scores.length]; for (int c = 0; c < scores.length; c++) { temp_scores[c] = scores[c]; } Arrays.sort(temp_scores); double min = temp_scores[Math.max(0,scores.length-size)]; for (int p = 0; p < scores.length; p++) { if (scores[p] < min) continue; //only advance first "size" outcomes out = model.getOutcome(p); if (validSequence(i, sequence, outcomes, out)) { Sequence ns = new Sequence(top, out, scores[p]); if (ns.getScore() > minSequenceScore) { next.add(ns); } } } } // make prev = next; and re-init next (we reuse existing prev set once we clear it) prev.clear(); tmp = prev; prev = next; next = tmp; } int numSeq = Math.min(numSequences, prev.size()); Sequence[] topSequences = new Sequence[numSeq]; int seqIndex = 0; for (; seqIndex < numSeq; seqIndex++) { topSequences[seqIndex] = (Sequence) prev.extract(); } return topSequences; } /** Returns the best sequence of outcomes based on model for this object. * @param sequence The input sequence. * @param additionalContext An Object[] of additional context. This is passed to the context generator blindly with the assumption that the context are appropiate. * @return The top ranked sequence of outcomes. */ public Sequence bestSequence(List sequence, Object[] additionalContext) { return bestSequences(1, sequence.toArray(), additionalContext)[0]; } /** Returns the best sequence of outcomes based on model for this object. * @param sequence The input sequence. * @param additionalContext An Object[] of additional context. This is passed to the context generator blindly with the assumption that the context are appropiate. * @return The top ranked sequence of outcomes. */ public Sequence bestSequence(Object[] sequence, Object[] additionalContext) { return bestSequences(1, sequence, additionalContext,0)[0]; } /** Determines wheter a particular continuation of a sequence is valid. * This is used to restrict invalid sequences such as thoses used in start/continure tag-based chunking * or could be used to implement tag dictionary restrictions. * @param i The index in the input sequence for which the new outcome is being proposed. * @param inputSequence The input sequnce. * @param outcomesSequence The outcomes so far in this sequence. * @param outcome The next proposed outcome for the outcomes sequence. * @return true is the sequence would still be valid with the new outcome, false otherwise. */ protected boolean validSequence(int i, List inputSequence, Sequence outcomesSequence, String outcome) { return true; } /** Determines wheter a particular continuation of a sequence is valid. * This is used to restrict invalid sequences such as thoses used in start/continure tag-based chunking * or could be used to implement tag dictionary restrictions. * @param i The index in the input sequence for which the new outcome is being proposed. * @param inputSequence The input sequnce. * @param outcomesSequence The outcomes so far in this sequence. * @param outcome The next proposed outcome for the outcomes sequence. * @return true is the sequence would still be valid with the new outcome, false otherwise. */ protected boolean validSequence(int i, Object[] inputSequence, String[] outcomesSequence, String outcome) { return true; } }
package org.apache.fop.image; import java.io.InputStream; import java.awt.color.ColorSpace; import java.awt.color.ICC_Profile; import java.awt.Color; import org.apache.fop.apps.FOUserAgent; /** * Fop image interface for loading images. * * @author Eric SCHAEFFER */ public interface FopImage { /** * Flag for loading dimensions. */ public static final int DIMENSIONS = 1; /** * Flag for loading original data. */ public static final int ORIGINAL_DATA = 2; /** * Flag for loading bitmap data. */ public static final int BITMAP = 4; /** * Get the mime type of this image. * This is used so that when reading from the image it knows * what type of image it is. * * @return the mime type string */ String getMimeType(); /** * Load particular inforamtion for this image * This must be called before attempting to get * the information. * * @param type the type of loading required * @param ua the user agent * @return boolean true if the information could be loaded */ boolean load(int type, FOUserAgent ua); /** * Returns the image width. * @return the width in pixels */ int getWidth(); /** * Returns the image height. * @return the height in pixels */ int getHeight(); /** * Returns the color space of the image. * @return the color space */ ColorSpace getColorSpace(); /** * Returns the ICC profile. * @return the ICC profile, null if none is available */ ICC_Profile getICCProfile(); /** * Returns the number of bits per pixel for the image. * @return the number of bits per pixel */ int getBitsPerPixel(); /** * Indicates whether the image is transparent. * @return True if it is transparent */ boolean isTransparent(); /** * For transparent images. Returns the transparent color. * @return the transparent color */ Color getTransparentColor(); /** * Indicates whether the image has a Soft Mask (See section 7.5.4 in the * PDF specs) * @return True if a Soft Mask exists */ boolean hasSoftMask(); /** * For images with a Soft Mask. Returns the Soft Mask as an array. * @return the Soft Mask */ byte[] getSoftMask(); /** * Returns the decoded and uncompressed image as a array of * width * height * [colorspace-multiplicator] pixels. * @return the bitmap */ byte[] getBitmaps(); /** * Returns the size of the image. * width * (bitsPerPixel / 8) * height, no ? * @return the size */ int getBitmapsSize(); /** * Returns the encoded/compressed image as an array of bytes. * @return the raw image */ byte[] getRessourceBytes(); /** * Returns the number of bytes of the raw image. * @return the size in bytes */ int getRessourceBytesSize(); /** * Image info class. * Information loaded from analyser and passed to image object. */ public static class ImageInfo { public InputStream inputStream; public int width; public int height; public Object data; public String mimeType; public String str; } }
package org.concord.otrunk; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.Vector; import java.util.WeakHashMap; import org.concord.framework.otrunk.OTBundle; import org.concord.framework.otrunk.OTControllerRegistry; import org.concord.framework.otrunk.OTID; import org.concord.framework.otrunk.OTObject; import org.concord.framework.otrunk.OTObjectList; import org.concord.framework.otrunk.OTObjectMap; import org.concord.framework.otrunk.OTObjectService; import org.concord.framework.otrunk.OTPackage; import org.concord.framework.otrunk.OTServiceContext; import org.concord.framework.otrunk.OTUser; import org.concord.framework.otrunk.OTrunk; import org.concord.framework.otrunk.otcore.OTClass; import org.concord.otrunk.datamodel.OTDataObject; import org.concord.otrunk.datamodel.OTDataObjectFinder; import org.concord.otrunk.datamodel.OTDataObjectType; import org.concord.otrunk.datamodel.OTDatabase; import org.concord.otrunk.datamodel.OTIDFactory; import org.concord.otrunk.datamodel.OTTransientMapID; import org.concord.otrunk.overlay.CompositeDataObject; import org.concord.otrunk.overlay.CompositeDatabase; import org.concord.otrunk.overlay.OTOverlay; import org.concord.otrunk.overlay.Overlay; import org.concord.otrunk.overlay.OverlayImpl; import org.concord.otrunk.user.OTReferenceMap; import org.concord.otrunk.user.OTUserObject; import org.concord.otrunk.view.OTViewerHelper; import org.concord.otrunk.xml.XMLDatabase; /** * @author scott * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ public class OTrunkImpl implements OTrunk { protected Hashtable loadedObjects = new Hashtable(); protected Hashtable compositeDatabases = new Hashtable(); protected Hashtable userObjectServices = new Hashtable(); protected Hashtable userDataObjects = new Hashtable(); protected WeakHashMap objectWrappers = new WeakHashMap(); OTServiceContext serviceContext = new OTServiceContextImpl(); protected OTDatabase rootDb; protected OTDatabase systemDb; protected OTObjectServiceImpl rootObjectService; Vector databases = new Vector(); Vector users = new Vector(); Vector objectServices = new Vector(); private Vector registeredPackageClasses = new Vector(); private OTObjectServiceImpl systemObjectService;; private static HashMap otClassMap = new HashMap(); public final static String getClassName(OTDataObject dataObject) { OTDataObjectType type = dataObject.getType(); return type.getClassName(); } public OTrunkImpl(OTDatabase db) { this(db, null, null); } public OTrunkImpl(OTDatabase db, Object [] services, Class [] serviceClasses) { this(null, db, services, serviceClasses); } public OTrunkImpl(OTDatabase systemDb, OTDatabase db, Object [] services, Class [] serviceClasses) { // Setup the services this has to be done before addDatabase // because addDatabase initializes the OTPackages loaded by that // database if(services != null) { for(int i=0; i<services.length; i++){ serviceContext.addService(serviceClasses[i], services[i]); } } serviceContext.addService(OTControllerRegistry.class, new OTControllerRegistryImpl()); // We should look up if there are any sevices. try { if(systemDb != null){ this.systemDb = systemDb; systemObjectService = initObjectService(systemDb, "system"); } this.rootDb = db; rootObjectService = initObjectService(rootDb, "root"); if(systemObjectService == null){ // there is no real system db so just use the main db this.systemDb = db; systemObjectService = rootObjectService; } OTSystem otSystem = getSystem(); if(otSystem == null){ System.err.println("Warning: No OTSystem object found"); return; } // This is deprecated but we use it anyhow for backward compatibility OTObjectList serviceList = otSystem.getServices(); OTObjectList bundleList = otSystem.getBundles(); Vector combined = new Vector(); combined.addAll(serviceList.getVector()); combined.addAll(bundleList.getVector()); for(int i=0; i<combined.size(); i++){ OTBundle bundle = (OTBundle)combined.get(i); bundle.registerServices(serviceContext); } for(int i=0; i<combined.size(); i++){ OTBundle bundle = (OTBundle)combined.get(i); bundle.initializeBundle(serviceContext); } } catch (Exception e) { e.printStackTrace(); } } /** * * @see org.concord.framework.otrunk.OTrunk#getOTID(java.lang.String) */ public OTID getOTID(String otidStr) { return OTIDFactory.createOTID(otidStr); } /* (non-Javadoc) */ public OTObject createObject(Class objectClass) throws Exception { return rootObjectService.createObject(objectClass); } public void setRoot(OTObject obj) throws Exception { // FIXME this doesn't do a good job if there // is an OTSystem OTID id = obj.getGlobalId(); rootDb.setRoot(id); } public OTSystem getSystem() throws Exception { OTDataObject systemDO = systemDb.getRoot(); OTID systemID = systemDO.getGlobalId(); OTObject systemObject = systemObjectService.getOTObject(systemID); if(systemObject instanceof OTSystem){ return (OTSystem) systemObject; } return null; } public OTObject getRealRoot() throws Exception { OTDataObject rootDO = getRootDataObject(); if(rootDO == null) { return null; } return rootObjectService.getOTObject(rootDO.getGlobalId()); } public OTObject getRoot() throws Exception { OTObject root = getRealRoot(); if(root instanceof OTSystem) { return ((OTSystem)root).getRoot(); } return root; } /** * return the database that is serving this id * currently there is only one database, so this is * easy * * @param id * @return */ public OTDatabase getOTDatabase(OTID id) { // look for the database that contains this id if(id == null) { return null; } for(int i=0; i<databases.size(); i++) { OTDatabase db = (OTDatabase)databases.get(i); if(db.contains(id)) { return db; } } return null; } public void close() { rootDb.close(); } /** * Warning: this is method should only be used when you don't know * which object is requesting the new OTObject. The requestion object * is currently used to keep the context of user mode or authoring mode * @param childID * @return * @throws Exception */ public OTObject getOTObject(OTID childID) throws Exception { return rootObjectService.getOTObject(childID); } public Object getService(Class serviceInterface) { return serviceContext.getService(serviceInterface); } public OTObjectServiceImpl createObjectService(OTDatabase db) { OTObjectServiceImpl objService = new OTObjectServiceImpl(this); objService.setCreationDb(db); objService.setMainDb(db); registerObjectService(objService, "" + db); return objService; } public void registerObjectService(OTObjectServiceImpl objService, String label) { objectServices.add(objService); if(OTViewerHelper.isTrace()){ objService.addObjectServiceListener(new TraceListener(label)); } } /** * This is a temporary method. It works for files that * represent a single user. This method finds that user and registers * them. It could be modified to register all the users referenced in * the passed in database and in which case it should check if the user * is already registered with another database. * * @param userDataDb * @throws Exception */ public OTUserObject registerUserDataDatabase(OTDatabase userDataDb, String name) throws Exception { // add this database as one of our databases addDatabase(userDataDb); OTReferenceMap refMap = getReferenceMapFromUserDb(userDataDb); OTUser user = refMap.getUser(); OTUserObject aUser = (OTUserObject)user; if(name != null){ aUser.setName(name); } users.add(aUser); setupUserDatabase(user, refMap); return aUser; } /** * the parentObjectService needs to be passed in so the returned object * uses the correct layers based on the context in which this method is * called. * * @param url * @param parentObjectService * @return * @throws Exception */ public OTObject getExternalObject(URL url, OTObjectService parentObjectService) throws Exception { OTObjectServiceImpl externalObjectService = loadDatabase(url); // get the root object either the real root or the system root OTObject root = getRoot(externalObjectService); return parentObjectService.getOTObject(root.getGlobalId()); } protected OTObjectServiceImpl loadDatabase(URL url) throws Exception { // load the data base XMLDatabase includeDb = new XMLDatabase(url); if(databases.contains(includeDb)){ // we've already loaded this database. // It is nice to print an error here because the equals method of the databases // just use the database id. So if 2 databases have the same id then it will // seem like the database has already been loaded. // FIXME this should check the url of the database, and only print this message // if the urls are different. System.err.println("already loaded database with id: " + includeDb.getDatabaseId() + " database: " + url.toExternalForm() + " will not be loaded again"); for(int i=0; i<objectServices.size(); i++){ OTObjectServiceImpl objectService = (OTObjectServiceImpl) objectServices.get(i); OTDatabase db = objectService.getMainDb(); if(db.equals(includeDb)){ return objectService; } } System.err.println("Cannot find objectService for database: " + includeDb.getDatabaseId()); return null; } // register it with the OTrunkImpl // well track the resource info to be safe here. includeDb.setTrackResourceInfo(true); includeDb.loadObjects(); return initObjectService(includeDb, url.toExternalForm()); } protected OTObject getRoot(OTObjectServiceImpl objectService) throws Exception { OTDatabase db = objectService.getMainDb(); OTDataObject rootDO = db.getRoot(); OTObject root = objectService.getOTObject(rootDO.getGlobalId()); if(root instanceof OTSystem) { return ((OTSystem)root).getRoot(); } return root; } protected OTObjectServiceImpl initObjectService(OTDatabase db, String logLabel) throws Exception { addDatabase(db); OTObjectServiceImpl objectService = createObjectService(db); if(OTViewerHelper.isTrace()) { objectService.addObjectServiceListener(new TraceListener(logLabel + ": " + db)); } loadIncludes(objectService); return objectService; } protected void loadIncludes(OTObjectServiceImpl objectService) throws Exception { OTDatabase db = objectService.getMainDb(); OTDataObject rootDO = db.getRoot(); OTID rootID = rootDO.getGlobalId(); OTObject otRoot = objectService.getOTObject(rootID); if(!(otRoot instanceof OTSystem)){ return; } OTSystem otSystem = (OTSystem) otRoot; OTObjectList includes = otSystem.getIncludes(); for(int i=0; i<includes.size(); i++){ OTInclude include = (OTInclude) includes.get(i); URL hrefUrl = include.getHref(); loadDatabase(hrefUrl); } } protected OTReferenceMap getReferenceMapFromUserDb(OTDatabase userDataDb) throws Exception { OTObjectService objService = createObjectService(userDataDb); OTDataObject rootDO = userDataDb.getRoot(); OTStateRoot stateRoot = (OTStateRoot)objService.getOTObject(rootDO.getGlobalId()); OTObjectMap userMap = stateRoot.getUserMap(); // find the user from this database. // this currently is the first user in the userMap Vector keys = userMap.getObjectKeys(); OTReferenceMap refMap = (OTReferenceMap)userMap.getObject((String)keys.get(0)); return refMap; } public void reloadOverlays(OTUserObject user, OTDatabase userDataDb) throws Exception { OTID userId = user.getUserId(); OTReferenceMap refMap = getReferenceMapFromUserDb(userDataDb); // need to make a new composite database. // the user database should remain the same. OTDatabase oldCompositeDB = (OTDatabase) compositeDatabases.remove(userId); userObjectServices.remove(userId); databases.remove(oldCompositeDB); setupUserDatabase(user, refMap); } protected OTObjectService setupUserDatabase(OTUser user, OTReferenceMap userStateMap) { OTObjectServiceImpl userObjService; OTID userId = user.getUserId(); OTDataObjectFinder objectFinder = new OTDataObjectFinder() { public OTDataObject findDataObject(OTID id) throws Exception { OTDatabase db = getOTDatabase(id); return db.getOTDataObject(null, id); } }; CompositeDatabase userDb = new CompositeDatabase(objectFinder, userStateMap); addDatabase(userDb); userObjService = createObjectService(userDb); compositeDatabases.put(userId, userDb); userObjectServices.put(userId, userObjService); // After the user database is complete setup, now we get the overlays. This way // the user can change the overlays list. try { ArrayList overlays = null; OTObjectList otOverlays = getSystemOverlays(user); if(otOverlays != null && otOverlays.size() > 0){ overlays = new ArrayList(); for(int i=0; i<otOverlays.size(); i++){ OTOverlay otOverlay = (OTOverlay) otOverlays.get(i); Overlay overlay = new OverlayImpl(otOverlay); overlays.add(overlay); } } userDb.setOverlays(overlays); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return userObjService; } public Hashtable getCompositeDatabases() { return compositeDatabases; } public Vector getUsers() { return users; } public boolean hasUserModified(OTObject authoredObject, OTUser user) throws Exception { OTID authoredId = authoredObject.getGlobalId(); OTID userId = user.getUserId(); CompositeDatabase db = (CompositeDatabase)compositeDatabases.get(userId); if(db == null) { // FIXME this should throw an exception return false; } OTDataObject userDataObject = db.getOTDataObject(null, authoredId); if(userDataObject instanceof CompositeDataObject) { OTDataObject userModifications = ((CompositeDataObject)userDataObject).getActiveDeltaObject(); return userModifications != null; } return false; } public OTObjectService initUserObjectService(OTObjectServiceImpl objService, OTUser user, OTStateRoot stateRoot) throws Exception { OTID userId = user.getUserId(); // this should probably look for the user object service instead // of the template database OTObjectService userObjService = (OTObjectService)userObjectServices.get(userId); if(userObjService != null){ return userObjService; } OTObjectMap userStateMapMap = stateRoot.getUserMap(); OTReferenceMap userStateMap = (OTReferenceMap)userStateMapMap.getObject(userId.toExternalForm()); if(userStateMap == null) { // this is inferring that the createObject method will // create the object in the correct database. userStateMap = (OTReferenceMap)objService.createObject(OTReferenceMap.class); userStateMapMap.putObject(userId.toExternalForm(), userStateMap); userStateMap.setUser((OTUserObject)user); } userObjService = setupUserDatabase(user, userStateMap); return userObjService; } protected void addDatabase(OTDatabase db) { if(!databases.contains(db)) { databases.add(db); Vector packageClasses = db.getPackageClasses(); if(packageClasses != null){ for(int i=0; i<packageClasses.size(); i++){ registerPackageClass((Class)packageClasses.get(i)); } } } } /** * @param class1 */ public void registerPackageClass(Class packageClass) { // check to see if this package has already been registered if(registeredPackageClasses.contains(packageClass)){ return; } registeredPackageClasses.add(packageClass); OTPackage otPackage; try { otPackage = (OTPackage)packageClass.newInstance(); Class [] dependencies = otPackage.getPackageDependencies(); if(dependencies != null){ for(int i=0; i<dependencies.length; i++){ registerPackageClass(dependencies[i]); } } otPackage.initialize(this); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } return; } public OTObject getUserRuntimeObject(OTObject authoredObject, OTUser user) throws Exception { //authoredObject = getRuntimeAuthoredObject(authoredObject, user); OTID authoredId = authoredObject.getGlobalId(); OTID userId = user.getUserId(); OTObjectService objService = (OTObjectService)userObjectServices.get(userId); // the objService should be non null if not this is coding error // that needs to be fixed so we will just let it throw an null pointer // exception return objService.getOTObject(authoredId); } /** * This method is a legacy method. It should be generalized now that "user objects" and * "author objects" are just specific versions of "overlay delta objects" and "base objects" * * @param userObject * @param user * @return * @throws Exception */ public OTObject getRuntimeAuthoredObject(OTObject userObject, OTUser user) throws Exception { OTID objectId = userObject.getGlobalId(); OTID userId = user.getUserId(); if(!(objectId instanceof OTTransientMapID)){ return userObject; } CompositeDatabase db = (CompositeDatabase)compositeDatabases.get(userId); //System.out.println("is relative"); Object objectMapToken = ((OTTransientMapID) objectId).getMapToken(); if(objectMapToken != null && objectMapToken == db.getDatabaseId()) { //System.out.print(" equals to databaseid"); objectId = ((OTTransientMapID) objectId).getMappedId(); //System.out.println(": " + objectId.toString()); return getOTObject(objectId); } return userObject; } public OTObject getRootObject(OTDatabase db) throws Exception { OTDataObject rootDO = db.getRoot(); OTObject rootObject = rootObjectService.getOTObject(rootDO.getGlobalId()); return rootObject; } /** * @return */ public OTDataObject getRootDataObject() throws Exception { return rootDb.getRoot(); } public OTObjectList getSystemOverlays(OTUser user) throws Exception { OTObject root = getRealRoot(); if(!(root instanceof OTSystem)) { return null; } OTSystem userRoot = (OTSystem) getUserRuntimeObject(root, user); return userRoot.getOverlays(); } /** * @return */ public OTObject getFirstObjectNoUserData() throws Exception { OTObject root = getRealRoot(); if(!(root instanceof OTSystem)) { return null; } return ((OTSystem)root).getFirstObjectNoUserData(); } void putLoadedObject(OTObject otObject, OTID otId) { WeakReference objRef = new WeakReference(otObject); loadedObjects.put(otId, objRef); } OTObject getLoadedObject(OTID otId) { OTObject otObject = null; Reference otObjectRef = (Reference)loadedObjects.get(otId); if(otObjectRef != null) { otObject = (OTObject)otObjectRef.get(); } if(otObject != null) { return otObject; } loadedObjects.remove(otId); return null; } /** * This method is used by object services that can't handle a requested object * this happens in reports when a report object needs to access a user object. * * It might be possible to clean this up by explicitly giving the object service * of the report access to the users objects. * * @param childID * @return * @throws Exception */ OTObject getOrphanOTObject(OTID childID, OTObjectServiceImpl oldService) throws Exception { for(int i=0; i<objectServices.size(); i++) { OTObjectServiceImpl objService = (OTObjectServiceImpl)objectServices.get(i); // To avoid infinite loop, the objService must not equal to oldService if(objService.managesObject(childID) && objService != oldService) { return objService.getOTObject(childID); } } System.err.println("Data object is not found for: " + childID); return null; } public OTObjectServiceImpl getRootObjectService() { return rootObjectService; } public static OTClass getOTClass(String className) { return (OTClass) otClassMap.get(className); } public static void putOTClass(String className, OTClass otClass) { otClassMap.put(className, otClass); } }
package de.geeksfactory.opacclient.apis; import java.io.IOException; import java.io.InterruptedIOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.UnknownHostException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.http.HttpResponse; import org.apache.http.MalformedChunkCodingException; import org.apache.http.NameValuePair; import org.apache.http.NoHttpResponseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import de.geeksfactory.opacclient.NotReachableException; import de.geeksfactory.opacclient.apis.OpacApi.MultiStepResult.Status; import de.geeksfactory.opacclient.i18n.StringProvider; import de.geeksfactory.opacclient.objects.Account; import de.geeksfactory.opacclient.objects.AccountData; import de.geeksfactory.opacclient.objects.Detail; import de.geeksfactory.opacclient.objects.DetailledItem; import de.geeksfactory.opacclient.objects.Filter; import de.geeksfactory.opacclient.objects.Filter.Option; import de.geeksfactory.opacclient.objects.Library; import de.geeksfactory.opacclient.objects.SearchRequestResult; import de.geeksfactory.opacclient.objects.SearchResult; import de.geeksfactory.opacclient.objects.SearchResult.MediaType; import de.geeksfactory.opacclient.searchfields.DropdownSearchField; import de.geeksfactory.opacclient.searchfields.SearchField; import de.geeksfactory.opacclient.searchfields.SearchQuery; import de.geeksfactory.opacclient.searchfields.TextSearchField; public class Adis extends BaseApi implements OpacApi { protected String opac_url = ""; protected JSONObject data; protected boolean initialised = false; protected Library library; protected int s_requestCount = 0; protected String s_service; protected String s_sid; protected String s_exts; protected String s_alink; protected List<NameValuePair> s_pageform; protected int s_lastpage; protected Document s_reusedoc; protected boolean s_accountcalled; protected static HashMap<String, MediaType> types = new HashMap<String, MediaType>(); protected static HashSet<String> ignoredFieldNames = new HashSet<String>(); static { types.put("Buch", MediaType.BOOK); types.put("Band", MediaType.BOOK); types.put("DVD-ROM", MediaType.CD_SOFTWARE); types.put("CD-ROM", MediaType.CD_SOFTWARE); types.put("Medienkombination", MediaType.PACKAGE); types.put("DVD-Video", MediaType.DVD); types.put("Noten", MediaType.SCORE_MUSIC); types.put("Konsolenspiel", MediaType.GAME_CONSOLE); types.put("CD", MediaType.CD); types.put("Zeitschrift", MediaType.MAGAZINE); types.put("Zeitschriftenheft", MediaType.MAGAZINE); types.put("Zeitung", MediaType.NEWSPAPER); types.put("Beitrag E-Book", MediaType.EBOOK); types.put("Elektronische Ressource", MediaType.EBOOK); types.put("E-Book", MediaType.EBOOK); types.put("Karte", MediaType.MAP); // TODO: The following fields from Berlin make no sense and don't work // when they are displayed alone. // We can only include them if we automatically deselect the "Verbund" // checkbox // when one of these dropdowns has a value other than "". ignoredFieldNames.add("oder Bezirk"); ignoredFieldNames.add("oder Bibliothek"); } public Document htmlGet(String url) throws ClientProtocolException, IOException { if (!url.contains("requestCount")) { url = url + (url.contains("?") ? "&" : "?") + "requestCount=" + s_requestCount; } HttpGet httpget = new HttpGet(cleanUrl(url)); HttpResponse response; try { response = http_client.execute(httpget); } catch (ConnectTimeoutException e) { e.printStackTrace(); throw new NotReachableException(); } catch (IllegalStateException e) { e.printStackTrace(); throw new NotReachableException(); } catch (UnknownHostException e) { e.printStackTrace(); throw new NotReachableException(); } catch (NoHttpResponseException e) { e.printStackTrace(); throw new NotReachableException(); } catch (MalformedChunkCodingException e) { e.printStackTrace(); throw new NotReachableException(); } catch (javax.net.ssl.SSLPeerUnverifiedException e) { // TODO: Handly this well throw e; } catch (javax.net.ssl.SSLException e) { // TODO: Handly this well // Can be "Not trusted server certificate" or can be a // aborted/interrupted handshake/connection if (e.getMessage().contains("timed out") || e.getMessage().contains("reset by")) { e.printStackTrace(); throw new NotReachableException(); } else { throw e; } } catch (InterruptedIOException e) { e.printStackTrace(); throw new NotReachableException(); } catch (IOException e) { if (e.getMessage().contains("Request aborted")) { e.printStackTrace(); throw new NotReachableException(); } else { throw e; } } if (response.getStatusLine().getStatusCode() >= 400) { throw new NotReachableException(); } String html = convertStreamToString(response.getEntity().getContent(), getDefaultEncoding()); response.getEntity().consumeContent(); Document doc = Jsoup.parse(html); Pattern patRequestCount = Pattern.compile("requestCount=([0-9]+)"); for (Element a : doc.select("a")) { Matcher objid_matcher = patRequestCount.matcher(a.attr("href")); if (objid_matcher.matches()) { s_requestCount = Integer.parseInt(objid_matcher.group(1)); } } doc.setBaseUri(url); return doc; } public Document htmlPost(String url, List<NameValuePair> data) throws ClientProtocolException, IOException { HttpPost httppost = new HttpPost(cleanUrl(url)); boolean rcf = false; for (NameValuePair nv : data) { if (nv.getName().equals("requestCount")) { rcf = true; break; } } if (!rcf) { data.add(new BasicNameValuePair("requestCount", s_requestCount + "")); } httppost.setEntity(new UrlEncodedFormEntity(data)); HttpResponse response = null; try { response = http_client.execute(httppost); } catch (ConnectTimeoutException e) { e.printStackTrace(); throw new NotReachableException(); } catch (IllegalStateException e) { e.printStackTrace(); throw new NotReachableException(); } catch (UnknownHostException e) { e.printStackTrace(); throw new NotReachableException(); } catch (NoHttpResponseException e) { e.printStackTrace(); throw new NotReachableException(); } catch (MalformedChunkCodingException e) { e.printStackTrace(); throw new NotReachableException(); } catch (javax.net.ssl.SSLPeerUnverifiedException e) { // TODO: Handle this well throw e; } catch (javax.net.ssl.SSLException e) { // TODO: Handly this well // Can be "Not trusted server certificate" or can be a // aborted/interrupted handshake/connection if (e.getMessage().contains("timed out") || e.getMessage().contains("reset by")) { e.printStackTrace(); throw new NotReachableException(); } else { throw e; } } catch (InterruptedIOException e) { e.printStackTrace(); throw new NotReachableException(); } catch (IOException e) { if (e.getMessage().contains("Request aborted")) { e.printStackTrace(); throw new NotReachableException(); } else { throw e; } } if (response.getStatusLine().getStatusCode() >= 400) { throw new NotReachableException(); } String html = convertStreamToString(response.getEntity().getContent(), getDefaultEncoding()); response.getEntity().consumeContent(); Document doc = Jsoup.parse(html); Pattern patRequestCount = Pattern .compile(".*requestCount=([0-9]+)[^0-9].*"); for (Element a : doc.select("a")) { Matcher objid_matcher = patRequestCount.matcher(a.attr("href")); if (objid_matcher.matches()) { s_requestCount = Integer.parseInt(objid_matcher.group(1)); } } doc.setBaseUri(url); return doc; } @Override public void start() throws IOException, NotReachableException { s_accountcalled = false; try { Document doc = htmlGet(opac_url + "?" + data.getString("startparams")); Pattern padSid = Pattern .compile(".*;jsessionid=([0-9A-Fa-f]+)[^0-9A-Fa-f].*"); for (Element navitem : doc.select("#unav li a")) { if (navitem.attr("href").contains("service=")) { s_service = getQueryParams(navitem.attr("href")).get( "service").get(0); } if (navitem.text().contains("Erweiterte Suche")) { s_exts = getQueryParams(navitem.attr("href")).get("sp") .get(0); } Matcher objid_matcher = padSid.matcher(navitem.attr("href")); if (objid_matcher.matches()) { s_sid = objid_matcher.group(1); } } if (s_exts == null) s_exts = "SS6"; } catch (JSONException e) { throw new RuntimeException(e); } initialised = true; } @Override protected String getDefaultEncoding() { return "UTF-8"; } @Override public SearchRequestResult search(List<SearchQuery> queries) throws IOException, NotReachableException, OpacErrorException { start(); // TODO: There are also libraries with a different search form, // s_exts=SS2 instead of s_exts=SS6 // e.g. munich. Treat them differently! Document doc = htmlGet(opac_url + ";jsessionid=" + s_sid + "?service=" + s_service + "&sp=" + s_exts); int cnt = 0; List<NameValuePair> nvpairs = new ArrayList<NameValuePair>(); for (SearchQuery query : queries) { if (!query.getValue().equals("")) { if (query.getSearchField() instanceof DropdownSearchField) { doc.select("select#" + query.getKey()) .val(query.getValue()); continue; } cnt++; if (s_exts.equals("SS2") || (query.getSearchField().getData() != null && !query .getSearchField().getData() .optBoolean("selectable", true))) { doc.select("input#" + query.getKey()).val(query.getValue()); } else { doc.select("select#SUCH01_" + cnt).val(query.getKey()); doc.select("input#FELD01_" + cnt).val(query.getValue()); } if (cnt > 4) { throw new OpacErrorException( stringProvider.getFormattedString( StringProvider.LIMITED_NUM_OF_CRITERIA, 4)); } } } for (Element input : doc.select("input, select")) { if (!"image".equals(input.attr("type")) && !"submit".equals(input.attr("type")) && !"".equals(input.attr("name"))) { nvpairs.add(new BasicNameValuePair(input.attr("name"), input .attr("value"))); } } nvpairs.add(new BasicNameValuePair("$Toolbar_0.x", "1")); nvpairs.add(new BasicNameValuePair("$Toolbar_0.y", "1")); if (cnt == 0) { throw new OpacErrorException( stringProvider.getString(StringProvider.NO_CRITERIA_INPUT)); } Document docresults = htmlPost(opac_url + ";jsessionid=" + s_sid, nvpairs); return parse_search(docresults, 1); } private SearchRequestResult parse_search(Document doc, int page) throws OpacErrorException { if (doc.select(".message h1").size() > 0 && doc.select("#right #R06").size() == 0) { throw new OpacErrorException(doc.select(".message h1").text()); } int total_result_count = -1; List<SearchResult> results = new ArrayList<SearchResult>(); if (doc.select("#right #R06").size() > 0) { Pattern patNum = Pattern .compile(".*Treffer: .* von ([0-9]+)[^0-9]*"); Matcher matcher = patNum.matcher(doc.select("#right #R06").text() .trim()); if (matcher.matches()) { total_result_count = Integer.parseInt(matcher.group(1)); } } if (doc.select("#right #R03").size() == 1 && doc.select("#right #R03").text().trim() .endsWith("Treffer: 1")) { s_reusedoc = doc; throw new OpacErrorException("is_a_redirect"); } Pattern patId = Pattern .compile("javascript:.*htmlOnLink\\('([0-9A-Za-z]+)'\\)"); for (Element tr : doc.select("table.rTable_table tbody tr")) { SearchResult res = new SearchResult(); res.setInnerhtml(tr.select(".rTable_td_text a").first().html()); res.setNr(Integer.parseInt(tr.child(0).text().trim())); Matcher matcher = patId.matcher(tr.select(".rTable_td_text a") .first().attr("href")); if (matcher.matches()) { res.setId(matcher.group(1)); } String typetext = tr.select(".rTable_td_img img").first() .attr("title"); if (types.containsKey(typetext)) res.setType(types.get(typetext)); else if (typetext.contains("+") && types.containsKey(typetext.split("\\+")[0].trim())) res.setType(types.get(typetext.split("\\+")[0].trim())); results.add(res); } s_pageform = new ArrayList<NameValuePair>(); for (Element input : doc.select("input, select")) { if (!"image".equals(input.attr("type")) && !"submit".equals(input.attr("type")) && !"checkbox".equals(input.attr("type")) && !"".equals(input.attr("name"))) { s_pageform.add(new BasicNameValuePair(input.attr("name"), input .attr("value"))); } } s_lastpage = page; return new SearchRequestResult(results, total_result_count, page); } @Override public void init(Library library) { super.init(library); this.library = library; this.data = library.getData(); try { this.opac_url = data.getString("baseurl"); } catch (JSONException e) { throw new RuntimeException(e); } } @Override public SearchRequestResult filterResults(Filter filter, Option option) throws IOException, NotReachableException { throw new UnsupportedOperationException(); } @Override public SearchRequestResult searchGetPage(int page) throws IOException, NotReachableException, OpacErrorException { SearchRequestResult res = null; while (page != s_lastpage) { List<NameValuePair> nvpairs = s_pageform; int i = 0; List<Integer> indexes = new ArrayList<Integer>(); for (NameValuePair np : nvpairs) { if (np.getName().contains("$Toolbar_")) { indexes.add(i); } i++; } for (int j = indexes.size() - 1; j >= 0; j nvpairs.remove((int) indexes.get(j)); } int p; if (page > s_lastpage) { nvpairs.add(new BasicNameValuePair("$Toolbar_5.x", "1")); nvpairs.add(new BasicNameValuePair("$Toolbar_5.y", "1")); p = s_lastpage + 1; } else { nvpairs.add(new BasicNameValuePair("$Toolbar_4.x", "1")); nvpairs.add(new BasicNameValuePair("$Toolbar_4.y", "1")); p = s_lastpage - 1; } Document docresults = htmlPost(opac_url + ";jsessionid=" + s_sid, nvpairs); res = parse_search(docresults, p); } return res; } @Override public DetailledItem getResultById(String id, String homebranch) throws IOException, NotReachableException, OpacErrorException { Document doc; List<NameValuePair> nvpairs; if (id == null && s_reusedoc != null) { doc = s_reusedoc; } else { nvpairs = s_pageform; int i = 0; List<Integer> indexes = new ArrayList<Integer>(); for (NameValuePair np : nvpairs) { if (np.getName().contains("$Toolbar_") || np.getName().contains("selected")) { indexes.add(i); } i++; } for (int j = indexes.size() - 1; j >= 0; j nvpairs.remove((int) indexes.get(j)); } nvpairs.add(new BasicNameValuePair("selected", "ZTEXT " + id)); doc = htmlPost(opac_url + ";jsessionid=" + s_sid, nvpairs); List<NameValuePair> form = new ArrayList<NameValuePair>(); for (Element input : doc.select("input, select")) { if (!"image".equals(input.attr("type")) && !"submit".equals(input.attr("type")) && !"checkbox".equals(input.attr("type")) && !"".equals(input.attr("name")) && !"selected".equals(input.attr("name"))) { form.add(new BasicNameValuePair(input.attr("name"), input .attr("value"))); } } form.add(new BasicNameValuePair("selected", "ZTEXT " + id)); doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form); // Yep, two times. } DetailledItem res = new DetailledItem(); if (doc.select("#R001 img").size() == 1) { res.setCover(doc.select("#R001 img").first().absUrl("src")); } for (Element tr : doc.select("#R06 .aDISListe table tbody tr")) { if (tr.children().size() < 2) continue; if (tr.child(1).text().contains("hier klicken")) { res.addDetail(new Detail(tr.child(0).text().trim(), tr.child(1) .select("a").first().absUrl("href"))); } else { res.addDetail(new Detail(tr.child(0).text().trim(), tr.child(1) .text().trim())); } if (tr.child(0).text().trim().contains("Titel") && res.getTitle() == null) { res.setTitle(tr.child(1).text().split("[:/;]")[0].trim()); } } if (doc.select("input[value*=Reservieren], input[value*=Vormerken]") .size() > 0) { res.setReservable(true); res.setReservation_info(id); } Map<Integer, String> colmap = new HashMap<Integer, String>(); int i = 0; for (Element th : doc.select("#R08 table.rTable_table thead tr th")) { String head = th.text().trim(); if (head.contains("Bibliothek")) { colmap.put(i, DetailledItem.KEY_COPY_BRANCH); } else if (head.contains("Standort")) { colmap.put(i, DetailledItem.KEY_COPY_LOCATION); } else if (head.contains("Signatur")) { colmap.put(i, DetailledItem.KEY_COPY_SHELFMARK); } else if (head.contains("Status") || head.contains("Hinweis") || head.matches(".*Verf.+gbarkeit.*")) { colmap.put(i, DetailledItem.KEY_COPY_STATUS); } i++; } for (Element tr : doc.select("#R08 table.rTable_table tbody tr")) { Map<String, String> line = new HashMap<String, String>(); for (Entry<Integer, String> entry : colmap.entrySet()) { if (entry.getValue().equals(DetailledItem.KEY_COPY_STATUS)) { String status = tr.child(entry.getKey()).text().trim(); if (status.contains(" am: ")) { line.put(DetailledItem.KEY_COPY_STATUS, status.split("-")[0]); line.put(DetailledItem.KEY_COPY_RETURN, status.split(": ")[1]); } else { line.put(DetailledItem.KEY_COPY_STATUS, status); } } else { line.put(entry.getValue(), tr.child(entry.getKey()).text() .trim()); } } res.addCopy(line); } // Reset s_pageform = new ArrayList<NameValuePair>(); for (Element input : doc.select("input, select")) { if (!"image".equals(input.attr("type")) && !"submit".equals(input.attr("type")) && !"checkbox".equals(input.attr("type")) && !"".equals(input.attr("name"))) { s_pageform.add(new BasicNameValuePair(input.attr("name"), input .attr("value"))); } } nvpairs = s_pageform; nvpairs.add(new BasicNameValuePair("$Toolbar_1.x", "1")); nvpairs.add(new BasicNameValuePair("$Toolbar_1.y", "1")); parse_search(htmlPost(opac_url + ";jsessionid=" + s_sid, nvpairs), 1); nvpairs = s_pageform; nvpairs.add(new BasicNameValuePair("$Toolbar_3.x", "1")); nvpairs.add(new BasicNameValuePair("$Toolbar_3.y", "1")); parse_search(htmlPost(opac_url + ";jsessionid=" + s_sid, nvpairs), 1); res.setId(""); // null would be overridden by the UI, because there _is_ // an id,< we just can not use it. return res; } @Override public DetailledItem getResult(int position) throws IOException, OpacErrorException { if (s_reusedoc != null) { return getResultById(null, null); } throw new UnsupportedOperationException(); } @Override public ReservationResult reservation(DetailledItem item, Account account, int useraction, String selection) throws IOException { Document doc; List<NameValuePair> nvpairs; ReservationResult res = null; if (selection != null && selection.equals("")) selection = null; if (s_pageform == null) return new ReservationResult(Status.ERROR); // Load details nvpairs = s_pageform; int i = 0; List<Integer> indexes = new ArrayList<Integer>(); for (NameValuePair np : nvpairs) { if (np.getName().contains("$Toolbar_") || np.getName().contains("selected")) { indexes.add(i); } i++; } for (int j = indexes.size() - 1; j >= 0; j nvpairs.remove((int) indexes.get(j)); } nvpairs.add(new BasicNameValuePair("selected", "ZTEXT " + item.getReservation_info())); doc = htmlPost(opac_url + ";jsessionid=" + s_sid, nvpairs); doc = htmlPost(opac_url + ";jsessionid=" + s_sid, nvpairs); // Yep, two // times. List<NameValuePair> form = new ArrayList<NameValuePair>(); for (Element input : doc.select("input, select")) { if (!"image".equals(input.attr("type")) && (!"submit".equals(input.attr("type")) || input.val().contains("Reservieren") || input .val().contains("Vormerken")) && !"checkbox".equals(input.attr("type")) && !"".equals(input.attr("name"))) { form.add(new BasicNameValuePair(input.attr("name"), input .attr("value"))); } } doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form); if (doc.select(".message h1").size() > 0) { String msg = doc.select(".message h1").text().trim(); res = new ReservationResult(MultiStepResult.Status.ERROR, msg); form = new ArrayList<NameValuePair>(); for (Element input : doc.select("input")) { if (!"image".equals(input.attr("type")) && !"checkbox".equals(input.attr("type")) && !"".equals(input.attr("name"))) { form.add(new BasicNameValuePair(input.attr("name"), input .attr("value"))); } } doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form); } else { try { doc = handleLoginForm(doc, account); } catch (OpacErrorException e1) { return new ReservationResult(MultiStepResult.Status.ERROR, e1.getMessage()); } if (useraction == 0 && selection == null && doc.select("#AUSGAB_1").size() == 0) { res = new ReservationResult( MultiStepResult.Status.CONFIRMATION_NEEDED); List<String[]> details = new ArrayList<String[]>(); details.add(new String[] { doc.select("#F23").text() }); res.setDetails(details); } else if (doc.select("#AUSGAB_1").size() > 0 && selection == null) { Map<String, String> sel = new HashMap<String, String>(); for (Element opt : doc.select("#AUSGAB_1 option")) { if (opt.text().trim().length() > 0) sel.put(opt.val(), opt.text()); } res = new ReservationResult( MultiStepResult.Status.SELECTION_NEEDED, doc.select( "#F23").text()); res.setSelection(sel); } else if (selection != null || doc.select("#AUSGAB_1").size() == 0) { if (doc.select("#AUSGAB_1").size() > 0) { doc.select("#AUSGAB_1").attr("value", selection); } if (doc.select(".message h1").size() > 0) { String msg = doc.select(".message h1").text().trim(); form = new ArrayList<NameValuePair>(); for (Element input : doc.select("input")) { if (!"image".equals(input.attr("type")) && !"checkbox".equals(input.attr("type")) && !"".equals(input.attr("name"))) { form.add(new BasicNameValuePair(input.attr("name"), input.attr("value"))); } } doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form); if (!msg.contains("Reservation ist erfolgt")) { res = new ReservationResult( MultiStepResult.Status.ERROR, msg); } else { res = new ReservationResult(MultiStepResult.Status.OK, msg); } } else { form = new ArrayList<NameValuePair>(); for (Element input : doc.select("input, select")) { if (!"image".equals(input.attr("type")) && !"submit".equals(input.attr("type")) && !"checkbox".equals(input.attr("type")) && !"".equals(input.attr("name"))) { form.add(new BasicNameValuePair(input.attr("name"), input.attr("value"))); } } form.add(new BasicNameValuePair("textButton", "Reservation abschicken")); res = new ReservationResult(MultiStepResult.Status.OK); doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form); if (doc.select(".message h1").size() > 0) { String msg = doc.select(".message h1").text().trim(); form = new ArrayList<NameValuePair>(); for (Element input : doc.select("input")) { if (!"image".equals(input.attr("type")) && !"checkbox".equals(input.attr("type")) && !"".equals(input.attr("name"))) { form.add(new BasicNameValuePair(input .attr("name"), input.attr("value"))); } } doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form); if (!msg.contains("Reservation ist erfolgt")) { res = new ReservationResult( MultiStepResult.Status.ERROR, msg); } else { res = new ReservationResult( MultiStepResult.Status.OK, msg); } } else if (doc.select("#R01").text() .contains("Informationen zu Ihrer Reservation")) { String msg = doc.select("#OPACLI").text().trim(); form = new ArrayList<NameValuePair>(); for (Element input : doc.select("input")) { if (!"image".equals(input.attr("type")) && !"checkbox".equals(input.attr("type")) && !"".equals(input.attr("name"))) { form.add(new BasicNameValuePair(input .attr("name"), input.attr("value"))); } } doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form); if (!msg.contains("Reservation ist erfolgt")) { res = new ReservationResult( MultiStepResult.Status.ERROR, msg); } else { res = new ReservationResult( MultiStepResult.Status.OK, msg); } } } } } if (res == null || res.getStatus() == MultiStepResult.Status.SELECTION_NEEDED || res.getStatus() == MultiStepResult.Status.CONFIRMATION_NEEDED) { form = new ArrayList<NameValuePair>(); for (Element input : doc.select("input, select")) { if (!"image".equals(input.attr("type")) && !"submit".equals(input.attr("type")) && !"checkbox".equals(input.attr("type")) && !"".equals(input.attr("name"))) { form.add(new BasicNameValuePair(input.attr("name"), input .attr("value"))); } } form.add(new BasicNameValuePair("textButton$0", "Abbrechen")); doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form); } // Reset s_pageform = new ArrayList<NameValuePair>(); for (Element input : doc.select("input, select")) { if (!"image".equals(input.attr("type")) && !"submit".equals(input.attr("type")) && !"checkbox".equals(input.attr("type")) && !"".equals(input.attr("name"))) { s_pageform.add(new BasicNameValuePair(input.attr("name"), input .attr("value"))); } } try { nvpairs = s_pageform; nvpairs.add(new BasicNameValuePair("$Toolbar_1.x", "1")); nvpairs.add(new BasicNameValuePair("$Toolbar_1.y", "1")); parse_search(htmlPost(opac_url + ";jsessionid=" + s_sid, nvpairs), 1); nvpairs = s_pageform; nvpairs.add(new BasicNameValuePair("$Toolbar_3.x", "1")); nvpairs.add(new BasicNameValuePair("$Toolbar_3.y", "1")); parse_search(htmlPost(opac_url + ";jsessionid=" + s_sid, nvpairs), 1); } catch (OpacErrorException e) { // TODO Auto-generated catch block e.printStackTrace(); } return res; } @Override public ProlongResult prolong(String media, Account account, int useraction, String selection) throws IOException { String alink = null; Document doc; if (s_accountcalled) { alink = media.split("\\|")[1].replace("requestCount=", "fooo="); } else { start(); doc = htmlGet(opac_url + ";jsessionid=" + s_sid + "?service=" + s_service + "&sp=SBK"); try { doc = handleLoginForm(doc, account); } catch (OpacErrorException e) { return new ProlongResult(Status.ERROR, e.getMessage()); } for (Element tr : doc.select(".rTable_div tr")) { if (tr.select("a").size() == 1) { if (tr.select("a").first().absUrl("href") .contains("sp=SZA")) { alink = tr.select("a").first().absUrl("href"); } } } if (alink == null) return new ProlongResult(Status.ERROR); } doc = htmlGet(alink); List<NameValuePair> form = new ArrayList<NameValuePair>(); for (Element input : doc.select("input, select")) { if (!"image".equals(input.attr("type")) && !"submit".equals(input.attr("type")) && !"checkbox".equals(input.attr("type")) && !"".equals(input.attr("name"))) { form.add(new BasicNameValuePair(input.attr("name"), input .attr("value"))); } } for (Element tr : doc.select(".rTable_div tr")) { if (tr.select("input").attr("name").equals(media.split("\\|")[0]) && tr.select("input").hasAttr("disabled")) { form.add(new BasicNameValuePair("$Toolbar_0.x", "1")); form.add(new BasicNameValuePair("$Toolbar_0.y", "1")); doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form); return new ProlongResult(Status.ERROR, tr.child(4).text() .trim()); } } form.add(new BasicNameValuePair(media.split("\\|")[0], "on")); form.add(new BasicNameValuePair("textButton$1", "Markierte Titel verlängern")); doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form); form = new ArrayList<NameValuePair>(); for (Element input : doc.select("input, select")) { if (!"image".equals(input.attr("type")) && !"submit".equals(input.attr("type")) && !"checkbox".equals(input.attr("type")) && !"".equals(input.attr("name"))) { form.add(new BasicNameValuePair(input.attr("name"), input .attr("value"))); } } form.add(new BasicNameValuePair("$Toolbar_0.x", "1")); form.add(new BasicNameValuePair("$Toolbar_0.y", "1")); doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form); return new ProlongResult(Status.OK); } @Override public ProlongAllResult prolongAll(Account account, int useraction, String selection) throws IOException { String alink = null; Document doc; if (s_accountcalled) { alink = s_alink.replace("requestCount=", "fooo="); } else { start(); doc = htmlGet(opac_url + ";jsessionid=" + s_sid + "?service=" + s_service + "&sp=SBK"); try { doc = handleLoginForm(doc, account); } catch (OpacErrorException e) { return new ProlongAllResult(Status.ERROR, e.getMessage()); } for (Element tr : doc.select(".rTable_div tr")) { if (tr.select("a").size() == 1) { if (tr.select("a").first().absUrl("href") .contains("sp=SZA")) { alink = tr.select("a").first().absUrl("href"); } } } if (alink == null) return new ProlongAllResult(Status.ERROR); } doc = htmlGet(alink); List<NameValuePair> form = new ArrayList<NameValuePair>(); for (Element input : doc.select("input, select")) { if (!"image".equals(input.attr("type")) && !"submit".equals(input.attr("type")) && !"checkbox".equals(input.attr("type")) && !"".equals(input.attr("name"))) { form.add(new BasicNameValuePair(input.attr("name"), input .attr("value"))); } if ("checkbox".equals(input.attr("type")) && !input.hasAttr("disabled")) { form.add(new BasicNameValuePair(input.attr("name"), "on")); } } form.add(new BasicNameValuePair("textButton$1", "Markierte Titel verlängern")); doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form); List<Map<String, String>> result = new ArrayList<Map<String, String>>(); for (Element tr : doc.select(".rTable_div tbody tr")) { Map<String, String> line = new HashMap<String, String>(); line.put(ProlongAllResult.KEY_LINE_TITLE, tr.child(3).text().split("[:/;]")[0].trim()); line.put(ProlongAllResult.KEY_LINE_NEW_RETURNDATE, tr.child(1) .text()); line.put(ProlongAllResult.KEY_LINE_MESSAGE, tr.child(4).text()); result.add(line); } form = new ArrayList<NameValuePair>(); for (Element input : doc.select("input, select")) { if (!"image".equals(input.attr("type")) && !"submit".equals(input.attr("type")) && !"checkbox".equals(input.attr("type")) && !"".equals(input.attr("name"))) { form.add(new BasicNameValuePair(input.attr("name"), input .attr("value"))); } } form.add(new BasicNameValuePair("$Toolbar_0.x", "1")); form.add(new BasicNameValuePair("$Toolbar_0.y", "1")); doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form); return new ProlongAllResult(Status.OK, result); } @Override public CancelResult cancel(String media, Account account, int useraction, String selection) throws IOException, OpacErrorException { String rlink = null; Document doc; if (s_accountcalled) { rlink = media.split("\\|")[1].replace("requestCount=", "fooo="); } else { start(); doc = htmlGet(opac_url + ";jsessionid=" + s_sid + "?service=" + s_service + "&sp=SBK"); try { doc = handleLoginForm(doc, account); } catch (OpacErrorException e) { return new CancelResult(Status.ERROR, e.getMessage()); } for (Element tr : doc.select(".rTable_div tr")) { if (tr.select("a").size() == 1) { if (tr.text().contains("Reservationen") && !tr.child(0).text().trim().equals("") && tr.select("a").first().attr("href") .toUpperCase(Locale.GERMAN) .contains("SP=SZM")) { rlink = tr.select("a").first().absUrl("href"); } } } if (rlink == null) return new CancelResult(Status.ERROR); } doc = htmlGet(rlink); List<NameValuePair> form = new ArrayList<NameValuePair>(); for (Element input : doc.select("input, select")) { if (!"image".equals(input.attr("type")) && !"submit".equals(input.attr("type")) && !"checkbox".equals(input.attr("type")) && !"".equals(input.attr("name"))) { form.add(new BasicNameValuePair(input.attr("name"), input .attr("value"))); } } form.add(new BasicNameValuePair(media.split("\\|")[0], "on")); form.add(new BasicNameValuePair("textButton$0", "Markierte Titel löschen")); doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form); form = new ArrayList<NameValuePair>(); for (Element input : doc.select("input, select")) { if (!"image".equals(input.attr("type")) && !"submit".equals(input.attr("type")) && !"checkbox".equals(input.attr("type")) && !"".equals(input.attr("name"))) { form.add(new BasicNameValuePair(input.attr("name"), input .attr("value"))); } } form.add(new BasicNameValuePair("$Toolbar_0.x", "1")); form.add(new BasicNameValuePair("$Toolbar_0.y", "1")); doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form); return new CancelResult(Status.OK); } @Override public AccountData account(Account account) throws IOException, JSONException, OpacErrorException { start(); s_accountcalled = true; Document doc = htmlGet(opac_url + ";jsessionid=" + s_sid + "?service=" + s_service + "&sp=SBK"); doc = handleLoginForm(doc, account); AccountData adata = new AccountData(account.getId()); for (Element tr : doc.select(".aDISListe tr")) { if (tr.child(0).text().matches(".*F.+llige Geb.+hren.*")) { adata.setPendingFees(tr.child(1).text().trim()); } if (tr.child(0).text().matches(".*Ausweis g.+ltig bis.*")) { adata.setValidUntil(tr.child(1).text().trim()); } } SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN); // Ausleihen String alink = null; int anum = 0; List<Map<String, String>> lent = new ArrayList<Map<String, String>>(); for (Element tr : doc.select(".rTable_div tr")) { if (tr.select("a").size() == 1) { if (tr.select("a").first().absUrl("href").contains("sp=SZA")) { alink = tr.select("a").first().absUrl("href"); anum = Integer.parseInt(tr.child(0).text().trim()); } } } if (alink != null) { Document adoc = htmlGet(alink); s_alink = alink; List<NameValuePair> form = new ArrayList<NameValuePair>(); String prolongTest = null; for (Element input : adoc.select("input, select")) { if (!"image".equals(input.attr("type")) && !"submit".equals(input.attr("type")) && !"".equals(input.attr("name"))) { if (input.attr("type").equals("checkbox") && !input.hasAttr("value")) { input.val("on"); } form.add(new BasicNameValuePair(input.attr("name"), input .attr("value"))); } else if (input.val().matches(".+verl.+ngerbar.+")) { prolongTest = input.attr("name"); } } if (prolongTest != null) { form.add(new BasicNameValuePair(prolongTest, "Markierte Titel verlängerbar?")); adoc = htmlPost(opac_url + ";jsessionid=" + s_sid, form); } for (Element tr : adoc.select(".rTable_div tbody tr")) { Map<String, String> line = new HashMap<String, String>(); line.put(AccountData.KEY_LENT_TITLE, tr.child(3).text().split("[:/;]")[0].trim()); line.put(AccountData.KEY_LENT_DEADLINE, tr.child(1).text() .trim()); try { line.put(AccountData.KEY_LENT_DEADLINE_TIMESTAMP, String .valueOf(sdf.parse(tr.child(1).text().trim()) .getTime())); } catch (ParseException e) { e.printStackTrace(); } line.put(AccountData.KEY_LENT_BRANCH, tr.child(2).text().trim()); line.put(AccountData.KEY_LENT_LINK, tr.select("input[type=checkbox]").attr("name") + "|" + alink); // line.put(AccountData.KEY_LENT_RENEWABLE, tr.child(4).text() // .matches(".*nicht verl.+ngerbar.*") ? "N" : "Y"); lent.add(line); } assert (lent.size() == anum); form = new ArrayList<NameValuePair>(); for (Element input : adoc.select("input, select")) { if (!"image".equals(input.attr("type")) && !"submit".equals(input.attr("type")) && !"checkbox".equals(input.attr("type")) && !"".equals(input.attr("name"))) { form.add(new BasicNameValuePair(input.attr("name"), input .attr("value"))); } } form.add(new BasicNameValuePair("$Toolbar_0.x", "1")); form.add(new BasicNameValuePair("$Toolbar_0.y", "1")); doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form); } else { assert (anum == 0); } adata.setLent(lent); List<String> rlinks = new ArrayList<String>(); int rnum = 0; List<Map<String, String>> res = new ArrayList<Map<String, String>>(); for (Element tr : doc.select(".rTable_div tr")) { if (tr.select("a").size() == 1) { if (tr.text().contains("Reservationen") && !tr.child(0).text().trim().equals("")) { rlinks.add(tr.select("a").first().absUrl("href")); rnum += Integer.parseInt(tr.child(0).text().trim()); } } } for (String rlink : rlinks) { Document rdoc = htmlGet(rlink); boolean error = false; for (Element tr : rdoc.select(".rTable_div tbody tr")) { if (tr.children().size() >= 4) { Map<String, String> line = new HashMap<String, String>(); line.put(AccountData.KEY_RESERVATION_TITLE, tr.child(2) .text().split("[:/;]")[0].trim()); line.put(AccountData.KEY_RESERVATION_READY, tr.child(3) .text().trim().substring(0, 10)); line.put(AccountData.KEY_RESERVATION_BRANCH, tr.child(1) .text().trim()); if (tr.select("input[type=checkbox]").size() > 0 && rlink.toUpperCase(Locale.GERMAN).contains( "SP=SZM")) line.put(AccountData.KEY_RESERVATION_CANCEL, tr.select("input[type=checkbox]").attr("name") + "|" + rlink); res.add(line); } else { // This is a strange bug where sometimes there is only three // columns error = true; } } if (error) { // Maybe we should send a bug report here, but using ACRA breaks // the unit tests adata.setWarning("Beim Abrufen der Reservationen ist ein Problem aufgetreten"); } List<NameValuePair> form = new ArrayList<NameValuePair>(); for (Element input : rdoc.select("input, select")) { if (!"image".equals(input.attr("type")) && !"submit".equals(input.attr("type")) && !"checkbox".equals(input.attr("type")) && !"".equals(input.attr("name"))) { form.add(new BasicNameValuePair(input.attr("name"), input .attr("value"))); } } form.add(new BasicNameValuePair("$Toolbar_0.x", "1")); form.add(new BasicNameValuePair("$Toolbar_0.y", "1")); doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form); } assert (res.size() == rnum); adata.setReservations(res); return adata; } protected Document handleLoginForm(Document doc, Account account) throws IOException, OpacErrorException { if (doc.select("#LPASSW_1").size() == 0) { return doc; } doc.select("#LPASSW_1").val(account.getPassword()); List<NameValuePair> form = new ArrayList<NameValuePair>(); for (Element input : doc.select("input, select")) { if (!"image".equals(input.attr("type")) && !"checkbox".equals(input.attr("type")) && !input.attr("value").contains("vergessen") && !"".equals(input.attr("name"))) { if (input.attr("id").equals("L#AUSW_1") || input.attr("id").equals("IDENT_1") || input.attr("id").equals("LMATNR_1")) { input.attr("value", account.getName()); } form.add(new BasicNameValuePair(input.attr("name"), input .attr("value"))); } } doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form); if (doc.select(".message h1").size() > 0) { String msg = doc.select(".message h1").text().trim(); form = new ArrayList<NameValuePair>(); for (Element input : doc.select("input")) { if (!"image".equals(input.attr("type")) && !"checkbox".equals(input.attr("type")) && !"".equals(input.attr("name"))) { form.add(new BasicNameValuePair(input.attr("name"), input .attr("value"))); } } doc = htmlPost(opac_url + ";jsessionid=" + s_sid, form); if (!msg.contains("Sie sind angemeldet")) { throw new OpacErrorException(msg); } return doc; } else { return doc; } } @Override public List<SearchField> getSearchFields() throws IOException, JSONException { if (!initialised) start(); Document doc = htmlGet(opac_url + ";jsessionid=" + s_sid + "?service=" + s_service + "&sp=" + s_exts); List<SearchField> fields = new ArrayList<SearchField>(); // dropdown to select which field you want to search in for (Element opt : doc.select("#SUCH01_1 option")) { TextSearchField field = new TextSearchField(); field.setId(opt.attr("value")); field.setDisplayName(opt.text()); field.setHint(""); fields.add(field); } // Save data so that the search() function knows that this // is not a selectable search field JSONObject selectableData = new JSONObject(); selectableData.put("selectable", false); for (Element row : doc.select("div[id~=F\\d+]")) { if (row.select("input[type=text]").size() == 1 && row.select("input, select").first().tagName() .equals("input")) { // A single text search field Element input = row.select("input[type=text]").first(); TextSearchField field = new TextSearchField(); field.setId(input.attr("id")); field.setDisplayName(row.select("label").first().text()); field.setHint(""); field.setData(selectableData); fields.add(field); } else if (row.select("select").size() == 1 && row.select("input[type=text]").size() == 0) { // Things like language, media type, etc. Element select = row.select("select").first(); DropdownSearchField field = new DropdownSearchField(); field.setId(select.id()); field.setDisplayName(row.select("label").first().text()); List<Map<String, String>> values = new ArrayList<Map<String, String>>(); for (Element opt : select.select("option")) { Map<String, String> value = new HashMap<String, String>(); value.put("key", opt.attr("value")); value.put("value", opt.text()); values.add(value); } field.setDropdownValues(values); fields.add(field); } else if (row.select("select").size() == 0 && row.select("input[type=text]").size() == 3 && row.select("label").size() == 3) { // Three text inputs. // Year single/from/to or things like Band-/Heft-/Satznummer String name1 = row.select("label").get(0).text(); String name2 = row.select("label").get(1).text(); String name3 = row.select("label").get(2).text(); Element input1 = row.select("input[type=text]").get(0); Element input2 = row.select("input[type=text]").get(1); Element input3 = row.select("input[type=text]").get(2); if (name2.contains("von") && name3.contains("bis")) { TextSearchField field1 = new TextSearchField(); field1.setId(input1.id()); field1.setDisplayName(name1); field1.setHint(""); field1.setData(selectableData); fields.add(field1); TextSearchField field2 = new TextSearchField(); field2.setId(input2.id()); field2.setDisplayName(name2.replace("von", "").trim()); field2.setHint("von"); field2.setData(selectableData); fields.add(field2); TextSearchField field3 = new TextSearchField(); field3.setId(input3.id()); field3.setDisplayName(name3.replace("bis", "").trim()); field3.setHint("bis"); field3.setHalfWidth(true); field3.setData(selectableData); fields.add(field3); } else { TextSearchField field1 = new TextSearchField(); field1.setId(input1.id()); field1.setDisplayName(name1); field1.setHint(""); field1.setData(selectableData); fields.add(field1); TextSearchField field2 = new TextSearchField(); field2.setId(input2.id()); field2.setDisplayName(name2); field2.setHint(""); field2.setData(selectableData); fields.add(field2); TextSearchField field3 = new TextSearchField(); field3.setId(input3.id()); field3.setDisplayName(name3); field3.setHint(""); field3.setData(selectableData); fields.add(field3); } } } for (Iterator<SearchField> iterator = fields.iterator(); iterator .hasNext();) { SearchField field = iterator.next(); if (ignoredFieldNames.contains(field.getDisplayName())) { iterator.remove(); } } return fields; } @Override public boolean isAccountSupported(Library library) { return true; } @Override public boolean isAccountExtendable() { return false; } @Override public String getAccountExtendableInfo(Account account) throws IOException, NotReachableException { throw new UnsupportedOperationException(); } @Override public String getShareUrl(String id, String title) { // TODO Auto-generated method stub return null; } @Override public int getSupportFlags() { return SUPPORT_FLAG_ACCOUNT_PROLONG_ALL | SUPPORT_FLAG_ENDLESS_SCROLLING; } public static Map<String, List<String>> getQueryParams(String url) { try { Map<String, List<String>> params = new HashMap<String, List<String>>(); String[] urlParts = url.split("\\?"); if (urlParts.length > 1) { String query = urlParts[1]; for (String param : query.split("&")) { String[] pair = param.split("="); String key = URLDecoder.decode(pair[0], "UTF-8"); String value = ""; if (pair.length > 1) { value = URLDecoder.decode(pair[1], "UTF-8"); } List<String> values = params.get(key); if (values == null) { values = new ArrayList<String>(); params.put(key, values); } values.add(value); } } return params; } catch (UnsupportedEncodingException ex) { throw new AssertionError(ex); } } @Override public void checkAccountData(Account account) throws IOException, JSONException, OpacErrorException { start(); s_accountcalled = true; Document doc = htmlGet(opac_url + ";jsessionid=" + s_sid + "?service=" + s_service + "&sp=SBK"); doc = handleLoginForm(doc, account); } }
package de.geeksfactory.opacclient.apis; import java.io.IOException; import java.net.URI; import java.net.URLDecoder; import java.net.URLEncoder; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CookieStore; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.Node; import org.jsoup.nodes.TextNode; import org.jsoup.select.Elements; import de.geeksfactory.opacclient.NotReachableException; import de.geeksfactory.opacclient.i18n.StringProvider; import de.geeksfactory.opacclient.objects.Account; import de.geeksfactory.opacclient.objects.AccountData; import de.geeksfactory.opacclient.objects.Detail; import de.geeksfactory.opacclient.objects.DetailledItem; import de.geeksfactory.opacclient.objects.Filter; import de.geeksfactory.opacclient.objects.Filter.Option; import de.geeksfactory.opacclient.objects.Library; import de.geeksfactory.opacclient.objects.SearchRequestResult; import de.geeksfactory.opacclient.objects.SearchResult; import de.geeksfactory.opacclient.objects.SearchResult.MediaType; import de.geeksfactory.opacclient.searchfields.CheckboxSearchField; import de.geeksfactory.opacclient.searchfields.DropdownSearchField; import de.geeksfactory.opacclient.searchfields.SearchField; import de.geeksfactory.opacclient.searchfields.SearchQuery; import de.geeksfactory.opacclient.searchfields.TextSearchField; import de.geeksfactory.opacclient.utils.ISBNTools; /** * @author Johan von Forstner, 16.09.2013 * */ public class Pica extends BaseApi implements OpacApi { protected String opac_url = ""; protected String https_url = ""; protected JSONObject data; protected boolean initialised = false; protected Library library; protected int resultcount = 10; protected String reusehtml; protected Integer searchSet; protected String db; protected String pwEncoded; CookieStore cookieStore = new BasicCookieStore(); protected String lor_reservations; protected static HashMap<String, MediaType> defaulttypes = new HashMap<String, MediaType>(); static { defaulttypes.put("book", MediaType.BOOK); defaulttypes.put("article", MediaType.BOOK); defaulttypes.put("binary", MediaType.EBOOK); defaulttypes.put("periodical", MediaType.MAGAZINE); defaulttypes.put("onlineper", MediaType.EBOOK); defaulttypes.put("letter", MediaType.UNKNOWN); defaulttypes.put("handwriting", MediaType.UNKNOWN); defaulttypes.put("map", MediaType.MAP); defaulttypes.put("picture", MediaType.ART); defaulttypes.put("audiovisual", MediaType.MOVIE); defaulttypes.put("score", MediaType.SCORE_MUSIC); defaulttypes.put("sound", MediaType.CD_MUSIC); defaulttypes.put("software", MediaType.CD_SOFTWARE); defaulttypes.put("microfilm", MediaType.UNKNOWN); defaulttypes.put("empty", MediaType.UNKNOWN); } @Override public void start() throws IOException, NotReachableException { // String html = httpGet(opac_url // + "/DB=" + db + "/SET=1/TTL=1/ADVANCED_SEARCHFILTER", // getDefaultEncoding(), false, cookieStore); // Document doc = Jsoup.parse(html); // updateSearchSetValue(doc); } @Override public void init(Library lib) { super.init(lib); this.library = lib; this.data = lib.getData(); try { this.opac_url = data.getString("baseurl"); this.db = data.getString("db"); if (!library.getData().isNull("accountSupported")) { if (data.has("httpsbaseurl")) { this.https_url = data.getString("httpsbaseurl"); } else { this.https_url = this.opac_url; } } } catch (JSONException e) { throw new RuntimeException(e); } } protected int addParameters(SearchQuery query, List<NameValuePair> params, int index) throws JSONException { if (query.getValue().equals("") || query.getValue().equals("false")) return index; if (query.getSearchField() instanceof TextSearchField) { if (query.getSearchField().getData().getBoolean("ADI")) { params.add(new BasicNameValuePair(query.getKey(), query .getValue())); } else { if (index == 0) { params.add(new BasicNameValuePair("ACT" + index, "SRCH")); } else { params.add(new BasicNameValuePair("ACT" + index, "*")); } params.add(new BasicNameValuePair("IKT" + index, query.getKey())); params.add(new BasicNameValuePair("TRM" + index, query .getValue())); return index + 1; } } else if (query.getSearchField() instanceof CheckboxSearchField) { boolean checked = Boolean.valueOf(query.getValue()); if (checked) { params.add(new BasicNameValuePair(query.getKey(), "Y")); } } else if (query.getSearchField() instanceof DropdownSearchField) { params.add(new BasicNameValuePair(query.getKey(), query.getValue())); } return index; } @Override public SearchRequestResult search(List<SearchQuery> query) throws IOException, NotReachableException, OpacErrorException, JSONException { List<NameValuePair> params = new ArrayList<NameValuePair>(); int index = 0; start(); params.add(new BasicNameValuePair("ACT", "SRCHM")); params.add(new BasicNameValuePair("MATCFILTER", "Y")); params.add(new BasicNameValuePair("MATCSET", "Y")); params.add(new BasicNameValuePair("NOSCAN", "Y")); params.add(new BasicNameValuePair("PARSE_MNEMONICS", "N")); params.add(new BasicNameValuePair("PARSE_OPWORDS", "N")); params.add(new BasicNameValuePair("PARSE_OLDSETS", "N")); for (SearchQuery singleQuery : query) { index = addParameters(singleQuery, params, index); } if (index == 0) { throw new OpacErrorException( stringProvider.getString(StringProvider.NO_CRITERIA_INPUT)); } if (index > 4) { throw new OpacErrorException(stringProvider.getFormattedString( StringProvider.LIMITED_NUM_OF_CRITERIA, 4)); } String html = httpGet(opac_url + "/DB=" + db + "/SET=1/TTL=1/CMD?" + URLEncodedUtils.format(params, getDefaultEncoding()), getDefaultEncoding(), false, cookieStore); return parse_search(html, 1); } protected SearchRequestResult parse_search(String html, int page) throws OpacErrorException { Document doc = Jsoup.parse(html); updateSearchSetValue(doc); if (doc.select(".error").size() > 0) { if (doc.select(".error").text().trim() .equals("Es wurde nichts gefunden.")) { // nothing found return new SearchRequestResult(new ArrayList<SearchResult>(), 0, 1, 1); } else { // error throw new OpacErrorException(doc.select(".error").first() .text().trim()); } } reusehtml = html; int results_total = -1; String resultnumstr = doc.select(".pages").first().text(); Pattern p = Pattern.compile("[0-9]+$"); Matcher m = p.matcher(resultnumstr); if (m.find()) { resultnumstr = m.group(); } if (resultnumstr.contains("(")) { results_total = Integer.parseInt(resultnumstr.replaceAll( ".*\\(([0-9]+)\\).*", "$1")); } else if (resultnumstr.contains(": ")) { results_total = Integer.parseInt(resultnumstr.replaceAll( ".*: ([0-9]+)$", "$1")); } else { results_total = Integer.parseInt(resultnumstr); } List<SearchResult> results = new ArrayList<SearchResult>(); if (results_total == 1) { // Only one result try { DetailledItem singleResult = parse_result(html); SearchResult sr = new SearchResult(); sr.setType(getMediaTypeInSingleResult(html)); sr.setInnerhtml("<b>" + singleResult.getTitle() + "</b><br>" + singleResult.getDetails().get(0).getContent()); results.add(sr); } catch (IOException e) { e.printStackTrace(); } } Elements table = doc .select("table[summary=hitlist] tbody tr[valign=top]"); // identifier = null; Elements links = doc.select("table[summary=hitlist] a"); boolean haslink = false; for (int i = 0; i < links.size(); i++) { Element node = links.get(i); if (node.hasAttr("href") & node.attr("href").contains("SHW?") && !haslink) { haslink = true; try { List<NameValuePair> anyurl = URLEncodedUtils.parse(new URI( node.attr("href")), getDefaultEncoding()); for (NameValuePair nv : anyurl) { if (nv.getName().equals("identifier")) { // identifier = nv.getValue(); break; } } } catch (Exception e) { e.printStackTrace(); } } } for (int i = 0; i < table.size(); i++) { Element tr = table.get(i); SearchResult sr = new SearchResult(); if (tr.select("td.hit img").size() > 0) { String[] fparts = tr.select("td img").get(0).attr("src") .split("/"); String fname = fparts[fparts.length - 1]; if (data.has("mediatypes")) { try { sr.setType(MediaType.valueOf(data.getJSONObject( "mediatypes").getString(fname))); } catch (JSONException e) { sr.setType(defaulttypes.get(fname .toLowerCase(Locale.GERMAN).replace(".jpg", "") .replace(".gif", "").replace(".png", ""))); } catch (IllegalArgumentException e) { sr.setType(defaulttypes.get(fname .toLowerCase(Locale.GERMAN).replace(".jpg", "") .replace(".gif", "").replace(".png", ""))); } } else { sr.setType(defaulttypes.get(fname .toLowerCase(Locale.GERMAN).replace(".jpg", "") .replace(".gif", "").replace(".png", ""))); } } Element middlething = tr.child(2); List<Node> children = middlething.childNodes(); int childrennum = children.size(); List<String[]> strings = new ArrayList<String[]>(); for (int ch = 0; ch < childrennum; ch++) { Node node = children.get(ch); if (node instanceof TextNode) { String text = ((TextNode) node).text().trim(); if (text.length() > 3) strings.add(new String[] { "text", "", text }); } else if (node instanceof Element) { List<Node> subchildren = node.childNodes(); for (int j = 0; j < subchildren.size(); j++) { Node subnode = subchildren.get(j); if (subnode instanceof TextNode) { String text = ((TextNode) subnode).text().trim(); if (text.length() > 3) strings.add(new String[] { ((Element) node).tag().getName(), "text", text, ((Element) node).className(), ((Element) node).attr("style") }); } else if (subnode instanceof Element) { String text = ((Element) subnode).text().trim(); if (text.length() > 3) strings.add(new String[] { ((Element) node).tag().getName(), ((Element) subnode).tag().getName(), text, ((Element) node).className(), ((Element) node).attr("style") }); } } } } StringBuilder description = new StringBuilder(); int k = 0; for (String[] part : strings) { if (part[0] == "a" && k == 0) { description.append("<b>" + part[2] + "</b>"); } else if (k < 3) { description.append("<br />" + part[2]); } k++; } sr.setInnerhtml(description.toString()); sr.setNr(10 * (page - 1) + i); sr.setId(null); results.add(sr); } resultcount = results.size(); return new SearchRequestResult(results, results_total, page); } @Override public SearchRequestResult searchGetPage(int page) throws IOException, NotReachableException, OpacErrorException { if (!initialised) start(); String html = httpGet(opac_url + "/DB=" + db + "/SET=" + searchSet + "/TTL=1/NXT?FRST=" + (((page - 1) * resultcount) + 1), getDefaultEncoding(), false, cookieStore); return parse_search(html, page); } @Override public SearchRequestResult filterResults(Filter filter, Option option) throws IOException, NotReachableException { return null; } @Override public DetailledItem getResultById(String id, String homebranch) throws IOException, NotReachableException { if (id == null && reusehtml != null) { return parse_result(reusehtml); } String html = httpGet(id, getDefaultEncoding()); return parse_result(html); } @Override public DetailledItem getResult(int position) throws IOException { String html = httpGet(opac_url + "/DB=" + db + "/SET=" + searchSet + "/TTL=1/SHW?FRST=" + (position + 1), getDefaultEncoding(), false, cookieStore); return parse_result(html); } protected DetailledItem parse_result(String html) throws IOException { Document doc = Jsoup.parse(html); doc.setBaseUri(opac_url); DetailledItem result = new DetailledItem(); if (doc.select("img[src*=permalink], img[src*=zitierlink]").size() > 0) { String id = opac_url + doc.select("img[src*=permalink], img[src*=zitierlink]") .get(0).parent().absUrl("href"); result.setId(id); } else { for (Element a : doc.select("a")) { if (a.attr("href").contains("PPN=")) { Map<String, String> hrefq = getQueryParamsFirst(a .absUrl("href")); String ppn = hrefq.get("PPN"); try { result.setId(opac_url + "/DB=" + data.getString("db") + "/PPNSET?PPN=" + ppn); } catch (JSONException e1) { e1.printStackTrace(); } break; } } } // GET COVER if (doc.select("td.preslabel:contains(ISBN) + td.presvalue").size() > 0) { Element isbnElement = doc.select( "td.preslabel:contains(ISBN) + td.presvalue").first(); String isbn = ""; for (Node child : isbnElement.childNodes()) { if (child instanceof TextNode) { isbn = ((TextNode) child).text().trim(); break; } } result.setCover(ISBNTools.getAmazonCoverURL(isbn, true)); } // GET TITLE AND SUBTITLE String titleAndSubtitle = ""; if (doc.select("td.preslabel:contains(Titel) + td.presvalue").size() > 0) { titleAndSubtitle = doc .select("td.preslabel:contains(Titel) + td.presvalue") .first().text().trim(); int slashPosition = titleAndSubtitle.indexOf("/"); String title; String subtitle; if (slashPosition > 0) { title = titleAndSubtitle.substring(0, slashPosition).trim(); subtitle = titleAndSubtitle.substring(slashPosition + 1).trim(); result.addDetail(new Detail(stringProvider .getString(StringProvider.SUBTITLE), subtitle)); } else { title = titleAndSubtitle; subtitle = ""; } result.setTitle(title); } else if (doc.select("td.preslabel:contains(Aufsatz) + td.presvalue") .size() > 0) { titleAndSubtitle = doc .select("td.preslabel:contains(Aufsatz) + td.presvalue") .first().text().trim(); int slashPosition = titleAndSubtitle.indexOf("/"); String title; String subtitle; if (slashPosition > 0) { title = titleAndSubtitle.substring(0, slashPosition).trim(); subtitle = titleAndSubtitle.substring(slashPosition + 1).trim(); result.addDetail(new Detail(stringProvider .getString(StringProvider.SUBTITLE), subtitle)); } else { title = titleAndSubtitle; subtitle = ""; } result.setTitle(title); } else if (doc.select( "td.preslabel:contains(Zeitschrift) + td.presvalue").size() > 0) { titleAndSubtitle = doc .select("td.preslabel:contains(Zeitschrift) + td.presvalue") .first().text().trim(); int slashPosition = titleAndSubtitle.indexOf("/"); String title; String subtitle; if (slashPosition > 0) { title = titleAndSubtitle.substring(0, slashPosition).trim(); subtitle = titleAndSubtitle.substring(slashPosition + 1).trim(); result.addDetail(new Detail(stringProvider .getString(StringProvider.SUBTITLE), subtitle)); } else { title = titleAndSubtitle; subtitle = ""; } result.setTitle(title); } else { result.setTitle(""); } // GET OTHER INFORMATION Map<String, String> e = new HashMap<String, String>(); String location = ""; // reservation info will be stored as JSON, because it can get // complicated JSONArray reservationInfo = new JSONArray(); for (Element element : doc.select("td.preslabel + td.presvalue")) { Element titleElem = element.firstElementSibling(); String detail = element.text().trim(); String title = titleElem.text().trim().replace("\u00a0", ""); if (element.select("hr").size() == 0) { // no separator if (title.indexOf(":") != -1) { title = title.substring(0, title.indexOf(":")); // remove // colon } if (title.contains("Standort") || title.contains("Vorhanden in")) { location += detail; } else if (title.contains("Sonderstandort")) { location += " - " + detail; } else if (title.contains("Fachnummer")) { e.put(DetailledItem.KEY_COPY_LOCATION, detail); } else if (title.contains("Signatur")) { e.put(DetailledItem.KEY_COPY_SHELFMARK, detail); } else if (title.contains("Anmerkung")) { location += " (" + detail + ")"; } else if (title.contains("Status") || title.contains("Ausleihinfo")) { detail = detail.replace("Bestellen", "") .replace("verfuegbar", "verfügbar") .replace("Verfuegbar", "verfügbar") .replace("Vormerken", "") .replace("Liste der Exemplare", "").trim(); e.put(DetailledItem.KEY_COPY_STATUS, detail); // Get reservation info if (element.select( "a:contains(Vormerken), a:contains(Exemplare)") .size() > 0) { Element a = element.select( "a:contains(Vormerken), a:contains(Exemplare)") .first(); boolean multipleCopies = a.text().contains("Exemplare"); JSONObject reservation = new JSONObject(); try { reservation.put("multi", multipleCopies); reservation.put("link", opac_url + a.attr("href")); reservation.put("desc", location); reservationInfo.put(reservation); } catch (JSONException e1) { e1.printStackTrace(); } result.setReservable(true); } } else if (!title.equals("Titel")) { result.addDetail(new Detail(title, detail)); } } else if (e.size() > 0) { e.put(DetailledItem.KEY_COPY_BRANCH, location); result.addCopy(e); location = ""; e = new HashMap<String, String>(); } } e.put(DetailledItem.KEY_COPY_BRANCH, location); result.addCopy(e); result.setReservation_info(reservationInfo.toString()); return result; } @Override public ReservationResult reservation(DetailledItem item, Account account, int useraction, String selection) throws IOException { try { if (selection == null || !selection.startsWith("{")) { JSONArray json = new JSONArray(item.getReservation_info()); int selectedPos; if (selection != null) { selectedPos = Integer.parseInt(selection); } else if (json.length() == 1) { selectedPos = 0; } else { // a location must be selected ReservationResult res = new ReservationResult( MultiStepResult.Status.SELECTION_NEEDED); res.setActionIdentifier(ReservationResult.ACTION_BRANCH); Map<String, String> selections = new HashMap<String, String>(); for (int i = 0; i < json.length(); i++) { selections.put(String.valueOf(i), json.getJSONObject(i) .getString("desc")); } res.setSelection(selections); return res; } if (json.getJSONObject(selectedPos).getBoolean("multi")) { // A copy must be selected String html1 = httpGet(json.getJSONObject(selectedPos) .getString("link"), getDefaultEncoding()); Document doc1 = Jsoup.parse(html1); Elements trs = doc1 .select("table[summary=list of volumes header] tr:has(input[type=radio])"); if (trs.size() > 0) { Map<String, String> selections = new HashMap<String, String>(); for (Element tr : trs) { JSONObject values = new JSONObject(); for (Element input : doc1 .select("input[type=hidden]")) { values.put(input.attr("name"), input.attr("value")); } values.put(tr.select("input").attr("name"), tr .select("input").attr("value")); selections.put(values.toString(), tr.text()); } ReservationResult res = new ReservationResult( MultiStepResult.Status.SELECTION_NEEDED); res.setActionIdentifier(ReservationResult.ACTION_USER); res.setMessage(stringProvider .getString(StringProvider.PICA_WHICH_COPY)); res.setSelection(selections); return res; } else { ReservationResult res = new ReservationResult( MultiStepResult.Status.ERROR); res.setMessage(stringProvider .getString(StringProvider.NO_COPY_RESERVABLE)); return res; } } else { String html1 = httpGet(json.getJSONObject(selectedPos) .getString("link"), getDefaultEncoding()); Document doc1 = Jsoup.parse(html1); List<NameValuePair> params = new ArrayList<NameValuePair>(); for (Element input : doc1.select("input[type=hidden]")) { params.add(new BasicNameValuePair(input.attr("name"), input.attr("value"))); } params.add(new BasicNameValuePair("BOR_U", account .getName())); params.add(new BasicNameValuePair("BOR_PW", account .getPassword())); return reservation_result(params, false); } } else { // A copy has been selected JSONObject values = new JSONObject(selection); List<NameValuePair> params = new ArrayList<NameValuePair>(); Iterator<String> keys = values.keys(); while (keys.hasNext()) { String key = (String) keys.next(); String value = values.getString(key); params.add(new BasicNameValuePair(key, value)); } params.add(new BasicNameValuePair("BOR_U", account.getName())); params.add(new BasicNameValuePair("BOR_PW", account .getPassword())); return reservation_result(params, true); } } catch (JSONException e) { e.printStackTrace(); ReservationResult res = new ReservationResult( MultiStepResult.Status.ERROR); res.setMessage(stringProvider .getString(StringProvider.INTERNAL_ERROR)); return res; } } public ReservationResult reservation_result(List<NameValuePair> params, boolean multi) throws IOException { String html2 = httpPost(https_url + "/loan/LNG=DU/DB=" + db + "/SET=" + searchSet + "/TTL=1/" + (multi ? "REQCONT" : "RESCONT"), new UrlEncodedFormEntity(params, getDefaultEncoding()), getDefaultEncoding()); Document doc2 = Jsoup.parse(html2); if (doc2.select(".alert").text().contains("ist fuer Sie vorgemerkt")) { return new ReservationResult(MultiStepResult.Status.OK); } else { ReservationResult res = new ReservationResult( MultiStepResult.Status.ERROR); res.setMessage(doc2.select(".cnt .alert").text()); return res; } } @Override public ProlongResult prolong(String media, Account account, int useraction, String Selection) throws IOException { if (pwEncoded == null) try { account(account); } catch (JSONException e1) { return new ProlongResult(MultiStepResult.Status.ERROR); } catch (OpacErrorException e1) { return new ProlongResult(MultiStepResult.Status.ERROR, e1.getMessage()); } List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("ACT", "UI_RENEWLOAN")); params.add(new BasicNameValuePair("BOR_U", account.getName())); params.add(new BasicNameValuePair("BOR_PW_ENC", URLDecoder.decode( pwEncoded, "UTF-8"))); params.add(new BasicNameValuePair("VB", media)); String html = httpPost(https_url + "/loan/DB=" + db + "/USERINFO", new UrlEncodedFormEntity(params, getDefaultEncoding()), getDefaultEncoding()); Document doc = Jsoup.parse(html); if (doc.select("td.regular-text") .text() .contains( "Die Leihfrist Ihrer ausgeliehenen Publikationen ist ") || doc.select("td.regular-text").text() .contains("Ihre ausgeliehenen Publikationen sind verl")) { return new ProlongResult(MultiStepResult.Status.OK); } else if (doc.select(".cnt").text().contains("identify")) { try { account(account); return prolong(media, account, useraction, Selection); } catch (JSONException e) { return new ProlongResult(MultiStepResult.Status.ERROR); } catch (OpacErrorException e) { return new ProlongResult(MultiStepResult.Status.ERROR, e.getMessage()); } } else { ProlongResult res = new ProlongResult(MultiStepResult.Status.ERROR); res.setMessage(doc.select(".cnt").text()); return res; } } @Override public ProlongAllResult prolongAll(Account account, int useraction, String selection) throws IOException { return null; } @Override public CancelResult cancel(String media, Account account, int useraction, String selection) throws IOException, OpacErrorException { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("ACT", "UI_CANCELRES")); params.add(new BasicNameValuePair("BOR_U", account.getName())); params.add(new BasicNameValuePair("BOR_PW_ENC", URLDecoder.decode( pwEncoded, "UTF-8"))); if (lor_reservations != null) params.add(new BasicNameValuePair("LOR_RESERVATIONS", lor_reservations)); params.add(new BasicNameValuePair("VB", media)); String html = httpPost(https_url + "/loan/DB=" + db + "/SET=" + searchSet + "/TTL=1/USERINFO", new UrlEncodedFormEntity( params, getDefaultEncoding()), getDefaultEncoding()); Document doc = Jsoup.parse(html); if (doc.select("td.regular-text").text() .contains("Ihre Vormerkungen sind ")) { return new CancelResult(MultiStepResult.Status.OK); } else if (doc.select(".cnt .alert").text() .contains("identify yourself")) { try { account(account); return cancel(media, account, useraction, selection); } catch (JSONException e) { throw new OpacErrorException( stringProvider.getString(StringProvider.INTERNAL_ERROR)); } } else { CancelResult res = new CancelResult(MultiStepResult.Status.ERROR); res.setMessage(doc.select(".cnt").text()); return res; } } @Override public AccountData account(Account account) throws IOException, JSONException, OpacErrorException { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("ACT", "UI_DATA")); params.add(new BasicNameValuePair("HOST_NAME", "")); params.add(new BasicNameValuePair("HOST_PORT", "")); params.add(new BasicNameValuePair("HOST_SCRIPT", "")); params.add(new BasicNameValuePair("LOGIN", "KNOWNUSER")); params.add(new BasicNameValuePair("STATUS", "HML_OK")); params.add(new BasicNameValuePair("BOR_U", account.getName())); params.add(new BasicNameValuePair("BOR_PW", account.getPassword())); String html = httpPost(https_url + "/loan/DB=" + db + "/LNG=DU/USERINFO", new UrlEncodedFormEntity(params, getDefaultEncoding()), getDefaultEncoding()); Document doc = Jsoup.parse(html); if (doc.select(".cnt .alert, .cnt .error").size() > 0) { throw new OpacErrorException(doc.select(".cnt .alert, .cnt .error") .text()); } if (doc.select("input[name=BOR_PW_ENC]").size() > 0) { pwEncoded = URLEncoder.encode(doc.select("input[name=BOR_PW_ENC]") .attr("value"), "UTF-8"); } else { // TODO: do something here to help fix bug #229 } html = httpGet(https_url + "/loan/DB=" + db + "/USERINFO?ACT=UI_LOL&BOR_U=" + account.getName() + "&BOR_PW_ENC=" + pwEncoded, getDefaultEncoding()); doc = Jsoup.parse(html); html = httpGet(https_url + "/loan/DB=" + db + "/USERINFO?ACT=UI_LOR&BOR_U=" + account.getName() + "&BOR_PW_ENC=" + pwEncoded, getDefaultEncoding()); Document doc2 = Jsoup.parse(html); AccountData res = new AccountData(account.getId()); List<Map<String, String>> medien = new ArrayList<Map<String, String>>(); List<Map<String, String>> reserved = new ArrayList<Map<String, String>>(); if (doc.select("table[summary^=list]").size() > 0) { parse_medialist(medien, doc, 1, account.getName()); } if (doc2.select("table[summary^=list]").size() > 0) { parse_reslist(reserved, doc2, 1); } res.setLent(medien); res.setReservations(reserved); if (medien == null || reserved == null) { throw new OpacErrorException( stringProvider .getString(StringProvider.UNKNOWN_ERROR_ACCOUNT)); // Log.d("OPACCLIENT", html); } return res; } protected void parse_medialist(List<Map<String, String>> medien, Document doc, int offset, String accountName) throws ClientProtocolException, IOException { Elements copytrs = doc .select("table[summary^=list] > tbody > tr[valign=top]"); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy", Locale.GERMAN); int trs = copytrs.size(); if (trs < 1) { medien = null; return; } assert (trs > 0); for (int i = 0; i < trs; i++) { Element tr = copytrs.get(i); if (tr.select("table[summary=title data]").size() > 0) { // According to HTML code from Bug reports (Server TU Darmstadt, // Berlin Ibero-Amerikanisches Institut) Map<String, String> e = new HashMap<String, String>(); // Check if there is a checkbox to prolong this item if (tr.select("input").size() > 0) e.put(AccountData.KEY_LENT_LINK, tr.select("input").attr("value")); else e.put(AccountData.KEY_LENT_RENEWABLE, "N"); Elements datatrs = tr.select("table[summary=title data] tr"); e.put(AccountData.KEY_LENT_TITLE, datatrs.get(0).text()); List<TextNode> textNodes = datatrs.get(1).select("td").first() .textNodes(); List<TextNode> nodes = new ArrayList<TextNode>(); Elements titles = datatrs.get(1).select("span.label-small"); for (TextNode node : textNodes) { if (!node.text().equals(" ")) nodes.add(node); } assert (nodes.size() == titles.size()); for (int j = 0; j < nodes.size(); j++) { String title = titles.get(j).text(); String value = nodes.get(j).text().trim().replace(";", ""); if (title.contains("Signatur")) { // not supported } else if (title.contains("Status")) { e.put(AccountData.KEY_LENT_STATUS, value); } else if (title.contains("Leihfristende")) { e.put(AccountData.KEY_LENT_DEADLINE, value); try { e.put(AccountData.KEY_LENT_DEADLINE_TIMESTAMP, String.valueOf(sdf.parse(value).getTime())); } catch (ParseException e1) { e1.printStackTrace(); } } else if (title.contains("Vormerkungen")) { // not supported } } medien.add(e); } else { // like in Kiel String prolongCount = ""; try { String html = httpGet(https_url + "/nr_renewals.php?U=" + accountName + "&DB=" + db + "&VBAR=" + tr.child(1).select("input").attr("value"), getDefaultEncoding()); prolongCount = Jsoup.parse(html).text(); } catch (IOException e) { } String reminderCount = tr.child(13).text().trim(); if (reminderCount.indexOf(" Mahn") >= 0 && reminderCount.indexOf("(") >= 0 && reminderCount.indexOf("(") < reminderCount .indexOf(" Mahn")) reminderCount = reminderCount.substring( reminderCount.indexOf("(") + 1, reminderCount.indexOf(" Mahn")); else reminderCount = ""; Map<String, String> e = new HashMap<String, String>(); if (tr.child(4).text().trim().length() < 5 && tr.child(5).text().trim().length() > 4) { e.put(AccountData.KEY_LENT_TITLE, tr.child(5).text().trim()); } else { e.put(AccountData.KEY_LENT_TITLE, tr.child(4).text().trim()); } String status = ""; if (!reminderCount.equals("0") && !reminderCount.equals("")) { status += reminderCount + " " + stringProvider .getString(StringProvider.REMINDERS) + ", "; } status += prolongCount + "x " + stringProvider .getString(StringProvider.PROLONGED_ABBR); // tr.child(25).text().trim() // + " Vormerkungen"); e.put(AccountData.KEY_LENT_STATUS, status); e.put(AccountData.KEY_LENT_DEADLINE, tr.child(21).text().trim()); try { e.put(AccountData.KEY_LENT_DEADLINE_TIMESTAMP, String .valueOf(sdf.parse( e.get(AccountData.KEY_LENT_DEADLINE)) .getTime())); } catch (ParseException e1) { e1.printStackTrace(); } e.put(AccountData.KEY_LENT_LINK, tr.child(1).select("input") .attr("value")); medien.add(e); } } assert (medien.size() == trs - 1); } protected void parse_reslist(List<Map<String, String>> medien, Document doc, int offset) throws ClientProtocolException, IOException { if (doc.select("input[name=LOR_RESERVATIONS]").size() > 0) { lor_reservations = doc.select("input[name=LOR_RESERVATIONS]").attr( "value"); } Elements copytrs = doc.select("table[summary^=list] tr[valign=top]"); int trs = copytrs.size(); if (trs < 1) { medien = null; return; } assert (trs > 0); for (int i = 0; i < trs; i++) { Element tr = copytrs.get(i); Map<String, String> e = new HashMap<String, String>(); e.put(AccountData.KEY_RESERVATION_TITLE, tr.child(5).text().trim()); e.put(AccountData.KEY_RESERVATION_READY, tr.child(17).text().trim()); e.put(AccountData.KEY_RESERVATION_CANCEL, tr.child(1).select("input").attr("value")); medien.add(e); } assert (medien.size() == trs - 1); } @Override public List<SearchField> getSearchFields() throws ClientProtocolException, IOException, JSONException { String html = httpGet(opac_url + "/ADVANCED_SEARCHFILTER", getDefaultEncoding()); Document doc = Jsoup.parse(html); List<SearchField> fields = new ArrayList<SearchField>(); Elements options = doc.select("select[name=IKT0] option"); for (Element option : options) { TextSearchField field = new TextSearchField(); field.setDisplayName(option.text()); field.setId(option.attr("value")); field.setHint(""); field.setData(new JSONObject("{\"ADI\": false}")); Pattern pattern = Pattern.compile("\\[[A-Z:]+\\]|\\([A-Z:]+\\)"); Matcher matcher = pattern.matcher(field.getDisplayName()); if (matcher.find()) { field.getData() .put("meaning", matcher.group().replace(":", "")); field.setDisplayName(matcher.replaceFirst("").trim()); } fields.add(field); } Elements sort = doc.select("select[name=SRT]"); if (sort.size() > 0) { DropdownSearchField field = new DropdownSearchField(); field.setDisplayName(sort.first().parent().parent() .select(".longval").first().text()); field.setId("SRT"); List<Map<String, String>> sortOptions = new ArrayList<Map<String, String>>(); for (Element option : sort.select("option")) { Map<String, String> sortOption = new HashMap<String, String>(); sortOption.put("key", option.attr("value")); sortOption.put("value", option.text()); sortOptions.add(sortOption); } field.setDropdownValues(sortOptions); fields.add(field); } for (Element input : doc.select("input[type=text][name^=ADI]")) { TextSearchField field = new TextSearchField(); field.setDisplayName(input.parent().parent().select(".longkey") .text()); field.setId(input.attr("name")); field.setHint(input.parent().select("span").text()); field.setData(new JSONObject("{\"ADI\": true}")); fields.add(field); } for (Element dropdown : doc.select("select[name^=ADI]")) { DropdownSearchField field = new DropdownSearchField(); field.setDisplayName(dropdown.parent().parent().select(".longkey") .text()); field.setId(dropdown.attr("name")); List<Map<String, String>> dropdownOptions = new ArrayList<Map<String, String>>(); for (Element option : dropdown.select("option")) { Map<String, String> dropdownOption = new HashMap<String, String>(); dropdownOption.put("key", option.attr("value")); dropdownOption.put("value", option.text()); dropdownOptions.add(dropdownOption); } field.setDropdownValues(dropdownOptions); fields.add(field); } Elements fuzzy = doc.select("input[name=FUZZY]"); if (fuzzy.size() > 0) { CheckboxSearchField field = new CheckboxSearchField(); field.setDisplayName(fuzzy.first().parent().parent() .select(".longkey").first().text()); field.setId("FUZZY"); fields.add(field); } Elements mediatypes = doc.select("input[name=ADI_MAT]"); if (mediatypes.size() > 0) { DropdownSearchField field = new DropdownSearchField(); field.setDisplayName("Materialart"); field.setId("ADI_MAT"); List<Map<String, String>> values = new ArrayList<Map<String, String>>(); Map<String, String> all = new HashMap<String, String>(); all.put("key", ""); all.put("value", "Alle"); values.add(all); for (Element mt : mediatypes) { Map<String, String> value = new HashMap<String, String>(); value.put("key", mt.attr("value")); value.put("value", mt.parent().nextElementSibling().text() .replace("\u00a0", "")); values.add(value); } field.setDropdownValues(values); fields.add(field); } return fields; } @Override public boolean isAccountSupported(Library library) { if (!library.getData().isNull("accountSupported")) { try { return library.getData().getBoolean("accountSupported"); } catch (JSONException e) { e.printStackTrace(); } } return false; } @Override public boolean isAccountExtendable() { return false; } @Override public String getAccountExtendableInfo(Account account) throws IOException, NotReachableException { return null; } @Override public String getShareUrl(String id, String title) { return id; } @Override public int getSupportFlags() { return SUPPORT_FLAG_ENDLESS_SCROLLING | SUPPORT_FLAG_CHANGE_ACCOUNT; } public void updateSearchSetValue(Document doc) { String url = doc.select("base").first().attr("href"); Integer setPosition = url.indexOf("SET=") + 4; String searchSetString = url.substring(setPosition, url.indexOf("/", setPosition)); searchSet = Integer.parseInt(searchSetString); } public MediaType getMediaTypeInSingleResult(String html) { Document doc = Jsoup.parse(html); MediaType mediatype = MediaType.UNKNOWN; if (doc.select("table[summary=presentation switch] img").size() > 0) { String[] fparts = doc .select("table[summary=presentation switch] img").get(0) .attr("src").split("/"); String fname = fparts[fparts.length - 1]; if (data.has("mediatypes")) { try { mediatype = MediaType.valueOf(data.getJSONObject( "mediatypes").getString(fname)); } catch (JSONException e) { mediatype = defaulttypes.get(fname .toLowerCase(Locale.GERMAN).replace(".jpg", "") .replace(".gif", "").replace(".png", "")); } catch (IllegalArgumentException e) { mediatype = defaulttypes.get(fname .toLowerCase(Locale.GERMAN).replace(".jpg", "") .replace(".gif", "").replace(".png", "")); } } else { mediatype = defaulttypes.get(fname.toLowerCase(Locale.GERMAN) .replace(".jpg", "").replace(".gif", "") .replace(".png", "")); } } return mediatype; } @Override protected String getDefaultEncoding() { try { if (data.has("charset")) return data.getString("charset"); } catch (JSONException e) { e.printStackTrace(); } return "UTF-8"; } @Override public void checkAccountData(Account account) throws IOException, JSONException, OpacErrorException { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("ACT", "UI_DATA")); params.add(new BasicNameValuePair("HOST_NAME", "")); params.add(new BasicNameValuePair("HOST_PORT", "")); params.add(new BasicNameValuePair("HOST_SCRIPT", "")); params.add(new BasicNameValuePair("LOGIN", "KNOWNUSER")); params.add(new BasicNameValuePair("STATUS", "HML_OK")); params.add(new BasicNameValuePair("BOR_U", account.getName())); params.add(new BasicNameValuePair("BOR_PW", account.getPassword())); String html = httpPost(https_url + "/loan/DB=" + db + "/LNG=DU/USERINFO", new UrlEncodedFormEntity(params, getDefaultEncoding()), getDefaultEncoding()); Document doc = Jsoup.parse(html); if (doc.select(".cnt .alert, .cnt .error").size() > 0) { throw new OpacErrorException(doc.select(".cnt .alert, .cnt .error") .text()); } } }
package org.observe; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; import org.junit.Test; import org.observe.collect.DefaultObservableList; import org.observe.collect.DefaultObservableSet; import org.observe.collect.ObservableCollection; import org.observe.collect.ObservableList; import org.observe.collect.ObservableOrderedCollection; import org.observe.collect.ObservableSet; import org.observe.collect.OrderedObservableElement; import org.observe.collect.TransactableList; import org.observe.util.ObservableUtils; import org.observe.util.Transaction; import prisms.lang.Type; /** Tests observable classes in the org.muis.core.rx package */ public class ObservableTest { /** Tests simple {@link SimpleSettableValue} functionality */ @Test public void settableValue() { SimpleSettableValue<Integer> obs = new SimpleSettableValue<>(Integer.TYPE, false); obs.set(0, null); int [] received = new int[] {0}; obs.act(value -> received[0] = value.getValue()); for(int i = 1; i < 10; i++) { obs.set(i, null); assertEquals(i, received[0]); } } /** Tests {@link ObservableValue#mapV(java.util.function.Function)} */ @Test public void valueMap() { SimpleSettableValue<Integer> obs = new SimpleSettableValue<>(Integer.TYPE, false); obs.set(0, null); int [] received = new int[] {0}; obs.mapV(value -> value * 10).act(value -> received[0] = value.getValue()); for(int i = 1; i < 10; i++) { obs.set(i, null); assertEquals(i * 10, received[0]); } } /** Tests {@link Observable#filter(java.util.function.Function)} */ @Test public void filter() { DefaultObservable<Integer> obs = new DefaultObservable<>(); Observer<Integer> controller = obs.control(null); int [] received = new int[] {0}; obs.filter(value -> value % 3 == 0).act(value -> received[0] = value); for(int i = 1; i < 30; i++) { controller.onNext(i); assertEquals((i / 3) * 3, received[0]); } } /** Tests {@link Observable#take(int)} */ @Test public void takeNumber() { DefaultObservable<Integer> obs = new DefaultObservable<>(); Observer<Integer> controller = obs.control(null); int [] received = new int[] {0}; boolean [] complete = new boolean[1]; Observable<Integer> take = obs.take(10); take.act(value -> received[0] = value); take.completed().act(value -> complete[0] = true); for(int i = 1; i < 30; i++) { controller.onNext(i); if(i < 10) { assertEquals(i, received[0]); assertEquals(false, complete[0]); } else { assertEquals(10, received[0]); assertEquals(true, complete[0]); } } } /** Tests {@link Observable#takeUntil(Observable)} */ @Test public void takeUntil() { DefaultObservable<Integer> obs = new DefaultObservable<>(); Observer<Integer> controller = obs.control(null); DefaultObservable<Boolean> stop = new DefaultObservable<>(); Observer<Boolean> stopControl = stop.control(null); int [] received = new int[] {0}; int [] count = new int[1]; boolean [] complete = new boolean[1]; Observable<Integer> take = obs.takeUntil(stop); take.act(value -> { count[0]++; received[0] = value; }); take.completed().act(value -> complete[0] = true); for(int i = 1; i <= 30; i++) { controller.onNext(i); assertEquals(i, received[0]); assertEquals(i, count[0]); } stopControl.onNext(true); assertEquals(true, complete[0]); final int finalValue = received[0]; for(int i = 1; i <= 30; i++) { controller.onNext(i); assertEquals(finalValue, received[0]); assertEquals(30, count[0]); } complete[0] = false; controller.onCompleted(0); assertEquals(false, complete[0]); obs = new DefaultObservable<>(); controller = obs.control(null); complete[0] = false; take = obs.takeUntil(stop); take.completed().act(value -> complete[0] = true); controller.onCompleted(0); assertEquals(true, complete[0]); } /** Tests {@link ObservableValue#takeUntil(Observable)} */ @Test public void valueTakeUntil() { SimpleSettableValue<Integer> obs = new SimpleSettableValue<>(Integer.TYPE, false); obs.set(0, null); DefaultObservable<Boolean> stop = new DefaultObservable<>(); Observer<Boolean> stopControl = stop.control(null); int [] received = new int[] {0}; int [] count = new int[1]; boolean [] complete = new boolean[1]; ObservableValue<Integer> take = obs.takeUntil(stop); take.act(value -> { count[0]++; received[0] = value.getValue(); }); take.completed().act(value -> complete[0] = true); for(int i = 1; i <= 30; i++) { obs.set(i, null); assertEquals(i, received[0]); assertEquals(i + 1, count[0]); // Plus 1 because of the initialization } stopControl.onNext(true); assertEquals(true, complete[0]); final int finalValue = received[0]; for(int i = 1; i <= 30; i++) { obs.set(i, null); assertEquals(finalValue, received[0]); assertEquals(31, count[0]); } } /** Tests {@link Observable#skip(int)} */ @Test public void skip() { DefaultObservable<Integer> obs = new DefaultObservable<>(); Observer<Integer> controller = obs.control(null); int [] received = new int[1]; obs.skip(5).act(value -> received[0] = value); for(int i = 0; i < 10; i++) { controller.onNext(i); int correct = i < 5 ? 0 : i; assertEquals(correct, received[0]); } } /** * Tests {@link Subscription} as an observable to ensure that it is closed (and its observers notified) when * {@link Subscription#unsubscribe()} is called */ @Test public void subSubscription() { DefaultObservable<Integer> obs = new DefaultObservable<>(); Observer<Integer> controller = obs.control(null); int [] received = new int[] {0}; Subscription<Integer> sub = obs.act(value -> received[0] = value); int [] received2 = new int[] {0}; Subscription<Integer> sub2 = sub.act(value -> received2[0] = value); int [] received3 = new int[] {0}; sub2.act(value -> received3[0] = value); for(int i = 1; i < 30; i++) { controller.onNext(i); assertEquals(i, received[0]); assertEquals(i, received2[0]); assertEquals(i, received3[0]); } final int finalValue = received[0]; sub2.unsubscribe(); for(int i = 1; i < 30; i++) { controller.onNext(i); assertEquals(i, received[0]); assertEquals(finalValue, received2[0]); assertEquals(finalValue, received3[0]); } } /** Tests {@link Observable#completed()} */ @Test public void completed() { DefaultObservable<Integer> obs = new DefaultObservable<>(); Observer<Integer> controller = obs.control(null); int [] received = new int[] {0}; obs.completed().act(value -> received[0] = value); for(int i = 1; i < 30; i++) { controller.onNext(i); assertEquals(0, received[0]); } controller.onCompleted(10); assertEquals(10, received[0]); } /** Tests {@link ObservableValue#combineV(TriFunction, ObservableValue, ObservableValue)} */ @Test public void combine() { int [] events = new int[1]; SimpleSettableValue<Integer> obs1 = new SimpleSettableValue<>(Integer.TYPE, false); obs1.set(0, null); SimpleSettableValue<Integer> obs2 = new SimpleSettableValue<>(Integer.TYPE, false); obs2.set(10, null); SimpleSettableValue<Integer> obs3 = new SimpleSettableValue<>(Integer.TYPE, false); obs3.set(0, null); int [] received = new int[] {0}; obs1.combineV((arg1, arg2, arg3) -> arg1 * arg2 + arg3, obs2, obs3).act(event -> { events[0]++; received[0] = event.getValue(); }); for(int i = 1; i < 10; i++) { obs1.set(i + 3, null); obs2.set(i * 10, null); obs3.set(i, null); assertEquals(i * 3 + 1, events[0]); assertEquals((i + 3) * i * 10 + i, received[0]); } } /** Tests {@link ObservableValue#flatten(Type, ObservableValue)} */ @Test public void observableValueFlatten() { SimpleSettableValue<ObservableValue<Integer>> outer = new SimpleSettableValue<>(new Type(ObservableValue.class, new Type( Integer.TYPE)), false); SimpleSettableValue<Integer> inner1 = new SimpleSettableValue<>(Integer.TYPE, false); inner1.set(1, null); outer.set(inner1, null); SimpleSettableValue<Integer> inner2 = new SimpleSettableValue<>(Integer.TYPE, false); inner2.set(2, null); int [] received = new int[1]; ObservableValue.flatten(new Type(Integer.TYPE), outer).act(value -> received[0] = value.getValue()); assertEquals(1, received[0]); inner1.set(3, null); assertEquals(3, received[0]); inner2.set(4, null); assertEquals(3, received[0]); outer.set(inner2, null); assertEquals(4, received[0]); inner1.set(5, null); assertEquals(4, received[0]); inner2.set(6, null); assertEquals(6, received[0]); } /** Tests basic {@link ObservableSet} functionality */ @Test public void observableSet() { DefaultObservableSet<Integer> set = new DefaultObservableSet<>(new Type(Integer.TYPE)); Set<Integer> controller = set.control(null); Set<Integer> compare1 = new TreeSet<>(); Set<Integer> correct = new TreeSet<>(); Runnable sub = set.onElement(element -> { element.observe(new Observer<ObservableValueEvent<Integer>>() { @Override public <V extends ObservableValueEvent<Integer>> void onNext(V value) { compare1.add(value.getValue()); } @Override public <V extends ObservableValueEvent<Integer>> void onCompleted(V value) { compare1.remove(value.getValue()); } }); }); for(int i = 0; i < 30; i++) { controller.add(i); correct.add(i); assertEquals(new TreeSet<>(set), compare1); assertEquals(correct, compare1); } for(int i = 0; i < 30; i++) { controller.remove(i); correct.remove(i); assertEquals(new TreeSet<>(set), compare1); assertEquals(correct, compare1); } for(int i = 0; i < 30; i++) { controller.add(i); correct.add(i); assertEquals(new TreeSet<>(set), compare1); assertEquals(correct, compare1); } sub.run(); for(int i = 30; i < 50; i++) { controller.add(i); assertEquals(correct, compare1); } for(int i = 0; i < 30; i++) { controller.remove(i); assertEquals(correct, compare1); } } /** Tests basic {@link ObservableList} functionality */ @Test public void observableList() { DefaultObservableList<Integer> list = new DefaultObservableList<>(new Type(Integer.TYPE)); List<Integer> controller = list.control(null); List<Integer> compare1 = new ArrayList<>(); List<Integer> correct = new ArrayList<>(); Runnable sub = list.onElement(element -> { OrderedObservableElement<Integer> listEl = (OrderedObservableElement<Integer>) element; element.observe(new Observer<ObservableValueEvent<Integer>>() { @Override public <V extends ObservableValueEvent<Integer>> void onNext(V value) { compare1.add(listEl.getIndex(), value.getValue()); } @Override public <V extends ObservableValueEvent<Integer>> void onCompleted(V value) { compare1.remove(listEl.getIndex()); } }); }); for(int i = 0; i < 30; i++) { controller.add(i); correct.add(i); assertEquals(new ArrayList<>(list), compare1); assertEquals(correct, compare1); } for(int i = 0; i < 30; i++) { controller.remove((Integer) i); correct.remove((Integer) i); assertEquals(new ArrayList<>(list), compare1); assertEquals(correct, compare1); } for(int i = 0; i < 30; i++) { controller.add(i); correct.add(i); assertEquals(new ArrayList<>(list), compare1); assertEquals(correct, compare1); } sub.run(); for(int i = 30; i < 50; i++) { controller.add(i); assertEquals(correct, compare1); } for(int i = 0; i < 30; i++) { controller.remove((Integer) i); assertEquals(correct, compare1); } } /** Tests {@link ObservableSet#map(java.util.function.Function)} */ @Test public void observableSetMap() { DefaultObservableSet<Integer> set = new DefaultObservableSet<>(new Type(Integer.TYPE)); Set<Integer> controller = set.control(null); Set<Integer> compare1 = new TreeSet<>(); Set<Integer> correct = new TreeSet<>(); set.map(value -> value * 10).onElement(element -> { element.observe(new Observer<ObservableValueEvent<Integer>>() { @Override public <V extends ObservableValueEvent<Integer>> void onNext(V value) { compare1.add(value.getValue()); } @Override public <V extends ObservableValueEvent<Integer>> void onCompleted(V value) { compare1.remove(value.getValue()); } }); }); for(int i = 0; i < 30; i++) { controller.add(i); correct.add(i * 10); assertEquals(correct, compare1); } for(int i = 0; i < 30; i++) { controller.remove(i); correct.remove(i * 10); assertEquals(correct, compare1); } } /** Tests {@link ObservableSet#filter(java.util.function.Function)} */ @Test public void observableSetFilter() { DefaultObservableSet<Integer> set = new DefaultObservableSet<>(new Type(Integer.TYPE)); Set<Integer> controller = set.control(null); Set<Integer> compare1 = new TreeSet<>(); Set<Integer> correct = new TreeSet<>(); set.filter(value -> value != null && value % 2 == 0).onElement(element -> { element.observe(new Observer<ObservableValueEvent<Integer>>() { @Override public <V extends ObservableValueEvent<Integer>> void onNext(V value) { compare1.add(value.getValue()); } @Override public <V extends ObservableValueEvent<Integer>> void onCompleted(V value) { compare1.remove(value.getValue()); } }); }); for(int i = 0; i < 30; i++) { controller.add(i); if(i % 2 == 0) correct.add(i); assertEquals(correct, compare1); } for(int i = 0; i < 30; i++) { controller.remove(i); if(i % 2 == 0) correct.remove(i); assertEquals(correct, compare1); } } /** Tests {@link ObservableSet#filterMap(java.util.function.Function)} */ @Test public void observableSetFilterMap() { DefaultObservableSet<Integer> set = new DefaultObservableSet<>(new Type(Integer.TYPE)); Set<Integer> controller = set.control(null); Set<Integer> compare1 = new TreeSet<>(); Set<Integer> correct = new TreeSet<>(); set.filterMap(value -> { if(value == null || value % 2 != 0) return null; return value / 2; }).onElement(element -> { element.observe(new Observer<ObservableValueEvent<Integer>>() { @Override public <V extends ObservableValueEvent<Integer>> void onNext(V value) { compare1.add(value.getValue()); } @Override public <V extends ObservableValueEvent<Integer>> void onCompleted(V value) { compare1.remove(value.getValue()); } }); }); for(int i = 0; i < 30; i++) { controller.add(i); if(i % 2 == 0) correct.add(i / 2); assertEquals(correct, compare1); } for(int i = 0; i < 30; i++) { controller.remove(i); if(i % 2 == 0) correct.remove(i / 2); assertEquals(correct, compare1); } } /** Tests {@link ObservableSet#combine(ObservableValue, java.util.function.BiFunction)} */ @Test // TODO This test hangs, not sure why, ever since I refactored the observable collections to not be observables public void observableSetCombine() { DefaultObservableSet<Integer> set = new DefaultObservableSet<>(new Type(Integer.TYPE)); SimpleSettableValue<Integer> value1 = new SimpleSettableValue<>(Integer.TYPE, false); value1.set(1, null); Set<Integer> controller = set.control(null); List<Integer> compare1 = new ArrayList<>(); Set<Integer> correct = new TreeSet<>(); set.combine(value1, (v1, v2) -> v1 * v2).filter(value -> value != null && value % 3 == 0).onElement(element -> { element.observe(new Observer<ObservableValueEvent<Integer>>() { @Override public <V extends ObservableValueEvent<Integer>> void onNext(V event) { if(event.getOldValue() != null) compare1.remove(event.getOldValue()); compare1.add(event.getValue()); } @Override public <V extends ObservableValueEvent<Integer>> void onCompleted(V event) { compare1.remove(event.getValue()); } }); }); for(int i = 0; i < 30; i++) { controller.add(i); int value = i * value1.get(); if(value % 3 == 0) correct.add(value); assertEquals(correct, new TreeSet<>(compare1)); assertEquals(correct.size(), compare1.size()); } value1.set(3, null); correct.clear(); for(int i = 0; i < 30; i++) { int value = i * value1.get(); if(value % 3 == 0) correct.add(value); } assertEquals(correct, new TreeSet<>(compare1)); assertEquals(correct.size(), compare1.size()); value1.set(10, null); correct.clear(); for(int i = 0; i < 30; i++) { int value = i * value1.get(); if(value % 3 == 0) correct.add(value); } assertEquals(correct, new TreeSet<>(compare1)); assertEquals(correct.size(), compare1.size()); for(int i = 0; i < 30; i++) { controller.remove(i); int value = i * value1.get(); if(value % 3 == 0) correct.remove(value); assertEquals(correct, new TreeSet<>(compare1)); assertEquals(correct.size(), compare1.size()); } } /** Tests {@link ObservableSet#unique(ObservableCollection)} */ @Test public void observableSetUnique() { DefaultObservableList<Integer> list = new DefaultObservableList<>(new Type(Integer.TYPE)); List<Integer> controller = list.control(null); ObservableSet<Integer> unique = ObservableSet.unique(list); List<Integer> compare1 = new ArrayList<>(); Set<Integer> correct = new TreeSet<>(); unique.onElement(element -> { element.observe(new Observer<ObservableValueEvent<Integer>>() { @Override public <V extends ObservableValueEvent<Integer>> void onNext(V event) { if(event.getOldValue() != null) compare1.remove(event.getOldValue()); compare1.add(event.getValue()); } @Override public <V extends ObservableValueEvent<Integer>> void onCompleted(V event) { compare1.remove(event.getValue()); } }); }); for(int i = 0; i < 30; i++) { controller.add(i); correct.add(i); } assertEquals(correct, new TreeSet<>(unique)); assertEquals(correct, new TreeSet<>(compare1)); assertEquals(correct.size(), compare1.size()); for(int i = 0; i < 30; i++) { controller.add(i); } assertEquals(correct, new TreeSet<>(unique)); assertEquals(correct, new TreeSet<>(compare1)); assertEquals(correct.size(), compare1.size()); for(int i = 29; i >= 0; i controller.remove(30 + i); } assertEquals(correct, new TreeSet<>(unique)); assertEquals(correct, new TreeSet<>(compare1)); assertEquals(correct.size(), compare1.size()); for(int i = 0; i < 30; i++) { controller.add(i); } assertEquals(correct, new TreeSet<>(unique)); assertEquals(correct, new TreeSet<>(compare1)); assertEquals(correct.size(), compare1.size()); for(int i = 29; i >= 0; i controller.remove(i); } assertEquals(correct, new TreeSet<>(unique)); assertEquals(correct, new TreeSet<>(compare1)); assertEquals(correct.size(), compare1.size()); for(int i = 29; i >= 0; i controller.remove(i); correct.remove(i); } assertEquals(correct, new TreeSet<>(unique)); assertEquals(correct, new TreeSet<>(compare1)); assertEquals(correct.size(), compare1.size()); } /** Tests {@link ObservableCollection#flatten(ObservableCollection)} */ @Test public void observableCollectionFlatten() { DefaultObservableSet<Integer> set1 = new DefaultObservableSet<>(new Type(Integer.TYPE)); DefaultObservableSet<Integer> set2 = new DefaultObservableSet<>(new Type(Integer.TYPE)); DefaultObservableSet<Integer> set3 = new DefaultObservableSet<>(new Type(Integer.TYPE)); DefaultObservableList<ObservableSet<Integer>> outer = new DefaultObservableList<>(new Type(ObservableSet.class, new Type(Integer.TYPE))); List<ObservableSet<Integer>> outerControl = outer.control(null); outerControl.add(set1); outerControl.add(set2); ObservableCollection<Integer> flat = ObservableCollection.flatten(outer); List<Integer> compare1 = new ArrayList<>(); List<Integer> filtered = new ArrayList<>(); flat.onElement(element -> { element.observe(new Observer<ObservableValueEvent<Integer>>() { @Override public <V extends ObservableValueEvent<Integer>> void onNext(V event) { if(event.getOldValue() != null) compare1.remove(event.getOldValue()); compare1.add(event.getValue()); } @Override public <V extends ObservableValueEvent<Integer>> void onCompleted(V event) { compare1.remove(event.getValue()); } }); }); flat.filter(value -> value != null && value % 3 == 0).onElement(element -> { element.observe(new Observer<ObservableValueEvent<Integer>>() { @Override public <V extends ObservableValueEvent<Integer>> void onNext(V event) { if(event.getOldValue() != null) filtered.remove(event.getOldValue()); filtered.add(event.getValue()); } @Override public <V extends ObservableValueEvent<Integer>> void onCompleted(V event) { filtered.remove(event.getValue()); } }); }); Set<Integer> controller1 = set1.control(null); Set<Integer> controller2 = set2.control(null); Set<Integer> controller3 = set3.control(null); List<Integer> correct1 = new ArrayList<>(); List<Integer> correct2 = new ArrayList<>(); List<Integer> correct3 = new ArrayList<>(); List<Integer> correct = new ArrayList<>(); List<Integer> filteredCorrect = new ArrayList<>(); for(int i = 0; i < 30; i++) { controller1.add(i); controller2.add(i * 10); controller3.add(i * 100); correct1.add(i); correct2.add(i * 10); correct3.add(i * 100); correct.clear(); correct.addAll(correct1); correct.addAll(correct2); filteredCorrect.clear(); for(int j : correct1) if(j % 3 == 0) filteredCorrect.add(j); for(int j : correct2) if(j % 3 == 0) filteredCorrect.add(j); assertEquals(new TreeSet<>(flat), new TreeSet<>(compare1)); assertEquals(flat.size(), compare1.size()); assertEquals(new TreeSet<>(correct), new TreeSet<>(compare1)); assertEquals(correct.size(), compare1.size()); assertEquals(new TreeSet<>(filteredCorrect), new TreeSet<>(filtered)); assertEquals(filteredCorrect.size(), filtered.size()); } outerControl.add(set3); correct.clear(); correct.addAll(correct1); correct.addAll(correct2); correct.addAll(correct3); filteredCorrect.clear(); for(int j : correct1) if(j % 3 == 0) filteredCorrect.add(j); for(int j : correct2) if(j % 3 == 0) filteredCorrect.add(j); for(int j : correct3) if(j % 3 == 0) filteredCorrect.add(j); assertEquals(new TreeSet<>(flat), new TreeSet<>(compare1)); assertEquals(flat.size(), compare1.size()); assertEquals(new TreeSet<>(correct), new TreeSet<>(compare1)); assertEquals(correct.size(), compare1.size()); assertEquals(new TreeSet<>(filteredCorrect), new TreeSet<>(filtered)); assertEquals(filteredCorrect.size(), filtered.size()); outerControl.remove(set2); correct.clear(); correct.addAll(correct1); correct.addAll(correct3); filteredCorrect.clear(); for(int j : correct1) if(j % 3 == 0) filteredCorrect.add(j); for(int j : correct3) if(j % 3 == 0) filteredCorrect.add(j); assertEquals(new TreeSet<>(flat), new TreeSet<>(compare1)); assertEquals(flat.size(), compare1.size()); assertEquals(new TreeSet<>(correct), new TreeSet<>(compare1)); assertEquals(correct.size(), compare1.size()); assertEquals(new TreeSet<>(filteredCorrect), new TreeSet<>(filtered)); assertEquals(filteredCorrect.size(), filtered.size()); for(int i = 0; i < 30; i++) { controller1.remove(i); controller2.remove(i * 10); controller3.remove(i * 100); correct1.remove((Integer) i); correct2.remove((Integer) (i * 10)); correct3.remove((Integer) (i * 100)); correct.clear(); correct.addAll(correct1); correct.addAll(correct3); filteredCorrect.clear(); for(int j : correct1) if(j % 3 == 0) filteredCorrect.add(j); for(int j : correct3) if(j % 3 == 0) filteredCorrect.add(j); assertEquals(new TreeSet<>(flat), new TreeSet<>(compare1)); assertEquals(flat.size(), compare1.size()); assertEquals(new TreeSet<>(correct), new TreeSet<>(compare1)); assertEquals(correct.size(), compare1.size()); assertEquals(new TreeSet<>(filteredCorrect), new TreeSet<>(filtered)); assertEquals(filteredCorrect.size(), filtered.size()); } } /** Tests {@link ObservableCollection#fold(ObservableCollection)} */ @Test public void observableCollectionFold() { SimpleSettableValue<Integer> obs1 = new SimpleSettableValue<>(Integer.class, true); SimpleSettableValue<Integer> obs2 = new SimpleSettableValue<>(Integer.class, true); SimpleSettableValue<Integer> obs3 = new SimpleSettableValue<>(Integer.class, true); DefaultObservableSet<ObservableValue<Integer>> set = new DefaultObservableSet<>(new Type(Observable.class, new Type( Integer.TYPE))); Set<ObservableValue<Integer>> controller = set.control(null); controller.add(obs1); controller.add(obs2); Observable<Integer> folded = ObservableCollection.fold(set.map(value -> value.value())); int [] received = new int[1]; folded.noInit().act(value -> received[0] = value); obs1.set(1, null); assertEquals(1, received[0]); obs2.set(2, null); assertEquals(2, received[0]); obs3.set(3, null); assertEquals(2, received[0]); controller.add(obs3); assertEquals(3, received[0]); // Initial value fired obs3.set(4, null); assertEquals(4, received[0]); controller.remove(obs2); obs2.set(5, null); assertEquals(4, received[0]); } /** Tests {@link ObservableList#map(java.util.function.Function)} */ @Test public void observableListMap() { DefaultObservableList<Integer> list = new DefaultObservableList<>(new Type(Integer.TYPE)); List<Integer> controller = list.control(null); List<Integer> compare1 = new ArrayList<>(); List<Integer> correct = new ArrayList<>(); list.map(value -> value * 10).onElement(element -> { OrderedObservableElement<Integer> listEl = (OrderedObservableElement<Integer>) element; element.observe(new Observer<ObservableValueEvent<Integer>>() { @Override public <V extends ObservableValueEvent<Integer>> void onNext(V value) { if(value.getOldValue() != null) compare1.set(listEl.getIndex(), value.getValue()); else compare1.add(listEl.getIndex(), value.getValue()); } @Override public <V extends ObservableValueEvent<Integer>> void onCompleted(V value) { compare1.remove(listEl.getIndex()); } }); }); for(int i = 0; i < 30; i++) { controller.add(i); correct.add(i * 10); assertEquals(correct, compare1); } for(int i = 0; i < 30; i++) { controller.add(i); correct.add(i * 10); assertEquals(correct, compare1); } for(int i = 0; i < 30; i++) { controller.remove(Integer.valueOf(i)); correct.remove(Integer.valueOf(i * 10)); assertEquals(correct, compare1); } } /** Tests {@link ObservableList#filter(java.util.function.Function)} */ @Test public void observableListFilter() { DefaultObservableList<Integer> list = new DefaultObservableList<>(new Type(Integer.TYPE)); List<Integer> controller = list.control(null); List<Integer> compare1 = new ArrayList<>(); List<Integer> correct = new ArrayList<>(); list.filter(value -> value != null && value % 2 == 0).onElement(element -> { OrderedObservableElement<Integer> listEl = (OrderedObservableElement<Integer>) element; element.observe(new Observer<ObservableValueEvent<Integer>>() { @Override public <V extends ObservableValueEvent<Integer>> void onNext(V value) { if(value.getOldValue() != null) compare1.set(listEl.getIndex(), value.getValue()); else compare1.add(listEl.getIndex(), value.getValue()); } @Override public <V extends ObservableValueEvent<Integer>> void onCompleted(V value) { compare1.remove(listEl.getIndex()); } }); }); for(int i = 0; i < 30; i++) { controller.add(i); if(i % 2 == 0) correct.add(i); assertEquals(correct, compare1); } for(int i = 0; i < 30; i++) { controller.add(i); if(i % 2 == 0) correct.add(i); assertEquals(correct, compare1); } for(int i = 0; i < 30; i++) { controller.remove(Integer.valueOf(i)); if(i % 2 == 0) correct.remove(Integer.valueOf(i)); assertEquals(correct, compare1); } } /** Slight variation on {@link #observableListFilter()} */ @Test public void observableListFilter2() { DefaultObservableList<Integer> list = new DefaultObservableList<>(new Type(Integer.TYPE)); List<Integer> controller = list.control(null); List<Integer> compare0 = new ArrayList<>(); List<Integer> correct0 = new ArrayList<>(); List<Integer> compare1 = new ArrayList<>(); List<Integer> correct1 = new ArrayList<>(); List<Integer> compare2 = new ArrayList<>(); List<Integer> correct2 = new ArrayList<>(); list.filter(value -> value % 3 == 0).onElement(element -> { OrderedObservableElement<Integer> oel = (OrderedObservableElement<Integer>) element; element.observe(new Observer<ObservableValueEvent<Integer>>() { @Override public <V extends ObservableValueEvent<Integer>> void onNext(V value) { if(value.getOldValue() != null) compare0.set(oel.getIndex(), value.getValue()); else compare0.add(oel.getIndex(), value.getValue()); } @Override public <V extends ObservableValueEvent<Integer>> void onCompleted(V value) { compare0.remove(oel.getIndex()); } }); }); list.filter(value -> value % 3 == 1).onElement(element -> { OrderedObservableElement<Integer> oel = (OrderedObservableElement<Integer>) element; element.observe(new Observer<ObservableValueEvent<Integer>>() { @Override public <V extends ObservableValueEvent<Integer>> void onNext(V value) { if(value.getOldValue() != null) compare1.set(oel.getIndex(), value.getValue()); else compare1.add(oel.getIndex(), value.getValue()); } @Override public <V extends ObservableValueEvent<Integer>> void onCompleted(V value) { compare1.remove(oel.getIndex()); } }); }); list.filter(value -> value % 3 == 2).onElement(element -> { OrderedObservableElement<Integer> oel = (OrderedObservableElement<Integer>) element; element.observe(new Observer<ObservableValueEvent<Integer>>() { @Override public <V extends ObservableValueEvent<Integer>> void onNext(V value) { if(value.getOldValue() != null) compare2.set(oel.getIndex(), value.getValue()); else compare2.add(oel.getIndex(), value.getValue()); } @Override public <V extends ObservableValueEvent<Integer>> void onCompleted(V value) { compare2.remove(oel.getIndex()); } }); }); for(int i = 0; i < 30; i++) { controller.add(i); switch (i % 3) { case 0: correct0.add(i); break; case 1: correct1.add(i); break; case 2: correct2.add(i); break; } assertEquals(correct0, compare0); assertEquals(correct1, compare1); assertEquals(correct2, compare2); } for(int i = 0; i < 30; i++) { int value = i + 1; controller.set(i, value); switch (i % 3) { case 0: correct0.remove(Integer.valueOf(i)); break; case 1: correct1.remove(Integer.valueOf(i)); break; case 2: correct2.remove(Integer.valueOf(i)); break; } switch (value % 3) { case 0: correct0.add(i / 3, value); break; case 1: correct1.add(i / 3, value); break; case 2: correct2.add(i / 3, value); break; } assertEquals(correct0, compare0); assertEquals(correct1, compare1); assertEquals(correct2, compare2); } for(int i = 0; i < 30; i++) { int value = controller.get(i); controller.remove(Integer.valueOf(value)); switch (i % 3) { case 0: correct0.remove(Integer.valueOf(value)); break; case 1: correct1.remove(Integer.valueOf(value)); break; case 2: correct2.remove(Integer.valueOf(value)); break; } assertEquals(correct0, compare0); assertEquals(correct1, compare1); assertEquals(correct2, compare2); } } /** Tests {@link ObservableList#filterMap(java.util.function.Function)} */ @Test public void observableListFilterMap() { DefaultObservableList<Integer> list = new DefaultObservableList<>(new Type(Integer.TYPE)); List<Integer> controller = list.control(null); List<Integer> compare1 = new ArrayList<>(); List<Integer> correct = new ArrayList<>(); list.filterMap(value -> { if(value == null || value % 2 != 0) return null; return value / 2; }).onElement(element -> { OrderedObservableElement<Integer> listEl = (OrderedObservableElement<Integer>) element; element.observe(new Observer<ObservableValueEvent<Integer>>() { @Override public <V extends ObservableValueEvent<Integer>> void onNext(V value) { if(value.getOldValue() != null) compare1.set(listEl.getIndex(), value.getValue()); else compare1.add(listEl.getIndex(), value.getValue()); } @Override public <V extends ObservableValueEvent<Integer>> void onCompleted(V value) { compare1.remove(listEl.getIndex()); } }); }); for(int i = 0; i < 30; i++) { controller.add(i); if(i % 2 == 0) correct.add(i / 2); assertEquals(correct, compare1); } for(int i = 0; i < 30; i++) { controller.add(i); if(i % 2 == 0) correct.add(i / 2); assertEquals(correct, compare1); } for(int i = 0; i < 30; i++) { controller.remove(Integer.valueOf(i)); if(i % 2 == 0) correct.remove(Integer.valueOf(i / 2)); assertEquals(correct, compare1); } } /** Tests {@link ObservableList#combine(ObservableValue, java.util.function.BiFunction)} */ @Test // TODO This test hangs, not sure why, ever since I refactored the observable collections to not be observables public void observableListCombine() { DefaultObservableList<Integer> set = new DefaultObservableList<>(new Type(Integer.TYPE)); SimpleSettableValue<Integer> value1 = new SimpleSettableValue<>(Integer.TYPE, false); value1.set(1, null); List<Integer> controller = set.control(null); List<Integer> compare1 = new ArrayList<>(); List<Integer> correct = new ArrayList<>(); set.combine(value1, (v1, v2) -> v1 * v2).filter(value -> value != null && value % 3 == 0).onElement(element -> { OrderedObservableElement<Integer> listEl = (OrderedObservableElement<Integer>) element; element.observe(new Observer<ObservableValueEvent<Integer>>() { @Override public <V extends ObservableValueEvent<Integer>> void onNext(V event) { if(event.getOldValue() != null) compare1.set(listEl.getIndex(), event.getValue()); else compare1.add(listEl.getIndex(), event.getValue()); } @Override public <V extends ObservableValueEvent<Integer>> void onCompleted(V event) { compare1.remove(listEl.getIndex()); } }); }); for(int i = 0; i < 30; i++) { controller.add(i); int value = i * value1.get(); if(value % 3 == 0) correct.add(value); assertEquals(correct, compare1); assertEquals(correct.size(), compare1.size()); } value1.set(3, null); correct.clear(); for(int i = 0; i < 30; i++) { int value = i * value1.get(); if(value % 3 == 0) correct.add(value); } assertEquals(correct, compare1); assertEquals(correct.size(), compare1.size()); value1.set(10, null); correct.clear(); for(int i = 0; i < 30; i++) { int value = i * value1.get(); if(value % 3 == 0) correct.add(value); } assertEquals(correct, compare1); assertEquals(correct.size(), compare1.size()); for(int i = 0; i < 30; i++) { controller.remove(Integer.valueOf(i)); int value = i * value1.get(); if(value % 3 == 0) correct.remove(Integer.valueOf(value)); assertEquals(correct, compare1); assertEquals(correct.size(), compare1.size()); } } /** Tests {@link ObservableList#flatten(ObservableList)} */ @Test public void observableListFlatten() { DefaultObservableList<Integer> set1 = new DefaultObservableList<>(new Type(Integer.TYPE)); DefaultObservableList<Integer> set2 = new DefaultObservableList<>(new Type(Integer.TYPE)); DefaultObservableList<Integer> set3 = new DefaultObservableList<>(new Type(Integer.TYPE)); DefaultObservableList<ObservableList<Integer>> outer = new DefaultObservableList<>(new Type(ObservableList.class, new Type( Integer.TYPE))); List<ObservableList<Integer>> outerControl = outer.control(null); outerControl.add(set1); outerControl.add(set2); ObservableList<Integer> flat = ObservableList.flatten(outer); List<Integer> compare1 = new ArrayList<>(); List<Integer> filtered = new ArrayList<>(); flat.onElement(element -> { OrderedObservableElement<Integer> listEl = (OrderedObservableElement<Integer>) element; element.observe(new Observer<ObservableValueEvent<Integer>>() { @Override public <V extends ObservableValueEvent<Integer>> void onNext(V event) { if(event.getOldValue() != null) compare1.set(listEl.getIndex(), event.getOldValue()); else compare1.add(listEl.getIndex(), event.getValue()); } @Override public <V extends ObservableValueEvent<Integer>> void onCompleted(V event) { compare1.remove(listEl.getIndex()); } }); }); flat.filter(value -> value != null && value % 3 == 0).onElement(element -> { OrderedObservableElement<Integer> listEl = (OrderedObservableElement<Integer>) element; element.observe(new Observer<ObservableValueEvent<Integer>>() { @Override public <V extends ObservableValueEvent<Integer>> void onNext(V event) { if(event.getOldValue() != null) { filtered.set(listEl.getIndex(), event.getValue()); } else { filtered.add(listEl.getIndex(), event.getValue()); } } @Override public <V extends ObservableValueEvent<Integer>> void onCompleted(V event) { filtered.remove(listEl.getIndex()); } }); }); List<Integer> controller1 = set1.control(null); List<Integer> controller2 = set2.control(null); List<Integer> controller3 = set3.control(null); List<Integer> correct1 = new ArrayList<>(); List<Integer> correct2 = new ArrayList<>(); List<Integer> correct3 = new ArrayList<>(); List<Integer> correct = new ArrayList<>(); List<Integer> filteredCorrect = new ArrayList<>(); for(int i = 0; i < 30; i++) { controller1.add(i); controller2.add(i * 10); controller3.add(i * 100); correct1.add(i); correct2.add(i * 10); correct3.add(i * 100); correct.clear(); correct.addAll(correct1); correct.addAll(correct2); filteredCorrect.clear(); for(int j : correct1) if(j % 3 == 0) filteredCorrect.add(j); for(int j : correct2) if(j % 3 == 0) filteredCorrect.add(j); assertEquals(flat, compare1); assertEquals(flat.size(), compare1.size()); assertEquals(correct, compare1); assertEquals(correct.size(), compare1.size()); assertEquals(filteredCorrect, filtered); assertEquals(filteredCorrect.size(), filtered.size()); } outerControl.add(set3); correct.clear(); correct.addAll(correct1); correct.addAll(correct2); correct.addAll(correct3); filteredCorrect.clear(); for(int j : correct1) if(j % 3 == 0) filteredCorrect.add(j); for(int j : correct2) if(j % 3 == 0) filteredCorrect.add(j); for(int j : correct3) if(j % 3 == 0) filteredCorrect.add(j); assertEquals(flat, compare1); assertEquals(flat.size(), compare1.size()); assertEquals(correct, compare1); assertEquals(correct.size(), compare1.size()); assertEquals(filteredCorrect, filtered); assertEquals(filteredCorrect.size(), filtered.size()); outerControl.remove(set2); correct.clear(); correct.addAll(correct1); correct.addAll(correct3); filteredCorrect.clear(); for(int j : correct1) if(j % 3 == 0) filteredCorrect.add(j); for(int j : correct3) if(j % 3 == 0) filteredCorrect.add(j); assertEquals(flat, compare1); assertEquals(flat.size(), compare1.size()); assertEquals(correct, compare1); assertEquals(correct.size(), compare1.size()); assertEquals(filteredCorrect, filtered); assertEquals(filteredCorrect.size(), filtered.size()); for(int i = 0; i < 30; i++) { controller1.remove((Integer) i); controller2.remove((Integer) (i * 10)); controller3.remove((Integer) (i * 100)); correct1.remove((Integer) i); correct2.remove((Integer) (i * 10)); correct3.remove((Integer) (i * 100)); correct.clear(); correct.addAll(correct1); correct.addAll(correct3); filteredCorrect.clear(); for(int j : correct1) if(j % 3 == 0) filteredCorrect.add(j); for(int j : correct3) if(j % 3 == 0) filteredCorrect.add(j); assertEquals(flat, compare1); assertEquals(flat.size(), compare1.size()); assertEquals(correct, compare1); assertEquals(correct.size(), compare1.size()); assertEquals(filteredCorrect, filtered); assertEquals(filteredCorrect.size(), filtered.size()); } } /** Tests {@link ObservableList#find(java.util.function.Predicate)} */ @Test public void observableListFind() { DefaultObservableList<Integer> list = new DefaultObservableList<>(new Type(Integer.TYPE)); List<Integer> controller = list.control(null); ObservableValue<Integer> found = list.find(value -> value % 3 == 0); Integer [] received = new Integer[] {0}; found.act(value -> received[0] = value.getValue()); Integer [] correct = new Integer[] {null}; assertEquals(correct[0], received[0]); assertEquals(correct[0], found.get()); for(int i = 1; i < 30; i++) { controller.add(i); if(i % 3 == 0 && correct[0] == null) correct[0] = i; assertEquals(correct[0], received[0]); assertEquals(correct[0], found.get()); } for(int i = 1; i < 30; i++) { controller.remove(Integer.valueOf(i)); if(i % 3 == 0) { correct[0] += 3; if(correct[0] >= 30) correct[0] = null; } assertEquals(correct[0], received[0]); assertEquals(correct[0], found.get()); } } /** Tests {@link ObservableUtils#flattenListValues(Type, ObservableList)} */ @Test public void flattenListValues() { DefaultObservableList<ObservableValue<Integer>> list = new DefaultObservableList<>(new Type(ObservableValue.class, new Type( Integer.TYPE))); List<ObservableValue<Integer>> listControl = list.control(null); SimpleSettableValue<Integer> value1 = new SimpleSettableValue<>(Integer.TYPE, false); value1.set(1, null); SimpleSettableValue<Integer> value2 = new SimpleSettableValue<>(Integer.TYPE, false); value2.set(2, null); SimpleSettableValue<Integer> value3 = new SimpleSettableValue<>(Integer.TYPE, false); value3.set(3, null); SimpleSettableValue<Integer> value4 = new SimpleSettableValue<>(Integer.TYPE, false); value4.set(4, null); SimpleSettableValue<Integer> value5 = new SimpleSettableValue<>(Integer.TYPE, false); value5.set(9, null); listControl.addAll(java.util.Arrays.asList(value1, value2, value3, value4)); Integer [] received = new Integer[1]; ObservableUtils.flattenListValues(new Type(Integer.TYPE), list).find(value -> value % 3 == 0).value() .act(value -> received[0] = value); assertEquals(Integer.valueOf(3), received[0]); value3.set(4, null); assertEquals(null, received[0]); value4.set(6, null); assertEquals(Integer.valueOf(6), received[0]); listControl.remove(value4); assertEquals(null, received[0]); listControl.add(value5); assertEquals(Integer.valueOf(9), received[0]); } /** Tests {@link ObservableOrderedCollection#sort(ObservableCollection, java.util.Comparator)} */ @Test public void sortedObservableList() { DefaultObservableList<Integer> list = new DefaultObservableList<>(new Type(Integer.TYPE)); List<Integer> controller = list.control(null); List<Integer> compare = new ArrayList<>(); ObservableOrderedCollection.sort(list, null).onElement(element -> { OrderedObservableElement<Integer> orderedEl = (OrderedObservableElement<Integer>) element; element.observe(new Observer<ObservableValueEvent<Integer>>() { @Override public <V extends ObservableValueEvent<Integer>> void onNext(V event) { if(event.getOldValue() == null) compare.add(orderedEl.getIndex(), event.getValue()); else compare.set(orderedEl.getIndex(), event.getValue()); } @Override public <V extends ObservableValueEvent<Integer>> void onCompleted(V event) { compare.remove(orderedEl.getIndex()); } }); }); List<Integer> correct = new ArrayList<>(); for(int i = 30; i >= 0; i controller.add(i); correct.add(i); } java.util.Collections.sort(correct); assertEquals(correct, compare); for(int i = 30; i >= 0; i controller.remove((Integer) i); correct.remove((Integer) i); assertEquals(correct, compare); } } /** Tests {@link ObservableOrderedCollection#flatten(ObservableOrderedCollection, java.util.Comparator)} */ @Test public void observableOrderedFlatten() { DefaultObservableList<ObservableList<Integer>> outer = new DefaultObservableList<>(new Type(ObservableList.class, new Type( Integer.TYPE))); DefaultObservableList<Integer> list1 = new DefaultObservableList<>(new Type(Integer.TYPE)); DefaultObservableList<Integer> list2 = new DefaultObservableList<>(new Type(Integer.TYPE)); DefaultObservableList<Integer> list3 = new DefaultObservableList<>(new Type(Integer.TYPE)); List<ObservableList<Integer>> outerControl = outer.control(null); List<Integer> control1 = list1.control(null); List<Integer> control2 = list2.control(null); List<Integer> control3 = list3.control(null); outerControl.add(list1); outerControl.add(list2); ArrayList<Integer> compare = new ArrayList<>(); ArrayList<Integer> correct = new ArrayList<>(); for(int i = 0; i <= 30; i++) { if(i % 3 == 1) { control1.add(i); correct.add(i); } else if(i % 3 == 0) { control2.add(i); correct.add(i); } else { control3.add(i); } } ObservableOrderedCollection.flatten(outer, null).onElement(element -> { OrderedObservableElement<Integer> orderedEl = (OrderedObservableElement<Integer>) element; element.observe(new Observer<ObservableValueEvent<Integer>>() { @Override public <V extends ObservableValueEvent<Integer>> void onNext(V event) { if(event.getOldValue() == null) compare.add(orderedEl.getIndex(), event.getValue()); else compare.set(orderedEl.getIndex(), event.getValue()); } @Override public <V extends ObservableValueEvent<Integer>> void onCompleted(V event) { compare.remove(orderedEl.getIndex()); } }); }); assertEquals(correct, compare); outerControl.add(list3); correct.clear(); for(int i = 0; i <= 30; i++) correct.add(i); assertEquals(correct, compare); outerControl.remove(list2); correct.clear(); for(int i = 0; i <= 30; i++) if(i % 3 != 0) correct.add(i); assertEquals(correct, compare); control1.remove((Integer) 16); correct.remove((Integer) 16); assertEquals(correct, compare); control1.add(control1.indexOf(19), 16); correct.add(correct.indexOf(17), 16); assertEquals(correct, compare); } /** Tests basic transaction functionality on observable collections */ @Test public void testTransactionsBasic() { // Use find() and changes() to test DefaultObservableList<Integer> list = new DefaultObservableList<>(new Type(Integer.TYPE)); testTransactionsByFind(list, list); testTransactionsByChanges(list, list); } /** Tests transactions in {@link ObservableList#flatten(ObservableList) flattened} collections */ @Test public void testTransactionsFlattened() { DefaultObservableList<Integer> list1 = new DefaultObservableList<>(new Type(Integer.TYPE)); DefaultObservableList<Integer> list2 = new DefaultObservableList<>(new Type(Integer.TYPE)); ObservableList<Integer> flat = ObservableList.flattenLists(list1, list2); list1.add(50); testTransactionsByFind(flat, list2); testTransactionsByChanges(flat, list2); } /** * Tests transactions caused by {@link ObservableCollection#combine(ObservableValue, java.util.function.BiFunction) combining} a list * with an observable value */ @Test public void testTransactionsCombined() { // TODO } /** Tests transactions caused by {@link ObservableCollection#refresh(Observable) refreshing} on an observable */ @Test public void testTransactionsRefresh() { // TODO } private void testTransactionsByFind(ObservableList<Integer> observable, TransactableList<Integer> controller) { Integer [] found = new Integer[1]; int [] findCount = new int[1]; Runnable sub = observable.find(value -> value % 5 == 4).act(event -> { findCount[0]++; found[0] = event.getValue(); }); assertEquals(1, findCount[0]); controller.add(0); assertEquals(1, findCount[0]); controller.add(3); assertEquals(1, findCount[0]); controller.add(9); assertEquals(2, findCount[0]); assertEquals(9, (int) found[0]); Transaction trans = controller.startTransaction(null); assertEquals(2, findCount[0]); controller.add(0, 4); assertEquals(2, findCount[0]); trans.close(); assertEquals(3, findCount[0]); assertEquals(4, (int) found[0]); sub.run(); controller.clear(); } private void testTransactionsByChanges(ObservableList<Integer> observable, TransactableList<Integer> controller) { ArrayList<Integer> compare = new ArrayList<>(observable); ArrayList<Integer> correct = new ArrayList<>(observable); int [] changeCount = new int[1]; Runnable sub = observable.changes().act(event -> { changeCount[0]++; for(int i = 0; i < event.indexes.size(); i++) { switch (event.type) { case add: compare.add(event.indexes.get(i), event.values.get(i)); break; case remove: compare.remove(event.indexes.get(i)); break; case set: compare.set(event.indexes.get(i), event.values.get(i)); break; } } }); assertEquals(0, changeCount[0]); for(int i = 0; i < 30; i++) { assertEquals(i, changeCount[0]); int toAdd = (int) (Math.random() * 2000000) - 1000000; controller.add(toAdd); correct.add(toAdd); assertEquals(correct, new ArrayList<>(observable)); assertEquals(correct, compare); } assertEquals(30, changeCount[0]); Transaction trans = controller.startTransaction(null); controller.clear(); correct.clear(); correct.addAll(observable); for(int i = 0; i < 30; i++) { int toAdd = (int) (Math.random() * 2000000) - 1000000; controller.add(toAdd); correct.add(toAdd); assertEquals(correct, new ArrayList<>(observable)); } assertEquals(31, changeCount[0]); trans.close(); assertEquals(32, changeCount[0]); assertEquals(correct, compare); sub.run(); controller.clear(); } }
package dr.evomodel.tree; import dr.evolution.tree.Tree; import dr.inference.model.Statistic; import dr.xml.*; import jebl.evolution.treemetrics.BilleraMetric; import jebl.evolution.treemetrics.CladeHeightMetric; import jebl.evolution.treemetrics.RobinsonsFouldMetric; import jebl.evolution.treemetrics.RootedTreeMetric; import jebl.evolution.trees.SimpleRootedTree; /** * A statistic that returns the distance between two trees. * * Currently supports the following metrics, * 1. compare - returns a 0 for identity of topology, 1 otherwise. * 2. Billera tree distance. * 3. ROBINSONS FOULD * 4. Clade height * * @author Alexei Drummond * @author Andrew Rambaut * @author Joseph Heled * * @version $Id: TreeMetricStatistic.java,v 1.14 2005/07/11 14:06:25 rambaut Exp $ */ public class TreeMetricStatistic extends Statistic.Abstract implements TreeStatistic { public static final String TREE_METRIC_STATISTIC = "treeMetricStatistic"; public static final String TARGET = "target"; public static final String REFERENCE = "reference"; public static final String METHOD = "method"; enum Method { COMPARISON, BILLERA, ROBINSONSFOULD, CLADEHEIGHTM, } public TreeMetricStatistic(String name, Tree target, Tree reference, Method method) { super(name); this.target = target; //this.reference = reference; this.method = method; switch( method ) { case COMPARISON: { this.referenceNewick = Tree.Utils.uniqueNewick(reference, reference.getRoot()); break; } default: { jreference = Tree.Utils.asJeblTree(reference); break; } } switch( method ) { case BILLERA: metric = new BilleraMetric(); break; case ROBINSONSFOULD: metric = new RobinsonsFouldMetric(); break; case CLADEHEIGHTM: metric = new CladeHeightMetric(); break; } } public void setTree(Tree tree) { this.target = tree; } public Tree getTree() { return target; } public int getDimension() { return 1; } /** @return value. */ public double getStatisticValue(int dim) { if( method == Method.COMPARISON ) { return compareTreeDistance(); } return metric.getMetric(jreference, Tree.Utils.asJeblTree(target)); } private double compareTreeDistance() { if (Tree.Utils.uniqueNewick(target, target.getRoot()).equals(referenceNewick)) { return 0.0; } else { return 1.0; } } public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return TREE_METRIC_STATISTIC; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { String name; if (xo.hasAttribute(NAME)) { name = xo.getStringAttribute(NAME); } else { name = xo.getId(); } Tree target = (Tree)xo.getSocketChild(TARGET); Tree reference = (Tree)xo.getSocketChild(REFERENCE); Method m = Method.COMPARISON; if( xo.hasAttribute(METHOD) ) { String s = xo.getStringAttribute(METHOD); m = Method.valueOf(s.toUpperCase()); } return new TreeMetricStatistic(name, target, reference, m); }
package es.ucm.fdi.tp.views.swing; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.lang.reflect.InvocationTargetException; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; import es.ucm.fdi.tp.basecode.bgame.model.Piece; import es.ucm.fdi.tp.control.multiplayer.GameServer; import es.ucm.fdi.tp.control.multiplayer.NetObserver; import es.ucm.fdi.tp.views.swing.controlpanel.textbox.MessagesBox; public class ServerView implements NetObserver { static { setDefaultLookAndFeel(); } private final JFrame WINDOW; private MessagesBox textarea; private GameServer server; public ServerView(GameServer s) { this.WINDOW = new JFrame(); this.server = s; server.setView(this); try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { initGUI(); } }); } catch (InvocationTargetException | InterruptedException e) { e.printStackTrace(); } } private void initGUI() { JPanel panel = new JPanel(new BorderLayout()); this.textarea = new MessagesBox(8, 32); panel.add(textarea, BorderLayout.CENTER); JButton quitBtn = new JButton("Disconnect all"); panel.add(quitBtn, BorderLayout.SOUTH); quitBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { confirmAndExit(); } }); WINDOW.setContentPane(panel); WINDOW.setMinimumSize(new Dimension(512,256)); WINDOW.setLocationByPlatform(true); WINDOW.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); WINDOW.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { confirmAndExit(); } }); } @Override public void onPlayerConnected(Piece p) { log("Player " + p + " connected (" + server.playersConnected() + "/" + server.requiredPlayers() + ")" ); } @Override public void onPlayerDisconected(Piece p) { log("Player " + p + " disconnected (" + server.playersConnected() + "/" + server.requiredPlayers() + ")" ); } @Override public void onServerOpened(String gameDesc) { WINDOW.setTitle("Server: " + gameDesc); WINDOW.setVisible(true); log("Server started. Waiting for players... (" + server.playersConnected() + "/" + server.requiredPlayers() + ")"); } @Override public void onServerClosed() { WINDOW.setVisible(false); WINDOW.dispose(); } public void log(String msg) { textarea.append(msg); } private void confirmAndExit() { if((new QuitDialog(WINDOW)).getValue()) server.stop(); } private static void setDefaultLookAndFeel() { try { javax.swing.UIManager.setLookAndFeel( javax.swing.UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { System.err.println("Look and feel mode: " + e.getMessage()); } } }
package com.zutubi.diff; import com.zutubi.diff.unified.UnifiedPatchParser; import com.zutubi.util.FileSystemUtils; import com.zutubi.util.SystemUtils; import com.zutubi.util.ZipUtils; import com.zutubi.util.junit.ZutubiTestCase; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.zip.ZipInputStream; public class PatchFileParserTest extends ZutubiTestCase { private static final String PREFIX_TEST = "test"; private static final String EXTENSION_PATCH = "txt"; private File tempDir; private File oldDir; private File newDir; private PatchFileParser parser; @Override protected void setUp() throws Exception { super.setUp(); tempDir = createTempDirectory(); oldDir = new File(tempDir, "old"); newDir = new File(tempDir, "new"); ZipUtils.extractZip(new ZipInputStream(getInput("old", "zip")), oldDir); ZipUtils.extractZip(new ZipInputStream(getInput("new", "zip")), newDir); parser = new PatchFileParser(new UnifiedPatchParser()); } @Override protected void tearDown() throws Exception { FileSystemUtils.rmdir(tempDir); super.tearDown(); } public void testEdited() throws Exception { readApplyAndCheck(); } public void testEditedSingleLine() throws Exception { readApplyAndCheck(); } public void testEditedFirstLine() throws Exception { readApplyAndCheck(); } public void testEditedSecondLine() throws Exception { readApplyAndCheck(); } public void testEditedSecondLastLine() throws Exception { readApplyAndCheck(); } public void testEditedLastLine() throws Exception { readApplyAndCheck(); } public void testLinesAdded() throws Exception { readApplyAndCheck(); } public void testFirstLineAdded() throws Exception { readApplyAndCheck(); } public void testLastLineAdded() throws Exception { readApplyAndCheck(); } public void testLinesDeleted() throws Exception { readApplyAndCheck(); } public void testFirstLineDeleted() throws Exception { readApplyAndCheck(); } public void testLastLineDeleted() throws Exception { readApplyAndCheck(); } public void testEmptied() throws Exception { readApplyAndCheck(); } public void testUnemptied() throws Exception { readApplyAndCheck(); } public void testVariousChanges() throws Exception { readApplyAndCheck(); } public void testAddNewline() throws Exception { readApplyAndCheck(); } public void testDeleteNewline() throws Exception { readApplyAndCheck(); } public void testDeleted() throws Exception { readApplyAndCheck(); } public void testNestedFile() throws Exception { readApplyAndCheck("nested/file-nested.txt"); } public void testSpaceCharactersInFilename() throws Exception { readApplyAndCheck("file with space characters.txt"); } public void testSubversionFileEdited() throws Exception { singleFilePatchHelper(); } public void testSubversionFileEditedFirstLine() throws Exception { singleFilePatchHelper(); } public void testSubversionFileEditedLastLine() throws Exception { singleFilePatchHelper(); } public void testSubversionFileEditedSecondLine() throws Exception { singleFilePatchHelper(); } public void testSubversionFileEditedSecondLastLine() throws Exception { singleFilePatchHelper(); } public void testSubversionFileEditedSingleLine() throws Exception { singleFilePatchHelper(); } public void testSubversionFileNested() throws Exception { singleFilePatchHelper(); } public void testSubversionFileVariousChanges() throws Exception { singleFilePatchHelper(); } public void testSubversionFileWithSpaceCharacters() throws Exception { singleFilePatchHelper(); } public void testSubversionFileLinesAdded() throws Exception { singleFilePatchHelper(); } public void testSubversionFileLinesDeleted() throws Exception { singleFilePatchHelper(); } public void testSubversionFileFirstLineAdded() throws Exception { singleFilePatchHelper(); } public void testSubversionFileFirstLineDeleted() throws Exception { singleFilePatchHelper(); } public void testSubversionFileLastLineAdded() throws Exception { singleFilePatchHelper(); } public void testSubversionFileLastLineDeleted() throws Exception { singleFilePatchHelper(); } public void testSubversionFileAdded() throws Exception { singleFilePatchHelper(); } public void testSubversionFileAddNewline() throws Exception { singleFilePatchHelper(); } public void testSubversionFileDeleteNewline() throws Exception { singleFilePatchHelper(); } public void testBadOldFile() throws Exception { try { parseSinglePatch(); fail("Input file shouldn't parse"); } catch (PatchParseException e) { assertEquals(e.getMessage(), "1: Patch header line '---' is missing filename"); } } private void readApplyAndCheck() throws Exception { readApplyAndCheck(convertName()); } private void readApplyAndCheck(String name) throws DiffException, IOException { ProcessBuilder processBuilder = new ProcessBuilder("diff", "-uN", "old/" + name, "new/" + name); processBuilder.directory(tempDir); String diff = SystemUtils.runCommandWithInput(1, null, processBuilder); File patch = new File(tempDir, "patch"); FileSystemUtils.createFile(patch, diff); PatchFile patchFile = parser.parse(new FileReader(patch)); applyAndCheck(patchFile, 1, name); } private void singleFilePatchHelper() throws PatchParseException, PatchApplyException, IOException { PatchFile pf = parseSinglePatch(); assertEquals(1, pf.getPatches().size()); String patchedFile = pf.getPatches().get(0).getNewFile(); applyAndCheck(pf, 0, patchedFile); } private PatchFile parseSinglePatch() throws PatchParseException { return parser.parse(new InputStreamReader(getInput(EXTENSION_PATCH))); } private void applyAndCheck(PatchFile patchFile, int prefixStripCount, String name) throws PatchParseException, PatchApplyException, IOException { File in = new File(oldDir, name); boolean existedBefore = in.exists(); patchFile.apply(oldDir, prefixStripCount); File out = new File(newDir, name); if (out.exists()) { if (!existedBefore) { assertTrue("Expected file '" + in.getName() + "' to be added, but it does not exist", in.exists()); } if (SystemUtils.IS_WINDOWS) { FileSystemUtils.translateEOLs(out, SystemUtils.CRLF_BYTES, true); } ProcessBuilder processBuilder = new ProcessBuilder("diff", "-uN", "old/" + name, "new/" + name); processBuilder.directory(tempDir); String diff = SystemUtils.runCommandWithInput(-1, null, processBuilder); assertTrue("Expected no differences, got:\n" + diff, diff.length() == 0); } else { assertFalse("Expected file '" + in.getName() + "' to be deleted, but it still exists", in.exists()); } } private String convertName() { String name = getName(); if (name.startsWith(PREFIX_TEST)) { name = name.substring(PREFIX_TEST.length()); } String convertedName = ""; for (int i = 0; i < name.length(); i++) { char c = name.charAt(i); if (Character.isUpperCase(c)) { convertedName += "-"; } convertedName += Character.toLowerCase(c); } return "file" + convertedName + ".txt"; } }
package com.github.fakemongo; import ch.qos.logback.classic.Level; import com.github.fakemongo.impl.ExpressionParser; import com.github.fakemongo.impl.Util; import com.github.fakemongo.junit.FongoRule; import com.mongodb.AggregationOutput; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; import com.mongodb.BasicDBObjectBuilder; import com.mongodb.BulkWriteOperation; import com.mongodb.BulkWriteResult; import com.mongodb.CommandResult; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.DBRef; import com.mongodb.DuplicateKeyException; import com.mongodb.FongoDBCollection; import com.mongodb.MongoException; import com.mongodb.QueryBuilder; import com.mongodb.ServerAddress; import com.mongodb.WriteConcern; import com.mongodb.WriteResult; import com.mongodb.util.JSON; import java.net.InetSocketAddress; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import org.assertj.core.api.Assertions; import static org.assertj.core.api.Assertions.assertThat; import org.assertj.core.util.Lists; import org.bson.BSON; import org.bson.Transformer; import org.bson.types.Binary; import org.bson.types.MaxKey; import org.bson.types.MinKey; import org.bson.types.ObjectId; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.RuleChain; import org.junit.rules.TestRule; import org.slf4j.LoggerFactory; public class FongoTest { public final FongoRule fongoRule = new FongoRule(false); public final ExpectedException exception = ExpectedException.none(); @Rule public TestRule rules = RuleChain.outerRule(exception).around(fongoRule); @Test public void testGetDb() { Fongo fongo = newFongo(); DB db = fongo.getDB("db"); assertNotNull(db); assertSame("getDB should be idempotent", db, fongo.getDB("db")); assertEquals(Arrays.asList(db), fongo.getUsedDatabases()); assertEquals(Arrays.asList("db"), fongo.getDatabaseNames()); } @Test public void testGetCollection() { Fongo fongo = newFongo(); DB db = fongo.getDB("db"); DBCollection collection = db.getCollection("coll"); assertNotNull(collection); assertSame("getCollection should be idempotent", collection, db.getCollection("coll")); assertSame("getCollection should be idempotent", collection, db.getCollectionFromString("coll")); assertEquals(newHashSet("coll", "system.indexes", "system.users"), db.getCollectionNames()); } @Test public void testCreateCollection() { DB db = fongoRule.getDB("db"); db.createCollection("coll", null); assertEquals(new HashSet<String>(Arrays.asList("coll", "system.indexes", "system.users")), db.getCollectionNames()); } @Test public void testCountMethod() { DBCollection collection = newCollection(); assertEquals(0, collection.count()); } @Test public void testCountWithQueryCommand() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("n", 1)); collection.insert(new BasicDBObject("n", 2)); collection.insert(new BasicDBObject("n", 2)); assertEquals(2, collection.count(new BasicDBObject("n", 2))); } @Test public void testCountOnCursor() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("n", 1)); collection.insert(new BasicDBObject("n", 2)); collection.insert(new BasicDBObject("n", 2)); assertEquals(3, collection.find(QueryBuilder.start("n").exists(true).get()).count()); } @Test public void testInsertIncrementsCount() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("name", "jon")); assertEquals(1, collection.count()); } @Test public void testFindOne() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("name", "jon")); DBObject result = collection.findOne(); assertNotNull(result); assertNotNull("should have an _id", result.get("_id")); } @Test public void testFindOneNoData() { DBCollection collection = newCollection(); DBObject result = collection.findOne(); assertNull(result); } @Test public void testFindOneInId() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); DBObject result = collection.findOne(new BasicDBObject("_id", new BasicDBObject("$in", Arrays.asList(1, 2)))); assertEquals(new BasicDBObject("_id", 1), result); } @Test public void testFindOneInSetOfId() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); DBObject result = collection.findOne(new BasicDBObject("_id", new BasicDBObject("$in", newHashSet(1, 2)))); assertEquals(new BasicDBObject("_id", 1), result); } @Test public void testFindOneInSetOfData() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("data", 1)); DBObject result = collection.findOne(new BasicDBObject("data", new BasicDBObject("$in", newHashSet(1, 2)))); assertEquals(new BasicDBObject("_id", 1).append("data", 1), result); } @Test public void testFindOneIn() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("date", 1)); DBObject result = collection.findOne(new BasicDBObject("date", new BasicDBObject("$in", Arrays.asList(1, 2))), new BasicDBObject("date", 1).append("_id", 0)); assertEquals(new BasicDBObject("date", 1), result); } @Test public void testFindOneIn_within_array_and_given_index_set() { DBCollection collection = newCollection(); // prepare documents collection.insert( new BasicDBObject("_id", 1) .append("animals", new BasicDBObject[]{ new BasicDBObject("name", "dolphin").append("type", "mammal"), }), new BasicDBObject("_id", 2) .append("animals", new BasicDBObject[]{ new BasicDBObject("name", "horse").append("type", "mammal"), new BasicDBObject("name", "shark").append("type", "fish") })); // prepare index collection.createIndex(new BasicDBObject("animals.type", "text")); DBObject result = collection.findOne(new BasicDBObject("animals.type", new BasicDBObject("$in", new String[]{"fish"}))); assertNotNull(result); assertEquals(2, result.get("_id")); } @Test public void testFindOneInWithArray() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); DBObject result = collection.findOne(new BasicDBObject("_id", new BasicDBObject("$in", new Integer[]{1, 3}))); assertEquals(new BasicDBObject("_id", 1), result); } @Test public void testFindOneOrId() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); DBObject result = collection.findOne(new BasicDBObject("$or", Util.list(new BasicDBObject("_id", 1), new BasicDBObject("_id", 2)))); assertEquals(new BasicDBObject("_id", 1), result); } @Test public void testFindOneOrIdCollection() throws Exception { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); DBObject result = collection.findOne(new BasicDBObject("$or", newHashSet(new BasicDBObject("_id", 1), new BasicDBObject("_id", 2)))); assertEquals(new BasicDBObject("_id", 1), result); } @Test public void testFindOneOrData() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("date", 1)); DBObject result = collection.findOne(new BasicDBObject("$or", Util.list(new BasicDBObject("date", 1), new BasicDBObject("date", 2)))); assertEquals(1, result.get("date")); } @Test public void testFindOneNinWithArray() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); DBObject result = collection.findOne(new BasicDBObject("_id", new BasicDBObject("$nin", new Integer[]{1, 3}))); assertEquals(new BasicDBObject("_id", 2), result); } @Test public void testFindOneAndIdCollection() throws Exception { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("data", 2)); DBObject result = collection.findOne(new BasicDBObject("$and", newHashSet(new BasicDBObject("_id", 1), new BasicDBObject("data", 2)))); assertEquals(new BasicDBObject("_id", 1).append("data", 2), result); } @Test public void testFindOneById() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); DBObject result = collection.findOne(new BasicDBObject("_id", 1)); assertEquals(new BasicDBObject("_id", 1), result); assertEquals(null, collection.findOne(new BasicDBObject("_id", 2))); } @Test public void testFindOneWithFields() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject().append("name", "jon").append("foo", "bar")); DBObject result = collection.findOne(new BasicDBObject(), new BasicDBObject("foo", 1)); assertNotNull(result); assertNotNull("should have an _id", result.get("_id")); assertEquals("property 'foo'", "bar", result.get("foo")); assertNull("should not have the property 'name'", result.get("name")); } @Test public void testFindInWithRegex() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); collection.insert(new BasicDBObject("_id", "s")); collection.insert(new BasicDBObject("_id", "a")); collection.insert(new BasicDBObject("_id", "abbb")); DBCursor cursor = collection.find(new BasicDBObject("_id", new BasicDBObject("$in", new Object[]{1, "s", Pattern.compile("ab+")}))); List<DBObject> dbObjects = cursor.toArray(); assertEquals(3, dbObjects.size()); assertTrue(dbObjects.contains(new BasicDBObject("_id", 1))); assertTrue(dbObjects.contains(new BasicDBObject("_id", "s"))); assertTrue(dbObjects.contains(new BasicDBObject("_id", "abbb"))); } @Test public void testFindWithQuery() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("name", "jon")); collection.insert(new BasicDBObject("name", "leo")); collection.insert(new BasicDBObject("name", "neil")); collection.insert(new BasicDBObject("name", "neil")); DBCursor cursor = collection.find(new BasicDBObject("name", "neil")); assertEquals("should have two neils", 2, cursor.toArray().size()); } @Test public void testFindWithNullOrNoFieldFilter() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("name", "jon").append("group", "group1")); collection.insert(new BasicDBObject("name", "leo").append("group", "group1")); collection.insert(new BasicDBObject("name", "neil1").append("group", "group2")); collection.insert(new BasicDBObject("name", "neil2").append("group", null)); collection.insert(new BasicDBObject("name", "neil3")); // check {group: null} vs {group: {$exists: false}} filter DBCursor cursor1 = collection.find(new BasicDBObject("group", null)); assertEquals("should have two neils (neil2, neil3)", 2, cursor1.toArray().size()); DBCursor cursor2 = collection.find(new BasicDBObject("group", new BasicDBObject("$exists", false))); assertEquals("should have one neil (neil3)", 1, cursor2.toArray().size()); // same check but for fields which don't exist in DB DBCursor cursor3 = collection.find(new BasicDBObject("other", null)); assertEquals("should return all documents", 5, cursor3.toArray().size()); DBCursor cursor4 = collection.find(new BasicDBObject("other", new BasicDBObject("$exists", false))); assertEquals("should return all documents", 5, cursor4.toArray().size()); } @Test public void testFindExcludingOnlyId() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", "1").append("a", 1)); collection.insert(new BasicDBObject("_id", "2").append("a", 2)); DBCursor cursor = collection.find(new BasicDBObject(), new BasicDBObject("_id", 0)); assertEquals("should have 2 documents", 2, cursor.toArray().size()); assertEquals(Arrays.asList(new BasicDBObject("a", 1), new BasicDBObject("a", 2)), cursor.toArray()); } @Test public void testFindElemMatch() { DBCollection collection = newCollection(); collection.insert((DBObject) JSON.parse("{ _id:1, array: [ { value1:1, value2:0 }, { value1:2, value2:2 } ] }")); collection.insert((DBObject) JSON.parse("{ _id:2, array: [ { value1:1, value2:0 }, { value1:1, value2:2 } ] }")); DBCursor cursor = collection.find((DBObject) JSON.parse("{ array: { $elemMatch: { value1: 1, value2: { $gt: 1 } } } }")); assertEquals(Arrays.asList((DBObject) JSON.parse("{ _id:2, array: [ { value1:1, value2:0 }, { value1:1, value2:2 } ] }") ), cursor.toArray()); } @Test public void testCommandTextSearch() { DBCollection collection = newCollection(); collection.insert((DBObject) JSON.parse("{ _id:1, textField: \"aaa bbb\" }")); collection.insert((DBObject) JSON.parse("{ _id:2, textField: \"ccc ddd\" }")); collection.insert((DBObject) JSON.parse("{ _id:3, textField: \"eee fff\" }")); collection.insert((DBObject) JSON.parse("{ _id:4, textField: \"aaa eee\" }")); collection.createIndex(new BasicDBObject("textField", "text")); DBObject textSearchCommand = new BasicDBObject(); // textSearchCommand.put("text", Interest.COLLECTION); textSearchCommand.put("search", "aaa -eee"); DBObject textSearchResult = collection.getDB() .command(new BasicDBObject(collection.getName(), new BasicDBObject("text", textSearchCommand))); ServerAddress serverAddress = new ServerAddress(new InetSocketAddress(ServerAddress.defaultHost(), ServerAddress.defaultPort())); String host = serverAddress.getHost() + ":" + serverAddress.getPort(); DBObject expected = new BasicDBObject("serverUsed", host).append("ok", 1.0); expected.put("results", JSON.parse("[ " + "{ \"score\" : 0.75 , " + "\"obj\" : { \"_id\" : 1 , \"textField\" : \"aaa bbb\"}}]" )); expected.put("stats", new BasicDBObject("nscannedObjects", 4L) .append("nscanned", 2L) .append("n", 1L) .append("timeMicros", 1) ); Assertions.assertThat(textSearchResult).isEqualTo(expected); assertEquals("aaa bbb", ((DBObject) ((DBObject) ((List) textSearchResult.get("results")).get(0)).get("obj")).get("textField")); } @Test public void testFindWithLimit() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); collection.insert(new BasicDBObject("_id", 3)); collection.insert(new BasicDBObject("_id", 4)); DBCursor cursor = collection.find().limit(2); assertEquals(Arrays.asList( new BasicDBObject("_id", 1), new BasicDBObject("_id", 2) ), cursor.toArray()); } @Test public void testFindWithSkipLimit() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); collection.insert(new BasicDBObject("_id", 3)); collection.insert(new BasicDBObject("_id", 4)); DBCursor cursor = collection.find().limit(2).skip(2); assertEquals(Arrays.asList( new BasicDBObject("_id", 3), new BasicDBObject("_id", 4) ), cursor.toArray()); } @Test public void testFindWithSkipLimitNoResult() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); collection.insert(new BasicDBObject("_id", 3)); collection.insert(new BasicDBObject("_id", 4)); collection.insert(new BasicDBObject("_id", 5)); QueryBuilder builder = new QueryBuilder().start("_id").greaterThanEquals(1).lessThanEquals(4); DBCursor cursor = collection.find(builder.get()).limit(2).skip(4); assertEquals(Arrays.asList(), cursor.toArray()); } @Test public void testFindWithSkipLimitWithSort() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("date", 5L).append("str", "1")); collection.insert(new BasicDBObject("_id", 2).append("date", 6L).append("str", "2")); collection.insert(new BasicDBObject("_id", 3).append("date", 7L).append("str", "3")); collection.insert(new BasicDBObject("_id", 4).append("date", 8L).append("str", "4")); collection.insert(new BasicDBObject("_id", 5).append("date", 5L)); QueryBuilder builder = new QueryBuilder().start("_id").greaterThanEquals(1).lessThanEquals(5).and("str").in(Arrays.asList("1", "2", "3", "4")); // Without sort. DBCursor cursor = collection.find(builder.get()).limit(2).skip(4); assertEquals(Arrays.asList(), cursor.toArray()); // With sort. cursor = collection.find(builder.get()).sort(new BasicDBObject("date", 1)).limit(2).skip(4); assertEquals(Arrays.asList(), cursor.toArray()); } @Test public void testFindWithWhere() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("say", "hi").append("n", 3), new BasicDBObject("_id", 2).append("say", "hello").append("n", 5)); DBCursor cursor = collection.find(new BasicDBObject("$where", "this.say == 'hello'")); assertEquals(Arrays.asList( new BasicDBObject("_id", 2).append("say", "hello").append("n", 5) ), cursor.toArray()); cursor = collection.find(new BasicDBObject("$where", "this.n < 4")); assertEquals(Arrays.asList( new BasicDBObject("_id", 1).append("say", "hi").append("n", 3) ), cursor.toArray()); } @Test public void findWithEmptyQueryFieldValue() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", 2)); collection.insert(new BasicDBObject("_id", 2).append("a", new BasicDBObject())); DBCursor cursor = collection.find(new BasicDBObject("a", new BasicDBObject())); assertEquals(Arrays.asList( new BasicDBObject("_id", 2).append("a", new BasicDBObject()) ), cursor.toArray()); } @Test public void testIdInQueryResultsInIndexOrder() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 4)); collection.insert(new BasicDBObject("_id", 3)); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); DBCursor cursor = collection.find(new BasicDBObject("_id", new BasicDBObject("$in", Arrays.asList(3, 2, 1)))); assertEquals(Arrays.asList( new BasicDBObject("_id", 1), new BasicDBObject("_id", 2), new BasicDBObject("_id", 3) ), cursor.toArray()); } @Test public void testIdInQueryResultsInIndexOrderEvenIfOrderByExistAndIsWrong() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 4)); collection.insert(new BasicDBObject("_id", 3)); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); DBCursor cursor = collection.find(new BasicDBObject("_id", new BasicDBObject("$in", Arrays.asList(3, 2, 1)))).sort(new BasicDBObject("wrongField", 1)); assertEquals(Arrays.asList( new BasicDBObject("_id", 1), new BasicDBObject("_id", 2), new BasicDBObject("_id", 3) ), cursor.toArray()); } /** * Must return in inserted order. */ @Test public void testIdInsertedOrder() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 4)); collection.insert(new BasicDBObject("_id", 3)); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); DBCursor cursor = collection.find(); assertEquals(Arrays.asList( new BasicDBObject("_id", 4), new BasicDBObject("_id", 3), new BasicDBObject("_id", 1), new BasicDBObject("_id", 2) ), cursor.toArray()); } @Test public void testSort() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("a", 1).append("_id", 1)); collection.insert(new BasicDBObject("a", 2).append("_id", 2)); collection.insert(new BasicDBObject("_id", 5)); collection.insert(new BasicDBObject("a", 3).append("_id", 3)); collection.insert(new BasicDBObject("a", 4).append("_id", 4)); DBCursor cursor = collection.find().sort(new BasicDBObject("a", -1)); assertEquals(Arrays.asList( new BasicDBObject("a", 4).append("_id", 4), new BasicDBObject("a", 3).append("_id", 3), new BasicDBObject("a", 2).append("_id", 2), new BasicDBObject("a", 1).append("_id", 1), new BasicDBObject("_id", 5) ), cursor.toArray()); } @Test public void testCompoundSort() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("a", 1).append("_id", 1)); collection.insert(new BasicDBObject("a", 2).append("_id", 5)); collection.insert(new BasicDBObject("a", 1).append("_id", 2)); collection.insert(new BasicDBObject("a", 2).append("_id", 4)); collection.insert(new BasicDBObject("a", 1).append("_id", 3)); DBCursor cursor = collection.find().sort(new BasicDBObject("a", 1).append("_id", -1)); assertEquals(Arrays.asList( new BasicDBObject("a", 1).append("_id", 3), new BasicDBObject("a", 1).append("_id", 2), new BasicDBObject("a", 1).append("_id", 1), new BasicDBObject("a", 2).append("_id", 5), new BasicDBObject("a", 2).append("_id", 4) ), cursor.toArray()); } @Test public void testCompoundSortFindAndModify() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("a", 1).append("_id", 1)); collection.insert(new BasicDBObject("a", 2).append("_id", 5)); collection.insert(new BasicDBObject("a", 1).append("_id", 2)); collection.insert(new BasicDBObject("a", 2).append("_id", 4)); collection.insert(new BasicDBObject("a", 1).append("_id", 3)); DBObject object = collection.findAndModify(null, new BasicDBObject("a", 1).append("_id", -1), new BasicDBObject("date", 1)); assertEquals( new BasicDBObject("_id", 3).append("a", 1), object); } @Test public void testCommandFindAndModify() { // Given DBCollection collection = newCollection(); DB db = collection.getDB(); collection.insert(new BasicDBObject("a", 1).append("_id", 1)); collection.insert(new BasicDBObject("a", 2).append("_id", 5)); collection.insert(new BasicDBObject("a", 1).append("_id", 2)); collection.insert(new BasicDBObject("a", 2).append("_id", 4)); collection.insert(new BasicDBObject("a", 1).append("_id", 3)); // When CommandResult result = db.command(new BasicDBObject("findAndModify", collection.getName()).append("sort", new BasicDBObject("a", 1).append("_id", -1)).append("update", new BasicDBObject("date", 1))); // Then assertTrue(result.ok()); assertEquals( new BasicDBObject("_id", 3).append("a", 1), result.get("value")); } @Test public void testEmbeddedSort() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); collection.insert(new BasicDBObject("_id", 3)); collection.insert(new BasicDBObject("_id", 4).append("counts", new BasicDBObject("done", 1))); collection.insert(new BasicDBObject("_id", 5).append("counts", new BasicDBObject("done", 2))); DBCursor cursor = collection.find(new BasicDBObject("c", new BasicDBObject("$ne", true))).sort(new BasicDBObject("counts.done", -1)); assertEquals(Arrays.asList( new BasicDBObject("_id", 5).append("counts", new BasicDBObject("done", 2)), new BasicDBObject("_id", 4).append("counts", new BasicDBObject("done", 1)), new BasicDBObject("_id", 1), new BasicDBObject("_id", 2), new BasicDBObject("_id", 3) ), cursor.toArray()); } @Test public void testBasicUpdate() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2).append("b", 5)); collection.insert(new BasicDBObject("_id", 3)); collection.insert(new BasicDBObject("_id", 4)); collection.update(new BasicDBObject("_id", 2), new BasicDBObject("a", 5)); assertEquals(new BasicDBObject("_id", 2).append("a", 5), collection.findOne(new BasicDBObject("_id", 2))); } @Test public void testFullUpdateWithSameId() throws Exception { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2).append("b", 5)); collection.insert(new BasicDBObject("_id", 3)); collection.insert(new BasicDBObject("_id", 4)); collection.update( new BasicDBObject("_id", 2).append("b", 5), new BasicDBObject("_id", 2).append("a", 5)); assertEquals(new BasicDBObject("_id", 2).append("a", 5), collection.findOne(new BasicDBObject("_id", 2))); } @Test public void testIdNotAllowedToBeUpdated() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); try { collection.update(new BasicDBObject("_id", 1), new BasicDBObject("_id", 2).append("a", 5)); fail("should throw exception"); } catch (MongoException e) { } } @Test public void testUpsert() { DBCollection collection = newCollection(); WriteResult result = collection.update(new BasicDBObject("_id", 1).append("n", "jon"), new BasicDBObject("$inc", new BasicDBObject("a", 1)), true, false); assertEquals(new BasicDBObject("_id", 1).append("n", "jon").append("a", 1), collection.findOne()); assertFalse(result.getLastError().getBoolean("updatedExisting")); } @Test public void testUpsertExisting() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); WriteResult result = collection.update(new BasicDBObject("_id", 1), new BasicDBObject("$inc", new BasicDBObject("a", 1)), true, false); assertEquals(new BasicDBObject("_id", 1).append("a", 1), collection.findOne()); assertTrue(result.getLastError().getBoolean("updatedExisting")); } @Test public void testUpsertWithConditional() { DBCollection collection = newCollection(); collection.update(new BasicDBObject("_id", 1).append("b", new BasicDBObject("$gt", 5)), new BasicDBObject("$inc", new BasicDBObject("a", 1)), true, false); assertEquals(new BasicDBObject("_id", 1).append("a", 1), collection.findOne()); } @Test public void testUpsertWithIdIn() { DBCollection collection = newCollection(); DBObject query = new BasicDBObjectBuilder().push("_id").append("$in", Arrays.asList(1)).pop().get(); DBObject update = new BasicDBObjectBuilder() .push("$push").push("n").append("_id", 2).append("u", 3).pop().pop() .push("$inc").append("c", 4).pop().get(); DBObject expected = new BasicDBObjectBuilder().append("_id", 1).append("n", Arrays.asList(new BasicDBObject("_id", 2).append("u", 3))).append("c", 4).get(); collection.update(query, update, true, false); assertEquals(expected, collection.findOne()); } @Test public void testUpdateWithIdIn() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); DBObject query = new BasicDBObjectBuilder().push("_id").append("$in", Arrays.asList(1)).pop().get(); DBObject update = new BasicDBObjectBuilder() .push("$push").push("n").append("_id", 2).append("u", 3).pop().pop() .push("$inc").append("c", 4).pop().get(); DBObject expected = new BasicDBObjectBuilder().append("_id", 1).append("n", Arrays.asList(new BasicDBObject("_id", 2).append("u", 3))).append("c", 4).get(); collection.update(query, update, false, true); assertEquals(expected, collection.findOne()); } @Test public void testUpdateWithObjectId() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", new BasicDBObject("n", 1))); DBObject query = new BasicDBObject("_id", new BasicDBObject("n", 1)); DBObject update = new BasicDBObject("$set", new BasicDBObject("a", 1)); collection.update(query, update, false, false); assertEquals(new BasicDBObject("_id", new BasicDBObject("n", 1)).append("a", 1), collection.findOne()); } @Test public void testUpdateWithIdInMulti() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1), new BasicDBObject("_id", 2)); collection.update(new BasicDBObject("_id", new BasicDBObject("$in", Arrays.asList(1, 2))), new BasicDBObject("$set", new BasicDBObject("n", 1)), false, true); List<DBObject> results = collection.find().toArray(); assertEquals(Arrays.asList( new BasicDBObject("_id", 1).append("n", 1), new BasicDBObject("_id", 2).append("n", 1) ), results); } @Test public void testUpdateWithIdQuery() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1), new BasicDBObject("_id", 2)); collection.update(new BasicDBObject("_id", new BasicDBObject("$gt", 1)), new BasicDBObject("$set", new BasicDBObject("n", 1)), false, true); List<DBObject> results = collection.find().toArray(); assertEquals(Arrays.asList( new BasicDBObject("_id", 1), new BasicDBObject("_id", 2).append("n", 1) ), results); } @Test public void testUpdateWithOneRename() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", new BasicDBObject("b", 1))); collection.update(new BasicDBObject("_id", 1), new BasicDBObject("$rename", new BasicDBObject("a.b", "a.c"))); List<DBObject> results = collection.find().toArray(); assertEquals(Arrays.asList( new BasicDBObject("_id", 1).append("a", new BasicDBObject("c", 1)) ), results); } @Test public void testUpdateWithMultipleRenames() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", new BasicDBObject("b", 1)) .append("x", 3) .append("h", new BasicDBObject("i", 8))); collection.update(new BasicDBObject("_id", 1), new BasicDBObject("$rename", new BasicDBObject("a.b", "a.c") .append("x", "y") .append("h.i", "u.r"))); List<DBObject> results = collection.find().toArray(); assertEquals(Arrays.asList( new BasicDBObject("_id", 1).append("a", new BasicDBObject("c", 1)) .append("y", 3) .append("u", new BasicDBObject("r", 8)) .append("h", new BasicDBObject()) ), results); } @Test public void testCompoundDateIdUpserts() { DBCollection collection = newCollection(); DBObject query = new BasicDBObjectBuilder().push("_id") .push("$lt").add("n", "a").add("t", 10).pop() .push("$gte").add("n", "a").add("t", 1).pop() .pop().get(); List<BasicDBObject> toUpsert = Arrays.asList( new BasicDBObject("_id", new BasicDBObject("n", "a").append("t", 1)), new BasicDBObject("_id", new BasicDBObject("n", "a").append("t", 2)), new BasicDBObject("_id", new BasicDBObject("n", "a").append("t", 3)), new BasicDBObject("_id", new BasicDBObject("n", "a").append("t", 11)) ); for (BasicDBObject dbo : toUpsert) { collection.update(dbo, ((BasicDBObject) dbo.copy()).append("foo", "bar"), true, false); } List<DBObject> results = collection.find(query).toArray(); assertEquals(Arrays.<DBObject>asList( new BasicDBObject("_id", new BasicDBObject("n", "a").append("t", 1)).append("foo", "bar"), new BasicDBObject("_id", new BasicDBObject("n", "a").append("t", 2)).append("foo", "bar"), new BasicDBObject("_id", new BasicDBObject("n", "a").append("t", 3)).append("foo", "bar") ), results); } @Test public void testAnotherUpsert() { DBCollection collection = newCollection(); BasicDBObjectBuilder queryBuilder = BasicDBObjectBuilder.start().push("_id"). append("f", "ca").push("1").append("l", 2).pop().push("t").append("t", 11).pop().pop(); DBObject query = queryBuilder.get(); DBObject update = BasicDBObjectBuilder.start().push("$inc").append("n.!", 1).append("n.a.b:false", 1).pop().get(); final WriteResult result = collection.update(query, update, true, false); assertFalse(result.isUpdateOfExisting()); assertTrue(result.getN() == 1); DBObject expected = queryBuilder.push("n").append("!", 1).push("a").append("b:false", 1).pop().pop().get(); assertEquals(expected, collection.findOne()); } @Test public void testAuthentication() { DB fongoDB = fongoRule.getDB("testDB"); assertFalse(fongoDB.isAuthenticated()); // Once authenticated, fongoDB should be available to answer yes, whatever the credentials were. assertTrue(fongoDB.authenticate("login", "password".toCharArray())); assertTrue(fongoDB.isAuthenticated()); } @Test public void testUpsertOnIdWithPush() { DBCollection collection = newCollection(); DBObject update1 = BasicDBObjectBuilder.start().push("$push") .push("c").append("a", 1).append("b", 2).pop().pop().get(); DBObject update2 = BasicDBObjectBuilder.start().push("$push") .push("c").append("a", 3).append("b", 4).pop().pop().get(); collection.update(new BasicDBObject("_id", 1), update1, true, false); collection.update(new BasicDBObject("_id", 1), update2, true, false); DBObject expected = new BasicDBObject("_id", 1).append("c", Util.list( new BasicDBObject("a", 1).append("b", 2), new BasicDBObject("a", 3).append("b", 4))); assertEquals(expected, collection.findOne(new BasicDBObject("c.a", 3).append("c.b", 4))); } @Test public void testUpsertWithEmbeddedQuery() { DBCollection collection = newCollection(); DBObject update = BasicDBObjectBuilder.start().push("$set").append("a", 1).pop().get(); collection.update(new BasicDBObject("_id", 1).append("e.i", 1), update, true, false); DBObject expected = BasicDBObjectBuilder.start().append("_id", 1).push("e").append("i", 1).pop().append("a", 1).get(); assertEquals(expected, collection.findOne(new BasicDBObject("_id", 1))); } @Test public void testFindAndModifyReturnOld() { final DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", 1).append("b", new BasicDBObject("c", 1))); final BasicDBObject query = new BasicDBObject("_id", 1); final BasicDBObject update = new BasicDBObject("$inc", new BasicDBObject("a", 1).append("b.c", 1)); final DBObject result = collection.findAndModify(query, null, null, false, update, false, false); assertEquals(new BasicDBObject("_id", 1).append("a", 1).append("b", new BasicDBObject("c", 1)), result); assertEquals(new BasicDBObject("_id", 1).append("a", 2).append("b", new BasicDBObject("c", 2)), collection.findOne()); } @Test public void testFindAndModifyWithEmptyObjectProjection() { final DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", 1).append("b", new BasicDBObject("c", 1))); final BasicDBObject query = new BasicDBObject("_id", 1); final BasicDBObject update = new BasicDBObject("$unset", new BasicDBObject("b", "")); final DBObject result = collection.findAndModify(query, new BasicDBObject(), null, false, update, true, false); assertEquals(new BasicDBObject("_id", 1).append("a", 1), result); } /** * See issue #35 */ @Test public void findAndModify_with_projection_and_nothing_found() { final DBCollection collection = newCollection(); final BasicDBObject query = new BasicDBObject("_id", 1); final BasicDBObject update = new BasicDBObject("$inc", new BasicDBObject("d", 1).append("b.c", 1)); final DBObject result = collection.findAndModify(query, new BasicDBObject("e", true), null, false, update, true, false); Assertions.assertThat(result).isNull(); } @Test public void testFindAndModifyWithInReturnOld() { final DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", 1).append("b", new BasicDBObject("c", 1))); final BasicDBObject query = new BasicDBObject("_id", new BasicDBObject("$in", Util.list(1, 2, 3))); final BasicDBObject update = new BasicDBObject("$inc", new BasicDBObject("a", 1).append("b.c", 1)); final DBObject result = collection.findAndModify(query, null, null, false, update, false, false); assertEquals(new BasicDBObject("_id", 1).append("a", 1).append("b", new BasicDBObject("c", 1)), result); assertEquals(new BasicDBObject("_id", 1).append("a", 2).append("b", new BasicDBObject("c", 2)), collection.findOne()); } @Test public void testFindAndModifyReturnNew() { final DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", 1).append("b", new BasicDBObject("c", 1))); final BasicDBObject query = new BasicDBObject("_id", 1); final BasicDBObject update = new BasicDBObject("$inc", new BasicDBObject("a", 1).append("b.c", 1)); final DBObject result = collection.findAndModify(query, null, null, false, update, true, false); assertEquals(new BasicDBObject("_id", 1).append("a", 2).append("b", new BasicDBObject("c", 2)), result); } @Test public void testFindAndModifyUpsert() { DBCollection collection = newCollection(); DBObject result = collection.findAndModify(new BasicDBObject("_id", 1), null, null, false, new BasicDBObject("$inc", new BasicDBObject("a", 1)), true, true); assertEquals(new BasicDBObject("_id", 1).append("a", 1), result); assertEquals(new BasicDBObject("_id", 1).append("a", 1), collection.findOne()); } @Test public void testFindAndModifyUpsertReturnNewFalse() { DBCollection collection = newCollection(); DBObject result = collection.findAndModify(new BasicDBObject("_id", 1), null, null, false, new BasicDBObject("$inc", new BasicDBObject("a", 1)), false, true); assertEquals(new BasicDBObject(), result); assertEquals(new BasicDBObject("_id", 1).append("a", 1), collection.findOne()); } @Test public void testFindAndRemoveFromEmbeddedList() { DBCollection collection = newCollection(); BasicDBObject obj = new BasicDBObject("_id", 1).append("a", Arrays.asList(1)); collection.insert(obj); DBObject result = collection.findAndRemove(new BasicDBObject("_id", 1)); assertEquals(obj, result); } @Test public void testFindAndRemoveNothingFound() { DBCollection coll = newCollection(); assertNull("should return null if nothing was found", coll.findAndRemove(new BasicDBObject())); } @Test public void testFindAndModifyRemove() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", 1)); DBObject result = collection.findAndModify(new BasicDBObject("_id", 1), null, null, true, null, false, false); assertEquals(new BasicDBObject("_id", 1).append("a", 1), result); assertEquals(null, collection.findOne()); } @Test public void testRemove() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); collection.insert(new BasicDBObject("_id", 3)); collection.insert(new BasicDBObject("_id", 4)); collection.remove(new BasicDBObject("_id", 2)); assertEquals(null, collection.findOne(new BasicDBObject("_id", 2))); } @Test public void testConvertJavaListToDbList() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("n", Arrays.asList(1, 2))); DBObject result = collection.findOne(); assertTrue("not a DBList", result.get("n") instanceof BasicDBList); } @Test public void testConvertJavaMapToDBObject() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("n", Collections.singletonMap("a", 1))); DBObject result = collection.findOne(); assertTrue("not a DBObject", result.get("n") instanceof BasicDBObject); } @Test public void testDistinctQuery() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("n", 1).append("_id", 1)); collection.insert(new BasicDBObject("n", 2).append("_id", 2)); collection.insert(new BasicDBObject("n", 3).append("_id", 3)); collection.insert(new BasicDBObject("n", 1).append("_id", 4)); collection.insert(new BasicDBObject("n", 1).append("_id", 5)); assertEquals(Arrays.asList(1, 2, 3), collection.distinct("n")); } @Test public void testDistinctHierarchicalQuery() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("n", new BasicDBObject("i", 1)).append("_id", 1)); collection.insert(new BasicDBObject("n", new BasicDBObject("i", 2)).append("_id", 2)); collection.insert(new BasicDBObject("n", new BasicDBObject("i", 3)).append("_id", 3)); collection.insert(new BasicDBObject("n", new BasicDBObject("i", 1)).append("_id", 4)); collection.insert(new BasicDBObject("n", new BasicDBObject("i", 1)).append("_id", 5)); assertEquals(Arrays.asList(1, 2, 3), collection.distinct("n.i")); } @Test public void testDistinctHierarchicalQueryWithArray() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("n", new BasicDBObject("i", Util.list(1, 2, 3))).append("_id", 1)); collection.insert(new BasicDBObject("n", new BasicDBObject("i", Util.list(3, 4))).append("_id", 2)); collection.insert(new BasicDBObject("n", new BasicDBObject("i", Util.list(1, 5))).append("_id", 3)); assertEquals(Arrays.asList(1, 2, 3, 4, 5), collection.distinct("n.i")); } @Test public void testGetLastError() { Fongo fongo = newFongo(); DB db = fongo.getDB("db"); DBCollection collection = db.getCollection("coll"); collection.insert(new BasicDBObject("_id", 1)); CommandResult error = db.getLastError(); assertTrue(error.ok()); } @Test public void testSave() { DBCollection collection = newCollection(); BasicDBObject inserted = new BasicDBObject("_id", 1); collection.insert(inserted); collection.save(inserted); } @Test(expected = DuplicateKeyException.class) public void testInsertDuplicateWithConcernThrows() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 1), WriteConcern.SAFE); } @Test(expected = DuplicateKeyException.class) public void testInsertDuplicateWithDefaultConcernOnMongo() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 1)); } @Test public void testInsertDuplicateIgnored() { DBCollection collection = newCollection(); collection.getDB().getMongo().setWriteConcern(WriteConcern.UNACKNOWLEDGED); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 1)); assertEquals(1, collection.count()); } @Test public void testSortByEmbeddedKey() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", new BasicDBObject("b", 1))); collection.insert(new BasicDBObject("_id", 2).append("a", new BasicDBObject("b", 2))); collection.insert(new BasicDBObject("_id", 3).append("a", new BasicDBObject("b", 3))); List<DBObject> results = collection.find().sort(new BasicDBObject("a.b", -1)).toArray(); assertEquals( Arrays.asList( new BasicDBObject("_id", 3).append("a", new BasicDBObject("b", 3)), new BasicDBObject("_id", 2).append("a", new BasicDBObject("b", 2)), new BasicDBObject("_id", 1).append("a", new BasicDBObject("b", 1)) ), results ); } @Test public void testCommandQuery() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", 3)); collection.insert(new BasicDBObject("_id", 2).append("a", 2)); collection.insert(new BasicDBObject("_id", 3).append("a", 1)); assertEquals( new BasicDBObject("_id", 3).append("a", 1), collection.findOne(new BasicDBObject(), null, new BasicDBObject("a", 1)) ); } @Test public void testInsertReturnModifiedDocumentCount() { DBCollection collection = newCollection(); WriteResult result = collection.insert(new BasicDBObject("_id", new BasicDBObject("n", 1))); assertEquals(1, result.getN()); } @Test public void testUpdateWithIdInMultiReturnModifiedDocumentCount() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1), new BasicDBObject("_id", 2)); WriteResult result = collection.update(new BasicDBObject("_id", new BasicDBObject("$in", Arrays.asList(1, 2))), new BasicDBObject("$set", new BasicDBObject("n", 1)), false, true); assertEquals(2, result.getN()); } @Test public void testUpdateWithObjectIdReturnModifiedDocumentCount() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", new BasicDBObject("n", 1))); DBObject query = new BasicDBObject("_id", new BasicDBObject("n", 1)); DBObject update = new BasicDBObject("$set", new BasicDBObject("a", 1)); WriteResult result = collection.update(query, update, false, false); assertEquals(1, result.getN()); } /** * Test that ObjectId is getting generated even if _id is present in * DBObject but it's value is null * * @throws Exception */ @Test public void testIdGenerated() throws Exception { DBObject toSave = new BasicDBObject(); toSave.put("_id", null); toSave.put("name", "test"); Fongo fongo = newFongo(); DB fongoDB = fongo.getDB("testDB"); DBCollection collection = fongoDB.getCollection("testCollection"); collection.save(toSave); DBObject result = collection.findOne(new BasicDBObject("name", "test")); //default index in mongoDB final String ID_KEY = "_id"; assertNotNull("Expected _id to be generated" + result.get(ID_KEY)); } @Test public void testDropDatabaseAlsoDropsCollectionData() throws Exception { DBCollection collection = newCollection(); collection.insert(new BasicDBObject()); collection.getDB().dropDatabase(); assertEquals("Collection should have no data", 0, collection.count()); } @Test public void testDropCollectionAlsoDropsFromDB() throws Exception { DBCollection collection = newCollection(); collection.insert(new BasicDBObject()); collection.drop(); assertEquals("Collection should have no data", 0.D, collection.count(), 0.D); assertFalse("Collection shouldn't exist in DB", collection.getDB().getCollectionNames().contains(collection.getName())); } @Test public void testDropDatabaseFromFongoDropsAllData() throws Exception { Fongo fongo = newFongo(); DBCollection collection = fongo.getDB("db").getCollection("coll"); collection.insert(new BasicDBObject()); fongo.dropDatabase("db"); assertEquals("Collection should have no data", 0.D, collection.count(), 0.D); assertFalse("Collection shouldn't exist in DB", collection.getDB().getCollectionNames().contains(collection.getName())); assertFalse("DB shouldn't exist in fongo", fongo.getDatabaseNames().contains("db")); } @Test public void testDropDatabaseFromFongoWithMultipleCollectionsDropsBothCollections() throws Exception { Fongo fongo = newFongo(); DB db = fongo.getDB("db"); DBCollection collection1 = db.getCollection("coll1"); DBCollection collection2 = db.getCollection("coll2"); db.dropDatabase(); assertFalse("Collection 1 shouldn't exist in DB", db.collectionExists(collection1.getName())); assertFalse("Collection 2 shouldn't exist in DB", db.collectionExists(collection2.getName())); assertFalse("DB shouldn't exist in fongo", fongo.getDatabaseNames().contains("db")); } @Test public void testDropCollectionsFromGetCollectionNames() { Fongo fongo = newFongo(); DB db = fongo.getDB("db"); db.getCollection("coll1"); db.getCollection("coll2"); int dropCount = 0; for (String name : db.getCollectionNames()) { if (!name.startsWith("system.")) { db.getCollection(name).drop(); dropCount++; } } assertEquals("should drop two collections", 2, dropCount); } @Test public void testDropCollectionsPermitReuseOfDBCollection() throws Exception { DB db = newFongo().getDB("db"); int startingCollectionSize = db.getCollectionNames().size(); DBCollection coll1 = db.getCollection("coll1"); DBCollection coll2 = db.getCollection("coll2"); assertEquals(startingCollectionSize + 2, db.getCollectionNames().size()); // when coll1.drop(); coll2.drop(); assertEquals(startingCollectionSize + 0, db.getCollectionNames().size()); // Insert a value must create the collection. coll1.insert(new BasicDBObject("_id", 1)); assertEquals(startingCollectionSize + 1, db.getCollectionNames().size()); } @Test public void testToString() { new Fongo("test").getMongo().toString(); } @Test public void testForceError() throws Exception { Fongo fongo = newFongo(); DB db = fongo.getDB("db"); CommandResult result = db.command("forceerror"); assertEquals("ok should always be defined", 0.0, result.get("ok")); assertEquals("exception: forced error", result.get("errmsg")); assertEquals(10038, result.get("code")); } @Test public void testUndefinedCommand() throws Exception { Fongo fongo = newFongo(); DB db = fongo.getDB("db"); CommandResult result = db.command("undefined"); assertEquals("ok should always be defined", 0.0, result.get("ok")); assertEquals("no such cmd: undefined", result.get("errmsg")); } @Test public void testCountCommand() throws Exception { Fongo fongo = newFongo(); DBObject countCmd = new BasicDBObject("count", "coll"); DB db = fongo.getDB("db"); DBCollection coll = db.getCollection("coll"); coll.insert(new BasicDBObject()); coll.insert(new BasicDBObject()); CommandResult result = db.command(countCmd); assertEquals("The command should have been succesful", 1.0, result.get("ok")); assertEquals("The count should be in the result", 2.0D, result.get("n")); } @Test public void testCountWithSkipLimitWithSort() { Fongo fongo = newFongo(); DB db = fongo.getDB("db"); DBCollection collection = db.getCollection("coll"); collection.insert(new BasicDBObject("_id", 0).append("date", 5L)); collection.insert(new BasicDBObject("_id", -1).append("date", 5L)); collection.insert(new BasicDBObject("_id", 1).append("date", 5L).append("str", "1")); collection.insert(new BasicDBObject("_id", 2).append("date", 6L).append("str", "2")); collection.insert(new BasicDBObject("_id", 3).append("date", 7L).append("str", "3")); collection.insert(new BasicDBObject("_id", 4).append("date", 8L).append("str", "4")); QueryBuilder builder = new QueryBuilder().start("_id").greaterThanEquals(1).lessThanEquals(5).and("str").in(Arrays.asList("1", "2", "3", "4")); DBObject countCmd = new BasicDBObject("count", "coll").append("limit", 2).append("skip", 4).append("query", builder.get()); CommandResult result = db.command(countCmd); // Without sort. assertEquals(0D, result.get("n")); } @Test public void testExplicitlyAddedObjectIdNotNew() { Fongo fongo = newFongo(); DB db = fongo.getDB("db"); DBCollection coll = db.getCollection("coll"); ObjectId oid = new ObjectId(); assertTrue("new should be true", oid.isNew()); coll.save(new BasicDBObject("_id", oid)); ObjectId retrievedOid = (ObjectId) coll.findOne().get("_id"); assertEquals("retrieved should still equal the inserted", oid, retrievedOid); assertFalse("retrieved should not be new", retrievedOid.isNew()); } @Test public void testAutoCreatedObjectIdNotNew() { Fongo fongo = newFongo(); DB db = fongo.getDB("db"); DBCollection coll = db.getCollection("coll"); coll.save(new BasicDBObject()); ObjectId retrievedOid = (ObjectId) coll.findOne().get("_id"); assertFalse("retrieved should not be new", retrievedOid.isNew()); } @Test public void testDbRefs() { Fongo fong = newFongo(); DB db = fong.getDB("db"); DBCollection coll1 = db.getCollection("coll"); DBCollection coll2 = db.getCollection("coll2"); final String coll2oid = "coll2id"; BasicDBObject coll2doc = new BasicDBObject("_id", coll2oid); coll2.insert(coll2doc); coll1.insert(new BasicDBObject("ref", new DBRef(db, "coll2", coll2oid))); DBRef ref = (DBRef) coll1.findOne().get("ref"); assertEquals("db", ref.getDB().getName()); assertEquals("coll2", ref.getRef()); assertEquals(coll2oid, ref.getId()); assertEquals(coll2doc, ref.fetch()); } @Test public void testDbRefsWithoutDbSet() { Fongo fong = newFongo(); DB db = fong.getDB("db"); DBCollection coll1 = db.getCollection("coll"); DBCollection coll2 = db.getCollection("coll2"); final String coll2oid = "coll2id"; BasicDBObject coll2doc = new BasicDBObject("_id", coll2oid); coll2.insert(coll2doc); coll1.insert(new BasicDBObject("ref", new DBRef(null, "coll2", coll2oid))); DBRef ref = (DBRef) coll1.findOne().get("ref"); assertNotNull(ref.getDB()); assertEquals("coll2", ref.getRef()); assertEquals(coll2oid, ref.getId()); assertEquals(coll2doc, ref.fetch()); } @Test public void nullable_db_for_dbref() { // Given DBCollection collection = this.newCollection(); DBObject saved = new BasicDBObjectBuilder().add("date", "now").get(); collection.save(saved); DBRef dbRef = new DBRef(null, collection.getName(), saved.get("_id")); DBObject ref = new BasicDBObject("ref", dbRef); // When collection.save(ref); DBRef result = (DBRef) collection.findOne(new BasicDBObject("_id", ref.get("_id"))).get("ref"); // Then assertThat(result.getDB()).isNotNull().isEqualTo(collection.getDB()); assertThat(result.fetch()).isEqualTo(saved); } @Test public void testFindAllWithDBList() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("tags", Util.list("mongo", "javascript"))); // When DBObject result = collection.findOne(new BasicDBObject("tags", new BasicDBObject("$all", Util.list("mongo", "javascript")))); // then assertEquals(new BasicDBObject("_id", 1).append("tags", Util.list("mongo", "javascript")), result); } @Test public void testFindAllWithList() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("tags", Util.list("mongo", "javascript"))); // When DBObject result = collection.findOne(new BasicDBObject("tags", new BasicDBObject("$all", Arrays.asList("mongo", "javascript")))); // then assertEquals(new BasicDBObject("_id", 1).append("tags", Util.list("mongo", "javascript")), result); } @Test public void testFindAllWithCollection() throws Exception { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("tags", Util.list("mongo", "javascript"))); // When DBObject result = collection.findOne(new BasicDBObject("tags", new BasicDBObject("$all", newHashSet("mongo", "javascript")))); // then assertEquals(new BasicDBObject("_id", 1).append("tags", Util.list("mongo", "javascript")), result); } @Test public void testEncodingHooks() { BSON.addEncodingHook(Seq.class, new Transformer() { @Override public Object transform(Object o) { return (o instanceof Seq) ? ((Seq) o).data : o; } }); DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); DBObject result1 = collection.findOne(new BasicDBObject("_id", new BasicDBObject("$in", new Seq(1, 3)))); assertEquals(new BasicDBObject("_id", 1), result1); DBObject result2 = collection.findOne(new BasicDBObject("_id", new BasicDBObject("$nin", new Seq(1, 3)))); assertEquals(new BasicDBObject("_id", 2), result2); } @Test public void testModificationsOfResultShouldNotChangeStorage() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); DBObject result = collection.findOne(); result.put("newkey", 1); assertEquals("should not have newkey", new BasicDBObject("_id", 1), collection.findOne()); } @Test(timeout = 16000) public void testMultiThreadInsert() throws Exception { ch.qos.logback.classic.Logger LOG = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(FongoDBCollection.class); Level oldLevel = LOG.getLevel(); try { LOG.setLevel(Level.ERROR); LOG = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ExpressionParser.class); LOG.setLevel(Level.ERROR); int size = 1000; final DBCollection col = new Fongo("InMemoryMongo").getDB("myDB").createCollection("myCollection", null); final CountDownLatch lockSynchro = new CountDownLatch(size); final CountDownLatch lockDone = new CountDownLatch(size); for (int i = 0; i < size; i++) { new Thread() { public void run() { lockSynchro.countDown(); col.insert(new BasicDBObject("multiple", 1), WriteConcern.ACKNOWLEDGED); lockDone.countDown(); } }.start(); } assertTrue("Too long :-(", lockDone.await(15, TimeUnit.SECONDS)); // Count must be same value as size assertEquals(size, col.getCount()); } finally { LOG.setLevel(oldLevel); } } // Don't know why, but request by _id only return document event if limit is set @Test public void testFindLimit0ById() throws Exception { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", "jon").append("name", "hoff")); List<DBObject> result = collection.find().limit(0).toArray(); assertNotNull(result); assertEquals(1, result.size()); } // Don't know why, but request by _id only return document even if skip is set @Test public void testFindSkip1yId() throws Exception { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", "jon").append("name", "hoff")); List<DBObject> result = collection.find(new BasicDBObject("_id", "jon")).skip(1).toArray(); assertNotNull(result); assertEquals(1, result.size()); } @Test public void testFindIdInSkip() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 4)); collection.insert(new BasicDBObject("_id", 3)); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); DBCursor cursor = collection.find(new BasicDBObject("_id", new BasicDBObject("$in", Arrays.asList(3, 2, 1)))).skip(3); assertEquals(Collections.emptyList(), cursor.toArray()); } @Test public void testFindIdInLimit() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 4)); collection.insert(new BasicDBObject("_id", 3)); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); DBCursor cursor = collection.find(new BasicDBObject("_id", new BasicDBObject("$in", Arrays.asList(3, 2, 1)))).skip(1); assertEquals(Arrays.asList( new BasicDBObject("_id", 2), new BasicDBObject("_id", 3)) , cursor.toArray()); } @Test public void testWriteConcern() { assertNotNull(newFongo().getWriteConcern()); } @Test public void shouldChangeWriteConcern() { Fongo fongo = newFongo(); WriteConcern writeConcern = fongo.getMongo().getMongoClientOptions().getWriteConcern(); assertEquals(writeConcern, fongo.getWriteConcern()); assertTrue(writeConcern != WriteConcern.FSYNC_SAFE); // Change write concern fongo.getMongo().setWriteConcern(WriteConcern.FSYNC_SAFE); assertEquals(WriteConcern.FSYNC_SAFE, fongo.getWriteConcern()); } // Id is always the first field. @Test public void shouldInsertIdFirst() throws Exception { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("date", 1).append("_id", new ObjectId())); collection.insert(new BasicDBObject("date", 2).append("_id", new ObjectId())); collection.insert(new BasicDBObject("date", 3).append("_id", new ObjectId())); List<DBObject> result = collection.find().toArray(); for (DBObject object : result) { // The _id field is always the first. assertEquals("_id", object.toMap().keySet().iterator().next()); } } @Test public void shouldSearchGteInArray() throws Exception { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", Util.list(1, 2, 3))); collection.insert(new BasicDBObject("_id", 2).append("a", 2)); // When List<DBObject> objects = collection.find(new BasicDBObject("a", new BasicDBObject("$gte", 2))).toArray(); // Then assertEquals(Arrays.asList( new BasicDBObject("_id", 1).append("a", Util.list(1, 2, 3)), new BasicDBObject("_id", 2).append("a", 2)), objects); } // issue #78 $gte throws Exception on non-Comparable @Test public void shouldNotThrowsExceptionOnNonComparableGte() throws Exception { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", new BasicDBObject("b", 1).append("c", 1))); collection.insert(new BasicDBObject("_id", 2).append("a", 2)); // When List<DBObject> objects = collection.find(new BasicDBObject("a", new BasicDBObject("$gte", 2))).toArray(); // Then assertEquals(Arrays.asList( new BasicDBObject("_id", 2).append("a", 2)), objects); } // issue #78 $gte throws Exception on non-Comparable @Test public void shouldNotThrowsExceptionOnNonComparableLte() throws Exception { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", new BasicDBObject("b", 1).append("c", 1))); collection.insert(new BasicDBObject("_id", 2).append("a", 2)); // When List<DBObject> objects = collection.find(new BasicDBObject("a", new BasicDBObject("$lte", 2))).toArray(); // Then assertEquals(Arrays.asList( new BasicDBObject("_id", 2).append("a", 2)), objects); } // issue #78 $gte throws Exception on non-Comparable @Test public void shouldNotThrowsExceptionOnNonComparableGt() throws Exception { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", new BasicDBObject("b", 1).append("c", 1))); collection.insert(new BasicDBObject("_id", 2).append("a", 2)); // When List<DBObject> objects = collection.find(new BasicDBObject("a", new BasicDBObject("$gt", 1))).toArray(); // Then assertEquals(Arrays.asList( new BasicDBObject("_id", 2).append("a", 2)), objects); } // issue #78 $gte throws Exception on non-Comparable @Test public void shouldNotThrowsExceptionOnNonComparableLt() throws Exception { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", new BasicDBObject("b", 1).append("c", 1))); collection.insert(new BasicDBObject("_id", 2).append("a", 2)); // When List<DBObject> objects = collection.find(new BasicDBObject("a", new BasicDBObject("$lt", 3))).toArray(); // Then assertEquals(Arrays.asList( new BasicDBObject("_id", 2).append("a", 2)), objects); } //PR @Test public void testAddOrReplaceElementMustWorkWithDollarOperator() { DBCollection collection = newCollection(); String random1 = UUID.randomUUID().toString(); String random2 = UUID.randomUUID().toString(); BasicDBList list1 = new BasicDBList(); list1.add(new BasicDBObject("_id", random1).append("var3", "val31")); list1.add(new BasicDBObject("_id", random2).append("var3", "val32")); collection.insert(new BasicDBObject("_id", 1234).append("var1", "val1").append("parentObject", new BasicDBObject("var2", "val21").append("subObject", list1))); DBObject query = new BasicDBObject("_id", 1234).append("parentObject.subObject._id", random1); DBObject update = new BasicDBObject("$set", new BasicDBObject ("parentObject.subObject.$", new BasicDBObject ("_id", random1).append("var3", "val33"))); BasicDBList list2 = new BasicDBList(); list2.add(new BasicDBObject("_id", random1).append("var3", "val33")); list2.add(new BasicDBObject("_id", random2).append("var3", "val32")); DBObject expected = new BasicDBObject("_id", 1234).append("var1", "val1").append("parentObject", new BasicDBObject("var2", "val21").append("subObject", list2)); collection.update(query, update); assertEquals(collection.findOne(new BasicDBObject("_id", 1234)), expected); } @Test public void shouldCompareObjectId() throws Exception { // Given DBCollection collection = newCollection(); ObjectId id1 = ObjectId.get(); ObjectId id2 = ObjectId.get(); collection.insert(new BasicDBObject("_id", id1)); collection.insert(new BasicDBObject("_id", id2)); // When List<DBObject> objects = collection.find(new BasicDBObject("_id", new BasicDBObject("$gte", id1))).toArray(); // Then assertEquals(Arrays.asList( new BasicDBObject("_id", id1), new BasicDBObject("_id", id2) ), objects); } @Test public void canInsertWithNewObjectId() throws Exception { DBCollection collection = newCollection(); ObjectId id = ObjectId.get(); collection.insert(new BasicDBObject("_id", id).append("name", "jon")); assertEquals(1, collection.count(new BasicDBObject("name", "jon"))); assertFalse(id.isNew()); } @Test public void saveStringAsObjectId() throws Exception { DBCollection collection = newCollection(); String id = ObjectId.get().toString(); BasicDBObject object = new BasicDBObject("_id", id).append("name", "jon"); collection.insert(object); assertEquals(1, collection.count(new BasicDBObject("name", "jon"))); assertEquals(id, object.get("_id")); } @Test public void shouldFilterByType() throws Exception { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("date", 1).append("_id", 1)); collection.insert(new BasicDBObject("date", 2D).append("_id", 2)); collection.insert(new BasicDBObject("date", "3").append("_id", 3)); ObjectId id = new ObjectId(); collection.insert(new BasicDBObject("date", true).append("_id", id)); collection.insert(new BasicDBObject("date", null).append("_id", 5)); collection.insert(new BasicDBObject("date", 6L).append("_id", 6)); collection.insert(new BasicDBObject("date", Util.list(1, 2, 3)).append("_id", 7)); collection.insert(new BasicDBObject("date", Util.list(1D, 2L, "3", 4)).append("_id", 8)); collection.insert(new BasicDBObject("date", Util.list(Util.list(1D, 2L, "3", 4))).append("_id", 9)); collection.insert(new BasicDBObject("date", 2F).append("_id", 10)); collection.insert(new BasicDBObject("date", new BasicDBObject("x", 1)).append("_id", 11)); // When List<DBObject> objects = collection.find(new BasicDBObject("date", new BasicDBObject("$type", 1))).toArray(); assertEquals(Arrays.asList( new BasicDBObject("_id", 2).append("date", 2D), new BasicDBObject("date", Util.list(1D, 2L, "3", 4)).append("_id", 8), new BasicDBObject("date", 2F).append("_id", 10)), objects); // When // String objects = collection.find(new BasicDBObject("date", new BasicDBObject("$type", 2))).toArray(); assertEquals(Arrays.asList( new BasicDBObject("_id", 3).append("date", "3"), new BasicDBObject("date", Util.list(1D, 2L, "3", 4)).append("_id", 8)), objects); // Integer objects = collection.find(new BasicDBObject("date", new BasicDBObject("$type", 16))).toArray(); assertEquals(Arrays.asList( new BasicDBObject("_id", 1).append("date", 1), new BasicDBObject("date", Util.list(1, 2, 3)).append("_id", 7), new BasicDBObject("date", Util.list(1D, 2L, "3", 4)).append("_id", 8)), objects); // ObjectId objects = collection.find(new BasicDBObject("_id", new BasicDBObject("$type", 7))).toArray(); assertEquals(Collections.singletonList(new BasicDBObject("_id", id).append("date", true)), objects); // Boolean objects = collection.find(new BasicDBObject("date", new BasicDBObject("$type", 8))).toArray(); assertEquals(Collections.singletonList(new BasicDBObject("_id", id).append("date", true)), objects); // Long ? objects = collection.find(new BasicDBObject("date", new BasicDBObject("$type", 18))).toArray(); assertEquals(Arrays.asList( new BasicDBObject("_id", 6).append("date", 6L), new BasicDBObject("date", Util.list(1D, 2L, "3", 4)).append("_id", 8)), objects); // Array ? objects = collection.find(new BasicDBObject("date", new BasicDBObject("$type", 4))).toArray(); assertEquals(Arrays.asList( new BasicDBObject("date", Util.list(Util.list(1D, 2L, "3", 4))).append("_id", 9)), objects); // Null ? objects = collection.find(new BasicDBObject("date", new BasicDBObject("$type", 10))).toArray(); assertEquals(Collections.singletonList(new BasicDBObject("_id", 5).append("date", null)), objects); // Object ? objects = collection.find(new BasicDBObject("date", new BasicDBObject("$type", 3))).toArray(); assertEquals(Arrays.asList( new BasicDBObject("_id", 1).append("date", 1), new BasicDBObject("_id", 2).append("date", 2D), new BasicDBObject("_id", 3).append("date", "3"), new BasicDBObject("_id", id).append("date", true), new BasicDBObject("_id", 6).append("date", 6L), new BasicDBObject("_id", 7).append("date", Util.list(1, 2, 3)), new BasicDBObject("_id", 8).append("date", Util.list(1D, 2L, "3", 4)), new BasicDBObject("_id", 9).append("date", Util.list(Util.list(1D, 2L, "3", 4))), new BasicDBObject("_id", 10).append("date", 2F), new BasicDBObject("_id", 11).append("date", new BasicDBObject("x", 1))), objects); } @Test public void testSorting() throws Exception { // Given DBCollection collection = newCollection(); Date date = new Date(); collection.insert(new BasicDBObject("_id", 1).append("x", 3)); collection.insert(new BasicDBObject("_id", 2).append("x", 2.9D)); collection.insert(new BasicDBObject("_id", 3).append("x", date)); collection.insert(new BasicDBObject("_id", 4).append("x", true)); collection.insert(new BasicDBObject("_id", 5).append("x", new MaxKey())); collection.insert(new BasicDBObject("_id", 6).append("x", new MinKey())); collection.insert(new BasicDBObject("_id", 7).append("x", false)); collection.insert(new BasicDBObject("_id", 8).append("x", 2)); collection.insert(new BasicDBObject("_id", 9).append("x", date.getTime() + 100)); collection.insert(new BasicDBObject("_id", 10)); // When List<DBObject> objects = collection.find().sort(new BasicDBObject("x", 1)).toArray(); // Then assertEquals(Arrays.asList( new BasicDBObject("_id", 6).append("x", new MinKey()), new BasicDBObject("_id", 10), new BasicDBObject("_id", 8).append("x", 2), new BasicDBObject("_id", 2).append("x", 2.9D), new BasicDBObject("_id", 1).append("x", 3), new BasicDBObject("_id", 9).append("x", date.getTime() + 100), new BasicDBObject("_id", 7).append("x", false), new BasicDBObject("_id", 4).append("x", true), new BasicDBObject("_id", 3).append("x", date), new BasicDBObject("_id", 5).append("x", new MaxKey()) ), objects); } @Test public void testSortingNull() throws Exception { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("x", new MinKey())); collection.insert(new BasicDBObject("_id", 2).append("x", new MaxKey())); collection.insert(new BasicDBObject("_id", 3).append("x", 3)); collection.insert(new BasicDBObject("_id", 4).append("x", null)); collection.insert(new BasicDBObject("_id", 5)); // When List<DBObject> objects = collection.find().sort(new BasicDBObject("x", 1)).toArray(); // Then assertEquals(Arrays.asList( new BasicDBObject("_id", 1).append("x", new MinKey()), new BasicDBObject("_id", 5), new BasicDBObject("_id", 4).append("x", null), new BasicDBObject("_id", 3).append("x", 3), new BasicDBObject("_id", 2).append("x", new MaxKey()) ), objects); } // Pattern is last. @Test public void testSortingPattern() throws Exception { // Given DBCollection collection = newCollection(); // DBCollection collection = new MongoClient().getDB("test").getCollection("sorting"); // collection.drop(); ObjectId id = ObjectId.get(); Date date = new Date(); collection.insert(new BasicDBObject("_id", 1).append("x", Pattern.compile("a*"))); collection.insert(new BasicDBObject("_id", 2).append("x", 2)); collection.insert(new BasicDBObject("_id", 3).append("x", "3")); collection.insert(new BasicDBObject("_id", 4).append("x", id)); collection.insert(new BasicDBObject("_id", 5).append("x", new BasicDBObject("a", 3))); collection.insert(new BasicDBObject("_id", 6).append("x", date)); // collection.insert(new BasicDBObject("_id", 7).append("x", "3".getBytes())); // later // When List<DBObject> objects = collection.find().sort(new BasicDBObject("x", 1)).toArray(); // Then assertEquals(Arrays.asList( new BasicDBObject("_id", 2).append("x", 2), new BasicDBObject("_id", 3).append("x", "3"), new BasicDBObject("_id", 5).append("x", new BasicDBObject("a", 3)), // new BasicDBObject("_id", 7).append("x", "3".getBytes()), // later. new BasicDBObject("_id", 4).append("x", id), new BasicDBObject("_id", 6).append("x", date), new BasicDBObject("_id", 1).append("x", Pattern.compile("a*")) ), objects); } @Test public void testSortingDBObject() throws Exception { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("x", new BasicDBObject("a", 3))); ObjectId val = ObjectId.get(); collection.insert(new BasicDBObject("_id", 2).append("x", val)); collection.insert(new BasicDBObject("_id", 3).append("x", "3")); collection.insert(new BasicDBObject("_id", 4).append("x", 3)); // When List<DBObject> objects = collection.find().sort(new BasicDBObject("x", 1)).toArray(); // Then assertEquals(Arrays.asList( new BasicDBObject("_id", 4).append("x", 3), new BasicDBObject("_id", 3).append("x", "3"), new BasicDBObject("_id", 1).append("x", new BasicDBObject("a", 3)), new BasicDBObject("_id", 2).append("x", val) ), objects); } @Test public void testSortingNullVsMinKey() throws Exception { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2).append("x", new MinKey())); // When List<DBObject> objects = collection.find().sort(new BasicDBObject("x", 1)).toArray(); // Then assertEquals(Arrays.asList( new BasicDBObject("_id", 2).append("x", new MinKey()), new BasicDBObject("_id", 1) ), objects); } // Previously on {@link ExpressionParserTest. @Test public void testStrangeSorting() throws Exception { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 2).append("b", 1)); collection.insert(new BasicDBObject("_id", 1).append("a", 3)); // When List<DBObject> objects = collection.find().sort(new BasicDBObject("a", 1)).toArray(); // Then assertEquals(Arrays.asList( new BasicDBObject("_id", 2).append("b", 1), new BasicDBObject("_id", 1).append("a", 3) ), objects); } /** * line 456 (LOG.debug("restrict with index {}, from {} to {} elements", matchingIndex.getName(), _idIndex.size(), dbObjectIterable.size());) obviously throws a null pointer if dbObjectIterable is null. This exact case is handled 4 lines below, but it does not apply to the log message. Please catch appropriately */ @Test public void testIssue1() { ch.qos.logback.classic.Logger LOG = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(FongoDBCollection.class); Level oldLevel = LOG.getLevel(); try { LOG.setLevel(Level.DEBUG); // Given DBCollection collection = newCollection(); // When collection.remove(new BasicDBObject("_id", 1)); } finally { LOG.setLevel(oldLevel); } } @Test public void testBinarySave() throws Exception { // Given DBCollection collection = newCollection(); Binary expectedId = new Binary("friend2".getBytes()); // When collection.save(BasicDBObjectBuilder.start().add("_id", expectedId).get()); collection.update(BasicDBObjectBuilder.start().add("_id", new Binary("friend2".getBytes())).get(), new BasicDBObject("date", 12)); // Then List<DBObject> result = collection.find().toArray(); assertThat(result).hasSize(1); assertThat(result.get(0).keySet()).containsExactly("_id", "date"); assertThat(result.get(0).get("_id")).isEqualTo("friend2".getBytes()); assertThat(result.get(0).get("date")).isEqualTo(12); } @Test public void testBinarySaveWithBytes() throws Exception { // Given DBCollection collection = newCollection(); Binary expectedId = new Binary("friend2".getBytes()); // When collection.save(BasicDBObjectBuilder.start().add("_id", expectedId).get()); collection.update(BasicDBObjectBuilder.start().add("_id", "friend2".getBytes()).get(), new BasicDBObject("date", 12)); // Then List<DBObject> result = collection.find().toArray(); assertThat(result).hasSize(1); assertThat(result.get(0).keySet()).containsExactly("_id", "date"); assertThat(result.get(0).get("_id")).isEqualTo("friend2".getBytes()); assertThat(result.get(0).get("date")).isEqualTo(12); } // can not change _id of a document query={ "_id" : "52986f667f6cc746624b0db5"}, document={ "name" : "Robert" , "_id" : { "$oid" : "52986f667f6cc746624b0db5"}} // See jongo SaveTest#canSaveWithObjectIdAsString @Test public void update_id_is_string_and_objectid() { // Given DBCollection collection = newCollection(); ObjectId objectId = ObjectId.get(); DBObject query = BasicDBObjectBuilder.start("_id", objectId.toString()).get(); DBObject object = BasicDBObjectBuilder.start("_id", objectId).add("name", "Robert").get(); ExpectedMongoException.expectWriteConcernException(exception, 16836); // When collection.update(query, object, true, false); } @Test public void projection_elemMatch() { // Given DBCollection collection = newCollection(); this.fongoRule.insertJSON(collection, "[{\n" + " _id: 1,\n" + " zipcode: 63109,\n" + " students: [\n" + " { name: \"john\"},\n" + " { name: \"jess\"},\n" + " { name: \"jeff\"}\n" + " ]\n" + "}\n," + "{\n" + " _id: 2,\n" + " zipcode: 63110,\n" + " students: [\n" + " { name: \"ajax\"},\n" + " { name: \"achilles\"}\n" + " ]\n" + "}\n," + "{\n" + " _id: 3,\n" + " zipcode: 63109,\n" + " students: [\n" + " { name: \"ajax\"},\n" + " { name: \"achilles\"}\n" + " ]\n" + "}\n," + "{\n" + " _id: 4,\n" + " zipcode: 63109,\n" + " students: [\n" + " { name: \"barney\"}\n" + " ]\n" + "}]\n"); // When List<DBObject> result = collection.find(fongoRule.parseDBObject("{ zipcode: 63109 },\n"), fongoRule.parseDBObject("{ students: { $elemMatch: { name: \"achilles\" } } }")).toArray(); // Then assertEquals(fongoRule.parseList("[{ \"_id\" : 1}, " + "{ \"_id\" : 3, \"students\" : [ { name: \"achilles\"} ] }, { \"_id\" : 4}]"), result); } @Test public void projection_elemMatchWithBigSubdocument() { // Given DBCollection collection = newCollection(); this.fongoRule.insertJSON(collection, "[{\n" + " _id: 1,\n" + " zipcode: 63109,\n" + " students: [\n" + " { name: \"john\", school: 102, age: 10 },\n" + " { name: \"jess\", school: 102, age: 11 },\n" + " { name: \"jeff\", school: 108, age: 15 }\n" + " ]\n" + "}\n," + "{\n" + " _id: 2,\n" + " zipcode: 63110,\n" + " students: [\n" + " { name: \"ajax\", school: 100, age: 7 },\n" + " { name: \"achilles\", school: 100, age: 8 }\n" + " ]\n" + "}\n," + "{\n" + " _id: 3,\n" + " zipcode: 63109,\n" + " students: [\n" + " { name: \"ajax\", school: 100, age: 7 },\n" + " { name: \"achilles\", school: 100, age: 8 }\n" + " ]\n" + "}\n," + "{\n" + " _id: 4,\n" + " zipcode: 63109,\n" + " students: [\n" + " { name: \"barney\", school: 102, age: 7 }\n" + " ]\n" + "}]\n"); // When List<DBObject> result = collection.find(fongoRule.parseDBObject("{ zipcode: 63109 }"), fongoRule.parseDBObject("{ students: { $elemMatch: { school: 102 } } }")).toArray(); // Then assertEquals(fongoRule.parseList("[{ \"_id\" : 1, \"students\" : [ { \"name\" : \"john\", \"school\" : 102, \"age\" : 10 } ] },\n" + "{ \"_id\" : 3 },\n" + "{ \"_id\" : 4, \"students\" : [ { \"name\" : \"barney\", \"school\" : 102, \"age\" : 7 } ] }]"), result); } @Test @Ignore public void query_elemMatch() { // Given DBCollection collection = newCollection(); this.fongoRule.insertJSON(collection, "[{\n" + " _id: 1,\n" + " zipcode: 63109,\n" + " students: [\n" + " { name: \"john\", school: 102, age: 10 },\n" + " { name: \"jess\", school: 102, age: 11 },\n" + " { name: \"jeff\", school: 108, age: 15 }\n" + " ]\n" + "}\n," + "{\n" + " _id: 2,\n" + " zipcode: 63110,\n" + " students: [\n" + " { name: \"ajax\", school: 100, age: 7 },\n" + " { name: \"achilles\", school: 100, age: 8 }\n" + " ]\n" + "}\n," + "{\n" + " _id: 3,\n" + " zipcode: 63109,\n" + " students: [\n" + " { name: \"ajax\", school: 100, age: 7 },\n" + " { name: \"achilles\", school: 100, age: 8 }\n" + " ]\n" + "}\n," + "{\n" + " _id: 4,\n" + " zipcode: 63109,\n" + " students: [\n" + " { name: \"barney\", school: 102, age: 7 }\n" + " ]\n" + "}]\n"); // When List<DBObject> result = collection.find(fongoRule.parseDBObject("{ zipcode: 63109 },\n" + "{ students: { $elemMatch: { school: 102 } } }")).toArray(); // Then assertEquals(fongoRule.parseList("[{ \"_id\" : 1, \"students\" : [ { \"name\" : \"john\", \"school\" : 102, \"age\" : 10 } ] },\n" + "{ \"_id\" : 3 },\n" + "{ \"_id\" : 4, \"students\" : [ { \"name\" : \"barney\", \"school\" : 102, \"age\" : 7 } ] }]"), result); } @Test public void find_and_modify_with_projection_old_object() { // Given DBCollection collection = newCollection(); collection.insert(fongoRule.parseDBObject("{ \"name\" : \"John\" , \"address\" : \"Jermin Street\"}")); // When DBObject result = collection.findAndModify(new BasicDBObject("name", "John"), new BasicDBObject("name", 1), null, false, new BasicDBObject("$set", new BasicDBObject("name", "Robert")), false, false); // Then assertThat(result.get("name")).isNotNull().isEqualTo("John"); assertFalse("Bad Projection", result.containsField("address")); } @Test public void find_and_modify_with_projection_new_object() { // Given DBCollection collection = newCollection(); collection.insert(fongoRule.parseDBObject("{ \"name\" : \"John\" , \"address\" : \"Jermin Street\"}")); // When DBObject result = collection.findAndModify(new BasicDBObject("name", "John"), new BasicDBObject("name", 1), null, false, new BasicDBObject("$set", new BasicDBObject("name", "Robert")), true, false); // Then assertThat(result.get("name")).isNotNull().isEqualTo("Robert"); assertFalse("Bad Projection", result.containsField("address")); } @Test public void find_and_modify_with_projection_new_object_upsert() { // Given DBCollection collection = newCollection(); // When DBObject result = collection.findAndModify(new BasicDBObject("name", "Rob"), new BasicDBObject("name", 1), null, false, new BasicDBObject("$set", new BasicDBObject("name", "Robert")), true, true); // Then assertThat(result.get("name")).isNotNull().isEqualTo("Robert"); assertFalse("Bad Projection", result.containsField("address")); } @Test public void find_with_maxScan() { // Given DBCollection collection = newCollection(); collection.insert(fongoRule.parseDBObject("{ \"name\" : \"John\" , \"address\" : \"Jermin Street\"}")); collection.insert(fongoRule.parseDBObject("{ \"name\" : \"Robert\" , \"address\" : \"Jermin Street\"}")); // When List<DBObject> objects = collection.find().addSpecial("$maxScan", 1).toArray(); // Then assertThat(objects).hasSize(1); } @Test public void mod_must_be_handled() { // Given DBCollection collection = newCollection(); collection.insert(fongoRule.parseList("[{ \"_id\" : 1, \"item\" : \"abc123\", \"qty\" : 0 },\n" + "{ \"_id\" : 2, \"item\" : \"xyz123\", \"qty\" : 5 },\n" + "{ \"_id\" : 3, \"item\" : \"ijk123\", \"qty\" : 12 }]")); // When List<DBObject> objects = collection.find(fongoRule.parseDBObject("{ qty: { $mod: [ 4, 0 ] } } ")).toArray(); // Then assertThat(objects).isEqualTo(fongoRule.parseList("[{ \"_id\" : 1, \"item\" : \"abc123\", \"qty\" : 0 },\n" + "{ \"_id\" : 3, \"item\" : \"ijk123\", \"qty\" : 12 }]")); } @Test public void mod_with_number_must_be_handled() { // Given DBCollection collection = newCollection(); collection.insert(fongoRule.parseList("[{ \"_id\" : 1, \"item\" : \"abc123\", \"qty\" : 0 },\n" + "{ \"_id\" : 2, \"item\" : \"xyz123\", \"qty\" : 5 },\n" + "{ \"_id\" : 3, \"item\" : \"ijk123\", \"qty\" : 12 }]")); // When List<DBObject> objects = collection.find(fongoRule.parseDBObject("{ qty: { $mod: [ 4., 0 ] } } ")).toArray(); // Then assertThat(objects).isEqualTo(fongoRule.parseList("[{ \"_id\" : 1, \"item\" : \"abc123\", \"qty\" : 0 },\n" + "{ \"_id\" : 3, \"item\" : \"ijk123\", \"qty\" : 12 }]")); } @Test public void should_$divide_in_group_work_well() { // Given DBCollection collection = newCollection(); collection.insert(fongoRule.parseDBObject("{_id:1, bar: 'bazz'}")); // When AggregationOutput result = collection .aggregate(fongoRule.parseList("[{ $project: { bla: {$divide: [4,2]} } }]")); // Then System.out.println(Lists.newArrayList(result.results())); // { "_id" : { "$oid" : "5368e0f3cf5a47d5a22d7b75"}} Assertions.assertThat(result.results()).isEqualTo(fongoRule.parseList("[{ \"_id\" : 1 , \"bla\" : 2.0}]")); } // @Test public void should_string_id_not_retrieve_objectId() { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject()); DBObject object = collection.findOne(); ObjectId objectId = (ObjectId) object.get("_id"); // When // Then Assertions.assertThat(collection.findOne(new BasicDBObject("_id", objectId))).isEqualTo(object); Assertions.assertThat(collection.findOne(new BasicDBObject("_id", objectId.toString()))).isNull(); } @Test public void should_$max_int_insert() { long now = new Date().getTime(); // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1) .append("a", 100) .append("b", 200) .append("x", -100.0) .append("y", 200.0) .append("later", new Date(now + 10000)) .append("before", new Date(now - 10000)) ); // When collection .update( new BasicDBObject("_id", 1), new BasicDBObject("$max", new BasicDBObject() .append("a", 101) .append("b", 102) .append("c", 103) .append("x", 1.0) .append("y", 2.0) .append("z", -1.0) .append("later", new Date(now)) .append("before", new Date(now)) .append("new", new Date(now)) ), true, true ); // Then DBObject result = collection.findOne(); Assertions.assertThat(result).isEqualTo(new BasicDBObject("_id", 1) .append("a", 101) .append("b", 200) .append("c", 103) .append("x", 1.0) .append("y", 200.0) .append("z", -1.0) .append("later", new Date(now + 10000)) .append("before", new Date(now)) .append("new", new Date(now))); } @Test public void should_$min_int_insert() { long now = new Date().getTime(); // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1) .append("a", 100) .append("b", 200) .append("x", -100.0) .append("y", 200.0) .append("later", new Date(now + 10000)) .append("before", new Date(now - 10000)) ); // When collection .update( new BasicDBObject("_id", 1), new BasicDBObject("$min", new BasicDBObject() .append("a", 99) .append("b", 202) .append("c", 103) .append("x", -101.0) .append("y", 202.0) .append("z", -1.0) .append("later", new Date(now)) .append("before", new Date(now)) .append("new", new Date(now)) ), true, true ); // Then DBObject result = collection.findOne(); Assertions.assertThat(result).isEqualTo(new BasicDBObject("_id", 1) .append("a", 99) .append("b", 200) .append("x", -101.0) .append("y", 200.0) .append("later", new Date(now)) .append("before", new Date(now - 10000)) .append("c", 103) .append("z", -1.0) .append("new", new Date(now))); } @Test public void test_bulk_update() { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 100).append("hi", 1)); // When collection.update(new BasicDBObject("fongo", "sucks"), new BasicDBObject("not", "upserted"), false, true); BulkWriteOperation bulkWriteOperation = collection.initializeOrderedBulkOperation(); bulkWriteOperation.find(new BasicDBObject("find", "me")).upsert().update(new BasicDBObject("_id", 1).append("foo", "bar").append("find", "me")); bulkWriteOperation.find(new BasicDBObject("cantFind", "me")).update(new BasicDBObject("not", "upserted")); bulkWriteOperation.find(new BasicDBObject("_id", 100)).update(new BasicDBObject("hi", 2)); BulkWriteResult bulkResult = bulkWriteOperation.execute(); // Then //assertEquals(1, bulkResult.getModifiedCount()); // 1 modified //assertEquals(1, bulkResult.getUpserts().size()); // 1 upsert assertEquals(0, bulkResult.getInsertedCount()); // 0 inserted assertEquals(0, bulkResult.getRemovedCount()); // 0 removed DBObject result; result = collection.findOne(new BasicDBObject("find", "me")); assertEquals(new BasicDBObject("_id", 1).append("find", "me").append("foo", "bar"), result); result = collection.findOne(new BasicDBObject("cantFind", "me")); assertNull(result); result = collection.findOne(new BasicDBObject("_id", 100)); assertEquals(new BasicDBObject("_id", 100).append("hi", 2), result); } @Test public void test_bulk_insert() { // Given DBCollection collection = newCollection(); // When DBObject o1 = new BasicDBObject("_id", 1).append("a", 1); DBObject o2 = new BasicDBObject("_id", 2).append("b", 2); DBObject o3 = new BasicDBObject("_id", 3).append("c", 3); BulkWriteOperation bulkWriteOperation = collection.initializeOrderedBulkOperation(); bulkWriteOperation.insert(o1); bulkWriteOperation.insert(o2); bulkWriteOperation.insert(o3); BulkWriteResult bulkResult = bulkWriteOperation.execute(); // Then assertEquals(0, bulkResult.getModifiedCount()); // 0 modified assertEquals(0, bulkResult.getUpserts().size()); // 0 upsert assertEquals(3, bulkResult.getInsertedCount()); // 0 inserted assertEquals(0, bulkResult.getRemovedCount()); // 0 removed List<DBObject> dbObjects = collection.find().toArray(); assertEquals(dbObjects.size(), 3); assertEquals(dbObjects, Lists.newArrayList(o1, o2, o3)); } @Test public void test_bulk_remove() { // Given DBCollection collection = newCollection(); DBObject o1 = new BasicDBObject("_id", 1).append("a", 1); DBObject o2 = new BasicDBObject("_id", 2).append("b", 2); DBObject o3 = new BasicDBObject("_id", 3).append("c", 3); collection.insert(o1, o2, o3); // When BulkWriteOperation bulkWriteOperation = collection.initializeOrderedBulkOperation(); bulkWriteOperation.find(o1).remove(); bulkWriteOperation.find(new BasicDBObject("x", "y")).remove(); bulkWriteOperation.find(o3).remove(); BulkWriteResult bulkResult = bulkWriteOperation.execute(); // Then assertEquals(0, bulkResult.getModifiedCount()); // 0 modified assertEquals(0, bulkResult.getUpserts().size()); // 0 upsert assertEquals(0, bulkResult.getInsertedCount()); // 0 inserted assertEquals(2, bulkResult.getRemovedCount()); // 2 removed List<DBObject> dbObjects = collection.find().toArray(); assertEquals(dbObjects.size(), 1); assertEquals(dbObjects, Lists.newArrayList(o2)); } @Test public void should_setOnInsert_insert_value() { // Given DBCollection collection = newCollection(); ObjectId objectId = ObjectId.get(); // When collection .update( new BasicDBObject(), new BasicDBObject() .append("$setOnInsert", new BasicDBObject("insertedAttr", "insertedValue")) .append("$set", new BasicDBObject("updatedAttr", "updatedValue").append("_id", objectId)), true, true ); // Then Assertions.assertThat(collection.findOne(new BasicDBObject("_id", objectId))).isEqualTo(new BasicDBObject("_id", objectId) .append("insertedAttr", "insertedValue") .append("updatedAttr", "updatedValue")); } @Test public void should_setOnInsert_insert_value_only_one() { // Given DBCollection collection = newCollection(); ObjectId objectId = ObjectId.get(); // When collection .update( new BasicDBObject(), new BasicDBObject() .append("$setOnInsert", new BasicDBObject("insertedAttr", "insertedValue")) .append("$set", new BasicDBObject("updatedAttr", "updatedValue").append("_id", objectId)), true, true ); collection .update( new BasicDBObject("_id", objectId), new BasicDBObject() .append("$setOnInsert", new BasicDBObject("insertedAttr", "insertedValue2")) .append("$set", new BasicDBObject("updatedAttr", "updatedValue2")), true, true ); // Then Assertions.assertThat(collection.findOne(new BasicDBObject("_id", objectId))).isEqualTo(new BasicDBObject("_id", objectId) .append("insertedAttr", "insertedValue") .append("updatedAttr", "updatedValue2")); } @Test public void should_setOnInsert_insert_value_on_composite_fields() { // Given DBCollection collection = newCollection(); DBObject insertedValues = new BasicDBObject("insertedAttr1", "insertedValue1").append("data.insertedAttr2", "insertedValue2"); DBObject updatedValues = new BasicDBObject("updatedAttr1", "updatedValue1").append("data.updatedAttr2", "updatedValue2"); collection.update( new BasicDBObject(), new BasicDBObject() .append("$setOnInsert", insertedValues) .append("$set", updatedValues), true, true ); DBObject obj = collection.findOne(); System.out.println(obj); // { "_id" : { "$oid" : "53bd59cd7c2e6dc6f98160e0"} , "insertedAttr1" : "insertedValue1" , "data" : { "insertedAttr2" : "insertedValue2" , "updatedAttr2" : "updatedValue2"} , "updatedAttr1" : "updatedValue1"} Assertions.assertThat(obj.get("insertedAttr1")).isEqualTo("insertedValue1"); Assertions.assertThat(obj.get("updatedAttr1")).isEqualTo("updatedValue1"); DBObject data = (DBObject) obj.get("data"); Assertions.assertThat(data.get("insertedAttr2")).isEqualTo("insertedValue2"); Assertions.assertThat(data.get("updatedAttr2")).isEqualTo("updatedValue2"); } @Test public void should_not_setOnInsert_insert_value_on_composite_fields() { // Given DBCollection collection = newCollection(); DBObject insertedValues = new BasicDBObject("insertedAttr1", "insertedValue1").append("data.insertedAttr2", "insertedValue2"); DBObject updatedValues = new BasicDBObject("updatedAttr1", "updatedValue1").append("data.updatedAttr2", "updatedValue2"); ObjectId objectId = ObjectId.get(); collection.update( new BasicDBObject("_id", objectId), new BasicDBObject() .append("$set", updatedValues), true, true ); collection.update( new BasicDBObject("_id", objectId), new BasicDBObject() .append("$setOnInsert", insertedValues) .append("$set", updatedValues), true, true ); DBObject obj = collection.findOne(); System.out.println(obj); // { "_id" : { "$oid" : "53bd59cd7c2e6dc6f98160e0"} , "insertedAttr1" : "insertedValue1" , "data" : { "insertedAttr2" : "insertedValue2" , "updatedAttr2" : "updatedValue2"} , "updatedAttr1" : "updatedValue1"} Assertions.assertThat(obj.get("insertedAttr1")).isNull(); Assertions.assertThat(obj.get("updatedAttr1")).isEqualTo("updatedValue1"); DBObject data = (DBObject) obj.get("data"); Assertions.assertThat(data).isEqualTo(new BasicDBObject("updatedAttr2", "updatedValue2")); } @Test public void should_mul_multiply_values() { // Given DBCollection collection = newCollection(); collection.insert(fongoRule.parseDBObject("{ _id: 1, item: \"ABC\", price: 10.99 }\n")); // When collection.update(new BasicDBObject("_id", 1), fongoRule.parseDBObject("{ $mul: { price: 1.25 } }")); // Then Assertions.assertThat(collection.findOne(new BasicDBObject("_id", 1))).isEqualTo(new BasicDBObject("_id", 1) .append("item", "ABC") .append("price", 13.7375D)); } @Test public void should_mul_add_field_if_not_exist() { // Given DBCollection collection = newCollection(); collection.insert(fongoRule.parseDBObject("{ _id: 2, item: \"Unknown\"}\n")); // When collection.update(new BasicDBObject("_id", 2), new BasicDBObject("$mul", new BasicDBObject("price", 100L))); // Then Assertions.assertThat(collection.findOne(new BasicDBObject("_id", 2))).isEqualTo(new BasicDBObject("_id", 2) .append("item", "Unknown") .append("price", 0L)); } @Test public void should_mul_with_mixed_types_handle_long_as_result() { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 3).append("item", "XYZ").append("price", 10L)); // When collection.update(new BasicDBObject("_id", 3), new BasicDBObject("$mul", new BasicDBObject("price", 5))); // Then Assertions.assertThat(collection.findOne(new BasicDBObject("_id", 3))).isEqualTo(new BasicDBObject("_id", 3) .append("item", "XYZ") .append("price", 50L)); } @Test public void should_be_able_to_query_array_elements() { // Given DBCollection collection = newCollection(); BasicDBList array = new BasicDBList(); array.add(0); array.add(1); collection.insert(new BasicDBObject("_id", 1).append("items", array)); // When DBObject result = collection.findOne(new BasicDBObject("items", 0)); // Then Assertions.assertThat(result).isEqualTo(new BasicDBObject("_id", 1).append("items", array)); } @Test public void should_not_$min_update_document() { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("price", 10)); // When collection.update(new BasicDBObject("_id", 1), new BasicDBObject("$min", new BasicDBObject("price", 11))); // Then DBObject result = collection.findOne(new BasicDBObject("_id", 1)); Assertions.assertThat(result).isEqualTo(new BasicDBObject("_id", 1).append("price", 10)); } @Test public void should_$min_update_document() { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("price", 10)); // When collection.update(new BasicDBObject("_id", 1), new BasicDBObject("$min", new BasicDBObject("price", 9))); // Then DBObject result = collection.findOne(new BasicDBObject("_id", 1)); Assertions.assertThat(result).isEqualTo(new BasicDBObject("_id", 1).append("price", 9)); } @Test public void should_not_$max_update_document() { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("price", 10)); // When collection.update(new BasicDBObject("_id", 1), new BasicDBObject("$max", new BasicDBObject("price", 9))); // Then DBObject result = collection.findOne(new BasicDBObject("_id", 1)); Assertions.assertThat(result).isEqualTo(new BasicDBObject("_id", 1).append("price", 10)); } @Test public void should_$max_update_document() { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("price", 10)); // When collection.update(new BasicDBObject("_id", 1), new BasicDBObject("$max", new BasicDBObject("price", 12))); // Then DBObject result = collection.findOne(new BasicDBObject("_id", 1)); Assertions.assertThat(result).isEqualTo(new BasicDBObject("_id", 1).append("price", 12)); } @Test public void should_fsync_return_value() { // Given // When final CommandResult fsync = fongoRule.getDB().getMongo().fsync(true); // Then Assertions.assertThat(fsync.get("ok")).isEqualTo(1.0); } @Test public void should_projection_$slice_return_simple_count() { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("array", Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); // When List<DBObject> dbObjects = collection.find(new BasicDBObject(), new BasicDBObject("array", new BasicDBObject("$slice", 3))).toArray(); // Then Assertions.assertThat(dbObjects).isEqualTo(Arrays.asList(new BasicDBObject("_id", 1).append("array", Arrays.asList(1, 2, 3)))); } @Test public void should_projection_$slice_return_last_elements() { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("array", Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); // When List<DBObject> dbObjects = collection.find(new BasicDBObject(), new BasicDBObject("array", new BasicDBObject("$slice", -3))).toArray(); // Then Assertions.assertThat(dbObjects).isEqualTo(Arrays.asList(new BasicDBObject("_id", 1).append("array", Arrays.asList(8, 9, 10)))); } @Test public void should_projection_$slice_return_sub() { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("array", Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); // When BasicDBList slice = new BasicDBList(); slice.add(3); slice.add(5); List<DBObject> dbObjects = collection.find(new BasicDBObject(), new BasicDBObject("array", new BasicDBObject("$slice", slice))).toArray(); // Then Assertions.assertThat(dbObjects).isEqualTo(Arrays.asList(new BasicDBObject("_id", 1).append("array", Arrays.asList(4, 5, 6, 7, 8)))); } @Test public void should_projection_$slice_return_empty_sub() { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("array", Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); // When BasicDBList slice = new BasicDBList(); slice.add(10); slice.add(5); List<DBObject> dbObjects = collection.find(new BasicDBObject(), new BasicDBObject("array", new BasicDBObject("$slice", slice))).toArray(); // Then Assertions.assertThat(dbObjects).isEqualTo(Arrays.asList(new BasicDBObject("_id", 1).append("array", Arrays.asList()))); } @Test(expected = MongoException.class) public void should_projection_$slice_return_empty_sub_if_limit_neg() { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("array", Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); // When BasicDBList slice = new BasicDBList(); slice.add(10); slice.add(-5); List<DBObject> dbObjects = collection.find(new BasicDBObject(), new BasicDBObject("array", new BasicDBObject("$slice", slice))).toArray(); // Then } @Test public void should_projection_$slice_return_last_sub() { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("array", Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); // When BasicDBList slice = new BasicDBList(); slice.add(-7); slice.add(5); List<DBObject> dbObjects = collection.find(new BasicDBObject(), new BasicDBObject("array", new BasicDBObject("$slice", slice))).toArray(); // Then Assertions.assertThat(dbObjects).isEqualTo(Arrays.asList(new BasicDBObject("_id", 1).append("array", Arrays.asList(4, 5, 6, 7, 8)))); } static class Seq { Object[] data; Seq(Object... data) { this.data = data; } } private static <T> Set<T> newHashSet(T... objects) { return new HashSet<T>(Arrays.asList(objects)); } public DBCollection newCollection() { return fongoRule.newCollection("db"); } private Fongo newFongo() { return new Fongo("FongoTest"); } }
package com.github.fakemongo; import ch.qos.logback.classic.Level; import com.github.fakemongo.impl.ExpressionParser; import com.github.fakemongo.impl.Util; import com.github.fakemongo.junit.FongoRule; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; import com.mongodb.BasicDBObjectBuilder; import com.mongodb.CommandResult; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.DBRef; import com.mongodb.FongoDBCollection; import com.mongodb.MongoException; import com.mongodb.QueryBuilder; import com.mongodb.WriteConcern; import com.mongodb.WriteResult; import com.mongodb.util.JSON; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import static org.assertj.core.api.Assertions.assertThat; import org.assertj.core.data.MapEntry; import org.bson.BSON; import org.bson.Transformer; import org.bson.types.Binary; import org.bson.types.MaxKey; import org.bson.types.MinKey; import org.bson.types.ObjectId; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.slf4j.LoggerFactory; public class FongoTest { @Rule public FongoRule fongoRule = new FongoRule(false); @Test public void testGetDb() { Fongo fongo = newFongo(); DB db = fongo.getDB("db"); assertNotNull(db); assertSame("getDB should be idempotent", db, fongo.getDB("db")); assertEquals(Arrays.asList(db), fongo.getUsedDatabases()); assertEquals(Arrays.asList("db"), fongo.getDatabaseNames()); } @Test public void testGetCollection() { Fongo fongo = newFongo(); DB db = fongo.getDB("db"); DBCollection collection = db.getCollection("coll"); assertNotNull(collection); assertSame("getCollection should be idempotent", collection, db.getCollection("coll")); assertSame("getCollection should be idempotent", collection, db.getCollectionFromString("coll")); assertEquals(newHashSet("coll", "system.indexes", "system.users"), db.getCollectionNames()); } @Test public void testCreateCollection() { Fongo fongo = newFongo(); DB db = fongo.getDB("db"); db.createCollection("coll", null); assertEquals(new HashSet<String>(Arrays.asList("coll", "system.indexes", "system.users")), db.getCollectionNames()); } @Test public void testCountMethod() { DBCollection collection = newCollection(); assertEquals(0, collection.count()); } @Test public void testCountWithQueryCommand() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("n", 1)); collection.insert(new BasicDBObject("n", 2)); collection.insert(new BasicDBObject("n", 2)); assertEquals(2, collection.count(new BasicDBObject("n", 2))); } @Test public void testCountOnCursor() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("n", 1)); collection.insert(new BasicDBObject("n", 2)); collection.insert(new BasicDBObject("n", 2)); assertEquals(3, collection.find(QueryBuilder.start("n").exists(true).get()).count()); } @Test public void testInsertIncrementsCount() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("name", "jon")); assertEquals(1, collection.count()); } @Test public void testFindOne() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("name", "jon")); DBObject result = collection.findOne(); assertNotNull(result); assertNotNull("should have an _id", result.get("_id")); } @Test public void testFindOneNoData() { DBCollection collection = newCollection(); DBObject result = collection.findOne(); assertNull(result); } @Test public void testFindOneInId() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); DBObject result = collection.findOne(new BasicDBObject("_id", new BasicDBObject("$in", Arrays.asList(1, 2)))); assertEquals(new BasicDBObject("_id", 1), result); } @Test public void testFindOneInSetOfId() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); DBObject result = collection.findOne(new BasicDBObject("_id", new BasicDBObject("$in", newHashSet(1, 2)))); assertEquals(new BasicDBObject("_id", 1), result); } @Test public void testFindOneInSetOfData() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("data", 1)); DBObject result = collection.findOne(new BasicDBObject("data", new BasicDBObject("$in", newHashSet(1, 2)))); assertEquals(new BasicDBObject("_id", 1).append("data", 1), result); } @Test public void testFindOneIn() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("date", 1)); DBObject result = collection.findOne(new BasicDBObject("date", new BasicDBObject("$in", Arrays.asList(1, 2))), new BasicDBObject("date", 1).append("_id", 0)); assertEquals(new BasicDBObject("date", 1), result); } @Test public void testFindOneInWithArray() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); DBObject result = collection.findOne(new BasicDBObject("_id", new BasicDBObject("$in", new Integer[]{1, 3}))); assertEquals(new BasicDBObject("_id", 1), result); } @Test public void testFindOneOrId() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); DBObject result = collection.findOne(new BasicDBObject("$or", Util.list(new BasicDBObject("_id", 1), new BasicDBObject("_id", 2)))); assertEquals(new BasicDBObject("_id", 1), result); } @Test public void testFindOneOrIdCollection() throws Exception { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); DBObject result = collection.findOne(new BasicDBObject("$or", newHashSet(new BasicDBObject("_id", 1), new BasicDBObject("_id", 2)))); assertEquals(new BasicDBObject("_id", 1), result); } @Test public void testFindOneOrData() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("date", 1)); DBObject result = collection.findOne(new BasicDBObject("$or", Util.list(new BasicDBObject("date", 1), new BasicDBObject("date", 2)))); assertEquals(1, result.get("date")); } @Test public void testFindOneNinWithArray() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); DBObject result = collection.findOne(new BasicDBObject("_id", new BasicDBObject("$nin", new Integer[]{1, 3}))); assertEquals(new BasicDBObject("_id", 2), result); } @Test public void testFindOneAndIdCollection() throws Exception { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("data", 2)); DBObject result = collection.findOne(new BasicDBObject("$and", newHashSet(new BasicDBObject("_id", 1), new BasicDBObject("data", 2)))); assertEquals(new BasicDBObject("_id", 1).append("data", 2), result); } @Test public void testFindOneById() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); DBObject result = collection.findOne(new BasicDBObject("_id", 1)); assertEquals(new BasicDBObject("_id", 1), result); assertEquals(null, collection.findOne(new BasicDBObject("_id", 2))); } @Test public void testFindOneWithFields() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject().append("name", "jon").append("foo", "bar")); DBObject result = collection.findOne(new BasicDBObject(), new BasicDBObject("foo", 1)); assertNotNull(result); assertNotNull("should have an _id", result.get("_id")); assertEquals("property 'foo'", "bar", result.get("foo")); assertNull("should not have the property 'name'", result.get("name")); } @Test public void testFindWithQuery() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("name", "jon")); collection.insert(new BasicDBObject("name", "leo")); collection.insert(new BasicDBObject("name", "neil")); collection.insert(new BasicDBObject("name", "neil")); DBCursor cursor = collection.find(new BasicDBObject("name", "neil")); assertEquals("should have two neils", 2, cursor.toArray().size()); } @Test public void testFindWithNullOrNoFieldFilter() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("name", "jon").append("group", "group1")); collection.insert(new BasicDBObject("name", "leo").append("group", "group1")); collection.insert(new BasicDBObject("name", "neil1").append("group", "group2")); collection.insert(new BasicDBObject("name", "neil2").append("group", null)); collection.insert(new BasicDBObject("name", "neil3")); // check {group: null} vs {group: {$exists: false}} filter DBCursor cursor1 = collection.find(new BasicDBObject("group", null)); assertEquals("should have two neils (neil2, neil3)", 2, cursor1.toArray().size()); DBCursor cursor2 = collection.find(new BasicDBObject("group", new BasicDBObject("$exists", false))); assertEquals("should have one neil (neil3)", 1, cursor2.toArray().size()); // same check but for fields which don't exist in DB DBCursor cursor3 = collection.find(new BasicDBObject("other", null)); assertEquals("should return all documents", 5, cursor3.toArray().size()); DBCursor cursor4 = collection.find(new BasicDBObject("other", new BasicDBObject("$exists", false))); assertEquals("should return all documents", 5, cursor4.toArray().size()); } @Test public void testFindExcludingOnlyId() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", "1").append("a", 1)); collection.insert(new BasicDBObject("_id", "2").append("a", 2)); DBCursor cursor = collection.find(new BasicDBObject(), new BasicDBObject("_id", 0)); assertEquals("should have 2 documents", 2, cursor.toArray().size()); assertEquals(Arrays.asList(new BasicDBObject("a", 1), new BasicDBObject("a", 2)), cursor.toArray()); } @Test public void testFindElemMatch() { DBCollection collection = newCollection(); collection.insert((DBObject) JSON.parse("{ _id:1, array: [ { value1:1, value2:0 }, { value1:2, value2:2 } ] }")); collection.insert((DBObject) JSON.parse("{ _id:2, array: [ { value1:1, value2:0 }, { value1:1, value2:2 } ] }")); DBCursor cursor = collection.find((DBObject) JSON.parse("{ array: { $elemMatch: { value1: 1, value2: { $gt: 1 } } } }")); assertEquals(Arrays.asList((DBObject) JSON.parse("{ _id:2, array: [ { value1:1, value2:0 }, { value1:1, value2:2 } ] }") ), cursor.toArray()); } @Test public void testFindWithLimit() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); collection.insert(new BasicDBObject("_id", 3)); collection.insert(new BasicDBObject("_id", 4)); DBCursor cursor = collection.find().limit(2); assertEquals(Arrays.asList( new BasicDBObject("_id", 1), new BasicDBObject("_id", 2) ), cursor.toArray()); } @Test public void testFindWithSkipLimit() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); collection.insert(new BasicDBObject("_id", 3)); collection.insert(new BasicDBObject("_id", 4)); DBCursor cursor = collection.find().limit(2).skip(2); assertEquals(Arrays.asList( new BasicDBObject("_id", 3), new BasicDBObject("_id", 4) ), cursor.toArray()); } @Test public void testFindWithSkipLimitNoResult() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); collection.insert(new BasicDBObject("_id", 3)); collection.insert(new BasicDBObject("_id", 4)); collection.insert(new BasicDBObject("_id", 5)); QueryBuilder builder = new QueryBuilder().start("_id").greaterThanEquals(1).lessThanEquals(4); DBCursor cursor = collection.find(builder.get()).limit(2).skip(4); assertEquals(Arrays.asList(), cursor.toArray()); } @Test public void testFindWithSkipLimitWithSort() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("date", 5L).append("str", "1")); collection.insert(new BasicDBObject("_id", 2).append("date", 6L).append("str", "2")); collection.insert(new BasicDBObject("_id", 3).append("date", 7L).append("str", "3")); collection.insert(new BasicDBObject("_id", 4).append("date", 8L).append("str", "4")); collection.insert(new BasicDBObject("_id", 5).append("date", 5L)); QueryBuilder builder = new QueryBuilder().start("_id").greaterThanEquals(1).lessThanEquals(5).and("str").in(Arrays.asList("1", "2", "3", "4")); // Without sort. DBCursor cursor = collection.find(builder.get()).limit(2).skip(4); assertEquals(Arrays.asList(), cursor.toArray()); // With sort. cursor = collection.find(builder.get()).sort(new BasicDBObject("date", 1)).limit(2).skip(4); assertEquals(Arrays.asList(), cursor.toArray()); } @Test public void testFindWithWhere() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("say", "hi").append("n", 3), new BasicDBObject("_id", 2).append("say", "hello").append("n", 5)); DBCursor cursor = collection.find(new BasicDBObject("$where", "this.say == 'hello'")); assertEquals(Arrays.asList( new BasicDBObject("_id", 2).append("say", "hello").append("n", 5) ), cursor.toArray()); cursor = collection.find(new BasicDBObject("$where", "this.n < 4")); assertEquals(Arrays.asList( new BasicDBObject("_id", 1).append("say", "hi").append("n", 3) ), cursor.toArray()); } @Test public void findWithEmptyQueryFieldValue() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", 2)); collection.insert(new BasicDBObject("_id", 2).append("a", new BasicDBObject())); DBCursor cursor = collection.find(new BasicDBObject("a", new BasicDBObject())); assertEquals(Arrays.asList( new BasicDBObject("_id", 2).append("a", new BasicDBObject()) ), cursor.toArray()); } @Test public void testIdInQueryResultsInIndexOrder() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 4)); collection.insert(new BasicDBObject("_id", 3)); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); DBCursor cursor = collection.find(new BasicDBObject("_id", new BasicDBObject("$in", Arrays.asList(3, 2, 1)))); assertEquals(Arrays.asList( new BasicDBObject("_id", 1), new BasicDBObject("_id", 2), new BasicDBObject("_id", 3) ), cursor.toArray()); } @Test public void testIdInQueryResultsInIndexOrderEvenIfOrderByExistAndIsWrong() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 4)); collection.insert(new BasicDBObject("_id", 3)); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); DBCursor cursor = collection.find(new BasicDBObject("_id", new BasicDBObject("$in", Arrays.asList(3, 2, 1)))).sort(new BasicDBObject("wrongField", 1)); assertEquals(Arrays.asList( new BasicDBObject("_id", 1), new BasicDBObject("_id", 2), new BasicDBObject("_id", 3) ), cursor.toArray()); } /** * Must return in inserted order. */ @Test public void testIdInsertedOrder() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 4)); collection.insert(new BasicDBObject("_id", 3)); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); DBCursor cursor = collection.find(); assertEquals(Arrays.asList( new BasicDBObject("_id", 4), new BasicDBObject("_id", 3), new BasicDBObject("_id", 1), new BasicDBObject("_id", 2) ), cursor.toArray()); } @Test public void testSort() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("a", 1).append("_id", 1)); collection.insert(new BasicDBObject("a", 2).append("_id", 2)); collection.insert(new BasicDBObject("_id", 5)); collection.insert(new BasicDBObject("a", 3).append("_id", 3)); collection.insert(new BasicDBObject("a", 4).append("_id", 4)); DBCursor cursor = collection.find().sort(new BasicDBObject("a", -1)); assertEquals(Arrays.asList( new BasicDBObject("a", 4).append("_id", 4), new BasicDBObject("a", 3).append("_id", 3), new BasicDBObject("a", 2).append("_id", 2), new BasicDBObject("a", 1).append("_id", 1), new BasicDBObject("_id", 5) ), cursor.toArray()); } @Test public void testCompoundSort() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("a", 1).append("_id", 1)); collection.insert(new BasicDBObject("a", 2).append("_id", 5)); collection.insert(new BasicDBObject("a", 1).append("_id", 2)); collection.insert(new BasicDBObject("a", 2).append("_id", 4)); collection.insert(new BasicDBObject("a", 1).append("_id", 3)); DBCursor cursor = collection.find().sort(new BasicDBObject("a", 1).append("_id", -1)); assertEquals(Arrays.asList( new BasicDBObject("a", 1).append("_id", 3), new BasicDBObject("a", 1).append("_id", 2), new BasicDBObject("a", 1).append("_id", 1), new BasicDBObject("a", 2).append("_id", 5), new BasicDBObject("a", 2).append("_id", 4) ), cursor.toArray()); } @Test public void testCompoundSortFindAndModify() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("a", 1).append("_id", 1)); collection.insert(new BasicDBObject("a", 2).append("_id", 5)); collection.insert(new BasicDBObject("a", 1).append("_id", 2)); collection.insert(new BasicDBObject("a", 2).append("_id", 4)); collection.insert(new BasicDBObject("a", 1).append("_id", 3)); DBObject object = collection.findAndModify(null, new BasicDBObject("a", 1).append("_id", -1), new BasicDBObject("date", 1)); assertEquals( new BasicDBObject("_id", 3).append("a", 1), object); } @Test public void testCommandFindAndModify() { // Given DBCollection collection = newCollection(); DB db = collection.getDB(); collection.insert(new BasicDBObject("a", 1).append("_id", 1)); collection.insert(new BasicDBObject("a", 2).append("_id", 5)); collection.insert(new BasicDBObject("a", 1).append("_id", 2)); collection.insert(new BasicDBObject("a", 2).append("_id", 4)); collection.insert(new BasicDBObject("a", 1).append("_id", 3)); // When CommandResult result = db.command(new BasicDBObject("findAndModify", collection.getName()).append("sort", new BasicDBObject("a", 1).append("_id", -1)).append("update", new BasicDBObject("date", 1))); // Then assertTrue(result.ok()); assertEquals( new BasicDBObject("_id", 3).append("a", 1), result.get("value")); } @Test public void testEmbeddedSort() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); collection.insert(new BasicDBObject("_id", 3)); collection.insert(new BasicDBObject("_id", 4).append("counts", new BasicDBObject("done", 1))); collection.insert(new BasicDBObject("_id", 5).append("counts", new BasicDBObject("done", 2))); DBCursor cursor = collection.find(new BasicDBObject("c", new BasicDBObject("$ne", true))).sort(new BasicDBObject("counts.done", -1)); assertEquals(Arrays.asList( new BasicDBObject("_id", 5).append("counts", new BasicDBObject("done", 2)), new BasicDBObject("_id", 4).append("counts", new BasicDBObject("done", 1)), new BasicDBObject("_id", 1), new BasicDBObject("_id", 2), new BasicDBObject("_id", 3) ), cursor.toArray()); } @Test public void testBasicUpdate() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2).append("b", 5)); collection.insert(new BasicDBObject("_id", 3)); collection.insert(new BasicDBObject("_id", 4)); collection.update(new BasicDBObject("_id", 2), new BasicDBObject("a", 5)); assertEquals(new BasicDBObject("_id", 2).append("a", 5), collection.findOne(new BasicDBObject("_id", 2))); } @Test public void testFullUpdateWithSameId() throws Exception { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2).append("b", 5)); collection.insert(new BasicDBObject("_id", 3)); collection.insert(new BasicDBObject("_id", 4)); collection.update( new BasicDBObject("_id", 2).append("b", 5), new BasicDBObject("_id", 2).append("a", 5)); assertEquals(new BasicDBObject("_id", 2).append("a", 5), collection.findOne(new BasicDBObject("_id", 2))); } @Test public void testIdNotAllowedToBeUpdated() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); try { collection.update(new BasicDBObject("_id", 1), new BasicDBObject("_id", 2).append("a", 5)); fail("should throw exception"); } catch (MongoException e) { } } @Test public void testUpsert() { DBCollection collection = newCollection(); WriteResult result = collection.update(new BasicDBObject("_id", 1).append("n", "jon"), new BasicDBObject("$inc", new BasicDBObject("a", 1)), true, false); assertEquals(new BasicDBObject("_id", 1).append("n", "jon").append("a", 1), collection.findOne()); assertFalse(result.getLastError().getBoolean("updatedExisting")); } @Test public void testUpsertExisting() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); WriteResult result = collection.update(new BasicDBObject("_id", 1), new BasicDBObject("$inc", new BasicDBObject("a", 1)), true, false); assertEquals(new BasicDBObject("_id", 1).append("a", 1), collection.findOne()); assertTrue(result.getLastError().getBoolean("updatedExisting")); } @Test public void testUpsertWithConditional() { DBCollection collection = newCollection(); collection.update(new BasicDBObject("_id", 1).append("b", new BasicDBObject("$gt", 5)), new BasicDBObject("$inc", new BasicDBObject("a", 1)), true, false); assertEquals(new BasicDBObject("_id", 1).append("a", 1), collection.findOne()); } @Test public void testUpsertWithIdIn() { DBCollection collection = newCollection(); DBObject query = new BasicDBObjectBuilder().push("_id").append("$in", Arrays.asList(1)).pop().get(); DBObject update = new BasicDBObjectBuilder() .push("$push").push("n").append("_id", 2).append("u", 3).pop().pop() .push("$inc").append("c", 4).pop().get(); DBObject expected = new BasicDBObjectBuilder().append("_id", 1).append("n", Arrays.asList(new BasicDBObject("_id", 2).append("u", 3))).append("c", 4).get(); collection.update(query, update, true, false); assertEquals(expected, collection.findOne()); } @Test public void testUpdateWithIdIn() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); DBObject query = new BasicDBObjectBuilder().push("_id").append("$in", Arrays.asList(1)).pop().get(); DBObject update = new BasicDBObjectBuilder() .push("$push").push("n").append("_id", 2).append("u", 3).pop().pop() .push("$inc").append("c", 4).pop().get(); DBObject expected = new BasicDBObjectBuilder().append("_id", 1).append("n", Arrays.asList(new BasicDBObject("_id", 2).append("u", 3))).append("c", 4).get(); collection.update(query, update, false, true); assertEquals(expected, collection.findOne()); } @Test public void testUpdateWithObjectId() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", new BasicDBObject("n", 1))); DBObject query = new BasicDBObject("_id", new BasicDBObject("n", 1)); DBObject update = new BasicDBObject("$set", new BasicDBObject("a", 1)); collection.update(query, update, false, false); assertEquals(new BasicDBObject("_id", new BasicDBObject("n", 1)).append("a", 1), collection.findOne()); } @Test public void testUpdateWithIdInMulti() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1), new BasicDBObject("_id", 2)); collection.update(new BasicDBObject("_id", new BasicDBObject("$in", Arrays.asList(1, 2))), new BasicDBObject("$set", new BasicDBObject("n", 1)), false, true); List<DBObject> results = collection.find().toArray(); assertEquals(Arrays.asList( new BasicDBObject("_id", 1).append("n", 1), new BasicDBObject("_id", 2).append("n", 1) ), results); } @Test public void testUpdateWithIdQuery() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1), new BasicDBObject("_id", 2)); collection.update(new BasicDBObject("_id", new BasicDBObject("$gt", 1)), new BasicDBObject("$set", new BasicDBObject("n", 1)), false, true); List<DBObject> results = collection.find().toArray(); assertEquals(Arrays.asList( new BasicDBObject("_id", 1), new BasicDBObject("_id", 2).append("n", 1) ), results); } @Test public void testUpdateWithOneRename() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", new BasicDBObject("b", 1))); collection.update(new BasicDBObject("_id", 1), new BasicDBObject("$rename", new BasicDBObject("a.b", "a.c"))); List<DBObject> results = collection.find().toArray(); assertEquals(Arrays.asList( new BasicDBObject("_id", 1).append("a", new BasicDBObject("c", 1)) ), results); } @Test public void testUpdateWithMultipleRenames() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", new BasicDBObject("b", 1)) .append("x", 3) .append("h", new BasicDBObject("i", 8))); collection.update(new BasicDBObject("_id", 1), new BasicDBObject("$rename", new BasicDBObject("a.b", "a.c") .append("x", "y") .append("h.i", "u.r"))); List<DBObject> results = collection.find().toArray(); assertEquals(Arrays.asList( new BasicDBObject("_id", 1).append("a", new BasicDBObject("c", 1)) .append("y", 3) .append("u", new BasicDBObject("r", 8)) .append("h", new BasicDBObject()) ), results); } @Test public void testCompoundDateIdUpserts() { DBCollection collection = newCollection(); DBObject query = new BasicDBObjectBuilder().push("_id") .push("$lt").add("n", "a").add("t", 10).pop() .push("$gte").add("n", "a").add("t", 1).pop() .pop().get(); List<BasicDBObject> toUpsert = Arrays.asList( new BasicDBObject("_id", new BasicDBObject("n", "a").append("t", 1)), new BasicDBObject("_id", new BasicDBObject("n", "a").append("t", 2)), new BasicDBObject("_id", new BasicDBObject("n", "a").append("t", 3)), new BasicDBObject("_id", new BasicDBObject("n", "a").append("t", 11)) ); for (BasicDBObject dbo : toUpsert) { collection.update(dbo, ((BasicDBObject) dbo.copy()).append("foo", "bar"), true, false); } List<DBObject> results = collection.find(query).toArray(); assertEquals(Arrays.<DBObject>asList( new BasicDBObject("_id", new BasicDBObject("n", "a").append("t", 1)).append("foo", "bar"), new BasicDBObject("_id", new BasicDBObject("n", "a").append("t", 2)).append("foo", "bar"), new BasicDBObject("_id", new BasicDBObject("n", "a").append("t", 3)).append("foo", "bar") ), results); } @Test public void testAnotherUpsert() { DBCollection collection = newCollection(); BasicDBObjectBuilder queryBuilder = BasicDBObjectBuilder.start().push("_id"). append("f", "ca").push("1").append("l", 2).pop().push("t").append("t", 11).pop().pop(); DBObject query = queryBuilder.get(); DBObject update = BasicDBObjectBuilder.start().push("$inc").append("n.!", 1).append("n.a.b:false", 1).pop().get(); collection.update(query, update, true, false); DBObject expected = queryBuilder.push("n").append("!", 1).push("a").append("b:false", 1).pop().pop().get(); assertEquals(expected, collection.findOne()); } @Test public void testUpsertOnIdWithPush() { DBCollection collection = newCollection(); DBObject update1 = BasicDBObjectBuilder.start().push("$push") .push("c").append("a", 1).append("b", 2).pop().pop().get(); DBObject update2 = BasicDBObjectBuilder.start().push("$push") .push("c").append("a", 3).append("b", 4).pop().pop().get(); collection.update(new BasicDBObject("_id", 1), update1, true, false); collection.update(new BasicDBObject("_id", 1), update2, true, false); DBObject expected = new BasicDBObject("_id", 1).append("c", Util.list( new BasicDBObject("a", 1).append("b", 2), new BasicDBObject("a", 3).append("b", 4))); assertEquals(expected, collection.findOne(new BasicDBObject("c.a", 3).append("c.b", 4))); } @Test public void testUpsertWithEmbeddedQuery() { DBCollection collection = newCollection(); DBObject update = BasicDBObjectBuilder.start().push("$set").append("a", 1).pop().get(); collection.update(new BasicDBObject("_id", 1).append("e.i", 1), update, true, false); DBObject expected = BasicDBObjectBuilder.start().append("_id", 1).push("e").append("i", 1).pop().append("a", 1).get(); assertEquals(expected, collection.findOne(new BasicDBObject("_id", 1))); } @Test public void testFindAndModifyReturnOld() { final DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", 1).append("b", new BasicDBObject("c", 1))); final BasicDBObject query = new BasicDBObject("_id", 1); final BasicDBObject update = new BasicDBObject("$inc", new BasicDBObject("a", 1).append("b.c", 1)); System.out.println("update: " + update); final DBObject result = collection.findAndModify(query, null, null, false, update, false, false); assertEquals(new BasicDBObject("_id", 1).append("a", 1).append("b", new BasicDBObject("c", 1)), result); assertEquals(new BasicDBObject("_id", 1).append("a", 2).append("b", new BasicDBObject("c", 2)), collection.findOne()); } @Test public void testFindAndModifyWithInReturnOld() { final DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", 1).append("b", new BasicDBObject("c", 1))); final BasicDBObject query = new BasicDBObject("_id", new BasicDBObject("$in", Util.list(1, 2, 3))); final BasicDBObject update = new BasicDBObject("$inc", new BasicDBObject("a", 1).append("b.c", 1)); System.out.println("update: " + update); final DBObject result = collection.findAndModify(query, null, null, false, update, false, false); assertEquals(new BasicDBObject("_id", 1).append("a", 1).append("b", new BasicDBObject("c", 1)), result); assertEquals(new BasicDBObject("_id", 1).append("a", 2).append("b", new BasicDBObject("c", 2)), collection.findOne()); } @Test public void testFindAndModifyReturnNew() { final DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", 1).append("b", new BasicDBObject("c", 1))); final BasicDBObject query = new BasicDBObject("_id", 1); final BasicDBObject update = new BasicDBObject("$inc", new BasicDBObject("a", 1).append("b.c", 1)); System.out.println("update: " + update); final DBObject result = collection.findAndModify(query, null, null, false, update, true, false); assertEquals(new BasicDBObject("_id", 1).append("a", 2).append("b", new BasicDBObject("c", 2)), result); } @Test public void testFindAndModifyUpsert() { DBCollection collection = newCollection(); DBObject result = collection.findAndModify(new BasicDBObject("_id", 1), null, null, false, new BasicDBObject("$inc", new BasicDBObject("a", 1)), true, true); assertEquals(new BasicDBObject("_id", 1).append("a", 1), result); assertEquals(new BasicDBObject("_id", 1).append("a", 1), collection.findOne()); } @Test public void testFindAndModifyUpsertReturnNewFalse() { DBCollection collection = newCollection(); DBObject result = collection.findAndModify(new BasicDBObject("_id", 1), null, null, false, new BasicDBObject("$inc", new BasicDBObject("a", 1)), false, true); assertEquals(new BasicDBObject(), result); assertEquals(new BasicDBObject("_id", 1).append("a", 1), collection.findOne()); } @Test public void testFindAndRemoveFromEmbeddedList() { DBCollection collection = newCollection(); BasicDBObject obj = new BasicDBObject("_id", 1).append("a", Arrays.asList(1)); collection.insert(obj); DBObject result = collection.findAndRemove(new BasicDBObject("_id", 1)); assertEquals(obj, result); } @Test public void testFindAndRemoveNothingFound() { DBCollection coll = newCollection(); assertNull("should return null if nothing was found", coll.findAndRemove(new BasicDBObject())); } @Test public void testFindAndModifyRemove() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", 1)); DBObject result = collection.findAndModify(new BasicDBObject("_id", 1), null, null, true, null, false, false); assertEquals(new BasicDBObject("_id", 1).append("a", 1), result); assertEquals(null, collection.findOne()); } @Test public void testRemove() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); collection.insert(new BasicDBObject("_id", 3)); collection.insert(new BasicDBObject("_id", 4)); collection.remove(new BasicDBObject("_id", 2)); assertEquals(null, collection.findOne(new BasicDBObject("_id", 2))); } @Test public void testConvertJavaListToDbList() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("n", Arrays.asList(1, 2))); DBObject result = collection.findOne(); assertTrue("not a DBList", result.get("n") instanceof BasicDBList); } @Test public void testConvertJavaMapToDBObject() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("n", Collections.singletonMap("a", 1))); DBObject result = collection.findOne(); assertTrue("not a DBObject", result.get("n") instanceof BasicDBObject); } @Test public void testDistinctQuery() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("n", 1).append("_id", 1)); collection.insert(new BasicDBObject("n", 2).append("_id", 2)); collection.insert(new BasicDBObject("n", 3).append("_id", 3)); collection.insert(new BasicDBObject("n", 1).append("_id", 4)); collection.insert(new BasicDBObject("n", 1).append("_id", 5)); assertEquals(Arrays.asList(1, 2, 3), collection.distinct("n")); } @Test public void testDistinctHierarchicalQuery() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("n", new BasicDBObject("i", 1)).append("_id", 1)); collection.insert(new BasicDBObject("n", new BasicDBObject("i", 2)).append("_id", 2)); collection.insert(new BasicDBObject("n", new BasicDBObject("i", 3)).append("_id", 3)); collection.insert(new BasicDBObject("n", new BasicDBObject("i", 1)).append("_id", 4)); collection.insert(new BasicDBObject("n", new BasicDBObject("i", 1)).append("_id", 5)); assertEquals(Arrays.asList(1, 2, 3), collection.distinct("n.i")); } @Test public void testDistinctHierarchicalQueryWithArray() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("n", new BasicDBObject("i", Util.list(1, 2, 3))).append("_id", 1)); collection.insert(new BasicDBObject("n", new BasicDBObject("i", Util.list(3, 4))).append("_id", 2)); collection.insert(new BasicDBObject("n", new BasicDBObject("i", Util.list(1, 5))).append("_id", 3)); assertEquals(Arrays.asList(1, 2, 3, 4, 5), collection.distinct("n.i")); } @Test public void testGetLastError() { Fongo fongo = newFongo(); DB db = fongo.getDB("db"); DBCollection collection = db.getCollection("coll"); collection.insert(new BasicDBObject("_id", 1)); CommandResult error = db.getLastError(); assertTrue(error.ok()); } @Test public void testSave() { DBCollection collection = newCollection(); BasicDBObject inserted = new BasicDBObject("_id", 1); collection.insert(inserted); collection.save(inserted); } @Test(expected = MongoException.DuplicateKey.class) public void testInsertDuplicateWithConcernThrows() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 1), WriteConcern.SAFE); } @Test(expected = MongoException.DuplicateKey.class) public void testInsertDuplicateWithDefaultConcernOnMongo() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 1)); } @Test public void testInsertDuplicateIgnored() { DBCollection collection = newCollection(); collection.getDB().getMongo().setWriteConcern(WriteConcern.UNACKNOWLEDGED); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 1)); assertEquals(1, collection.count()); } @Test public void testSortByEmbeddedKey() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", new BasicDBObject("b", 1))); collection.insert(new BasicDBObject("_id", 2).append("a", new BasicDBObject("b", 2))); collection.insert(new BasicDBObject("_id", 3).append("a", new BasicDBObject("b", 3))); List<DBObject> results = collection.find().sort(new BasicDBObject("a.b", -1)).toArray(); assertEquals( Arrays.asList( new BasicDBObject("_id", 3).append("a", new BasicDBObject("b", 3)), new BasicDBObject("_id", 2).append("a", new BasicDBObject("b", 2)), new BasicDBObject("_id", 1).append("a", new BasicDBObject("b", 1)) ), results); } @Test public void testCommandQuery() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", 3)); collection.insert(new BasicDBObject("_id", 2).append("a", 2)); collection.insert(new BasicDBObject("_id", 3).append("a", 1)); assertEquals( new BasicDBObject("_id", 3).append("a", 1), collection.findOne(new BasicDBObject(), null, new BasicDBObject("a", 1)) ); } @Test public void testInsertReturnModifiedDocumentCount() { DBCollection collection = newCollection(); WriteResult result = collection.insert(new BasicDBObject("_id", new BasicDBObject("n", 1))); assertEquals(1, result.getN()); } @Test public void testUpdateWithIdInMultiReturnModifiedDocumentCount() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1), new BasicDBObject("_id", 2)); WriteResult result = collection.update(new BasicDBObject("_id", new BasicDBObject("$in", Arrays.asList(1, 2))), new BasicDBObject("$set", new BasicDBObject("n", 1)), false, true); assertEquals(2, result.getN()); } @Test public void testUpdateWithObjectIdReturnModifiedDocumentCount() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", new BasicDBObject("n", 1))); DBObject query = new BasicDBObject("_id", new BasicDBObject("n", 1)); DBObject update = new BasicDBObject("$set", new BasicDBObject("a", 1)); WriteResult result = collection.update(query, update, false, false); assertEquals(1, result.getN()); } /** * Test that ObjectId is getting generated even if _id is present in * DBObject but it's value is null * * @throws Exception */ @Test public void testIdGenerated() throws Exception { DBObject toSave = new BasicDBObject(); toSave.put("_id", null); toSave.put("name", "test"); Fongo fongo = newFongo(); DB fongoDB = fongo.getDB("testDB"); DBCollection collection = fongoDB.getCollection("testCollection"); collection.save(toSave); DBObject result = collection.findOne(new BasicDBObject("name", "test")); //default index in mongoDB final String ID_KEY = "_id"; assertNotNull("Expected _id to be generated" + result.get(ID_KEY)); } @Test public void testDropDatabaseAlsoDropsCollectionData() throws Exception { DBCollection collection = newCollection(); collection.insert(new BasicDBObject()); collection.getDB().dropDatabase(); assertEquals("Collection should have no data", 0, collection.count()); } @Test public void testDropCollectionAlsoDropsFromDB() throws Exception { DBCollection collection = newCollection(); collection.insert(new BasicDBObject()); collection.drop(); assertEquals("Collection should have no data", 0.D, collection.count(), 0.D); assertFalse("Collection shouldn't exist in DB", collection.getDB().getCollectionNames().contains(collection.getName())); } @Test public void testDropDatabaseFromFongoDropsAllData() throws Exception { Fongo fongo = newFongo(); DBCollection collection = fongo.getDB("db").getCollection("coll"); collection.insert(new BasicDBObject()); fongo.dropDatabase("db"); assertEquals("Collection should have no data", 0.D, collection.count(), 0.D); assertFalse("Collection shouldn't exist in DB", collection.getDB().getCollectionNames().contains(collection.getName())); assertFalse("DB shouldn't exist in fongo", fongo.getDatabaseNames().contains("db")); } @Test public void testDropDatabaseFromFongoWithMultipleCollectionsDropsBothCollections() throws Exception { Fongo fongo = newFongo(); DB db = fongo.getDB("db"); DBCollection collection1 = db.getCollection("coll1"); DBCollection collection2 = db.getCollection("coll2"); db.dropDatabase(); assertFalse("Collection 1 shouldn't exist in DB", db.collectionExists(collection1.getName())); assertFalse("Collection 2 shouldn't exist in DB", db.collectionExists(collection2.getName())); assertFalse("DB shouldn't exist in fongo", fongo.getDatabaseNames().contains("db")); } @Test public void testDropCollectionsFromGetCollectionNames() { Fongo fongo = newFongo(); DB db = fongo.getDB("db"); db.getCollection("coll1"); db.getCollection("coll2"); int dropCount = 0; for (String name : db.getCollectionNames()) { if (!name.startsWith("system.")) { db.getCollection(name).drop(); dropCount++; } } assertEquals("should drop two collections", 2, dropCount); } @Test public void testDropCollectionsPermitReuseOfDBCollection() throws Exception { DB db = newFongo().getDB("db"); int startingCollectionSize = db.getCollectionNames().size(); DBCollection coll1 = db.getCollection("coll1"); DBCollection coll2 = db.getCollection("coll2"); assertEquals(startingCollectionSize + 2, db.getCollectionNames().size()); // when coll1.drop(); coll2.drop(); assertEquals(startingCollectionSize + 0, db.getCollectionNames().size()); // Insert a value must create the collection. coll1.insert(new BasicDBObject("_id", 1)); assertEquals(startingCollectionSize + 1, db.getCollectionNames().size()); } @Test public void testToString() { new Fongo("test").getMongo().toString(); } @Test public void testForceError() throws Exception { Fongo fongo = newFongo(); DB db = fongo.getDB("db"); CommandResult result = db.command("forceerror"); System.out.print(result); assertEquals("ok should always be defined", 0.0, result.get("ok")); assertEquals("exception: forced error", result.get("errmsg")); assertEquals(10038, result.get("code")); } @Test public void testUndefinedCommand() throws Exception { Fongo fongo = newFongo(); DB db = fongo.getDB("db"); CommandResult result = db.command("undefined"); assertEquals("ok should always be defined", 0.0, result.get("ok")); assertEquals("no such cmd: undefined", result.get("errmsg")); } @Test public void testCountCommand() throws Exception { Fongo fongo = newFongo(); DBObject countCmd = new BasicDBObject("count", "coll"); DB db = fongo.getDB("db"); DBCollection coll = db.getCollection("coll"); coll.insert(new BasicDBObject()); coll.insert(new BasicDBObject()); CommandResult result = db.command(countCmd); assertEquals("The command should have been succesful", 1.0, result.get("ok")); assertEquals("The count should be in the result", 2.0D, result.get("n")); } @Test public void testCountWithSkipLimitWithSort() { Fongo fongo = newFongo(); DB db = fongo.getDB("db"); DBCollection collection = db.getCollection("coll"); collection.insert(new BasicDBObject("_id", 0).append("date", 5L)); collection.insert(new BasicDBObject("_id", -1).append("date", 5L)); collection.insert(new BasicDBObject("_id", 1).append("date", 5L).append("str", "1")); collection.insert(new BasicDBObject("_id", 2).append("date", 6L).append("str", "2")); collection.insert(new BasicDBObject("_id", 3).append("date", 7L).append("str", "3")); collection.insert(new BasicDBObject("_id", 4).append("date", 8L).append("str", "4")); QueryBuilder builder = new QueryBuilder().start("_id").greaterThanEquals(1).lessThanEquals(5).and("str").in(Arrays.asList("1", "2", "3", "4")); DBObject countCmd = new BasicDBObject("count", "coll").append("limit", 2).append("skip", 4).append("query", builder.get()); CommandResult result = db.command(countCmd); // Without sort. assertEquals(0D, result.get("n")); } @Test public void testExplicitlyAddedObjectIdNotNew() { Fongo fongo = newFongo(); DB db = fongo.getDB("db"); DBCollection coll = db.getCollection("coll"); ObjectId oid = new ObjectId(); assertTrue("new should be true", oid.isNew()); coll.save(new BasicDBObject("_id", oid)); ObjectId retrievedOid = (ObjectId) coll.findOne().get("_id"); assertEquals("retrieved should still equal the inserted", oid, retrievedOid); assertFalse("retrieved should not be new", retrievedOid.isNew()); } @Test public void testAutoCreatedObjectIdNotNew() { Fongo fongo = newFongo(); DB db = fongo.getDB("db"); DBCollection coll = db.getCollection("coll"); coll.save(new BasicDBObject()); ObjectId retrievedOid = (ObjectId) coll.findOne().get("_id"); assertFalse("retrieved should not be new", retrievedOid.isNew()); } @Test public void testDbRefs() { Fongo fong = newFongo(); DB db = fong.getDB("db"); DBCollection coll1 = db.getCollection("coll"); DBCollection coll2 = db.getCollection("coll2"); final String coll2oid = "coll2id"; BasicDBObject coll2doc = new BasicDBObject("_id", coll2oid); coll2.insert(coll2doc); coll1.insert(new BasicDBObject("ref", new DBRef(db, "coll2", coll2oid))); DBRef ref = (DBRef) coll1.findOne().get("ref"); assertEquals("db", ref.getDB().getName()); assertEquals("coll2", ref.getRef()); assertEquals(coll2oid, ref.getId()); assertEquals(coll2doc, ref.fetch()); } @Test public void testDbRefsWithoutDbSet() { Fongo fong = newFongo(); DB db = fong.getDB("db"); DBCollection coll1 = db.getCollection("coll"); DBCollection coll2 = db.getCollection("coll2"); final String coll2oid = "coll2id"; BasicDBObject coll2doc = new BasicDBObject("_id", coll2oid); coll2.insert(coll2doc); coll1.insert(new BasicDBObject("ref", new DBRef(null, "coll2", coll2oid))); DBRef ref = (DBRef) coll1.findOne().get("ref"); assertNotNull(ref.getDB()); assertEquals("coll2", ref.getRef()); assertEquals(coll2oid, ref.getId()); assertEquals(coll2doc, ref.fetch()); } @Test public void nullable_db_for_dbref() { // Given DBCollection collection = this.newCollection(); DBObject saved = new BasicDBObjectBuilder().add("date", "now").get(); collection.save(saved); DBRef dbRef = new DBRef(null, collection.getName(), saved.get("_id")); DBObject ref = new BasicDBObject("ref", dbRef); // When collection.save(ref); DBRef result = (DBRef) collection.findOne(new BasicDBObject("_id", ref.get("_id"))).get("ref"); // Then assertThat(result.getDB()).isNotNull().isEqualTo(collection.getDB()); assertThat(result.fetch()).isEqualTo(saved); } @Test public void testFindAllWithDBList() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("tags", Util.list("mongo", "javascript"))); // When DBObject result = collection.findOne(new BasicDBObject("tags", new BasicDBObject("$all", Util.list("mongo", "javascript")))); // then assertEquals(new BasicDBObject("_id", 1).append("tags", Util.list("mongo", "javascript")), result); } @Test public void testFindAllWithList() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("tags", Util.list("mongo", "javascript"))); // When DBObject result = collection.findOne(new BasicDBObject("tags", new BasicDBObject("$all", Arrays.asList("mongo", "javascript")))); // then assertEquals(new BasicDBObject("_id", 1).append("tags", Util.list("mongo", "javascript")), result); } @Test public void testFindAllWithCollection() throws Exception { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("tags", Util.list("mongo", "javascript"))); // When DBObject result = collection.findOne(new BasicDBObject("tags", new BasicDBObject("$all", newHashSet("mongo", "javascript")))); // then assertEquals(new BasicDBObject("_id", 1).append("tags", Util.list("mongo", "javascript")), result); } @Test public void testEncodingHooks() { BSON.addEncodingHook(Seq.class, new Transformer() { @Override public Object transform(Object o) { return (o instanceof Seq) ? ((Seq) o).data : o; } }); DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); DBObject result1 = collection.findOne(new BasicDBObject("_id", new BasicDBObject("$in", new Seq(1, 3)))); assertEquals(new BasicDBObject("_id", 1), result1); DBObject result2 = collection.findOne(new BasicDBObject("_id", new BasicDBObject("$nin", new Seq(1, 3)))); assertEquals(new BasicDBObject("_id", 2), result2); } @Test public void testModificationsOfResultShouldNotChangeStorage() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); DBObject result = collection.findOne(); result.put("newkey", 1); assertEquals("should not have newkey", new BasicDBObject("_id", 1), collection.findOne()); } @Test(timeout = 16000) public void testMultiThreadInsert() throws Exception { ch.qos.logback.classic.Logger LOG = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(FongoDBCollection.class); Level oldLevel = LOG.getLevel(); try { LOG.setLevel(Level.ERROR); LOG = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ExpressionParser.class); LOG.setLevel(Level.ERROR); int size = 1000; final DBCollection col = new Fongo("InMemoryMongo").getDB("myDB").createCollection("myCollection", null); final CountDownLatch lockSynchro = new CountDownLatch(size); final CountDownLatch lockDone = new CountDownLatch(size); for (int i = 0; i < size; i++) { new Thread() { public void run() { lockSynchro.countDown(); col.insert(new BasicDBObject("multiple", 1), WriteConcern.ACKNOWLEDGED); lockDone.countDown(); } }.start(); } assertTrue("Too long :-(", lockDone.await(15, TimeUnit.SECONDS)); // Count must be same value as size assertEquals(size, col.getCount()); } finally { LOG.setLevel(oldLevel); } } // Don't know why, but request by _id only return document event if limit is set @Test public void testFindLimit0ById() throws Exception { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", "jon").append("name", "hoff")); List<DBObject> result = collection.find().limit(0).toArray(); assertNotNull(result); assertEquals(1, result.size()); } // Don't know why, but request by _id only return document even if skip is set @Test public void testFindSkip1yId() throws Exception { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", "jon").append("name", "hoff")); List<DBObject> result = collection.find(new BasicDBObject("_id", "jon")).skip(1).toArray(); assertNotNull(result); assertEquals(1, result.size()); } @Test public void testFindIdInSkip() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 4)); collection.insert(new BasicDBObject("_id", 3)); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); DBCursor cursor = collection.find(new BasicDBObject("_id", new BasicDBObject("$in", Arrays.asList(3, 2, 1)))).skip(3); assertEquals(Collections.emptyList(), cursor.toArray()); } @Test public void testFindIdInLimit() { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 4)); collection.insert(new BasicDBObject("_id", 3)); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2)); DBCursor cursor = collection.find(new BasicDBObject("_id", new BasicDBObject("$in", Arrays.asList(3, 2, 1)))).skip(1); assertEquals(Arrays.asList( new BasicDBObject("_id", 2), new BasicDBObject("_id", 3)) , cursor.toArray()); } @Test public void testWriteConcern() { assertNotNull(newFongo().getWriteConcern()); } @Test public void shouldChangeWriteConcern() { Fongo fongo = newFongo(); WriteConcern writeConcern = fongo.getMongo().getMongoClientOptions().getWriteConcern(); assertEquals(writeConcern, fongo.getWriteConcern()); assertTrue(writeConcern != WriteConcern.FSYNC_SAFE); // Change write concern fongo.getMongo().setWriteConcern(WriteConcern.FSYNC_SAFE); assertEquals(WriteConcern.FSYNC_SAFE, fongo.getWriteConcern()); } // Id is always the first field. @Test public void shouldInsertIdFirst() throws Exception { DBCollection collection = newCollection(); collection.insert(new BasicDBObject("date", 1).append("_id", new ObjectId())); collection.insert(new BasicDBObject("date", 2).append("_id", new ObjectId())); collection.insert(new BasicDBObject("date", 3).append("_id", new ObjectId())); List<DBObject> result = collection.find().toArray(); for (DBObject object : result) { // The _id field is always the first. assertEquals("_id", object.toMap().keySet().iterator().next()); } } @Test public void shouldSearchGteInArray() throws Exception { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", Util.list(1, 2, 3))); collection.insert(new BasicDBObject("_id", 2).append("a", 2)); // When List<DBObject> objects = collection.find(new BasicDBObject("a", new BasicDBObject("$gte", 2))).toArray(); // Then assertEquals(Arrays.asList( new BasicDBObject("_id", 1).append("a", Util.list(1, 2, 3)), new BasicDBObject("_id", 2).append("a", 2)), objects); } // issue #78 $gte throws Exception on non-Comparable @Test public void shouldNotThrowsExceptionOnNonComparableGte() throws Exception { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", new BasicDBObject("b", 1).append("c", 1))); collection.insert(new BasicDBObject("_id", 2).append("a", 2)); // When List<DBObject> objects = collection.find(new BasicDBObject("a", new BasicDBObject("$gte", 2))).toArray(); // Then assertEquals(Arrays.asList( new BasicDBObject("_id", 2).append("a", 2)), objects); } // issue #78 $gte throws Exception on non-Comparable @Test public void shouldNotThrowsExceptionOnNonComparableLte() throws Exception { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", new BasicDBObject("b", 1).append("c", 1))); collection.insert(new BasicDBObject("_id", 2).append("a", 2)); // When List<DBObject> objects = collection.find(new BasicDBObject("a", new BasicDBObject("$lte", 2))).toArray(); // Then assertEquals(Arrays.asList( new BasicDBObject("_id", 2).append("a", 2)), objects); } // issue #78 $gte throws Exception on non-Comparable @Test public void shouldNotThrowsExceptionOnNonComparableGt() throws Exception { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", new BasicDBObject("b", 1).append("c", 1))); collection.insert(new BasicDBObject("_id", 2).append("a", 2)); // When List<DBObject> objects = collection.find(new BasicDBObject("a", new BasicDBObject("$gt", 1))).toArray(); // Then assertEquals(Arrays.asList( new BasicDBObject("_id", 2).append("a", 2)), objects); } // issue #78 $gte throws Exception on non-Comparable @Test public void shouldNotThrowsExceptionOnNonComparableLt() throws Exception { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("a", new BasicDBObject("b", 1).append("c", 1))); collection.insert(new BasicDBObject("_id", 2).append("a", 2)); // When List<DBObject> objects = collection.find(new BasicDBObject("a", new BasicDBObject("$lt", 3))).toArray(); // Then assertEquals(Arrays.asList( new BasicDBObject("_id", 2).append("a", 2)), objects); } @Test public void shouldCompareObjectId() throws Exception { // Given DBCollection collection = newCollection(); ObjectId id1 = ObjectId.get(); ObjectId id2 = ObjectId.get(); collection.insert(new BasicDBObject("_id", id1)); collection.insert(new BasicDBObject("_id", id2)); // When List<DBObject> objects = collection.find(new BasicDBObject("_id", new BasicDBObject("$gte", id1))).toArray(); // Then assertEquals(Arrays.asList( new BasicDBObject("_id", id1), new BasicDBObject("_id", id2) ), objects); } @Test public void canInsertWithNewObjectId() throws Exception { DBCollection collection = newCollection(); ObjectId id = ObjectId.get(); collection.insert(new BasicDBObject("_id", id).append("name", "jon")); assertEquals(1, collection.count(new BasicDBObject("name", "jon"))); assertFalse(id.isNew()); } @Test public void saveStringAsObjectId() throws Exception { DBCollection collection = newCollection(); String id = ObjectId.get().toString(); BasicDBObject object = new BasicDBObject("_id", id).append("name", "jon"); collection.insert(object); assertEquals(1, collection.count(new BasicDBObject("name", "jon"))); assertEquals(id, object.get("_id")); } @Test public void shouldFilterByType() throws Exception { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("date", 1).append("_id", 1)); collection.insert(new BasicDBObject("date", 2D).append("_id", 2)); collection.insert(new BasicDBObject("date", "3").append("_id", 3)); ObjectId id = new ObjectId(); collection.insert(new BasicDBObject("date", true).append("_id", id)); collection.insert(new BasicDBObject("date", null).append("_id", 5)); collection.insert(new BasicDBObject("date", 6L).append("_id", 6)); collection.insert(new BasicDBObject("date", Util.list(1, 2, 3)).append("_id", 7)); collection.insert(new BasicDBObject("date", Util.list(1D, 2L, "3", 4)).append("_id", 8)); collection.insert(new BasicDBObject("date", Util.list(Util.list(1D, 2L, "3", 4))).append("_id", 9)); collection.insert(new BasicDBObject("date", 2F).append("_id", 10)); collection.insert(new BasicDBObject("date", new BasicDBObject("x", 1)).append("_id", 11)); // When List<DBObject> objects = collection.find(new BasicDBObject("date", new BasicDBObject("$type", 1))).toArray(); assertEquals(Arrays.asList( new BasicDBObject("_id", 2).append("date", 2D), new BasicDBObject("date", Util.list(1D, 2L, "3", 4)).append("_id", 8), new BasicDBObject("date", 2F).append("_id", 10)), objects); // When // String objects = collection.find(new BasicDBObject("date", new BasicDBObject("$type", 2))).toArray(); assertEquals(Arrays.asList( new BasicDBObject("_id", 3).append("date", "3"), new BasicDBObject("date", Util.list(1D, 2L, "3", 4)).append("_id", 8)), objects); // Integer objects = collection.find(new BasicDBObject("date", new BasicDBObject("$type", 16))).toArray(); assertEquals(Arrays.asList( new BasicDBObject("_id", 1).append("date", 1), new BasicDBObject("date", Util.list(1, 2, 3)).append("_id", 7), new BasicDBObject("date", Util.list(1D, 2L, "3", 4)).append("_id", 8)), objects); // ObjectId objects = collection.find(new BasicDBObject("_id", new BasicDBObject("$type", 7))).toArray(); assertEquals(Collections.singletonList(new BasicDBObject("_id", id).append("date", true)), objects); // Boolean objects = collection.find(new BasicDBObject("date", new BasicDBObject("$type", 8))).toArray(); assertEquals(Collections.singletonList(new BasicDBObject("_id", id).append("date", true)), objects); // Long ? objects = collection.find(new BasicDBObject("date", new BasicDBObject("$type", 18))).toArray(); assertEquals(Arrays.asList( new BasicDBObject("_id", 6).append("date", 6L), new BasicDBObject("date", Util.list(1D, 2L, "3", 4)).append("_id", 8)), objects); // Array ? objects = collection.find(new BasicDBObject("date", new BasicDBObject("$type", 4))).toArray(); assertEquals(Arrays.asList( new BasicDBObject("date", Util.list(Util.list(1D, 2L, "3", 4))).append("_id", 9)), objects); // Null ? objects = collection.find(new BasicDBObject("date", new BasicDBObject("$type", 10))).toArray(); assertEquals(Collections.singletonList(new BasicDBObject("_id", 5).append("date", null)), objects); // Object ? objects = collection.find(new BasicDBObject("date", new BasicDBObject("$type", 3))).toArray(); assertEquals(Arrays.asList( new BasicDBObject("_id", 1).append("date", 1), new BasicDBObject("_id", 2).append("date", 2D), new BasicDBObject("_id", 3).append("date", "3"), new BasicDBObject("_id", id).append("date", true), new BasicDBObject("_id", 6).append("date", 6L), new BasicDBObject("_id", 7).append("date", Util.list(1, 2, 3)), new BasicDBObject("_id", 8).append("date", Util.list(1D, 2L, "3", 4)), new BasicDBObject("_id", 9).append("date", Util.list(Util.list(1D, 2L, "3", 4))), new BasicDBObject("_id", 10).append("date", 2F), new BasicDBObject("_id", 11).append("date", new BasicDBObject("x", 1))), objects); } @Test public void testSorting() throws Exception { // Given DBCollection collection = newCollection(); Date date = new Date(); collection.insert(new BasicDBObject("_id", 1).append("x", 3)); collection.insert(new BasicDBObject("_id", 2).append("x", 2.9D)); collection.insert(new BasicDBObject("_id", 3).append("x", date)); collection.insert(new BasicDBObject("_id", 4).append("x", true)); collection.insert(new BasicDBObject("_id", 5).append("x", new MaxKey())); collection.insert(new BasicDBObject("_id", 6).append("x", new MinKey())); collection.insert(new BasicDBObject("_id", 7).append("x", false)); collection.insert(new BasicDBObject("_id", 8).append("x", 2)); collection.insert(new BasicDBObject("_id", 9).append("x", date.getTime() + 100)); collection.insert(new BasicDBObject("_id", 10)); // When List<DBObject> objects = collection.find().sort(new BasicDBObject("x", 1)).toArray(); // Then assertEquals(Arrays.asList( new BasicDBObject("_id", 6).append("x", new MinKey()), new BasicDBObject("_id", 10), new BasicDBObject("_id", 8).append("x", 2), new BasicDBObject("_id", 2).append("x", 2.9D), new BasicDBObject("_id", 1).append("x", 3), new BasicDBObject("_id", 9).append("x", date.getTime() + 100), new BasicDBObject("_id", 7).append("x", false), new BasicDBObject("_id", 4).append("x", true), new BasicDBObject("_id", 3).append("x", date), new BasicDBObject("_id", 5).append("x", new MaxKey()) ), objects); } @Test public void testSortingNull() throws Exception { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("x", new MinKey())); collection.insert(new BasicDBObject("_id", 2).append("x", new MaxKey())); collection.insert(new BasicDBObject("_id", 3).append("x", 3)); collection.insert(new BasicDBObject("_id", 4).append("x", null)); collection.insert(new BasicDBObject("_id", 5)); // When List<DBObject> objects = collection.find().sort(new BasicDBObject("x", 1)).toArray(); // Then assertEquals(Arrays.asList( new BasicDBObject("_id", 1).append("x", new MinKey()), new BasicDBObject("_id", 5), new BasicDBObject("_id", 4).append("x", null), new BasicDBObject("_id", 3).append("x", 3), new BasicDBObject("_id", 2).append("x", new MaxKey()) ), objects); } // Pattern is last. @Test public void testSortingPattern() throws Exception { // Given DBCollection collection = newCollection(); // DBCollection collection = new MongoClient().getDB("test").getCollection("sorting"); // collection.drop(); ObjectId id = ObjectId.get(); Date date = new Date(); collection.insert(new BasicDBObject("_id", 1).append("x", Pattern.compile("a*"))); collection.insert(new BasicDBObject("_id", 2).append("x", 2)); collection.insert(new BasicDBObject("_id", 3).append("x", "3")); collection.insert(new BasicDBObject("_id", 4).append("x", id)); collection.insert(new BasicDBObject("_id", 5).append("x", new BasicDBObject("a", 3))); collection.insert(new BasicDBObject("_id", 6).append("x", date)); // collection.insert(new BasicDBObject("_id", 7).append("x", "3".getBytes())); // later // When List<DBObject> objects = collection.find().sort(new BasicDBObject("x", 1)).toArray(); // Then assertEquals(Arrays.asList( new BasicDBObject("_id", 2).append("x", 2), new BasicDBObject("_id", 3).append("x", "3"), new BasicDBObject("_id", 5).append("x", new BasicDBObject("a", 3)), // new BasicDBObject("_id", 7).append("x", "3".getBytes()), // later. new BasicDBObject("_id", 4).append("x", id), new BasicDBObject("_id", 6).append("x", date), new BasicDBObject("_id", 1).append("x", Pattern.compile("a*")) ), objects); } @Test public void testSortingDBObject() throws Exception { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1).append("x", new BasicDBObject("a", 3))); ObjectId val = ObjectId.get(); collection.insert(new BasicDBObject("_id", 2).append("x", val)); collection.insert(new BasicDBObject("_id", 3).append("x", "3")); collection.insert(new BasicDBObject("_id", 4).append("x", 3)); // When List<DBObject> objects = collection.find().sort(new BasicDBObject("x", 1)).toArray(); // Then assertEquals(Arrays.asList( new BasicDBObject("_id", 4).append("x", 3), new BasicDBObject("_id", 3).append("x", "3"), new BasicDBObject("_id", 1).append("x", new BasicDBObject("a", 3)), new BasicDBObject("_id", 2).append("x", val) ), objects); } @Test public void testSortingNullVsMinKey() throws Exception { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 1)); collection.insert(new BasicDBObject("_id", 2).append("x", new MinKey())); // When List<DBObject> objects = collection.find().sort(new BasicDBObject("x", 1)).toArray(); // Then assertEquals(Arrays.asList( new BasicDBObject("_id", 2).append("x", new MinKey()), new BasicDBObject("_id", 1) ), objects); } // Previously on {@link ExpressionParserTest. @Test public void testStrangeSorting() throws Exception { // Given DBCollection collection = newCollection(); collection.insert(new BasicDBObject("_id", 2).append("b", 1)); collection.insert(new BasicDBObject("_id", 1).append("a", 3)); // When List<DBObject> objects = collection.find().sort(new BasicDBObject("a", 1)).toArray(); // Then assertEquals(Arrays.asList( new BasicDBObject("_id", 2).append("b", 1), new BasicDBObject("_id", 1).append("a", 3) ), objects); } /** * line 456 (LOG.debug("restrict with index {}, from {} to {} elements", matchingIndex.getName(), _idIndex.size(), dbObjectIterable.size());) obviously throws a null pointer if dbObjectIterable is null. This exact case is handled 4 lines below, but it does not apply to the log message. Please catch appropriately */ @Test public void testIssue1() { ch.qos.logback.classic.Logger LOG = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(FongoDBCollection.class); Level oldLevel = LOG.getLevel(); try { LOG.setLevel(Level.DEBUG); // Given DBCollection collection = newCollection(); // When collection.remove(new BasicDBObject("_id", 1)); } finally { LOG.setLevel(oldLevel); } } @Test public void testBinarySave() throws Exception { // Given DBCollection collection = newCollection(); Binary expectedId = new Binary("friend2".getBytes()); // When collection.save(BasicDBObjectBuilder.start().add("_id", expectedId).get()); collection.update(BasicDBObjectBuilder.start().add("_id", new Binary("friend2".getBytes())).get(), new BasicDBObject("date", 12)); // Then List<DBObject> result = collection.find().toArray(); assertThat(result).hasSize(1); assertThat(result.get(0).keySet()).containsExactly("_id", "date"); assertThat(result.get(0).get("_id")).isEqualTo("friend2".getBytes()); assertThat(result.get(0).get("date")).isEqualTo(12); } @Test public void testBinarySaveWithBytes() throws Exception { // Given DBCollection collection = newCollection(); Binary expectedId = new Binary("friend2".getBytes()); // When collection.save(BasicDBObjectBuilder.start().add("_id", expectedId).get()); collection.update(BasicDBObjectBuilder.start().add("_id", "friend2".getBytes()).get(), new BasicDBObject("date", 12)); // Then List<DBObject> result = collection.find().toArray(); assertThat(result).hasSize(1); assertThat(result.get(0).keySet()).containsExactly("_id", "date"); assertThat(result.get(0).get("_id")).isEqualTo("friend2".getBytes()); assertThat(result.get(0).get("date")).isEqualTo(12); } // can not change _id of a document query={ "_id" : "52986f667f6cc746624b0db5"}, document={ "name" : "Robert" , "_id" : { "$oid" : "52986f667f6cc746624b0db5"}} // See jongo SaveTest#canSaveWithObjectIdAsString @Test public void update_id_is_string_and_objectid() { // Given DBCollection collection = newCollection(); ObjectId objectId = ObjectId.get(); DBObject query = BasicDBObjectBuilder.start("_id", objectId.toString()).get(); DBObject object = BasicDBObjectBuilder.start("_id", objectId).add("name", "Robert").get(); // When collection.update(query, object, true, false); // Then List<DBObject> result = collection.find().toArray(); assertThat(result).hasSize(1); assertThat(result.get(0).toMap()).contains(MapEntry.entry("name", "Robert"), MapEntry.entry("_id", objectId)); } @Test public void projection_elemMatch() { // Given DBCollection collection = newCollection(); this.fongoRule.insertJSON(collection, "[{\n" + " _id: 1,\n" + " zipcode: 63109,\n" + " students: [\n" + " { name: \"john\"},\n" + " { name: \"jess\"},\n" + " { name: \"jeff\"}\n" + " ]\n" + "}\n," + "{\n" + " _id: 2,\n" + " zipcode: 63110,\n" + " students: [\n" + " { name: \"ajax\"},\n" + " { name: \"achilles\"}\n" + " ]\n" + "}\n," + "{\n" + " _id: 3,\n" + " zipcode: 63109,\n" + " students: [\n" + " { name: \"ajax\"},\n" + " { name: \"achilles\"}\n" + " ]\n" + "}\n," + "{\n" + " _id: 4,\n" + " zipcode: 63109,\n" + " students: [\n" + " { name: \"barney\"}\n" + " ]\n" + "}]\n"); // When List<DBObject> result = collection.find(fongoRule.parseDBObject("{ zipcode: 63109 },\n"), fongoRule.parseDBObject("{ students: { $elemMatch: { name: \"achilles\" } } }")).toArray(); // Then assertEquals(fongoRule.parseList("[{ \"_id\" : 1}, " + "{ \"_id\" : 3, \"students\" : [ { name: \"achilles\"} ] }, { \"_id\" : 4}]"), result); } @Test public void projection_elemMatchWithBigSubdocument() { // Given DBCollection collection = newCollection(); this.fongoRule.insertJSON(collection, "[{\n" + " _id: 1,\n" + " zipcode: 63109,\n" + " students: [\n" + " { name: \"john\", school: 102, age: 10 },\n" + " { name: \"jess\", school: 102, age: 11 },\n" + " { name: \"jeff\", school: 108, age: 15 }\n" + " ]\n" + "}\n," + "{\n" + " _id: 2,\n" + " zipcode: 63110,\n" + " students: [\n" + " { name: \"ajax\", school: 100, age: 7 },\n" + " { name: \"achilles\", school: 100, age: 8 }\n" + " ]\n" + "}\n," + "{\n" + " _id: 3,\n" + " zipcode: 63109,\n" + " students: [\n" + " { name: \"ajax\", school: 100, age: 7 },\n" + " { name: \"achilles\", school: 100, age: 8 }\n" + " ]\n" + "}\n," + "{\n" + " _id: 4,\n" + " zipcode: 63109,\n" + " students: [\n" + " { name: \"barney\", school: 102, age: 7 }\n" + " ]\n" + "}]\n"); // When List<DBObject> result = collection.find(fongoRule.parseDBObject("{ zipcode: 63109 }"), fongoRule.parseDBObject("{ students: { $elemMatch: { school: 102 } } }")).toArray(); // Then assertEquals(fongoRule.parseList("[{ \"_id\" : 1, \"students\" : [ { \"name\" : \"john\", \"school\" : 102, \"age\" : 10 } ] },\n" + "{ \"_id\" : 3 },\n" + "{ \"_id\" : 4, \"students\" : [ { \"name\" : \"barney\", \"school\" : 102, \"age\" : 7 } ] }]"), result); } @Test @Ignore public void query_elemMatch() { // Given DBCollection collection = newCollection(); this.fongoRule.insertJSON(collection, "[{\n" + " _id: 1,\n" + " zipcode: 63109,\n" + " students: [\n" + " { name: \"john\", school: 102, age: 10 },\n" + " { name: \"jess\", school: 102, age: 11 },\n" + " { name: \"jeff\", school: 108, age: 15 }\n" + " ]\n" + "}\n," + "{\n" + " _id: 2,\n" + " zipcode: 63110,\n" + " students: [\n" + " { name: \"ajax\", school: 100, age: 7 },\n" + " { name: \"achilles\", school: 100, age: 8 }\n" + " ]\n" + "}\n," + "{\n" + " _id: 3,\n" + " zipcode: 63109,\n" + " students: [\n" + " { name: \"ajax\", school: 100, age: 7 },\n" + " { name: \"achilles\", school: 100, age: 8 }\n" + " ]\n" + "}\n," + "{\n" + " _id: 4,\n" + " zipcode: 63109,\n" + " students: [\n" + " { name: \"barney\", school: 102, age: 7 }\n" + " ]\n" + "}]\n"); // When List<DBObject> result = collection.find(fongoRule.parseDBObject("{ zipcode: 63109 }"), fongoRule.parseDBObject("{ students: { $elemMatch: { school: 102 } } }")).toArray(); // Then assertEquals(fongoRule.parseList("[{ \"_id\" : 1, \"students\" : [ { \"name\" : \"john\", \"school\" : 102, \"age\" : 10 } ] },\n" + "{ \"_id\" : 3 },\n" + "{ \"_id\" : 4, \"students\" : [ { \"name\" : \"barney\", \"school\" : 102, \"age\" : 7 } ] }]"), result); } @Test public void find_and_modify_with_projection_old_object() { // Given DBCollection collection = newCollection(); collection.insert(fongoRule.parseDBObject("{ \"name\" : \"John\" , \"address\" : \"Jermin Street\"}")); // When DBObject result = collection.findAndModify(new BasicDBObject("name", "John"), new BasicDBObject("name", 1), null, false, new BasicDBObject("$set", new BasicDBObject("name", "Robert")), false, false); // Then assertThat(result.get("name")).isNotNull().isEqualTo("John"); assertFalse("Bad Projection", result.containsField("address")); } @Test public void find_and_modify_with_projection_new_object() { // Given DBCollection collection = newCollection(); collection.insert(fongoRule.parseDBObject("{ \"name\" : \"John\" , \"address\" : \"Jermin Street\"}")); // When DBObject result = collection.findAndModify(new BasicDBObject("name", "John"), new BasicDBObject("name", 1), null, false, new BasicDBObject("$set", new BasicDBObject("name", "Robert")), true, false); // Then assertThat(result.get("name")).isNotNull().isEqualTo("Robert"); assertFalse("Bad Projection", result.containsField("address")); } @Test public void find_and_modify_with_projection_new_object_upsert() { // Given DBCollection collection = newCollection(); // When DBObject result = collection.findAndModify(new BasicDBObject("name", "Rob"), new BasicDBObject("name", 1), null, false, new BasicDBObject("$set", new BasicDBObject("name", "Robert")), true, true); // Then assertThat(result.get("name")).isNotNull().isEqualTo("Robert"); assertFalse("Bad Projection", result.containsField("address")); } @Test public void find_with_maxScan() { // Given DBCollection collection = newCollection(); collection.insert(fongoRule.parseDBObject("{ \"name\" : \"John\" , \"address\" : \"Jermin Street\"}")); collection.insert(fongoRule.parseDBObject("{ \"name\" : \"Robert\" , \"address\" : \"Jermin Street\"}")); // When List<DBObject> objects = collection.find().addSpecial("$maxScan", 1).toArray(); // Then assertThat(objects).hasSize(1); } static class Seq { Object[] data; Seq(Object... data) { this.data = data; } } private static <T> Set<T> newHashSet(T... objects) { return new HashSet<T>(Arrays.asList(objects)); } public DBCollection newCollection() { return fongoRule.newCollection("db"); } public Fongo newFongo() { return fongoRule.newFongo(); } }
package com.rox.emu.p6502; import com.pholser.junit.quickcheck.Property; import com.pholser.junit.quickcheck.generator.InRange; import com.pholser.junit.quickcheck.runner.JUnitQuickcheck; import com.rox.emu.Memory; import com.rox.emu.SimpleMemory; import com.rox.emu.UnknownOpCodeException; import com.rox.emu.p6502.op.AddressingMode; import com.rox.emu.p6502.op.OpCode; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Arrays; import static com.rox.emu.p6502.Compiler.INDIRECT_PREFIX; import static com.rox.emu.p6502.Compiler.VALUE_PREFIX; import static com.rox.emu.p6502.InstructionSet.OP_LDA_I; import static junit.framework.TestCase.assertEquals; import static org.junit.Assert.*; @RunWith(JUnitQuickcheck.class) public class CompilerTest { @Test public void testPrefixExtraction(){ try { assertEquals("$", Compiler.extractFirstOccurrence(Compiler.PREFIX_REGEX, "$10", "LDA")); assertEquals("#$", Compiler.extractFirstOccurrence(Compiler.PREFIX_REGEX, "#$10", "ADC")); assertEquals("$", Compiler.extractFirstOccurrence(Compiler.PREFIX_REGEX, "$AA", "LDA")); assertEquals("#$", Compiler.extractFirstOccurrence(Compiler.PREFIX_REGEX, "#$AA", "ADC")); assertEquals("($", Compiler.extractFirstOccurrence(Compiler.PREFIX_REGEX, "($AA,X)", "ADC")); }catch (UnknownOpCodeException e){ fail(e.getMessage()); } } @Test public void testValueExtraction(){ try { assertEquals("10", Compiler.extractFirstOccurrence(Compiler.VALUE_REGEX, "$10", "LDA")); assertEquals("10", Compiler.extractFirstOccurrence(Compiler.VALUE_REGEX, "#$10", "LDA")); assertEquals("AA", Compiler.extractFirstOccurrence(Compiler.VALUE_REGEX, "$AA", "LDA")); assertEquals("AA", Compiler.extractFirstOccurrence(Compiler.VALUE_REGEX, "#$AA", "LDA")); assertEquals("AA", Compiler.extractFirstOccurrence(Compiler.VALUE_REGEX, "($AA,X)", "ADC")); }catch (UnknownOpCodeException e){ fail(e.getMessage()); } } @Test public void testPostfixExtraction(){ try { assertEquals(",X", Compiler.extractFirstOccurrence(Compiler.POSTFIX_REGEX, "$10,X", "LDA")); assertEquals(",Y", Compiler.extractFirstOccurrence(Compiler.POSTFIX_REGEX, "$AA,Y", "LDA")); assertEquals(",X)", Compiler.extractFirstOccurrence(Compiler.POSTFIX_REGEX, "($AA,X)", "ADC")); }catch (UnknownOpCodeException e){ fail(e.getMessage()); } } @Test public void testImpliedInstructions(){ OpCode.streamOf(AddressingMode.IMPLIED).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName()); int[] bytes = compiler.getBytes(); assertEquals("Wrong byte value for " + opcode.getOpCodeName() + "(" + opcode.getByteValue() + ")", opcode.getByteValue(), bytes[0]); }); } @Test public void testSingleDigitArgument(){ OpCode.streamOf(AddressingMode.ZERO_PAGE).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + "A"); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), 0xA}, bytes); }); } @Test public void testDoubleDigitArgument(){ OpCode.streamOf(AddressingMode.ZERO_PAGE).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + "AB"); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), 0xAB}, bytes); }); } @Test public void testTripleDigitArgument(){ OpCode.streamOf(AddressingMode.ABSOLUTE).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + "ABC"); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), 0xABC}, bytes); }); } @Test public void testQuadrupleDigitArgument(){ OpCode.streamOf(AddressingMode.ABSOLUTE).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + "ABCD"); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), 0xABCD}, bytes); }); } @Property public void testImmediateInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.IMMEDIATE).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.IMMEDIATE_VALUE_PREFIX + hexByte); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Property public void testAccumulatorInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.ACCUMULATOR).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.IMMEDIATE_PREFIX + hexByte); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Property public void testZeroPageInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.ZERO_PAGE).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + hexByte); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Property public void testZeroPageXInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.ZERO_PAGE_X).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + hexByte+ ",X"); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Property public void testZeroPageYInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.ZERO_PAGE_Y).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + hexByte + ",Y"); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Property public void testAbsoluteInstructions(@InRange(min = "256", max = "65535") int wordValue){ final String hexWord = Integer.toHexString(wordValue); OpCode.streamOf(AddressingMode.ABSOLUTE).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + hexWord); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), wordValue}, bytes); }); } @Property public void testAbsoluteXInstructions(@InRange(min = "256", max = "65535") int wordValue){ final String hexWord = Integer.toHexString(wordValue); OpCode.streamOf(AddressingMode.ABSOLUTE_X).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + hexWord + ",X"); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + " 0x" + hexWord + "' was wrong.", new int[] {opcode.getByteValue(), wordValue}, bytes); }); } @Property public void testAbsoluteYInstructions(@InRange(min = "256", max = "65535") int wordValue){ final String hexWord = Integer.toHexString(wordValue); OpCode.streamOf(AddressingMode.ABSOLUTE_Y).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + hexWord + ",Y"); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + " 0x" + hexWord + "' was wrong.", new int[] {opcode.getByteValue(), wordValue}, bytes); }); } @Property public void testIndirectXInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.INDIRECT_X).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " (" + Compiler.VALUE_PREFIX + hexByte + ",X)"); int[] bytes = compiler.getBytes(); assertArrayEquals(new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Property public void testIndirectYInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.INDIRECT_Y).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " (" + Compiler.VALUE_PREFIX + hexByte + "),Y"); int[] bytes = compiler.getBytes(); assertArrayEquals(new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Test public void testChainedInstruction(){ Compiler compiler = new Compiler("SEC LDA " + Compiler.IMMEDIATE_VALUE_PREFIX + "47"); final int[] bytes = compiler.getBytes(); int[] expected = new int[] {OpCode.OP_SEC.getByteValue(), OpCode.OP_LDA_I.getByteValue(), 0x47}; assertArrayEquals("Expected: " + Arrays.toString(expected) + ", Got: " + Arrays.toString(bytes), expected, bytes); } @Test public void testChainedTwoByteInstruction(){ Compiler compiler = new Compiler("LDA " + Compiler.IMMEDIATE_VALUE_PREFIX + "47 SEC"); final int[] bytes = compiler.getBytes(); int[] expected = new int[] {OpCode.OP_LDA_I.getByteValue(), 0x47, OpCode.OP_SEC.getByteValue()}; assertArrayEquals("Expected: " + Arrays.toString(expected) + ", Got: " + Arrays.toString(bytes), expected, bytes); } @Test public void testChainedTwoByteInstructions(){ Compiler compiler = new Compiler("LDA " + Compiler.IMMEDIATE_VALUE_PREFIX + "47 CLC LDA " + Compiler.IMMEDIATE_VALUE_PREFIX + "10 SEC"); final int[] bytes = compiler.getBytes(); int[] expected = new int[] {OpCode.OP_LDA_I.getByteValue(), 0x47, OpCode.OP_CLC.getByteValue(), OpCode.OP_LDA_I.getByteValue(), 0x10, OpCode.OP_SEC.getByteValue()}; assertArrayEquals("Expected: " + Arrays.toString(expected) + ", Got: " + Arrays.toString(bytes), expected, bytes); } @Test public void testProgram(){ Compiler compiler = new Compiler("LDA #$14 ADC #$5 STA $20"); final int[] bytes = compiler.getBytes(); int[] expected = new int[] {OpCode.OP_LDA_I.getByteValue(), 0x14, OpCode.OP_ADC_I.getByteValue(), 0x5, OpCode.OP_STA_Z.getByteValue(), 0x20}; assertArrayEquals("Expected: " + Arrays.toString(expected) + ", Got: " + Arrays.toString(bytes), expected, bytes); } @Test public void testIntegration(){ Compiler compiler = new Compiler("LDA #$14 ADC #$5 STA $20"); final int[] program = compiler.getBytes(); Memory memory = new SimpleMemory(); CPU processor = new CPU(memory); processor.reset(); memory.setMemory(0, program); processor.step(3); Registers registers = processor.getRegisters(); assertEquals(0x19, registers.getRegister(Registers.REG_ACCUMULATOR)); assertEquals(0x19, memory.getByte(0x20)); assertEquals(program.length, registers.getPC()); } @Test public void firstInvalidOpcode(){ Compiler compiler = new Compiler("ROX"); try { compiler.getBytes(); fail("Exception expected, 'ROX' is an invalid OpCode"); }catch(UnknownOpCodeException e){ assertNotNull(e); } } @Test public void opCodeJaCoCoCoverage(){ Compiler compiler = new Compiler("\0ADC $10"); try { compiler.getBytes(); fail("Exception expected. This should not pass a String switch statement"); }catch(UnknownOpCodeException e){ assertNotNull(e); } } @Test public void testInvalidValuePrefix(){ try { Compiler compiler = new Compiler("ADC @$10"); int[] bytes = compiler.getBytes(); fail("Invalid value prefix should throw an exception but was " + Arrays.toString(bytes)); }catch (UnknownOpCodeException e){ assertFalse(e.getMessage().isEmpty()); assertFalse(e.getOpCode() == null); } } @Test public void testInvalidIndirectIndexingMode(){ try { Compiler compiler = new Compiler("ADC " + INDIRECT_PREFIX + "10("); int[] bytes = compiler.getBytes(); fail("Invalid prefix for an indirect value should throw an exception but was " + Arrays.toString(bytes)); }catch (UnknownOpCodeException e){ assertFalse(e.getMessage().isEmpty()); assertFalse(e.getOpCode() == null); } } @Test public void testOversizedValue(){ try { Compiler compiler = new Compiler("ADC " + VALUE_PREFIX + "12345"); int[] bytes = compiler.getBytes(); fail("Argument size over " + 0xFFFF + " should throw an exception but was " + Arrays.toString(bytes)); }catch (UnknownOpCodeException e){ assertFalse(e.getMessage().isEmpty()); assertFalse(e.getOpCode() == null); } } }
package de.baumato.loc; import static org.assertj.core.api.Assertions.assertThat; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.Before; import org.junit.Test; import com.github.javaparser.JavaParser; import de.baumato.loc.configuration.Configuration; import de.baumato.loc.printer.ConsolePrinter; public class LineCounterTest { private final Path unformatted = Paths.get("src/test/resources/SomeClass.unformatted.java"); private final Path formatted = Paths.get("src/test/resources/SomeClass.formatted.java"); private LineCounter lc; @Before public void setup() { lc = new LineCounter(new Configuration(), new ConsolePrinter()); } @Test public void shouldReadJavaFileAfterApplyingDefaultFormatter() throws Exception { String expected = JavaParser.parse(unformatted).toString(); String actual = new String(Files.readAllBytes(formatted)); assertThat(actual).isEqualTo(expected); } @Test public void shouldReadJavaFileAfterApplyingDefaultFormatter2() throws Exception { long uc = lc.countLines(unformatted); long fc = lc.countLines(formatted); assertThat(uc).isEqualTo(fc).isEqualTo(31); } @Test public void shouldCountJavaFilesOnly() throws Exception { Path p = Paths.get("src/test/resources/container/dir"); lc = new LineCounter(Configuration.ofCmdLine("-d", p.toString()), new ConsolePrinter()); assertThat(lc.count()).isZero(); } @Test public void shouldCount() throws Exception { Path p = Paths.get("src/test/resources/container"); lc = new LineCounter(Configuration.ofCmdLine("-d", p.toString()), new ConsolePrinter()); assertThat(lc.count()).isEqualTo(31); } @Test public void shouldExcludeFoldersSpecifiedInConfiguration() throws Exception { Path p = Paths.get("src/test/resources"); lc = new LineCounter( Configuration.ofCmdLine("-d", p.toString(), "-e", "container"), new ConsolePrinter()); assertThat(lc.count()).isEqualTo(62); } }
package de.dhbw.humbuch.test; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.util.Calendar; import java.util.Date; import de.dhbw.humbuch.model.entity.BorrowedMaterial; import de.dhbw.humbuch.model.entity.Category; import de.dhbw.humbuch.model.entity.Grade; import de.dhbw.humbuch.model.entity.SchoolYear; import de.dhbw.humbuch.model.entity.SettingsEntry; import de.dhbw.humbuch.model.entity.SchoolYear.Term; import de.dhbw.humbuch.model.entity.Student; import de.dhbw.humbuch.model.entity.TeachingMaterial; import de.dhbw.humbuch.model.entity.User; import de.dhbw.humbuch.util.PasswordHash; public class TestUtils { public static final String USERNAME = "USERNAME"; public static final String PASSWORD = "PASSWORD"; public static final String PASSWORD_HASH = "HASH"; public static int rInt() { return (int) (Math.random() * 10000); } public static String rStr() { return "" + rInt(); } public static Date todayPlusDays(int days) { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.add(Calendar.DATE, days); return calendar.getTime(); } public static User user(String username, String password) { try { return new User.Builder(username, PasswordHash.createHash(password)) .email(rStr() + "@" + rStr() + "." + rStr()).build(); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { e.printStackTrace(); return new User.Builder(USERNAME, PASSWORD_HASH).email( rStr() + "@" + rStr() + "." + rStr()).build(); } } public static User randomUser() { return user(rStr(), rStr()); } public static User standardUser() { return user(USERNAME, PASSWORD); } public static Category category() { return new Category.Builder(rStr()).build(); } public static Grade grade(int grade) { return new Grade.Builder(grade, "").build(); } public static SettingsEntry settingsEntry() { return new SettingsEntry.Builder(rStr(), rStr(), rStr()).build(); } public static SchoolYear schoolYear(int fromDays, int endFirstTermDays, int beginSecondTermDays, int toDays) { SchoolYear schoolYear = new SchoolYear.Builder("now", todayPlusDays(fromDays), todayPlusDays(toDays)) .endFirstTerm(todayPlusDays(endFirstTermDays)) .beginSecondTerm(todayPlusDays(beginSecondTermDays)).build(); return schoolYear; } public static SchoolYear schoolYearFirstTermNotStarted() { return schoolYear(1, 2, 3, 4); } public static SchoolYear schoolYearFirstTermStarted() { return schoolYear(-1, 1, 1, 2); } public static SchoolYear schoolYearFirstTermEnded() { return schoolYear(-2, -1, 1, 2); } public static SchoolYear schoolYearSecondTermStarted() { return schoolYear(-3, -2, -1, 1); } public static SchoolYear schoolYearSecondTermEnded() { return schoolYear(-9, -8, -7, -6); } public static Student studentInGrade(int grade) { Grade gradeEntity = new Grade.Builder(grade, "").build(); gradeEntity.setId(grade); Student student = new Student.Builder(rInt(), "John", "Doe", null, gradeEntity).build(); return student; } public static TeachingMaterial teachingMaterialInBothTermsOfGrade(int grade) { TeachingMaterial teachingMaterial = new TeachingMaterial.Builder( category(), "FooBook1", null, todayPlusDays(-20)) .fromGrade(grade).fromTerm(Term.FIRST).toGrade(grade) .toTerm(Term.SECOND).build(); return teachingMaterial; } public static TeachingMaterial teachingMaterialInFirstTermOfGrade(int grade) { TeachingMaterial teachingMaterial = new TeachingMaterial.Builder( category(), "FooBook1", null, todayPlusDays(-20)) .fromGrade(grade).fromTerm(Term.FIRST).toGrade(grade) .toTerm(Term.FIRST).build(); return teachingMaterial; } public static TeachingMaterial teachingMaterialInSecondTermOfGrade(int grade) { TeachingMaterial teachingMaterial = new TeachingMaterial.Builder( category(), "FooBook1", null, todayPlusDays(-20)) .fromGrade(grade).fromTerm(Term.SECOND).toGrade(grade) .toTerm(Term.SECOND).build(); return teachingMaterial; } public static BorrowedMaterial borrowedMaterialReceivedInPast( Student student, TeachingMaterial teachingMaterial) { BorrowedMaterial borrowedMaterial = new BorrowedMaterial.Builder( student, teachingMaterial, todayPlusDays(-25)).received(true) .build(); return borrowedMaterial; } }
package dk.itu.kelvin.util; // General utilities import java.util.Iterator; // JUnit annotations import org.junit.Before; import org.junit.Test; // JUnit assertions import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; /** * UnitTest of the HashSet class which is part of the util classes. */ public final class HashSetTest { /** * A HashSet which we use in almost every testcases. */ private HashSet<String> h1; /** * an ArrayList to use in the addAll method. */ private ArrayList<String> a1; /** * A HashSet and an ArrayList, that we use more than once. */ @Before public void before() { this.h1 = new HashSet<>(); this.a1 = new ArrayList<>(); } /** * Test of add method. not done. */ @Test public void testAdd() { this.h1.add("ex1"); this.h1.add("ex2"); assertFalse(this.h1.add("ex1")); assertTrue(this.h1.contains("ex1")); assertFalse(this.h1.add(null)); // Add the same element again. assertFalse(this.h1.add("ex1")); } /** * Simple test of addAll method. */ @Test public void testAddAllFromCollection() { this.a1.add("ex1"); this.a1.add("ex2"); this.a1.add("ex3"); this.h1.addAll(this.a1); assertTrue(this.h1.contains("ex3")); } /** * part two of addAll method. */ @Test public void testAddAllIfNullOrEmpty() { // if the collection is empty it should return false. this.h1.addAll(this.a1); assertFalse(this.h1.addAll(this.a1)); // If it adds null it should be false. this.a1.add(null); assertFalse(this.h1.addAll(this.a1)); } /** * Here we test the remove method. */ @Test public void testRemove() { //We add two elements and check if the hashSet contains them. this.h1.add("ex1"); this.h1.add("ex2"); assertTrue(this.h1.contains("ex1") && this.h1.contains("ex2")); assertEquals(2, this.h1.size()); // We remove one of the elements, // and asserts that it doesn't contains it anymore. this.h1.remove("ex1"); assertFalse(this.h1.contains("ex1")); assertEquals(1, this.h1.size()); // we then try to remove the same element again, // to see if it returns false, as it should. assertFalse(this.h1.remove("ex1")); assertEquals(1, this.h1.size()); } /** * Test of HashSet constructors when it s given a collection. */ @Test public void testHashSetCollection() { this.a1.add("ex1"); this.a1.add("ex2"); this.a1.add("ex3"); HashSet<String> h2 = new HashSet<>(this.a1); assertTrue(h2.contains("ex1")); assertTrue(h2.contains("ex2")); assertTrue(h2.contains("ex3")); assertEquals(3, h2.size()); } /** * Test of the Iterator. */ @Test public void testIterator() { this.h1.add("ex1"); this.h1.add("ex2"); Iterator<String> i = this.h1.iterator(); int count = 0; while (i.hasNext()) { String n = i.next(); assertTrue(n.equals("ex1") || n.equals("ex2")); count++; } assertEquals(count, this.h1.size()); } }
package kr.co.vcnc.haeinsa; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.Iterator; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import kr.co.vcnc.haeinsa.exception.ConflictException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.MiniHBaseCluster; import org.apache.hadoop.hbase.ZooKeeperConnectionException; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.HConnectionManager; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.HTableInterface; import org.apache.hadoop.hbase.client.HTableInterfaceFactory; import org.apache.hadoop.hbase.util.Bytes; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class HaeinsaTest { private static MiniHBaseCluster CLUSTER; private static Configuration CONF; @BeforeClass public static void setUpHbase() throws Exception { Configuration conf = HBaseConfiguration.create(); HBaseTestingUtility utility = new HBaseTestingUtility(conf); utility.cleanupTestDir(); CLUSTER = utility.startMiniCluster(); CONF = CLUSTER.getConfiguration(); HBaseAdmin admin = new HBaseAdmin(CONF); // Table -> ColumnFamily // { test } -> { !lock!, data, meta } HTableDescriptor tableDesc = new HTableDescriptor("test"); HColumnDescriptor lockColumnDesc = new HColumnDescriptor(HaeinsaConstants.LOCK_FAMILY); lockColumnDesc.setMaxVersions(1); lockColumnDesc.setInMemory(true); tableDesc.addFamily(lockColumnDesc); HColumnDescriptor dataColumnDesc = new HColumnDescriptor("data"); tableDesc.addFamily(dataColumnDesc); HColumnDescriptor metaColumnDesc = new HColumnDescriptor("meta"); tableDesc.addFamily(metaColumnDesc); admin.createTable(tableDesc); // Table -> ColumnFamily // { log } -> { !lock!, raw } HTableDescriptor logDesc = new HTableDescriptor("log"); lockColumnDesc = new HColumnDescriptor(HaeinsaConstants.LOCK_FAMILY); lockColumnDesc.setMaxVersions(1); lockColumnDesc.setInMemory(true); logDesc.addFamily(lockColumnDesc); HColumnDescriptor rawColumnDesc = new HColumnDescriptor("raw"); logDesc.addFamily(rawColumnDesc); admin.createTable(logDesc); admin.close(); } @AfterClass public static void tearDownHBase() throws Exception { CLUSTER.shutdown(); } @Test public void testTransaction() throws Exception{ final ExecutorService threadPool = Executors.newCachedThreadPool(); HaeinsaTablePool tablePool = new HaeinsaTablePool(CONF, 128, new HTableInterfaceFactory() { @Override public void releaseHTableInterface(HTableInterface table) throws IOException { table.close(); } @Override public HTableInterface createHTableInterface(Configuration config, byte[] tableName) { try { return new HTable(tableName, HConnectionManager.getConnection(config), threadPool); } catch (ZooKeeperConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }); HaeinsaTransactionManager tm = new HaeinsaTransactionManager(tablePool); HaeinsaTableInterface testTable = tablePool.getTable("test"); // Test 2 puts tx HaeinsaTransaction tx = tm.begin(); HaeinsaPut put = new HaeinsaPut(Bytes.toBytes("ymkim")); put.add(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber"), Bytes.toBytes("010-1234-5678")); testTable.put(tx, put); HaeinsaPut testPut = new HaeinsaPut(Bytes.toBytes("kjwoo")); testPut.add(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber"), Bytes.toBytes("010-9876-5432")); testTable.put(tx, testPut); tx.commit(); tx = tm.begin(); HaeinsaGet get = new HaeinsaGet(Bytes.toBytes("ymkim")); HaeinsaResult result = testTable.get(tx, get); HaeinsaGet get2 = new HaeinsaGet(Bytes.toBytes("kjwoo")); HaeinsaResult result2 = testTable.get(tx, get2); tx.rollback(); assertArrayEquals(result.getValue(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber")), Bytes.toBytes("010-1234-5678")); assertArrayEquals(result2.getValue(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber")), Bytes.toBytes("010-9876-5432")); tx = tm.begin(); put = new HaeinsaPut(Bytes.toBytes("ymkim")); put.add(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber"), Bytes.toBytes("010-9876-5432")); testTable.put(tx, put); testPut = new HaeinsaPut(Bytes.toBytes("kjwoo")); testPut.add(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber"), Bytes.toBytes("010-1234-5678")); testTable.put(tx, testPut); tx.commit(); tx = tm.begin(); get = new HaeinsaGet(Bytes.toBytes("ymkim")); result = testTable.get(tx, get); get2 = new HaeinsaGet(Bytes.toBytes("kjwoo")); result2 = testTable.get(tx, get2); tx.rollback(); assertArrayEquals(result2.getValue(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber")), Bytes.toBytes("010-1234-5678")); assertArrayEquals(result.getValue(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber")), Bytes.toBytes("010-9876-5432")); tx = tm.begin(); HaeinsaScan scan = new HaeinsaScan(); HaeinsaResultScanner scanner = testTable.getScanner(tx, scan); result = scanner.next(); result2 = scanner.next(); HaeinsaResult result3 = scanner.next(); assertNull(result3); assertArrayEquals(result.getValue(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber")), Bytes.toBytes("010-1234-5678")); assertArrayEquals(result2.getValue(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber")), Bytes.toBytes("010-9876-5432")); scanner.close(); tx.rollback(); tx = tm.begin(); put = new HaeinsaPut(Bytes.toBytes("ymkim")); put.add(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber"), Bytes.toBytes("010-1234-5678")); testTable.put(tx, put); testPut = new HaeinsaPut(Bytes.toBytes("kjwoo")); testPut.add(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber"), Bytes.toBytes("010-9876-5432")); testTable.put(tx, testPut); scan = new HaeinsaScan(); scanner = testTable.getScanner(tx, scan); result = scanner.next(); result2 = scanner.next(); result3 = scanner.next(); assertNull(result3); assertArrayEquals(result.getValue(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber")), Bytes.toBytes("010-9876-5432")); assertArrayEquals(result2.getValue(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber")), Bytes.toBytes("010-1234-5678")); scanner.close(); tx.rollback(); tx = tm.begin(); put = new HaeinsaPut(Bytes.toBytes("ymkim")); put.add(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber"), Bytes.toBytes("010-1234-5678")); testTable.put(tx, put); testPut = new HaeinsaPut(Bytes.toBytes("kjwoo")); testPut.add(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber"), Bytes.toBytes("010-9876-5432")); testTable.put(tx, testPut); scan = new HaeinsaScan(); scan.setStartRow(Bytes.toBytes("kjwoo")); scan.setStopRow(Bytes.toBytes("ymkim")); scanner = testTable.getScanner(tx, scan); result = scanner.next(); result2 = scanner.next(); assertArrayEquals(result.getValue(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber")), Bytes.toBytes("010-9876-5432")); assertNull(result2); scanner.close(); tx.rollback(); tx = tm.begin(); HaeinsaDelete delete1 = new HaeinsaDelete(Bytes.toBytes("ymkim")); delete1.deleteFamily(Bytes.toBytes("data")); HaeinsaDelete delete2 = new HaeinsaDelete(Bytes.toBytes("kjwoo")); delete2.deleteColumns(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber")); testTable.delete(tx, delete1); testTable.delete(tx, delete2); testPut = new HaeinsaPut(Bytes.toBytes("kjwoo")); testPut.add(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber"), Bytes.toBytes("010-9876-5432")); testTable.put(tx, testPut); scan = new HaeinsaScan(); scanner = testTable.getScanner(tx, scan); result = scanner.next(); result2 = scanner.next(); assertNull(result2); assertArrayEquals(result.getValue(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber")), Bytes.toBytes("010-9876-5432")); scanner.close(); tx.commit(); tx = tm.begin(); get = new HaeinsaGet(Bytes.toBytes("ymkim")); result = testTable.get(tx, get); get2 = new HaeinsaGet(Bytes.toBytes("kjwoo")); result2 = testTable.get(tx, get2); tx.rollback(); assertArrayEquals(result2.getValue(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber")), Bytes.toBytes("010-9876-5432")); assertTrue(result.isEmpty()); assertFalse(result2.isEmpty()); tx = tm.begin(); put = new HaeinsaPut(Bytes.toBytes("ymkim")); put.add(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber"), Bytes.toBytes("010-9876-5432")); testTable.put(tx, put); testPut = new HaeinsaPut(Bytes.toBytes("kjwoo")); testPut.add(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber"), Bytes.toBytes("010-1234-5678")); testTable.put(tx, testPut); tx.commit(); tx = tm.begin(); get = new HaeinsaGet(Bytes.toBytes("ymkim")); result = testTable.get(tx, get); get2 = new HaeinsaGet(Bytes.toBytes("kjwoo")); result2 = testTable.get(tx, get2); tx.rollback(); assertArrayEquals(result2.getValue(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber")), Bytes.toBytes("010-1234-5678")); assertArrayEquals(result.getValue(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber")), Bytes.toBytes("010-9876-5432")); tx = tm.begin(); delete1 = new HaeinsaDelete(Bytes.toBytes("ymkim")); delete1.deleteFamily(Bytes.toBytes("data")); delete2 = new HaeinsaDelete(Bytes.toBytes("kjwoo")); delete2.deleteColumns(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber")); testTable.delete(tx, delete1); testTable.delete(tx, delete2); tx.commit(); // test Table-cross transaction & multi-Column transaction tx = tm.begin(); HaeinsaTableInterface logTable = tablePool.getTable("log"); put = new HaeinsaPut(Bytes.toBytes("previousTime")); put.add(Bytes.toBytes("raw"), Bytes.toBytes("time-0"), Bytes.toBytes("log-value-1")); logTable.put(tx, put); put = new HaeinsaPut(Bytes.toBytes("row-0")); put.add(Bytes.toBytes("data"), Bytes.toBytes("time-0"), Bytes.toBytes("data-value-1")); put.add(Bytes.toBytes("meta"), Bytes.toBytes("time-0"), Bytes.toBytes("meta-value-1")); testTable.put(tx, put); tx.commit(); // check tx result tx = tm.begin(); get = new HaeinsaGet(Bytes.toBytes("previousTime")); get.addColumn(Bytes.toBytes("raw"), Bytes.toBytes("time-0")); assertArrayEquals(logTable.get(tx, get).getValue(Bytes.toBytes("raw"), Bytes.toBytes("time-0")), Bytes.toBytes("log-value-1")); get = new HaeinsaGet(Bytes.toBytes("row-0")); get.addColumn(Bytes.toBytes("data"), Bytes.toBytes("time-0")); assertArrayEquals(testTable.get(tx, get).getValue(Bytes.toBytes("data"), Bytes.toBytes("time-0")), Bytes.toBytes("data-value-1")); get = new HaeinsaGet(Bytes.toBytes("row-0")); get.addColumn(Bytes.toBytes("meta"), Bytes.toBytes("time-0")); assertArrayEquals(testTable.get(tx, get).getValue(Bytes.toBytes("meta"), Bytes.toBytes("time-0")), Bytes.toBytes("meta-value-1")); tx.rollback(); // clear test - table tx = tm.begin(); scan = new HaeinsaScan(); scanner = testTable.getScanner(tx, scan); Iterator<HaeinsaResult> iter = scanner.iterator(); while(iter.hasNext()){ result = iter.next(); for(HaeinsaKeyValue kv : result.list()){ kv.getRow(); // delete specific kv HaeinsaDelete delete = new HaeinsaDelete(kv.getRow()); delete.deleteColumns(kv.getFamily(), kv.getQualifier()); testTable.delete(tx, delete); } } tx.commit(); scanner.close(); // clear log - table tx = tm.begin(); scan = new HaeinsaScan(); scanner = logTable.getScanner(tx, scan); iter = scanner.iterator(); while(iter.hasNext()){ result = iter.next(); for(HaeinsaKeyValue kv : result.list()){ kv.getRow(); // delete specific kv HaeinsaDelete delete = new HaeinsaDelete(kv.getRow()); delete.deleteColumns(kv.getFamily(), kv.getQualifier()); logTable.delete(tx, delete); } } tx.commit(); scanner.close(); // check whether table is clear - testTable tx = tm.begin(); scan = new HaeinsaScan(); scanner = testTable.getScanner(tx, scan); iter = scanner.iterator(); assertFalse(iter.hasNext()); tx.rollback(); scanner.close(); // check whether table is clear - logTable tx = tm.begin(); scan = new HaeinsaScan(); scanner = logTable.getScanner(tx, scan); iter = scanner.iterator(); assertFalse(iter.hasNext()); tx.rollback(); scanner.close(); testTable.close(); logTable.close(); tablePool.close(); } @Test public void testConflictAndAbort() throws Exception { final ExecutorService threadPool = Executors.newCachedThreadPool(); HaeinsaTablePool tablePool = new HaeinsaTablePool(CONF, 128, new HTableInterfaceFactory() { @Override public void releaseHTableInterface(HTableInterface table) throws IOException { table.close(); } @Override public HTableInterface createHTableInterface(Configuration config, byte[] tableName) { try { return new HTable(tableName, HConnectionManager.getConnection(config), threadPool); } catch (ZooKeeperConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }); HaeinsaTransactionManager tm = new HaeinsaTransactionManager(tablePool); HaeinsaTableInterface testTable = tablePool.getTable("test"); HaeinsaTransaction tx = tm.begin(); HaeinsaTransaction tx2 = tm.begin(); HaeinsaPut put = new HaeinsaPut(Bytes.toBytes("ymkim")); put.add(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber"), Bytes.toBytes("010-9876-5432")); HaeinsaPut put2 = new HaeinsaPut(Bytes.toBytes("kjwoo")); put2.add(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber"), Bytes.toBytes("010-1234-5678")); testTable.put(tx, put); testTable.put(tx, put2); testTable.put(tx2, put); tx2.commit(); try{ tx.commit(); assertTrue(false); }catch(Exception e){ assertTrue(e instanceof ConflictException); } tx = tm.begin(); HaeinsaScan scan = new HaeinsaScan(); HaeinsaResultScanner scanner = testTable.getScanner(tx, scan); HaeinsaResult result = scanner.next(); HaeinsaResult result2 = scanner.next(); assertNull(result2); assertArrayEquals(result.getValue(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber")), Bytes.toBytes("010-9876-5432")); assertArrayEquals(result.getRow(), Bytes.toBytes("ymkim")); scanner.close(); tx.rollback(); tx = tm.begin(); put = new HaeinsaPut(Bytes.toBytes("ymkim")); put.add(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber"), Bytes.toBytes("010-1234-5678")); put2 = new HaeinsaPut(Bytes.toBytes("kjwoo")); put2.add(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber"), Bytes.toBytes("010-9876-5432")); testTable.put(tx, put); testTable.put(tx, put2); tx.commit(); tx = tm.begin(); scan = new HaeinsaScan(); scanner = testTable.getScanner(tx, scan); result = scanner.next(); result2 = scanner.next(); HaeinsaResult result3 = scanner.next(); assertNull(result3); assertArrayEquals(result.getValue(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber")), Bytes.toBytes("010-9876-5432")); assertArrayEquals(result.getRow(), Bytes.toBytes("kjwoo")); assertArrayEquals(result2.getValue(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber")), Bytes.toBytes("010-1234-5678")); assertArrayEquals(result2.getRow(), Bytes.toBytes("ymkim")); scanner.close(); tx.rollback(); tx = tm.begin(); HaeinsaDelete delete1 = new HaeinsaDelete(Bytes.toBytes("ymkim")); delete1.deleteFamily(Bytes.toBytes("data")); HaeinsaDelete delete2 = new HaeinsaDelete(Bytes.toBytes("kjwoo")); delete2.deleteColumns(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber")); testTable.delete(tx, delete1); testTable.delete(tx, delete2); tx.commit(); testTable.close(); tablePool.close(); } @Test public void testConflictAndRecover() throws Exception { final ExecutorService threadPool = Executors.newCachedThreadPool(); HaeinsaTablePool tablePool = new HaeinsaTablePool(CONF, 128, new HTableInterfaceFactory() { @Override public void releaseHTableInterface(HTableInterface table) throws IOException { table.close(); } @Override public HTableInterface createHTableInterface(Configuration config, byte[] tableName) { try { return new HTable(tableName, HConnectionManager.getConnection(config), threadPool); } catch (ZooKeeperConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }); HaeinsaTransactionManager tm = new HaeinsaTransactionManager(tablePool); HaeinsaTable testTable = (HaeinsaTable) tablePool.getTable("test"); HaeinsaTransaction tx = tm.begin(); HaeinsaTransaction tx2 = tm.begin(); HaeinsaPut put = new HaeinsaPut(Bytes.toBytes("ymkim")); put.add(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber"), Bytes.toBytes("010-9876-5432")); HaeinsaPut put2 = new HaeinsaPut(Bytes.toBytes("kjwoo")); put2.add(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber"), Bytes.toBytes("010-1234-5678")); testTable.put(tx, put); testTable.put(tx, put2); testTable.put(tx2, put); HaeinsaTableTransaction tableState = tx2.createOrGetTableState(Bytes.toBytes("test")); HaeinsaRowTransaction rowState = tableState.createOrGetRowState(Bytes.toBytes("ymkim")); tx2.setPrewriteTimestamp(rowState.getCurrent().getCommitTimestamp() + 1); tx2.setCommitTimestamp(rowState.getCurrent().getCommitTimestamp() + 1); testTable.prewrite(rowState, Bytes.toBytes("ymkim"), true); try{ tx.commit(); assertTrue(false); }catch(Exception e){ assertTrue(e instanceof ConflictException); } tx = tm.begin(); try{ HaeinsaScan scan = new HaeinsaScan(); HaeinsaResultScanner scanner = testTable.getScanner(tx, scan); HaeinsaResult result = scanner.next(); HaeinsaResult result2 = scanner.next(); assertNull(result2); assertArrayEquals(result.getValue(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber")), Bytes.toBytes("010-9876-5432")); assertArrayEquals(result.getRow(), Bytes.toBytes("ymkim")); scanner.close(); tx.rollback(); assertTrue(false); }catch(Exception e){ assertTrue(e instanceof ConflictException); } Thread.sleep(HaeinsaConstants.ROW_LOCK_TIMEOUT + 100); try{ tx = tm.begin(); HaeinsaScan scan = new HaeinsaScan(); HaeinsaResultScanner scanner = testTable.getScanner(tx, scan); HaeinsaResult result = scanner.next(); assertNull(result); scanner.close(); }catch(Exception e) { assertTrue(false); } tx = tm.begin(); HaeinsaScan scan = new HaeinsaScan(); HaeinsaResultScanner scanner = testTable.getScanner(tx, scan); HaeinsaResult result = scanner.next(); assertNull(result); scanner.close(); put = new HaeinsaPut(Bytes.toBytes("ymkim")); put.add(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber"), Bytes.toBytes("010-1234-5678")); put2 = new HaeinsaPut(Bytes.toBytes("kjwoo")); put2.add(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber"), Bytes.toBytes("010-9876-5432")); testTable.put(tx, put); testTable.put(tx, put2); tx.commit(); tx = tm.begin(); scan = new HaeinsaScan(); scanner = testTable.getScanner(tx, scan); result = scanner.next(); HaeinsaResult result2 = scanner.next(); HaeinsaResult result3 = scanner.next(); assertNull(result3); assertArrayEquals(result.getValue(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber")), Bytes.toBytes("010-9876-5432")); assertArrayEquals(result.getRow(), Bytes.toBytes("kjwoo")); assertArrayEquals(result2.getValue(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber")), Bytes.toBytes("010-1234-5678")); assertArrayEquals(result2.getRow(), Bytes.toBytes("ymkim")); scanner.close(); tx.rollback(); tx = tm.begin(); HaeinsaDelete delete1 = new HaeinsaDelete(Bytes.toBytes("ymkim")); delete1.deleteFamily(Bytes.toBytes("data")); HaeinsaDelete delete2 = new HaeinsaDelete(Bytes.toBytes("kjwoo")); delete2.deleteColumns(Bytes.toBytes("data"), Bytes.toBytes("phoneNumber")); testTable.delete(tx, delete1); testTable.delete(tx, delete2); tx.commit(); testTable.close(); tablePool.close(); } }
package manon.util.basetest; import io.restassured.RestAssured; import io.restassured.response.Response; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import manon.Application; import manon.app.Cfg; import manon.document.user.User; import manon.err.user.UserExistsException; import manon.err.user.UserNotFoundException; import manon.service.app.AppTraceService; import manon.service.app.PerformanceRecorder; import manon.service.app.PingService; import manon.service.batch.JobRunnerService; import manon.service.user.FriendshipEventService; import manon.service.user.FriendshipRequestService; import manon.service.user.FriendshipService; import manon.service.user.PasswordEncoderService; import manon.service.user.RegistrationService; import manon.service.user.UserService; import manon.service.user.UserSnapshotService; import manon.service.user.UserStatsService; import manon.util.Tools; import manon.util.web.Page; import manon.util.web.Rs; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import org.mockito.Mockito; import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener; import org.springframework.boot.test.mock.mockito.SpyBean; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import java.io.IOException; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import static io.restassured.config.EncoderConfig.encoderConfig; import static java.lang.System.currentTimeMillis; import static manon.util.Tools.Mdc.KEY_ENV; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; /** * Base for integration tests. * Application starts with some users and one admin. Data is recreated before test methods. */ @Slf4j @TestInstance(TestInstance.Lifecycle.PER_CLASS) @Execution(value = ExecutionMode.SAME_THREAD) @SpringBootTest(classes = Application.class, webEnvironment = RANDOM_PORT) @TestExecutionListeners(listeners = {DependencyInjectionTestExecutionListener.class, MockitoTestExecutionListener.class}) public abstract class AbstractIT { @LocalServerPort private int port; @Autowired(required = false) protected PerformanceRecorder performanceRecorder; @Autowired protected Cfg cfg; @SpyBean protected AppTraceService appTraceService; @SpyBean protected FriendshipService friendshipService; @SpyBean protected FriendshipEventService friendshipEventService; @SpyBean protected FriendshipRequestService friendshipRequestService; @SpyBean protected JobRunnerService jobRunnerService; @SpyBean protected PasswordEncoderService passwordEncoderService; @SpyBean protected PingService pingService; @SpyBean protected RegistrationService registrationService; @SpyBean protected UserDetailsService userDetailsService; @SpyBean protected UserService userService; @SpyBean protected UserSnapshotService userSnapshotService; @SpyBean protected UserStatsService userStatsService; private final String API_V1 = "/api/v1"; public final String API_USER = API_V1 + "/user"; public final String API_USER_ADMIN = API_V1 + "/admin/user"; public final String API_SYS = API_V1 + "/sys"; public static final String MANAGED_ERROR_TYPE = "errorType"; public static final String VALIDATION_ERRORS_MSG = "errors.defaultMessage"; /** Simply a new unique objectId. */ public final long UNKNOWN_ID = Long.MAX_VALUE; public final String UNKNOWN_USER_NAME = "u" + UNKNOWN_ID; /** Number of times to start a batch to ensure its repeatability. */ public final int NB_TESTS_TO_ENSURE_BATCH_REPEATABILITY = 3; /** Number of batch chunks to process to ensure its reliability. */ public final int NB_BATCH_CHUNKS_TO_ENSURE_RELIABILITY = 3; protected final Map<Integer, Long> userIdCache = new HashMap<>(); public int userCount; public int getNumberOfUsers() { return 2; } /** Clear data before test class. Do NOT override it in non-abstract test classes. */ @BeforeAll public final void beforeClass() { RestAssured.config.encoderConfig(encoderConfig().defaultContentCharset(StandardCharsets.UTF_8)); RestAssured.baseURI = "http://localhost"; RestAssured.port = port; } /** Clear data before each test method. */ @BeforeEach public void clearData() throws Exception { userIdCache.clear(); initDb(); Mockito.clearInvocations(pingService); } private void clearDb() { appTraceService.deleteAll(); friendshipEventService.deleteAll(); friendshipRequestService.deleteAll(); friendshipService.deleteAll(); userSnapshotService.deleteAll(); userStatsService.deleteAll(); userService.deleteAll(); } public void initDb() throws UserExistsException, UserNotFoundException { long t1 = currentTimeMillis(); MDC.put(KEY_ENV, "junit"); clearDb(); registrationService.ensureActuator(); registrationService.ensureAdmin(); registrationService.ensureDev(); for (int idx = 0; idx < getNumberOfUsers(); idx++) { registrationService.registerPlayer(makeName(idx), makePwd(idx)); } additionalInitDb(); userCount = (int) userService.count(); log.debug("initDb from class {} took {} ms", this.getClass().getSimpleName(), currentTimeMillis() - t1); MDC.clear(); } /** Override do add logic that occurs at the end of the {@link #initDb()}. */ public void additionalInitDb() throws UserExistsException, UserNotFoundException { // override if needed } private String makeName(int idx) { return "USERNAME" + idx; } private String makePwd(int idx) { return "p4ssw0rd" + idx; } @AfterAll public final void afterClass() { MDC.put(KEY_ENV, "junit"); if (performanceRecorder != null && !performanceRecorder.getStats().isEmpty()) { log.info(performanceRecorder.getStats()); } logGCStats(); MDC.clear(); } private void logGCStats() { long totalGarbageCollections = 0; long garbageCollectionTime = 0; for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) { totalGarbageCollections += gc.getCollectionCount(); garbageCollectionTime += gc.getCollectionTime(); } long uptime = ManagementFactory.getRuntimeMXBean().getUptime(); long gcActivityRatio = (garbageCollectionTime * 100) / uptime; log.info("GC stats:\n - total GC collections: {}\n - total GC collection time: {}ms (activity ratio: {}%)\n - JVM uptime: {}ms\n", totalGarbageCollections, garbageCollectionTime, gcActivityRatio, uptime); assertThat(gcActivityRatio).as("GC pressure should be low (less than 10% execution time)").isLessThan(10); } // Helpers: get generated test users and authenticate with their credentials public final Rs whenAnonymous() { return new Rs(RestAssured.given() .header("X-Request-Id", "anon-" + currentTimeMillis()) .auth().none(), "", ""); } public final Rs whenAuthenticated(String username, String password) { return new Rs(RestAssured.given() .header("X-Request-Id", "user-" + currentTimeMillis()) .auth().preemptive().basic(username, password), username, password); } public final Rs whenActuator() { return whenAuthenticated(cfg.getDefaultUserActuatorUsername(), cfg.getDefaultUserActuatorPassword()); } public final Rs whenAdmin() { return whenAuthenticated(cfg.getDefaultUserAdminUsername(), cfg.getDefaultUserAdminPassword()); } public final Rs whenDev() { return whenAuthenticated(cfg.getDefaultUserDevUsername(), cfg.getDefaultUserDevPassword()); } public final Rs whenPX(int humanId) { int idx = humanId - 1; return whenAuthenticated(makeName(idx), makePwd(idx)); } /** When player 1. */ public final Rs whenP1() { return whenPX(1); } /** When player 2. */ public final Rs whenP2() { return whenPX(2); } /** When player 3. */ public final Rs whenP3() { return whenPX(3); } @SuppressWarnings("SameParameterValue") public final String pwd(int humanId) { return makePwd(humanId - 1); } @SuppressWarnings("SameParameterValue") public final String name(int humanId) { return makeName(humanId - 1); } @SneakyThrows(UserNotFoundException.class) public final User user(int humanId) { return userService.readByUsername(name(humanId)); } @SuppressWarnings("SameParameterValue") @SneakyThrows(UserNotFoundException.class) public final long userId(int humanId) { return findAndCacheUserIdByIdx(humanId - 1); } private long findAndCacheUserIdByIdx(int idx) throws UserNotFoundException { if (!userIdCache.containsKey(idx)) { userIdCache.put(idx, userService.readIdByUsername(makeName(idx)).getId()); } return userIdCache.get(idx); } // Utils /** Convert single object to JSON. */ @SneakyThrows(IOException.class) public final <T> T readValue(Response content, Class<T> valueType) { return Tools.JSON.readValue(content.asString(), valueType); } /** Convert generic paged objects to JSON. */ @SneakyThrows(IOException.class) public final <T> Page<T> readPage(Response content, Class<T> parameterClass) { return Tools.JSON.readValue(content.asString(), Tools.JSON.getTypeFactory().constructParametricType(Page.class, parameterClass)); } /** Compute a long string. */ public final String verylongString(String base) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 500; i++) { sb.append(base); } return sb.toString(); } }
package net.sf.katta; import java.io.IOException; import java.util.concurrent.TimeUnit; import net.sf.katta.master.Master; import net.sf.katta.node.Node; import net.sf.katta.testutil.ExtendedTestCase; import net.sf.katta.util.KattaException; import net.sf.katta.util.NetworkUtil; import net.sf.katta.util.NodeConfiguration; import net.sf.katta.util.ZkConfiguration; import net.sf.katta.zk.ZKClient; import net.sf.katta.zk.ZkPathes; import net.sf.katta.zk.ZkServer; import net.sf.katta.zk.ZKClient.ZkLock; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.ipc.RPC; import com.yahoo.zookeeper.ZooKeeper; import com.yahoo.zookeeper.ZooKeeper.States; /** * Basic katta test which provides some methods for starting master and nodes. * Also it always have a zk-server running. * */ public abstract class AbstractKattaTest extends ExtendedTestCase { private static ZkServer _zkServer; protected final ZkConfiguration _conf = new ZkConfiguration(); private final boolean _resetZkNamespaceBetweenTests; public AbstractKattaTest() { this(true); } public AbstractKattaTest(boolean resetZkNamespaceBetweenTests) { _resetZkNamespaceBetweenTests = resetZkNamespaceBetweenTests; } @Override protected final void beforeClass() throws Exception { cleanZookeeperData(_conf); startZkServer(); resetZkNamespace(); onBeforeClass(); } @Override protected final void afterClass() throws Exception { onAfterClass(); stopZkServer(); cleanZookeeperData(_conf); RPC.stopClient(); } @Override protected final void onSetUp() throws Exception { if (_resetZkNamespaceBetweenTests) { resetZkNamespace(); } onSetUp2(); } private void resetZkNamespace() throws KattaException { ZKClient zkClient = new ZKClient(_conf); zkClient.start(10000); if (zkClient.exists(ZkPathes.ROOT_PATH)) { zkClient.deleteRecursive(ZkPathes.ROOT_PATH); } zkClient.createDefaultNameSpace(); zkClient.close(); } protected void onBeforeClass() throws Exception { // subclasses may override } protected void onAfterClass() throws Exception { // subclasses may override } protected void onSetUp2() throws Exception { // subclasses may override } protected static void cleanZookeeperData(final ZkConfiguration configuration) throws IOException { FileUtil.fullyDelete(configuration.getZKDataDir()); FileUtil.fullyDelete(configuration.getZKDataLogDir()); FileUtil.fullyDelete(new NodeConfiguration().getShardFolder()); } protected void startZkServer() throws KattaException { if (_zkServer != null) { throw new IllegalStateException("zk server already running"); } if (!NetworkUtil.isPortFree(ZkServer.DEFAULT_PORT)) { throw new IllegalStateException("port " + ZkServer.DEFAULT_PORT + " blocked. Probably other zk server is running."); } _zkServer = new ZkServer(_conf); } protected void stopZkServer() { if (_zkServer != null) { _zkServer.shutdown(); int waitingTimes = 0; try { while (!NetworkUtil.isPortFree(ZkServer.DEFAULT_PORT)) { if (waitingTimes > 4) { throw new IllegalStateException("zk server did not freed it port"); } Thread.sleep(500); waitingTimes++; } } catch (InterruptedException e) { // proceed } _zkServer = null; } } protected MasterStartThread startMaster() throws KattaException { ZKClient zkMasterClient = new ZKClient(_conf); Master master = new Master(zkMasterClient); MasterStartThread masterStartThread = new MasterStartThread(master, zkMasterClient); masterStartThread.start(); return masterStartThread; } protected NodeStartThread startNode() { return startNode(new NodeConfiguration().getShardFolder().getAbsolutePath()); } protected NodeStartThread startNode(String shardFolder) { ZKClient zkNodeClient = new ZKClient(_conf); NodeConfiguration nodeConf = new NodeConfiguration(); nodeConf.setShardFolder(shardFolder); Node node = new Node(zkNodeClient, nodeConf); NodeStartThread nodeStartThread = new NodeStartThread(node, zkNodeClient); nodeStartThread.start(); return nodeStartThread; } protected void waitForStatus(ZKClient client, ZooKeeper.States state) throws Exception { waitForStatus(client, state, _conf.getZKTimeOut()); } protected void waitForStatus(ZKClient client, States state, long timeout) throws Exception { long maxWait = System.currentTimeMillis() + timeout; while ((maxWait > System.currentTimeMillis()) && (client.getZookeeperState() == null || client.getZookeeperState() != state)) { Thread.sleep(500); } assertEquals(state, client.getZookeeperState()); } public static void waitForPath(final ZKClient client, final String path) throws KattaException, InterruptedException { int tryCount = 0; while (!client.exists(path) && tryCount++ < 100) { Thread.sleep(500); } assertTrue("path '" + path + "' does not exists", client.exists(path)); } public static void waitForChilds(final ZKClient client, final String path, final int childCount) throws InterruptedException, KattaException { int tryCount = 0; while (client.getChildren(path).size() != childCount && tryCount++ < 100) { Thread.sleep(500); } assertEquals(childCount, client.getChildren(path).size()); } protected void waitOnNodes(MasterStartThread masterThread, int nodeCount) throws InterruptedException { long startWait = System.currentTimeMillis(); ZKClient zkClient = masterThread.getZkClient(); ZkLock eventLock = zkClient.getEventLock(); eventLock.lock(); while (masterThread.getMaster().getNodes().size() != nodeCount) { if (System.currentTimeMillis() - startWait > 1000 * 60) { break; } eventLock.getDataChangedCondition().await(10, TimeUnit.SECONDS); } eventLock.unlock(); assertEquals(nodeCount, masterThread.getMaster().getNodes().size()); } protected class MasterStartThread extends Thread { private final Master _master; private final ZKClient _zkMasterClient; public MasterStartThread(Master master, ZKClient zkMasterClient) { _master = master; _zkMasterClient = zkMasterClient; } public Master getMaster() { return _master; } public ZKClient getZkClient() { return _zkMasterClient; } public void run() { try { _master.start(); _master.joinLeaveSafeMode(); } catch (Exception e) { e.printStackTrace(); } } public void shutdown() { _master.shutdown(); } } protected class NodeStartThread extends Thread { private final Node _node; private final ZKClient _client; public NodeStartThread(Node node, ZKClient client) { _node = node; _client = client; } public Node getNode() { return _node; } public ZKClient getZkClient() { return _client; } public void run() { try { _node.start(); } catch (KattaException e) { e.printStackTrace(); } } public void shutdown() { _node.shutdown(); _node.shutdown(); try { int tryCount = 0; int maxTries = 100; while (!NetworkUtil.isPortFree(_node.getSearchServerPort())) { Thread.sleep(100); tryCount++; if (tryCount >= maxTries) { fail("node shutdown but port " + _node.getSearchServerPort() + " is still blocked"); } } } catch (InterruptedException e) { // proceed } } } }
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); if (a instanceof Copyable<?>) { final Object b = ((Copyable<?>)a).copy(); if (a.getClass() == b.getClass()) { 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.jfree.chart; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.GradientPaint; import java.awt.RenderingHints; import java.util.List; import org.jfree.chart.event.ChartChangeEvent; import org.jfree.chart.event.ChartChangeListener; import org.jfree.chart.plot.PiePlot; import org.jfree.chart.plot.RingPlot; import org.jfree.chart.title.LegendTitle; import org.jfree.chart.title.TextTitle; import org.jfree.chart.title.Title; import org.jfree.chart.ui.Align; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.ui.RectangleInsets; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.general.DefaultPieDataset; import org.jfree.data.time.Day; import org.jfree.data.time.RegularTimePeriod; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; /** * Tests for the {@link JFreeChart} class. */ public class JFreeChartTest implements ChartChangeListener { /** A pie chart. */ private JFreeChart pieChart; /** * Common test setup. */ @Before public void setUp() { DefaultPieDataset data = new DefaultPieDataset(); data.setValue("Java", 43.2); data.setValue("Visual Basic", 0.0); data.setValue("C/C++", 17.5); this.pieChart = ChartFactory.createPieChart("Pie Chart", data); } /** * Check that the equals() method can distinguish all fields. */ @Test public void testEquals() { JFreeChart chart1 = new JFreeChart("Title", new Font("SansSerif", Font.PLAIN, 12), new PiePlot(), true); JFreeChart chart2 = new JFreeChart("Title", new Font("SansSerif", Font.PLAIN, 12), new PiePlot(), true); assertEquals(chart1, chart2); assertEquals(chart2, chart1); // renderingHints chart1.setRenderingHints(new RenderingHints( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON)); assertFalse(chart1.equals(chart2)); chart2.setRenderingHints(new RenderingHints( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON)); assertEquals(chart1, chart2); // borderVisible chart1.setBorderVisible(true); assertFalse(chart1.equals(chart2)); chart2.setBorderVisible(true); assertEquals(chart1, chart2); // borderStroke BasicStroke s = new BasicStroke(2.0f); chart1.setBorderStroke(s); assertFalse(chart1.equals(chart2)); chart2.setBorderStroke(s); assertEquals(chart1, chart2); // borderPaint chart1.setBorderPaint(Color.RED); assertFalse(chart1.equals(chart2)); chart2.setBorderPaint(Color.RED); assertEquals(chart1, chart2); // padding chart1.setPadding(new RectangleInsets(1, 2, 3, 4)); assertFalse(chart1.equals(chart2)); chart2.setPadding(new RectangleInsets(1, 2, 3, 4)); assertEquals(chart1, chart2); // title chart1.setTitle("XYZ"); assertFalse(chart1.equals(chart2)); chart2.setTitle("XYZ"); assertEquals(chart1, chart2); // subtitles chart1.addSubtitle(new TextTitle("Subtitle")); assertFalse(chart1.equals(chart2)); chart2.addSubtitle(new TextTitle("Subtitle")); assertEquals(chart1, chart2); // plot chart1 = new JFreeChart("Title", new Font("SansSerif", Font.PLAIN, 12), new RingPlot(), false); chart2 = new JFreeChart("Title", new Font("SansSerif", Font.PLAIN, 12), new PiePlot(), false); assertFalse(chart1.equals(chart2)); chart2 = new JFreeChart("Title", new Font("SansSerif", Font.PLAIN, 12), new RingPlot(), false); assertEquals(chart1, chart2); // backgroundPaint chart1.setBackgroundPaint(new GradientPaint(1.0f, 2.0f, Color.RED, 3.0f, 4.0f, Color.BLUE)); assertFalse(chart1.equals(chart2)); chart2.setBackgroundPaint(new GradientPaint(1.0f, 2.0f, Color.RED, 3.0f, 4.0f, Color.BLUE)); assertEquals(chart1, chart2); // // backgroundImage // chart1.setBackgroundImage(JFreeChart.INFO.getLogo()); // assertFalse(chart1.equals(chart2)); // chart2.setBackgroundImage(JFreeChart.INFO.getLogo()); // assertEquals(chart1, chart2); // backgroundImageAlignment chart1.setBackgroundImageAlignment(Align.BOTTOM_LEFT); assertFalse(chart1.equals(chart2)); chart2.setBackgroundImageAlignment(Align.BOTTOM_LEFT); assertEquals(chart1, chart2); // backgroundImageAlpha chart1.setBackgroundImageAlpha(0.1f); assertFalse(chart1.equals(chart2)); chart2.setBackgroundImageAlpha(0.1f); assertEquals(chart1, chart2); } /** * A test to make sure that the legend is being picked up in the * equals() testing. */ @Test public void testEquals2() { JFreeChart chart1 = new JFreeChart("Title", new Font("SansSerif", Font.PLAIN, 12), new PiePlot(), true); JFreeChart chart2 = new JFreeChart("Title", new Font("SansSerif", Font.PLAIN, 12), new PiePlot(), false); assertFalse(chart1.equals(chart2)); assertFalse(chart2.equals(chart1)); } /** * Checks the subtitle count - should be 1 (the legend). */ @Test public void testSubtitleCount() { int count = this.pieChart.getSubtitleCount(); assertEquals(1, count); } /** * Some checks for the getSubtitle() method. */ @Test public void testGetSubtitle() { DefaultPieDataset dataset = new DefaultPieDataset(); JFreeChart chart = ChartFactory.createPieChart("title", dataset); Title t = chart.getSubtitle(0); assertTrue(t instanceof LegendTitle); try { chart.getSubtitle(-1); fail("Should have thrown an IllegalArgumentException on negative number"); } catch (IllegalArgumentException e) { assertEquals("Index out of range.", e.getMessage()); } try { chart.getSubtitle(1); fail("Should have thrown an IllegalArgumentException on excesive number"); } catch (IllegalArgumentException e) { assertEquals("Index out of range.", e.getMessage()); } try { chart.getSubtitle(2); fail("Should have thrown an IllegalArgumentException on number being out of range"); } catch (IllegalArgumentException e) { assertEquals("Index out of range.", e.getMessage()); } } /** * Serialize a pie chart, restore it, and check for equality. */ @Test public void testSerialization1() { DefaultPieDataset data = new DefaultPieDataset(); data.setValue("Type 1", 54.5); data.setValue("Type 2", 23.9); data.setValue("Type 3", 45.8); JFreeChart c1 = ChartFactory.createPieChart("Test", data); JFreeChart c2 = (JFreeChart) TestUtils.serialised(c1); assertEquals(c1, c2); LegendTitle lt2 = c2.getLegend(); assertSame(lt2.getSources()[0], c2.getPlot()); } /** * Serialize a 3D pie chart, restore it, and check for equality. */ @Test public void testSerialization2() { DefaultPieDataset data = new DefaultPieDataset(); data.setValue("Type 1", 54.5); data.setValue("Type 2", 23.9); data.setValue("Type 3", 45.8); JFreeChart c1 = ChartFactory.createPieChart3D("Test", data); JFreeChart c2 = (JFreeChart) TestUtils.serialised(c1); assertEquals(c1, c2); } /** * Serialize a bar chart, restore it, and check for equality. */ @Test public void testSerialization3() { // row keys... String series1 = "First"; String series2 = "Second"; String series3 = "Third"; // column keys... String category1 = "Category 1"; String category2 = "Category 2"; String category3 = "Category 3"; String category4 = "Category 4"; String category5 = "Category 5"; String category6 = "Category 6"; String category7 = "Category 7"; String category8 = "Category 8"; // create the dataset... DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(1.0, series1, category1); dataset.addValue(4.0, series1, category2); dataset.addValue(3.0, series1, category3); dataset.addValue(5.0, series1, category4); dataset.addValue(5.0, series1, category5); dataset.addValue(7.0, series1, category6); dataset.addValue(7.0, series1, category7); dataset.addValue(8.0, series1, category8); dataset.addValue(5.0, series2, category1); dataset.addValue(7.0, series2, category2); dataset.addValue(6.0, series2, category3); dataset.addValue(8.0, series2, category4); dataset.addValue(4.0, series2, category5); dataset.addValue(4.0, series2, category6); dataset.addValue(2.0, series2, category7); dataset.addValue(1.0, series2, category8); dataset.addValue(4.0, series3, category1); dataset.addValue(3.0, series3, category2); dataset.addValue(2.0, series3, category3); dataset.addValue(3.0, series3, category4); dataset.addValue(6.0, series3, category5); dataset.addValue(3.0, series3, category6); dataset.addValue(4.0, series3, category7); dataset.addValue(3.0, series3, category8); // create the chart... JFreeChart c1 = ChartFactory.createBarChart("Vertical Bar Chart", "Category", "Value", dataset); JFreeChart c2 = (JFreeChart) TestUtils.serialised(c1); assertEquals(c1, c2); } /** * Serialize a time seroes chart, restore it, and check for equality. */ @Test public void testSerialization4() { RegularTimePeriod t = new Day(); TimeSeries series = new TimeSeries("Series 1"); series.add(t, 36.4); t = t.next(); series.add(t, 63.5); TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(series); JFreeChart c1 = ChartFactory.createTimeSeriesChart("Test", "Date", "Value", dataset); JFreeChart c2 = (JFreeChart) TestUtils.serialised(c1); assertEquals(c1, c2); } /** * Some checks for the addSubtitle() methods. */ @Test public void testAddSubtitle() { DefaultPieDataset dataset = new DefaultPieDataset(); JFreeChart chart = ChartFactory.createPieChart("title", dataset); TextTitle t0 = new TextTitle("T0"); chart.addSubtitle(0, t0); assertEquals(t0, chart.getSubtitle(0)); TextTitle t1 = new TextTitle("T1"); chart.addSubtitle(t1); assertEquals(t1, chart.getSubtitle(2)); // subtitle 1 is the legend try { chart.addSubtitle(null); fail("Should have thrown a NullPointerException."); } catch (NullPointerException e) { assertEquals("subtitle", e.getMessage()); } try { chart.addSubtitle(-1, t0); fail("Should have thrown an IllegalArgumentException on index out of range"); } catch (IllegalArgumentException e) { assertEquals("The 'index' argument is out of range.", e.getMessage()); } try { chart.addSubtitle(4, t0); fail("Should have thrown an IllegalArgumentException on index out of range"); } catch (IllegalArgumentException e) { assertEquals("The 'index' argument is out of range.", e.getMessage()); } } /** * Some checks for the getSubtitles() method. */ @Test public void testGetSubtitles() { DefaultPieDataset dataset = new DefaultPieDataset(); JFreeChart chart = ChartFactory.createPieChart("title", dataset); List<Title> subtitles = chart.getSubtitles(); assertEquals(1, chart.getSubtitleCount()); // adding something to the returned list should NOT change the chart subtitles.add(new TextTitle("T")); assertEquals(1, chart.getSubtitleCount()); } /** * Some checks for the default legend firing change events. */ @Test public void testLegendEvents() { DefaultPieDataset dataset = new DefaultPieDataset(); JFreeChart chart = ChartFactory.createPieChart("title", dataset); chart.addChangeListener(this); this.lastChartChangeEvent = null; LegendTitle legend = chart.getLegend(); legend.setPosition(RectangleEdge.TOP); assertNotNull(this.lastChartChangeEvent); } /** * Some checks for title changes and event notification. */ @Test public void testTitleChangeEvent() { DefaultPieDataset dataset = new DefaultPieDataset(); JFreeChart chart = ChartFactory.createPieChart("title", dataset); chart.addChangeListener(this); this.lastChartChangeEvent = null; TextTitle t = chart.getTitle(); t.setFont(new Font("Dialog", Font.BOLD, 9)); assertNotNull(this.lastChartChangeEvent); this.lastChartChangeEvent = null; // now create a new title and replace the existing title, several // things should happen: // (1) Adding the new title should trigger an immediate // ChartChangeEvent; // (2) Modifying the new title should trigger a ChartChangeEvent; // (3) Modifying the old title should NOT trigger a ChartChangeEvent TextTitle t2 = new TextTitle("T2"); chart.setTitle(t2); assertNotNull(this.lastChartChangeEvent); this.lastChartChangeEvent = null; t2.setFont(new Font("Dialog", Font.BOLD, 9)); assertNotNull(this.lastChartChangeEvent); this.lastChartChangeEvent = null; t.setFont(new Font("Dialog", Font.BOLD, 9)); assertNull(this.lastChartChangeEvent); this.lastChartChangeEvent = null; } @Test public void testBug942() throws Exception { final String title = "Pie Chart Demo 1\n\n\ntestnew line"; assertEquals(title, ChartFactory.createPieChart(title, new DefaultPieDataset()).getTitle().getText()); } /** The last ChartChangeEvent received. */ private ChartChangeEvent lastChartChangeEvent; /** * Records the last chart change event. * * @param event the event. */ @Override public void chartChanged(ChartChangeEvent event) { this.lastChartChangeEvent = event; } }
package picocli; import org.junit.Test; import picocli.CommandLine.Model.CaseAwareLinkedMap; import static org.junit.Assert.*; public class CaseAwareLinkedMapTest { @Test public void testDefaultCaseSensitivity() { assertFalse(new CaseAwareLinkedMap<String, String>().isCaseInsensitive()); } @Test public void testCaseSensitiveAddDuplicateElement() { CaseAwareLinkedMap<String, String> map = new CaseAwareLinkedMap<String, String>(); map.setCaseInsensitive(false); map.put("key", "value"); assertEquals(1, map.size()); assertTrue(map.containsKey("key")); assertFalse(map.containsKey("KEY")); assertTrue(map.containsValue("value")); Object replacedValue = map.put("Key", "VALUE"); assertNull(replacedValue); assertEquals(2, map.size()); assertTrue(map.containsKey("key")); assertTrue(map.containsKey("Key")); assertFalse(map.containsKey("KEY")); assertTrue(map.containsValue("value")); replacedValue = map.put("key", "VALUE"); assertEquals("value", replacedValue); assertEquals(2, map.size()); assertTrue(map.containsKey("key")); assertTrue(map.containsKey("Key")); assertFalse(map.containsKey("KEY")); assertFalse(map.containsValue("value")); assertTrue(map.containsValue("VALUE")); } @Test public void testToggleCaseInsensitiveNoDuplicateElement() { CaseAwareLinkedMap<String, String> map = new CaseAwareLinkedMap<String, String>(); map.setCaseInsensitive(false); map.put("key", "value"); map.put("kee", "value"); assertTrue(map.containsKey("key")); assertFalse(map.containsKey("KEY")); assertEquals(2, map.size()); map.setCaseInsensitive(true); assertTrue(map.containsKey("key")); assertTrue(map.containsKey("KEY")); assertEquals(2, map.size()); } @Test public void testCaseSensitiveRemoveElement() { CaseAwareLinkedMap<String, String> map = new CaseAwareLinkedMap<String, String>(); map.setCaseInsensitive(false); map.put("key", "value"); assertEquals(1, map.size()); Object removedValue = map.remove("KEY"); assertNull(removedValue); assertEquals(1, map.size()); removedValue = map.remove("key"); assertEquals("value", removedValue); assertEquals(0, map.size()); } @Test public void testCaseInsensitiveAddDuplicateElement() { CaseAwareLinkedMap<String, String> map = new CaseAwareLinkedMap<String, String>(); map.setCaseInsensitive(true); map.put("key", "value"); assertEquals(1, map.size()); Object replacedValue = map.put("Key", "VALUE"); assertEquals("value", replacedValue); assertEquals(1, map.size()); } @Test public void testToggleCaseInsensitiveDuplicateElement() { CaseAwareLinkedMap<String, String> map = new CaseAwareLinkedMap<String, String>(); map.put("key", "value"); map.put("Key", "value"); assertEquals(2, map.size()); try { map.setCaseInsensitive(true); fail("Expected exception"); } catch (CommandLine.DuplicateNameException ex) { assertEquals("Duplicated keys: key and Key", ex.getMessage()); } } @Test public void testCaseInsensitiveRemoveElement() { CaseAwareLinkedMap<String, String> map = new CaseAwareLinkedMap<String, String>(); map.setCaseInsensitive(true); map.put("key", "value"); assertEquals(1, map.size()); Object removedValue = map.remove("KEY"); assertEquals("value", removedValue); assertEquals(0, map.size()); } @Test public void testNullKeys() { CaseAwareLinkedMap<String, String> map = new CaseAwareLinkedMap<String, String>(); map.setCaseInsensitive(false); assertNull(map.get(null)); assertFalse(map.containsKey(null)); assertNull(map.getCaseSensitiveKey(null)); map.put(null, "value"); assertTrue(map.containsKey(null)); assertTrue(map.containsValue("value")); assertEquals(1, map.size()); assertEquals("value", map.get(null)); assertNull(map.getCaseSensitiveKey(null)); map.setCaseInsensitive(true); assertEquals(1, map.size()); assertEquals("value", map.get(null)); assertTrue(map.containsKey(null)); assertTrue(map.containsValue("value")); assertNull(map.getCaseSensitiveKey(null)); assertEquals("value", map.put(null, "value2")); assertTrue(map.containsKey(null)); assertFalse(map.containsValue("value")); assertTrue(map.containsValue("value2")); assertEquals(1, map.size()); assertEquals("value2", map.get(null)); assertEquals("value2", map.remove(null)); assertEquals(0, map.size()); assertNull(map.get(null)); assertFalse(map.containsKey(null)); assertFalse(map.containsKey("value2")); assertNull(map.getCaseSensitiveKey(null)); } @Test public void testClearMap() { CaseAwareLinkedMap<String, String> map = new CaseAwareLinkedMap<String, String>(); map.clear(); map.setCaseInsensitive(false); map.put("key", "value"); map.clear(); assertEquals(0, map.size()); assertNull(map.get("key")); assertFalse(map.containsKey("key")); map.clear(); map.setCaseInsensitive(true); map.put("key", "value"); map.clear(); assertEquals(0, map.size()); assertNull(map.get("key")); assertFalse(map.containsKey("key")); } @Test public void testNonExistentKey() { CaseAwareLinkedMap<String, String> map = new CaseAwareLinkedMap<String, String>(); map.setCaseInsensitive(false); assertNull(map.get("key")); assertNull(map.put("key2", "value")); assertNull(map.remove("key")); map.clear(); map.setCaseInsensitive(true); assertNull(map.get("key")); assertNull(map.put("key2", "value")); assertNull(map.remove("key")); } @Test public void testInconvertibleClass() { assertTrue (CaseAwareLinkedMap.isCaseConvertible(String.class)); assertTrue (CaseAwareLinkedMap.isCaseConvertible(Character.class)); assertFalse(CaseAwareLinkedMap.isCaseConvertible(Object.class)); CaseAwareLinkedMap<Object, String> map = new CaseAwareLinkedMap<Object, String>(); Object dummy = new Object(); map.setCaseInsensitive(false); assertNull(map.get(dummy)); assertFalse(map.containsKey(dummy)); map.setCaseInsensitive(true); assertNull(map.get(dummy)); assertFalse(map.containsKey(dummy)); try { map.getCaseSensitiveKey(dummy); fail("Expected exception"); } catch (UnsupportedOperationException ex) { assertEquals("Unsupported case-conversion for key class java.lang.Object", ex.getMessage()); } } }
package krasa.mavenhelper.analyzer; import com.intellij.ide.CommonActionsManager; import com.intellij.ide.DefaultTreeExpander; import com.intellij.ide.util.PropertiesComponent; import com.intellij.notification.Notification; import com.intellij.notification.NotificationListener; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.openapi.actionSystem.ActionToolbar; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.actionSystem.ex.ActionManagerEx; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ex.ApplicationInfoEx; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.BuildNumber; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.*; import com.intellij.ui.components.JBList; import com.intellij.util.text.VersionComparatorUtil; import krasa.mavenhelper.ApplicationComponent; import krasa.mavenhelper.analyzer.action.LeftTreePopupHandler; import krasa.mavenhelper.analyzer.action.RightTreePopupHandler; import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.idea.maven.model.MavenArtifact; import org.jetbrains.idea.maven.model.MavenArtifactNode; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.idea.maven.server.MavenServerManager; import javax.swing.*; import javax.swing.event.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.lang.reflect.Method; import java.util.*; import java.util.List; /** * @author Vojtech Krasa */ public class GuiForm { private static final Logger LOG = Logger.getInstance("#krasa.mavenrun.analyzer.GuiForm"); public static final String WARNING = "Your settings indicates, that conflicts will not be visible, see IDEA-133331\n" + "If your project is Maven2 compatible, you could try one of the following:\n" + "-use IJ 2016.1+ and configure it to use external Maven 3.1.1+ (File | Settings | Build, Execution, Deployment | Build Tools | Maven | Maven home directory)\n" + "-press Apply Fix button to alter Maven VM options for importer (might cause trouble for IJ 2016.1+)\n" + "-turn off File | Settings | Build, Execution, Deployment | Build Tools | Maven | Importing | Use Maven3 to import project setting\n"; protected static final Comparator<MavenArtifactNode> BY_ARTICATF_ID = new Comparator<MavenArtifactNode>() { @Override public int compare(MavenArtifactNode o1, MavenArtifactNode o2) { return o1.getArtifact().getArtifactId().toLowerCase().compareTo(o2.getArtifact().getArtifactId().toLowerCase()); } }; private static final String LAST_RADIO_BUTTON = "MavenHelper.lastRadioButton"; private final Project project; private final VirtualFile file; private MavenProject mavenProject; private JBList leftPanelList; private JTree rightTree; private JPanel rootPanel; private JRadioButton conflictsRadioButton; private JRadioButton allDependenciesAsListRadioButton; private JRadioButton allDependenciesAsTreeRadioButton; private JLabel noConflictsLabel; private JScrollPane noConflictsWarningLabelScrollPane; private JTextPane noConflictsWarningLabel; private JButton refreshButton; private JSplitPane splitPane; private SearchTextField searchField; private JButton applyMavenVmOptionsFixButton; private JPanel leftPanelWrapper; private JTree leftTree; private JCheckBox showGroupId; private JPanel buttonsPanel; protected DefaultListModel listDataModel; protected Map<String, List<MavenArtifactNode>> allArtifactsMap; protected final DefaultTreeModel rightTreeModel; protected final DefaultTreeModel leftTreeModel; protected final DefaultMutableTreeNode rightTreeRoot; protected final DefaultMutableTreeNode leftTreeRoot; protected ListSpeedSearch myListSpeedSearch; protected List<MavenArtifactNode> dependencyTree; protected CardLayout leftPanelLayout; private boolean notificationShown; private final SimpleTextAttributes errorBoldAttributes; public GuiForm(final Project project, VirtualFile file, final MavenProject mavenProject) { this.project = project; this.file = file; this.mavenProject = mavenProject; final ActionListener radioButtonListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateLeftPanel(); String value = null; if (allDependenciesAsListRadioButton.isSelected()) { value = "list"; } else if (allDependenciesAsTreeRadioButton.isSelected()) { value = "tree"; } PropertiesComponent.getInstance().setValue(LAST_RADIO_BUTTON, value); } }; conflictsRadioButton.addActionListener(radioButtonListener); allDependenciesAsListRadioButton.addActionListener(radioButtonListener); allDependenciesAsTreeRadioButton.addActionListener(radioButtonListener); refreshButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { initializeModel(); rootPanel.requestFocus(); } }); myListSpeedSearch = new ListSpeedSearch(leftPanelList); searchField.addDocumentListener(new DocumentAdapter() { @Override protected void textChanged(DocumentEvent documentEvent) { updateLeftPanel(); } }); try { Method searchField = this.searchField.getClass().getMethod("getTextEditor"); JTextField invoke = (JTextField) searchField.invoke(this.searchField); invoke.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { if (GuiForm.this.searchField.getText() != null) { GuiForm.this.searchField.addCurrentTextToHistory(); } } }); } catch (Exception e) { throw new RuntimeException(e); } noConflictsWarningLabel.setBackground(null); applyMavenVmOptionsFixButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String mavenEmbedderVMOptions = MavenServerManager.getInstance().getMavenEmbedderVMOptions(); int baselineVersion = ApplicationInfoEx.getInstanceEx().getBuild().getBaselineVersion(); if (baselineVersion >= 140) { mavenEmbedderVMOptions += " -Didea.maven3.use.compat.resolver"; } else { mavenEmbedderVMOptions += " -Dmaven3.use.compat.resolver"; } MavenServerManager.getInstance().setMavenEmbedderVMOptions(mavenEmbedderVMOptions); final MavenProjectsManager projectsManager = MavenProjectsManager.getInstance(project); projectsManager.forceUpdateAllProjectsOrFindAllAvailablePomFiles(); refreshButton.getActionListeners()[0].actionPerformed(e); } }); noConflictsWarningLabel.setText(WARNING); leftPanelLayout = (CardLayout) leftPanelWrapper.getLayout(); rightTreeRoot = new DefaultMutableTreeNode(); rightTreeModel = new DefaultTreeModel(rightTreeRoot); rightTree.setModel(rightTreeModel); rightTree.setRootVisible(false); rightTree.setShowsRootHandles(true); rightTree.expandPath(new TreePath(rightTreeRoot.getPath())); rightTree.setCellRenderer(new TreeRenderer(showGroupId)); rightTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); rightTree.addMouseListener(new RightTreePopupHandler(project, mavenProject, rightTree)); leftTree.addTreeSelectionListener(new LeftTreeSelectionListener()); leftTreeRoot = new DefaultMutableTreeNode(); leftTreeModel = new DefaultTreeModel(leftTreeRoot); leftTree.setModel(leftTreeModel); leftTree.setRootVisible(false); leftTree.setShowsRootHandles(true); leftTree.expandPath(new TreePath(leftTreeRoot.getPath())); leftTree.setCellRenderer(new TreeRenderer(showGroupId)); leftTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); leftTree.addMouseListener(new LeftTreePopupHandler(project, mavenProject, leftTree)); showGroupId.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { leftPanelList.repaint(); TreeUtils.nodesChanged(GuiForm.this.rightTreeModel); TreeUtils.nodesChanged(GuiForm.this.leftTreeModel); } }); final DefaultTreeExpander treeExpander = new DefaultTreeExpander(leftTree); DefaultActionGroup actionGroup = new DefaultActionGroup(); actionGroup.add(CommonActionsManager.getInstance().createExpandAllAction(treeExpander, leftTree)); actionGroup.add(CommonActionsManager.getInstance().createCollapseAllAction(treeExpander, leftTree)); ActionToolbar actionToolbar = ActionManagerEx.getInstance().createActionToolbar("krasa.MavenHelper.buttons", actionGroup, true); buttonsPanel.add(actionToolbar.getComponent(), "1"); errorBoldAttributes = new SimpleTextAttributes(SimpleTextAttributes.STYLE_BOLD, SimpleTextAttributes.ERROR_ATTRIBUTES.getFgColor()); String lastRadioButton = PropertiesComponent.getInstance().getValue(LAST_RADIO_BUTTON); if ("tree".equals(lastRadioButton)) { allDependenciesAsTreeRadioButton.setSelected(true); } else if ("list".equals(lastRadioButton)) { allDependenciesAsListRadioButton.setSelected(true); } else { conflictsRadioButton.setSelected(true); } } private void createUIComponents() { listDataModel = new DefaultListModel(); leftPanelList = new JBList(listDataModel); leftPanelList.addListSelectionListener(new MyListSelectionListener()); // no generics in IJ12 leftPanelList.setCellRenderer(new ColoredListCellRenderer() { @Override protected void customizeCellRenderer(JList jList, Object o, int i, boolean b, boolean b2) { MyListNode value = (MyListNode) o; String rightVersion = value.getRightVersion(); final String[] split = value.key.split(":"); boolean conflict = value.isConflict(); SimpleTextAttributes attributes = SimpleTextAttributes.REGULAR_ATTRIBUTES; SimpleTextAttributes boldAttributes = SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES; if (conflict && allDependenciesAsListRadioButton.isSelected()) { attributes = SimpleTextAttributes.ERROR_ATTRIBUTES; boldAttributes = errorBoldAttributes; } if (showGroupId.isSelected()) { append(split[0] + " : ", attributes); } append(split[1], boldAttributes); append(" : " + rightVersion, attributes); } }); rightTree = new MyHighlightingTree(project, mavenProject); leftTree = new MyHighlightingTree(project, mavenProject); } public static String sortByVersion(List<MavenArtifactNode> value) { Collections.sort(value, new Comparator<MavenArtifactNode>() { @Override public int compare(MavenArtifactNode o1, MavenArtifactNode o2) { DefaultArtifactVersion version = new DefaultArtifactVersion(o1.getArtifact().getVersion()); DefaultArtifactVersion version1 = new DefaultArtifactVersion(o2.getArtifact().getVersion()); return version1.compareTo(version); } }); return value.get(0).getArtifact().getVersion(); } private class LeftTreeSelectionListener implements TreeSelectionListener { @Override public void valueChanged(TreeSelectionEvent e) { TreePath selectionPath = e.getPath(); if (selectionPath != null) { DefaultMutableTreeNode lastPathComponent = (DefaultMutableTreeNode) selectionPath.getLastPathComponent(); MyTreeUserObject userObject = (MyTreeUserObject) lastPathComponent.getUserObject(); final String key = getArtifactKey(userObject.getArtifact()); List<MavenArtifactNode> mavenArtifactNodes = allArtifactsMap.get(key); if (mavenArtifactNodes != null) {// can be null while refreshing fillRightTree(mavenArtifactNodes, sortByVersion(mavenArtifactNodes)); } } } } private class MyListSelectionListener implements ListSelectionListener { @Override public void valueChanged(ListSelectionEvent e) { if (listDataModel.isEmpty() || leftPanelList.getSelectedValue() == null) { return; } final MyListNode myListNode = (MyListNode) leftPanelList.getSelectedValue(); List<MavenArtifactNode> artifacts = myListNode.value; fillRightTree(artifacts, myListNode.getRightVersion()); } } private void fillRightTree(List<MavenArtifactNode> mavenArtifactNodes, String rightVersion) { rightTreeRoot.removeAllChildren(); for (MavenArtifactNode mavenArtifactNode : mavenArtifactNodes) { MyTreeUserObject userObject = MyTreeUserObject.create(mavenArtifactNode, rightVersion); userObject.showOnlyVersion = true; final DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(userObject); fillRightTree(mavenArtifactNode, newNode); rightTreeRoot.add(newNode); } rightTreeModel.nodeStructureChanged(rightTreeRoot); TreeUtils.expandAll(rightTree); } private void fillRightTree(MavenArtifactNode mavenArtifactNode, DefaultMutableTreeNode node) { final MavenArtifactNode parent = mavenArtifactNode.getParent(); if (parent == null) { return; } final DefaultMutableTreeNode parentDependencyNode = new DefaultMutableTreeNode(new MyTreeUserObject(parent)); node.add(parentDependencyNode); parentDependencyNode.setParent(node); fillRightTree(parent, parentDependencyNode); } private void initializeModel() { final Object selectedValue = leftPanelList.getSelectedValue(); dependencyTree = mavenProject.getDependencyTree(); allArtifactsMap = createAllArtifactsMap(dependencyTree); updateLeftPanel(); rightTreeRoot.removeAllChildren(); rightTreeModel.reload(); leftPanelWrapper.revalidate(); if (selectedValue != null) { leftPanelList.setSelectedValue(selectedValue, true); } } private void updateLeftPanel() { listDataModel.clear(); leftTreeRoot.removeAllChildren(); final String searchFieldText = searchField.getText(); boolean conflictsWarning = false; boolean showNoConflictsLabel = false; if (conflictsRadioButton.isSelected()) { for (Map.Entry<String, List<MavenArtifactNode>> s : allArtifactsMap.entrySet()) { final List<MavenArtifactNode> nodes = s.getValue(); if (nodes.size() > 1 && hasConflicts(nodes)) { if (searchFieldText == null || s.getKey().toLowerCase().contains(searchFieldText.toLowerCase())) { listDataModel.addElement(new MyListNode(s)); } } } showNoConflictsLabel = listDataModel.isEmpty(); BuildNumber build = ApplicationInfoEx.getInstanceEx().getBuild(); int baselineVersion = build.getBaselineVersion(); MavenServerManager server = MavenServerManager.getInstance(); boolean useMaven2 = server.isUseMaven2(); boolean containsCompatResolver139 = server.getMavenEmbedderVMOptions().contains("-Dmaven3.use.compat.resolver"); boolean containsCompatResolver140 = server.getMavenEmbedderVMOptions().contains("-Didea.maven3.use.compat.resolver"); boolean newIDE = VersionComparatorUtil.compare(build.asStringWithoutProductCode(), "145.258") >= 0; boolean newMaven = VersionComparatorUtil.compare(server.getCurrentMavenVersion(), "3.1.1") >= 0; if (showNoConflictsLabel && baselineVersion >= 139) { boolean containsProperty = (baselineVersion == 139 && containsCompatResolver139) || (baselineVersion >= 140 && containsCompatResolver140); conflictsWarning = !containsProperty && !useMaven2; if (conflictsWarning && newIDE) { conflictsWarning = conflictsWarning && !newMaven; } } if (!conflictsWarning && newIDE && newMaven && containsCompatResolver140) { if (!notificationShown) { notificationShown = true; final Notification notification = ApplicationComponent.NOTIFICATION.createNotification( "Fix your Maven VM options for importer", "<html>Your settings causes problems in multi-module Maven projects.<br> " + " <a href=\"fix\">Remove -Didea.maven3.use.compat.resolver</a> ", NotificationType.WARNING, new NotificationListener() { @Override public void hyperlinkUpdate(@NotNull Notification notification, @NotNull HyperlinkEvent hyperlinkEvent) { notification.expire(); String mavenEmbedderVMOptions = MavenServerManager.getInstance().getMavenEmbedderVMOptions(); MavenServerManager.getInstance().setMavenEmbedderVMOptions( mavenEmbedderVMOptions.replace("-Didea.maven3.use.compat.resolver", "")); final MavenProjectsManager projectsManager = MavenProjectsManager.getInstance(project); projectsManager.forceUpdateAllProjectsOrFindAllAvailablePomFiles(); } }); ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { Notifications.Bus.notify(notification, project); } }); } } leftPanelLayout.show(leftPanelWrapper, "list"); } else if (allDependenciesAsListRadioButton.isSelected()) { for (Map.Entry<String, List<MavenArtifactNode>> s : allArtifactsMap.entrySet()) { if (searchFieldText == null || s.getKey().toLowerCase().contains(searchFieldText.toLowerCase())) { listDataModel.addElement(new MyListNode(s)); } } showNoConflictsLabel = false; leftPanelLayout.show(leftPanelWrapper, "list"); } else { // tree fillLeftTree(leftTreeRoot, dependencyTree, searchFieldText); leftTreeModel.nodeStructureChanged(leftTreeRoot); TreeUtils.expandAll(leftTree); showNoConflictsLabel = false; leftPanelLayout.show(leftPanelWrapper, "allAsTree"); } if (conflictsWarning) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { noConflictsWarningLabelScrollPane.getVerticalScrollBar().setValue(0); } }); leftPanelLayout.show(leftPanelWrapper, "noConflictsWarningLabel"); } buttonsPanel.setVisible(allDependenciesAsTreeRadioButton.isSelected()); noConflictsWarningLabelScrollPane.setVisible(conflictsWarning); applyMavenVmOptionsFixButton.setVisible(conflictsWarning); noConflictsLabel.setVisible(showNoConflictsLabel); } private boolean fillLeftTree(DefaultMutableTreeNode parent, List<MavenArtifactNode> dependencyTree, String searchFieldText) { boolean search = StringUtils.isNotBlank(searchFieldText); Collections.sort(dependencyTree, BY_ARTICATF_ID); boolean hasAddedNodes = false; for (MavenArtifactNode mavenArtifactNode : dependencyTree) { boolean directMatch = false; MyTreeUserObject treeUserObject = new MyTreeUserObject(mavenArtifactNode, SimpleTextAttributes.REGULAR_ATTRIBUTES); if (search && contains(searchFieldText, mavenArtifactNode)) { directMatch = true; treeUserObject.highlight = true; } final DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(treeUserObject); boolean childAdded = fillLeftTree(newNode, mavenArtifactNode.getDependencies(), searchFieldText); if (!search || directMatch || childAdded) { parent.add(newNode); hasAddedNodes = true; } } return hasAddedNodes; } private boolean contains(String searchFieldText, MavenArtifactNode mavenArtifactNode) { MavenArtifact artifact = mavenArtifactNode.getArtifact(); String displayStringSimple = getArtifactKey(artifact); return displayStringSimple.toLowerCase().contains(searchFieldText.toLowerCase()); } private boolean hasConflicts(List<MavenArtifactNode> nodes) { String version = null; for (MavenArtifactNode node : nodes) { if (version != null && !version.equals(node.getArtifact().getVersion())) { return true; } version = node.getArtifact().getVersion(); } return false; } private Map<String, List<MavenArtifactNode>> createAllArtifactsMap(List<MavenArtifactNode> dependencyTree) { final Map<String, List<MavenArtifactNode>> map = new TreeMap<String, List<MavenArtifactNode>>(); addAll(map, dependencyTree, 0); return map; } private void addAll(Map<String, List<MavenArtifactNode>> map, List<MavenArtifactNode> artifactNodes, int i) { if (map == null) { return; } if (i > 100) { final StringBuilder stringBuilder = new StringBuilder(); for (MavenArtifactNode s : artifactNodes) { final String s1 = s.getArtifact().toString(); stringBuilder.append(s1); stringBuilder.append(" "); } LOG.error("Recursion aborted, artifactNodes = [" + stringBuilder + "]"); return; } for (MavenArtifactNode mavenArtifactNode : artifactNodes) { final MavenArtifact artifact = mavenArtifactNode.getArtifact(); final String key = getArtifactKey(artifact); final List<MavenArtifactNode> mavenArtifactNodes = map.get(key); if (mavenArtifactNodes == null) { final ArrayList<MavenArtifactNode> value = new ArrayList<MavenArtifactNode>(1); value.add(mavenArtifactNode); map.put(key, value); } else { mavenArtifactNodes.add(mavenArtifactNode); } addAll(map, mavenArtifactNode.getDependencies(), i + 1); } } @NotNull private String getArtifactKey(MavenArtifact artifact) { return artifact.getGroupId() + " : " + artifact.getArtifactId(); } public JComponent getRootComponent() { return rootPanel; } public JComponent getPreferredFocusedComponent() { return rootPanel; } public void selectNotify() { if (dependencyTree == null) { initializeModel(); splitPane.setDividerLocation(0.5); } } }
package view.controllers; import java.util.ArrayList; import java.util.List; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.scene.control.Button; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; public class WorkspaceTabsController { private HBox myHbox = new HBox(); private TabPane myTabPane = new TabPane(); private List<PaneController> myWorkspaces = new ArrayList<PaneController>(); private BorderPane myBorderPane; private VBox myVBox = new VBox(); public WorkspaceTabsController (BorderPane bp) { myBorderPane = bp; Button addWS = new Button("New Workspace"); addWS.setOnAction(event -> newTab()); addWS.setMinHeight(40); myHbox.getChildren().addAll(myTabPane, addWS); myVBox.getChildren().addAll(myHbox); newTab(); myTabPane.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Tab>() { @Override public void changed (ObservableValue<? extends Tab> ov, Tab t, Tab t1) { if (t1 != null) { makeActive(t1); } else{ newTab(); } } }); } private void newTab () { Tab tab = new Tab(); tab.setText("Workspace"); PaneController control = new PaneController(myBorderPane, myVBox); myWorkspaces.add(control); tab.setId("" + (myWorkspaces.size() - 1)); myTabPane.getTabs().add(tab); makeActive(myTabPane.getTabs().get(0)); } private void makeActive (Tab t1) { int i = new Integer(t1.getId()); PaneController pc = myWorkspaces.get(i); pc.populate(myBorderPane); } }
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); names.put("LF", (char)10); names.put("FF", (char)12); names.put("CR", (char)13); names.put("NEL", (char)133); 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: case NFA.EDGE_CHARRANGE: case NFA.EDGE_CHARRANGE_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); } else if (act == NFA.EDGE_CHARRANGE) { 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_CHARRANGE_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; } }
// AppContextHolder.java package ed.appserver; import java.io.*; import java.util.*; import ed.js.*; import ed.net.*; import ed.net.httpserver.*; import ed.log.*; import ed.git.*; import ed.util.*; import ed.lang.*; import ed.cloud.*; public class AppContextHolder { static boolean D = Boolean.getBoolean( "DEBUG.APP" ); static final String CDN_HOST[] = new String[]{ "origin." , "origin-local." , "static." , "static-local." , "secure." }; static final String OUR_DOMAINS[]; static { List<String> ourDomains = new ArrayList<String>(); ourDomains.add( ".local." + Config.getExternalDomain().toLowerCase() ); ourDomains.add( "." + Config.getExternalDomain().toLowerCase() ); String externalDomainAliases = Config.get().getProperty( "externalDomainAliases" ); if ( externalDomainAliases != null ){ for ( String s : externalDomainAliases.split( "," ) ){ s = s.trim().toLowerCase(); if ( s.length() == 0 ) continue; ourDomains.add( "." + s ); } } OUR_DOMAINS = ourDomains.toArray( new String[ ourDomains.size() ] ); if ( D ) System.out.println( "OUR_DOMAINS: " + ourDomains ); } static final Set<String> CDN_HOSTNAMES; static { Set<String> s = new HashSet<String>(); for ( String d : OUR_DOMAINS ) for ( String h : CDN_HOST ) s.add( (h + d).replaceAll( "\\.+" , "." ).toLowerCase() ); CDN_HOSTNAMES = Collections.unmodifiableSet( s ); } private static final String LOCAL_BRANCH_LIST[] = new String[]{ "master" , "test" , "www" }; private static final String WWW_BRANCH_LIST[] = new String[]{ "test" , "master" }; public static boolean isCDNHost( String host ){ return CDN_HOSTNAMES.contains( host ); } /** * @param defaultWebRoot default web site * @param root where all your sites live */ public AppContextHolder( String defaultWebRoot , String root ){ _defaultWebRoot = defaultWebRoot; _root = root; _rootFile = _root == null ? null : new File( _root ); } public void addToServer(){ HttpServer.addGlobalHandler( new HttpMonitor( "appcontextholder" ){ public void handle( MonitorRequest mr ){ if ( mr.getRequest().getBoolean( "gc" , false ) ) System.gc(); IdentitySet<AppContext> all = new IdentitySet<AppContext>(); synchronized ( _contextCreationLock ){ all.addAll( _contextCache.values() ); } SeenPath seen = new SeenPath(); long totalSize = 0; for ( AppContext ac : all ){ if ( ac == null ) continue; mr.startData( ac.getName() + ":" + ac.getEnvironmentName() ); mr.addData( "Num Requests" , ac._numRequests ); mr.addData( "Created" , ac._created ); try { int before = seen.size(); long size = ac.approxSize( seen ); totalSize += size; mr.addData( "Memory (kb)" , size / 1024 ); mr.addData( "Number Objects" , seen.size() - before ); if ( mr.getRequest().getBoolean( "reflect" , false ) ){ ReflectionVisitor.Reachable r = new AppContext.AppContextReachable(); ReflectionWalker walker = new ReflectionWalker( r ); walker.walk( ac ); mr.addData( "Reflection Object Count" , r.seenSize() ); } } catch ( Exception e ){ e.printStackTrace(); mr.addData( "Memory" , "error getting size : " + e ); } mr.endData(); } mr.startData( "TOTOAL" ); mr.addData( "Total Memory (kb)" , totalSize / 1024 ); mr.endData(); } } ); } public Result getContext( HttpRequest request ){ String host = request.getHeader( "X-Host" ); String uri = request.getURI(); if ( host != null ){ // if there is an X-Host, lets see if this is a cdn thing if ( CDN_HOSTNAMES.contains( request.getHost() ) && ! CDN_HOSTNAMES.contains( host ) && ! host.equals( request.getHost() ) // this should never happen, but is a weird case. ){ // X-Host was cleaned by someone else // so we need strip cdn thing from uri. int idx = uri.indexOf( "/" , 1 ); if ( idx > 0 ){ uri = uri.substring( idx ); } } } else { // no X-Host host = request.getHeader( "Host" ); } if ( host != null ){ int idx = host.indexOf( ":" ); if ( idx > 0 ) host = host.substring( 0 , idx ); } return getContext( host , uri ); } public Result getContext( String host , String uri ){ if ( host != null ) host = host.trim(); if ( D ) System.out.println( host + uri ); if ( host == null || _root == null || host.length() == 0 ){ if ( D ) System.out.println( "\t using default context for [" + host + "]" ); return new Result( _getDefaultContext() , host , uri ); } Info info = fixBase( host , uri ); host = info.host; uri = info.uri; if ( D ) System.out.println( "\t fixed host [" + host + "]" ); AppContext ac = _getContextFromMap( host ); if ( ac != null ){ if ( D ) System.out.println( "\t found in cache [" + host + "]" ); return new Result( ac , host , uri ); } synchronized ( _contextCreationLock ){ ac = _getContextFromMap( host ); if ( ac != null ){ if ( D ) System.out.println( "\t found in cache [" + host + "]" ); return _finish( ac , host, uri , host ); } for ( Info i : getPossibleSiteNames( info ) ){ if ( D ) System.out.println( "\t possible site name [" + i.host + "]" ); File temp = new File( _root , i.host ); if ( temp.exists() ) return _finish( getEnvironmentContext( temp , i , host ) , host , info.uri , host ); JSObject site = getSiteFromCloud( i.host ); if ( site != null ){ if ( D ) System.out.println( "\t found site from cloud" ); temp.mkdirs(); return _finish( getEnvironmentContext( temp , i , host ) , host , info.uri , host ); } } } return _finish( _getDefaultContext() , info.host , info.uri , host ); } private Result _finish( AppContext context , String host , String uri , String origHost ){ _contextCache.put( origHost , context ); return new Result( context , host , uri ); } private AppContext getEnvironmentContext( final File siteRoot , final Info info , final String originalHost ){ if ( ! siteRoot.exists() ) throw new RuntimeException( "\t trying to map [" + originalHost + "] to " + siteRoot + " which doesn't exist" ); AppContext ac = _getContextFromMap( originalHost ); if ( ac != null ) return ac; if ( D ) System.out.println( "\t mapping directory [" + originalHost + "] to " + siteRoot ); if ( isCodeDir( siteRoot ) ){ ac = _getContextFromMap( siteRoot.getAbsolutePath() ); if ( ac == null ){ ac = new AppContext( siteRoot ); _contextCache.put( siteRoot.getAbsolutePath() , ac ); } } else { if ( D ) System.out.println( "\t this is a holder for branches" ); final String env = info.getEnvironment( originalHost ); if ( D ) System.out.println( "\t\t env : " + env ); final File envRoot = getBranch( siteRoot , env , info.host ); if ( D ) System.out.println( "\t using full path : " + envRoot ); final String fileKey = envRoot.getAbsolutePath(); ac = _getContextFromMap( fileKey ); if ( ac == null ){ ac = new AppContext( envRoot.toString() , envRoot , siteRoot.getName() , env ); _contextCache.put( fileKey , ac ); } } _contextCache.put( originalHost , ac ); return ac; } void replace( AppContext oldOne , AppContext newOne ){ synchronized ( _contextCreationLock ){ List<String> names = new ArrayList<String>( _contextCache.keySet() ); for ( String s : names ){ AppContext temp = _contextCache.get( s ); if ( _same( temp , oldOne ) ){ _contextCache.put( s , newOne ); } } _contextCache.put( newOne._root , newOne ); if ( _same( _defaultContext , oldOne ) ) _defaultContext = newOne; } } private boolean _same( AppContext a , AppContext b ){ if ( a == b ) return true; if ( a == null || b == null ) return false; if ( a._rootFile == null ) throw new NullPointerException( "how could a's _rootFile be null" ); if ( b._rootFile == null ) throw new NullPointerException( "how could b's _rootFile be null" ); if ( a._rootFile.equals( b._rootFile ) ) return true; return false; } private AppContext _getContextFromMap( String host ){ AppContext ac = _contextCache.get( host ); if (ac != null && ac.isReset()) { _contextCache.put( host , null ); ac = null; } return ac; } File getBranch( File root , String subdomain , String siteName ){ GitDir git = _getBranch( root , subdomain , siteName ); JSObject envConfig = getEnvironmentFromCloud( siteName , subdomain ); if ( envConfig != null ){ String branch = envConfig.get( "branch" ).toString() ; if ( D ) System.out.println( "\t using branch [" + branch + "]" ); git.findAndSwitchTo( branch ); } return git.getRoot(); } GitDir _getBranch( File root , String subdomain , String siteName ){ GitDir test = new GitDir( root , subdomain ); if ( test.exists() ) return test; JSObject site = getSiteFromCloud( siteName ); if ( site != null ){ Object gitObject = site.get( "giturl" ); if ( gitObject != null ){ String giturl = gitObject.toString(); JSObject envConfig = getEnvironmentFromCloud( siteName , subdomain ); if ( envConfig != null ){ if ( D ) System.out.println( "\t found an env in grid" ); test.clone( giturl ); String branch = envConfig.get( "branch" ).toString(); if ( ! test.checkout( branch ) ) throw new RuntimeException( "couldn't checkout [" + branch + "] for [" + test + "]" ); return test; } } } if ( subdomain.equals( "dev" ) ){ test = new GitDir( root , "master" ); if ( test.exists() ) return test; } String searchList[] = null; if ( subdomain.equals( "local" ) ) searchList = LOCAL_BRANCH_LIST; else if ( subdomain.equals( "www" ) ) searchList = WWW_BRANCH_LIST; if ( searchList != null ){ for ( int i=0; i<searchList.length; i++ ){ test = new GitDir( root , searchList[i] ); if ( test.exists() ) return test; } } throw new RuntimeException( "can't find environment [" + subdomain + "] in [" + root + "] siteName [" + siteName + "] found site:" + ( site != null ) ); } private synchronized AppContext _getDefaultContext(){ if ( _defaultWebRoot == null ) return null; if ( _defaultContext != null && _defaultContext._reset ) _defaultContext = null; if ( _defaultContext != null ) return _defaultContext; _defaultContext = new AppContext( _defaultWebRoot ); return _defaultContext; } private boolean isCodeDir( final File test ){ File f = new File( test , ".git" ); if ( f.exists() ) return true; f = new File( test , "dot-git" ); if ( f.exists() ) return true; if ( ! test.exists() ) return false; File lst[] = test.listFiles(); for ( int j=0; j<lst.length; j++ ){ f = lst[j]; if ( f.isDirectory() ) continue; final String name = f.getName(); for ( int i=0; i<JSFileLibrary._srcExtensions.length; i++ ) if ( name.endsWith( JSFileLibrary._srcExtensions[i] ) ) return true; } return false; } static JSObject getEnvironmentFromCloud( String siteName , String envName ){ Cloud theCloud = Cloud.getInstanceIfOnGrid(); if ( theCloud == null ) return null; return theCloud.findEnvironment( siteName , envName ); } static JSObject getSiteFromCloud( String name ){ Cloud theCloud = Cloud.getInstanceIfOnGrid(); if ( theCloud == null ) return null; return theCloud.findSite( name , false ); } static List<Info> getPossibleSiteNames( String host , String uri ){ return getPossibleSiteNames( fixBase( host , uri ) ); } public static List<Info> getPossibleSiteNames( Info base ){ List<Info> all = new ArrayList<Info>( 6 ); all.add( base ); final String host = base.host; final String uri = base.uri; String domain = DNSUtil.getDomain( host ); if ( ! domain.equals( host ) ) all.add( new Info( domain , uri ) ); int idx = domain.indexOf( "." ); if ( idx > 0 ) all.add( new Info( domain.substring( 0 , idx ) , uri ) ); return all; } public static Info fixBase( String host , String uri ){ { int idx = host.indexOf( ":" ); if ( idx >= 0 ) host = host.substring( 0 , idx ); } if ( uri == null ){ uri = "/"; } else { if ( ! uri.startsWith( "/" ) ) uri = "/" + uri; } if ( CDN_HOSTNAMES.contains( host ) ){ final int idx = uri.indexOf( "/" , 1 ); if ( idx < 0 ) throw new HttpExceptions.BadRequest( 410 , "static host without valid host:[" + host + "] uri:[" + uri + "]" ); host = uri.substring( 1 , idx ); uri = uri.substring( idx ); } for ( String d : OUR_DOMAINS ){ if ( host.endsWith( d ) ){ host = host.substring( 0 , host.length() - d.length() ); if ( host.equals( "www" ) || host.equals( "www.www" ) ) host = "www"; else if ( host.indexOf( "." ) < 0 ) host += ".com"; break; } } if ( host.startsWith( "www." ) ) host = host.substring( 4 ); if ( host.equals( "com" ) ) host = "www.com"; return new Info( host , uri ); } public static class Info { Info( String host ){ this( host , "/" ); } Info( String host , String uri ){ this.host = host; this.uri = uri; } public String getHost(){ return host; } public String getURI(){ return uri; } public String getEnvironment( String big ){ if ( big.equalsIgnoreCase( host ) || host.startsWith( "www." ) || big.startsWith( host + "." ) ) return "www"; int idx = big.indexOf( "." + host ); if ( idx < 0 ){ idx = big.indexOf( host ); if ( idx < 0 ) throw new RuntimeException( "something is wrong host:" + host + " big:" + big ); } return big.substring( 0 , idx ); } public String toString(){ return host + uri; } final String host; final String uri; } class Result { Result( AppContext context , String host , String uri ){ this.context = context; this.host = host; this.uri = uri; if ( this.host.equalsIgnoreCase( "www" ) && getRoot().contains( "stage" ) ) throw new RuntimeException( "blah" ); } String getRoot(){ return context.getRoot(); } public String toString(){ return getRoot() + "||" + host + "||" + uri; } final AppContext context; final String uri; final String host; } final String _root; final File _rootFile; private final String _defaultWebRoot; private AppContext _defaultContext; private final Map<String,AppContext> _contextCache = Collections.synchronizedMap( new StringMap<AppContext>(){ public AppContext put( String name , AppContext c ){ if ( D ) System.out.println( "adding to cache [" + name + "] -> [" + c + "]" ); if ( name.equalsIgnoreCase( "www" ) && c.toString().contains( "stage" ) ) throw new RuntimeException( "here" ); return super.put( name , c ); } } ); private final String _contextCreationLock = ( "AppContextHolder-Lock-" + Math.random() ).intern(); }
// RunningApplication.java package ed.manager; import java.io.*; import java.util.*; import ed.io.*; import ed.log.*; import ed.util.*; public class RunningApplication extends Thread { public RunningApplication( Manager manager , Application app ){ super( "RunningApplication:" + app.getType() + ":" + app.getId() ); _manager = manager; _app = app; _fullId = app.getType() + "-" + app.getId(); _logger = _manager._logger.getChild( app.getType() ).getChild( app.getId() ); } public void run(){ while ( ! ( _shutdown || _manager.isShutDown() ) ){ _pid = -1; final Application app = _app; int exitValue = 0; _logger.info( "STARTING" ); try { _timesStarted++; _lastStart = System.currentTimeMillis(); exitValue = run( app ); } catch ( Exception ioe ){ _logger.error( "error running" , ioe ); exitValue = -1; } finally { _pid = -1; _process = null; } _logger.info( "exited : " + exitValue ); if ( ! ( _inRestart || _app.restart( exitValue ) ) ){ _logger.info( "DONE" ); break; } _inRestart = false; if ( _shutdown || _manager.isShutDown() ) break; _logger.info( "RESTARTING. exitValue : " + exitValue ); } _done = true; _process = null; _manager.interrupt(); } private int run( final Application app ) throws IOException , InterruptedException { fileRotate( app.getLogDir() , app.getType() , app.getId() ); app.getLogDir().mkdirs(); File logFile = _getLogFile( app.getLogDir() , app.getType() , app.getId() ); _logger.debug( "logFile : " + logFile.getAbsolutePath() ); OutputStream log = new FileOutputStream( logFile ); String[] command = app.getCommand(); if ( command[0].startsWith( "./" ) ){ String[] temp = new String[command.length]; System.arraycopy( command , 0 , temp , 0 , command.length ); temp[0] = (new File( app.getExecDir() , command[0] ) ).getAbsolutePath(); command = temp; } _logger.debug( "full command " + Arrays.toString( command ) ); _process = Runtime.getRuntime().exec( command , SysExec.envMapToArray( app.getEnvironmentVariables() ) , app.getExecDir() ); _pid = SysExec.getPID( _process ); _logger.info( "pid : " + _pid ); _process.getOutputStream().close(); // closing input because we're not using ut OutputPiper stdout = new OutputPiper( _process.getInputStream() , app , true , log ); OutputPiper stderr = new OutputPiper( _process.getErrorStream() , app , false , log ); stdout.start(); stderr.start(); stdout.join(); stderr.join(); log.close(); return _done ? _exitValue : _process.waitFor(); } void restart(){ restart( null ); } void restart( Application app ){ if ( _done ) throw new RuntimeException( "can't restart because done" ); if ( _shutdown ) throw new RuntimeException( "can't restart because shutdown" ); if ( app != null ) _app = app; _kill(); _inRestart = true; } public void shutdown(){ _shutdown = true; if ( _done ) return; _kill(); try { Thread.sleep( 2 ); } catch ( InterruptedException ie ){} assert( _done ); assert( _process == null ); } private void _kill(){ final Process p = _process; _done = true; if ( p == null ) return; if ( _pid <= 0 ){ _logger.error( "no pid, so just destroying" ); _destroy(); return; } try { SysExec.exec( "kill " + _pid ); } catch ( Exception e ){ _logger.error( "couldn't kill" ); _destroy(); return; } if ( ( _exitValue = SysExec.waitFor( p , _app.timeToShutDown() + 300, true ) ) == 0 ){ _logger.info( "shutdown cleanly" ); return; } _logger.error( "didn't shutdown. destroying" ); _destroy(); } private void _destroy(){ if ( _process == null ) return; try { _process.destroy(); _exitValue = _process.exitValue(); } catch ( Exception e ){ _logger.error( "destory had an error" , e ); } _process = null; _done = true; } public int hashCode(){ return _fullId.hashCode(); } public boolean equals( Object o ){ return ((RunningApplication)o)._fullId.equals( _fullId ); } public int getUptimeMinutes(){ return (int)( ( System.currentTimeMillis() - _lastStart ) / ( 1000 * 60 ) ); } public long getLastStart(){ return _lastStart; } public int timesStarted(){ return _timesStarted; } public OutputLine outputLine( int back ){ return _lastOutput.get( back ); } static void fileRotate( File dir , String type , String id ){ for ( int i=7; i>=0; i File f = _getLogFile( dir , type , id , i ); if ( f.exists() ) f.renameTo( _getLogFile( dir , type , id , i + 1 ) ); } } static File _getLogFile( File dir , String type , String id ){ return _getLogFile( dir , type , id , 0 ); } static File _getLogFile( File dir , String type , String id , int num ){ return new File( dir , type + "." + id + ".log" + ( num == 0 ? "" : "." + num ) ); } boolean isDone(){ return _done; } Application _app; final Manager _manager; final String _fullId; final Logger _logger; final CircularList<OutputLine> _lastOutput = new CircularList<OutputLine>( 100 , true ); private boolean _shutdown = false; private boolean _done = false; private boolean _inRestart = false; private int _pid = -1; private Process _process; private long _lastStart; private int _timesStarted = 0; private int _exitValue = 0; class OutputLine { OutputLine( String line , boolean out ){ _line = line; _out = out; } public String toString(){ return ( _out ? "OUT" : "ERR" ) + ": " + _line; } final String _line; final boolean _out; } class OutputPiper extends Thread { OutputPiper( InputStream in , Application app , boolean stdout , OutputStream out ){ super( "OutputPiper" ); setDaemon( true ); _in = new BufferedReader( new InputStreamReader( in ) ); _stdout = stdout; _app = app; _out = out; } public void run(){ String line; try { while ( ( line = _in.readLine() ) != null ){ try { if ( _stdout ){ if ( ! _app.gotOutputLine( line ) ) continue; } else { if ( ! _app.gotErrorLine( line ) ) continue; } } catch ( Application.RestartApp ra ){ _logger.alert( "got app restart because of line [" + line + "] beacuse of [" + ra._why + "]" ); restart(); } synchronized ( _out ){ _out.write( line.getBytes() ); _out.write( NEWLINE ); _lastOutput.add( new OutputLine( line , _stdout ) ); } } } catch ( IOException ioe ){ _logger.error( "error piping output" , ioe ); } } final BufferedReader _in; final Application _app; final boolean _stdout; final OutputStream _out; } private static final byte[] NEWLINE = "\n".getBytes(); }
package bdv.viewer; import net.imglib2.realtransform.AffineTransform3D; import net.imglib2.type.numeric.ARGBType; import net.imglib2.ui.TransformEventHandler3D; import net.imglib2.ui.TransformEventHandlerFactory; import bdv.behaviour.io.InputTriggerConfig; import bdv.viewer.animate.MessageOverlayAnimator; import bdv.viewer.render.AccumulateProjector; import bdv.viewer.render.AccumulateProjectorARGB; import bdv.viewer.render.AccumulateProjectorFactory; import bdv.viewer.render.MultiResolutionRenderer; /** * Optional parameters for {@link ViewerPanel}. * * @author Tobias Pietzsch &lt;tobias.pietzsch@gmail.com&gt; */ public class ViewerOptions { public final Values values = new Values(); /** * Create default {@link ViewerOptions}. * @return default {@link ViewerOptions}. */ public static ViewerOptions options() { return new ViewerOptions(); } /** * Set width of {@link ViewerPanel} canvas. */ public ViewerOptions width( final int w ) { values.width = w; return this; } /** * Set height of {@link ViewerPanel} canvas. */ public ViewerOptions height( final int h ) { values.height = h; return this; } /** * Set the number and scale factors for scaled screen images. * * @param s * Scale factors from the viewer canvas to screen images of * different resolutions. A scale factor of 1 means 1 pixel in * the screen image is displayed as 1 pixel on the canvas, a * scale factor of 0.5 means 1 pixel in the screen image is * displayed as 2 pixel on the canvas, etc. * @see MultiResolutionRenderer */ public ViewerOptions screenScales( final double[] s ) { values.screenScales = s; return this; } /** * Set target rendering time in nanoseconds. * * @param t * Target rendering time in nanoseconds. The rendering time for * the coarsest rendered scale should be below this threshold. * @see MultiResolutionRenderer */ public ViewerOptions targetRenderNanos( final long t ) { values.targetRenderNanos = t; return this; } /** * Set whether to used double buffered rendering. * * @param d * Whether to use double buffered rendering. * @see MultiResolutionRenderer */ public ViewerOptions doubleBuffered( final boolean d ) { values.doubleBuffered = d; return this; } /** * Set how many threads to use for rendering. * * @param n * How many threads to use for rendering. * @see MultiResolutionRenderer */ public ViewerOptions numRenderingThreads( final int n ) { values.numRenderingThreads = n; return this; } /** * Set whether volatile versions of sources should be used if available. * * @param v * whether volatile versions of sources should be used if * available. * @see MultiResolutionRenderer */ public ViewerOptions useVolatileIfAvailable( final boolean v ) { values.useVolatileIfAvailable = v; return this; } public ViewerOptions msgOverlay( final MessageOverlayAnimator o ) { values.msgOverlay = o; return this; } public ViewerOptions transformEventHandlerFactory( final TransformEventHandlerFactory< AffineTransform3D > f ) { values.transformEventHandlerFactory = f; return this; } /** * Set the factory for creating {@link AccumulateProjector}. This can be * used to customize how sources are combined. * * @param f * factory for creating {@link AccumulateProjector}. * @see MultiResolutionRenderer */ public ViewerOptions accumulateProjectorFactory( final AccumulateProjectorFactory< ARGBType > f ) { values.accumulateProjectorFactory = f; return this; } /** * TODO javadoc * TODO is this config option necessary? * * @param c * @return */ public ViewerOptions inputTriggerConfig( final InputTriggerConfig c ) { values.inputTriggerConfig = c; return this; } /** * Read-only {@link ViewerOptions} values. */ public static class Values { private int width = 800; private int height = 600; private double[] screenScales = new double[] { 1, 0.75, 0.5, 0.25, 0.125 }; private long targetRenderNanos = 30 * 1000000l; private boolean doubleBuffered = true; private int numRenderingThreads = 3; private boolean useVolatileIfAvailable = true; private MessageOverlayAnimator msgOverlay = new MessageOverlayAnimator( 800 ); private TransformEventHandlerFactory< AffineTransform3D > transformEventHandlerFactory = TransformEventHandler3D.factory(); private AccumulateProjectorFactory< ARGBType > accumulateProjectorFactory = AccumulateProjectorARGB.factory; private InputTriggerConfig inputTriggerConfig = null; public ViewerOptions optionsFromValues() { return new ViewerOptions(). width( width ). height( height ). screenScales( screenScales ). targetRenderNanos( targetRenderNanos ). doubleBuffered( doubleBuffered ). numRenderingThreads( numRenderingThreads ). useVolatileIfAvailable( useVolatileIfAvailable ). msgOverlay( msgOverlay ). transformEventHandlerFactory( transformEventHandlerFactory ). accumulateProjectorFactory( accumulateProjectorFactory ). inputTriggerConfig( inputTriggerConfig ); } public int getWidth() { return width; } public int getHeight() { return height; } public double[] getScreenScales() { return screenScales; } public long getTargetRenderNanos() { return targetRenderNanos; } public boolean isDoubleBuffered() { return doubleBuffered; } public int getNumRenderingThreads() { return numRenderingThreads; } public boolean isUseVolatileIfAvailable() { return useVolatileIfAvailable; } public MessageOverlayAnimator getMsgOverlay() { return msgOverlay; } public TransformEventHandlerFactory< AffineTransform3D > getTransformEventHandlerFactory() { return transformEventHandlerFactory; } public AccumulateProjectorFactory< ARGBType > getAccumulateProjectorFactory() { return accumulateProjectorFactory; } public InputTriggerConfig getInputTriggerConfig() { return inputTriggerConfig; } } }
package client_store; import client.PubSubHandler; import common.*; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class ClientState implements Serializable { private int tcpPort; private List<GamePublicData> availableGames; private Player player; private String host; private GameMap gameMap; private RRNotification currentReqRespNotification; private PSNotification currentPubSubNotification; private long delayReturnToGameList; private boolean connectionActive; private boolean inRoom; public ClientState() { this.availableGames = new ArrayList<>(); this.tcpPort = 29999; this.host = "localhost"; this.delayReturnToGameList = 5000; this.connectionActive = true; this.inRoom = false; this.currentReqRespNotification = new RRNotification(false,null,null,null,null,null,null,null); this.currentPubSubNotification = new PSNotification(null,null,null,false,false,null,null,false,false,false,false,null); } public int getTcpPort() { return tcpPort; } public void setTcpPort(int tcpPort) { this.tcpPort = tcpPort; } public List<GamePublicData> getAvailableGames() { return availableGames; } public void setAvailableGames(List<GamePublicData> availableGames) { this.availableGames = availableGames; } public Player getPlayer() { return player; } public void setPlayer(Player player) { this.player = player; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public GameMap getGameMap() { return gameMap; } public void setGameMap(GameMap gameMap) { this.gameMap = gameMap; } public RRNotification getCurrentReqRespNotification() { return currentReqRespNotification; } public void setCurrentReqRespNotification(RRNotification currentReqRespNotification) { this.currentReqRespNotification = currentReqRespNotification; } public PSNotification getCurrentPubSubNotification() { return currentPubSubNotification; } public void setCurrentPubSubNotification(PSNotification currentPubSubNotification) { this.currentPubSubNotification = currentPubSubNotification; } public long getDelayReturnToGameList() { return delayReturnToGameList; } public void setDelayReturnToGameList(long delayReturnToGameList) { this.delayReturnToGameList = delayReturnToGameList; } public boolean isConnectionActive() { return connectionActive; } public void setConnectionActive(boolean connectionActive) { this.connectionActive = connectionActive; } public boolean isInRoom() { return inRoom; } public void setInRoom(boolean inRoom) { this.inRoom = inRoom; } }
package com.fundynamic.d2tm; import com.fundynamic.d2tm.game.state.PlayingState; import com.fundynamic.d2tm.game.terrain.impl.DuneTerrainFactory; import com.fundynamic.d2tm.graphics.ImageRepository; import com.fundynamic.d2tm.graphics.Shroud; import com.fundynamic.d2tm.graphics.Theme; import com.fundynamic.d2tm.math.Vector2D; import org.newdawn.slick.GameContainer; import org.newdawn.slick.SlickException; import org.newdawn.slick.state.StateBasedGame; import org.newdawn.slick.util.Bootstrap; public class Game extends StateBasedGame { public static final int SCREEN_WIDTH = 800; public static final int SCREEN_HEIGHT = 600; public static final int TILE_SIZE = 32; public static final int HALF_TILE = TILE_SIZE / 2; public static final boolean DEBUG_INFO = false; // if true, it speeds up some things so we can demo it faster public static final boolean RECORDING_VIDEO = false; public static Vector2D getResolution() { return Vector2D.create(SCREEN_WIDTH, SCREEN_HEIGHT); } public Game(String title) { super(title); } @Override public void initStatesList(GameContainer container) throws SlickException { ImageRepository imageRepository = new ImageRepository(); DuneTerrainFactory terrainFactory = new DuneTerrainFactory( new Theme( imageRepository.loadAndCache("sheet_terrain.png"), TILE_SIZE ) ); container.setShowFPS(false); container.setVSync(true); PlayingState playingState = new PlayingState( container, terrainFactory, imageRepository, new Shroud( imageRepository.loadAndCache("shroud_edges.png"), TILE_SIZE ), TILE_SIZE ); addState(playingState); } public static void main(String[] args) { Bootstrap.runAsApplication(new Game("Dune II - The Maker"), SCREEN_WIDTH, SCREEN_HEIGHT, false); } }
package ljdp.minechem.common; import java.util.ArrayList; import java.util.List; import ljdp.minechem.api.core.EnumMolecule; import ljdp.minechem.api.util.Constants; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.util.DamageSource; import net.minecraft.world.World; public class Pharm { public static void triggerPlayerEffect(EnumMolecule molecule, EntityPlayer entityPlayer) { World world = entityPlayer.worldObj; // Mandrake's Realm switch (molecule) { case water: entityPlayer.getFoodStats().addStats(1, .1F); break; case starch: entityPlayer.getFoodStats().addStats(2, .2F); break; case stevenk: entityPlayer.getFoodStats().addStats(2, .2F); break; case sucrose: entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), Constants.TICKS_PER_SECOND * 5, 0)); entityPlayer.getFoodStats().addStats(1, .1F); break; case psilocybin: entityPlayer.addPotionEffect(new PotionEffect(Potion.confusion.getId(), Constants.TICKS_PER_SECOND * 30, 5)); entityPlayer.attackEntityFrom(DamageSource.generic, 2); entityPlayer.addPotionEffect(new PotionEffect(Potion.nightVision.getId(), Constants.TICKS_PER_SECOND * 30, 5)); break; case amphetamine: entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), Constants.TICKS_PER_SECOND * 20, 7)); break; case methamphetamine: entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), Constants.TICKS_PER_SECOND * 30, 7)); break; case poison: biocide: entityPlayer.addPotionEffect(new PotionEffect(Potion.wither.getId(), Constants.TICKS_PER_SECOND * 60, 2)); break; case biocide: entityPlayer.addPotionEffect(new PotionEffect(Potion.wither.getId(), Constants.TICKS_PER_SECOND * 60, 2)); break; case ethanol: entityPlayer.addPotionEffect(new PotionEffect(Potion.confusion.getId(), Constants.TICKS_PER_SECOND * 10, 1)); entityPlayer.getFoodStats().addStats(3, .1F); break; case cyanide: entityPlayer.attackEntityFrom(DamageSource.generic, 20); break; case penicillin: cureAllPotions(world, entityPlayer); entityPlayer.addPotionEffect(new PotionEffect(Potion.regeneration.getId(), Constants.TICKS_PER_MINUTE * 2, 1)); break; case testosterone: entityPlayer.addPotionEffect(new PotionEffect(Potion.damageBoost.getId(), Constants.TICKS_PER_MINUTE * 5, 2)); entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), Constants.TICKS_PER_MINUTE * 5, 0)); entityPlayer.addPotionEffect(new PotionEffect(Potion.damageBoost.getId(), Constants.TICKS_PER_MINUTE * 5, 2)); break; case xanax: // cureAllPotions(world, entityPlayer); pantherine: entityPlayer.addPotionEffect(new PotionEffect(Potion.confusion.getId(), Constants.TICKS_PER_SECOND * 30, 5)); entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSlowdown.getId(), Constants.TICKS_PER_SECOND * 30, 2)); break; case pantherine: entityPlayer.addPotionEffect(new PotionEffect(Potion.confusion.getId(), Constants.TICKS_PER_SECOND * 30, 5)); entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSlowdown.getId(), Constants.TICKS_PER_SECOND * 30, 2)); break; case mescaline: entityPlayer.attackEntityFrom(DamageSource.generic, 2); entityPlayer.addPotionEffect(new PotionEffect(Potion.confusion.getId(), Constants.TICKS_PER_SECOND * 30, 2)); entityPlayer.addPotionEffect(new PotionEffect(Potion.blindness.getId(), Constants.TICKS_PER_SECOND * 30, 2)); break; case asprin: cureAllPotions(world, entityPlayer); entityPlayer.addPotionEffect(new PotionEffect(Potion.regeneration.getId(), Constants.TICKS_PER_MINUTE * 1, 1)); break; case shikimicAcid: salt: // No effect. break; case phosgene: aalc: sulfuricAcid: buli: // all of these cause tons of damage to human flesh!!!!!!!! entityPlayer.setFire(100); break; case ttx: entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSlowdown.getId(), Constants.TICKS_PER_SECOND * 60, 10)); entityPlayer.addPotionEffect(new PotionEffect(Potion.wither.getId(), Constants.TICKS_PER_SECOND * 60, 1)); break; case fingolimod: entityPlayer.addPotionEffect(new PotionEffect(Potion.damageBoost.getId(), Constants.TICKS_PER_MINUTE * 5, 2)); entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), Constants.TICKS_PER_MINUTE * 5, 2)); entityPlayer.addPotionEffect(new PotionEffect(Potion.regeneration.getId(), Constants.TICKS_PER_MINUTE * 5, 2)); entityPlayer.addPotionEffect(new PotionEffect(Potion.hunger.getId(), Constants.TICKS_PER_SECOND * 80, 1)); break; case afroman: cureAllPotions(world, entityPlayer); entityPlayer.addPotionEffect(new PotionEffect(Potion.confusion.getId(), Constants.TICKS_PER_SECOND * 60, 5)); entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSlowdown.getId(), Constants.TICKS_PER_SECOND * 60, 1)); entityPlayer.addPotionEffect(new PotionEffect(Potion.hunger.getId(), Constants.TICKS_PER_SECOND * 120, 5)); break; case nod: entityPlayer.addPotionEffect(new PotionEffect(Potion.hunger.getId(), Constants.TICKS_PER_MINUTE * 8, 1)); break; case hist: cureAllPotions(world, entityPlayer); entityPlayer.addPotionEffect(new PotionEffect(Potion.confusion.getId(), Constants.TICKS_PER_SECOND * 20, 5)); entityPlayer.getFoodStats().addStats(2, .2F); break; case pal2: // this sh*t is real nasty entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSlowdown.getId(), Constants.TICKS_PER_SECOND * 60, 20)); entityPlayer.addPotionEffect(new PotionEffect(Potion.wither.getId(), Constants.TICKS_PER_SECOND * 60, 2)); entityPlayer.addPotionEffect(new PotionEffect(Potion.confusion.getId(), Constants.TICKS_PER_SECOND * 60, 5)); break; case theobromine: // Speed boost entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), Constants.TICKS_PER_MINUTE * 5, 1)); break; case ret: entityPlayer.addPotionEffect(new PotionEffect(Potion.nightVision.getId(), Constants.TICKS_PER_SECOND * 120, 1)); entityPlayer.getFoodStats().addStats(3, .1F); break; case glycine: entityPlayer.addPotionEffect(new PotionEffect(Potion.digSpeed.getId(), Constants.TICKS_PER_SECOND * 120, 1)); entityPlayer.addPotionEffect(new PotionEffect(Potion.jump.getId(), Constants.TICKS_PER_SECOND * 120, 1)); break; case alinine: entityPlayer.addPotionEffect(new PotionEffect(Potion.digSpeed.getId(), Constants.TICKS_PER_SECOND * 120, 1)); entityPlayer.addPotionEffect(new PotionEffect(Potion.jump.getId(), Constants.TICKS_PER_SECOND * 120, 1)); break; case serine: entityPlayer.addPotionEffect(new PotionEffect(Potion.digSpeed.getId(), Constants.TICKS_PER_SECOND * 120, 1)); entityPlayer.addPotionEffect(new PotionEffect(Potion.jump.getId(), Constants.TICKS_PER_SECOND * 120, 1)); break; case arginine: entityPlayer.addPotionEffect(new PotionEffect(Potion.digSpeed.getId(), Constants.TICKS_PER_SECOND * 120, 1)); entityPlayer.addPotionEffect(new PotionEffect(Potion.jump.getId(), Constants.TICKS_PER_SECOND * 120, 1)); break; case redrocks: entityPlayer.addPotionEffect(new PotionEffect(Potion.confusion.getId(), Constants.TICKS_PER_SECOND * 120, 5)); entityPlayer.attackEntityFrom(DamageSource.generic, 2); entityPlayer.addPotionEffect(new PotionEffect(Potion.nightVision.getId(), Constants.TICKS_PER_SECOND * 120, 5)); entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), Constants.TICKS_PER_SECOND * 120, 7)); break; case coke: entityPlayer.addPotionEffect(new PotionEffect(Potion.confusion.getId(), Constants.TICKS_PER_SECOND * 60, 5)); entityPlayer.attackEntityFrom(DamageSource.generic, 2); entityPlayer.addPotionEffect(new PotionEffect(Potion.nightVision.getId(), Constants.TICKS_PER_SECOND * 60, 5)); entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), Constants.TICKS_PER_SECOND * 60, 10)); break; case metblue: cureAllPotions(world, entityPlayer); entityPlayer.addPotionEffect(new PotionEffect(Potion.regeneration.getId(), Constants.TICKS_PER_SECOND * 30, 2)); entityPlayer.addPotionEffect(new PotionEffect(Potion.weakness.getId(), Constants.TICKS_PER_SECOND * 30, 2)); break; default: entityPlayer.attackEntityFrom(DamageSource.generic, 5); break; } } public static void cureAllPotions(World world, EntityPlayer entityPlayer) { List<PotionEffect> activePotions = new ArrayList<PotionEffect>(entityPlayer.getActivePotionEffects()); for (PotionEffect potionEffect : activePotions) { entityPlayer.removePotionEffect(potionEffect.getPotionID()); } } }
package com.mergesort; import java.io.*; import java.util.Arrays; import java.util.Scanner; /** * Output data: 1 - to txt files, 2 - to console. * Default output to console! */ public class OutputData { private static final String currentDir = System.getProperty("user.dir"); private static final String fs = System.getProperty("file.separator"); private static final String dirFileInProject = fs + "files" + fs + "SortedDataValuesArray.txt"; public static void setArray(int[] array) { chooseOutput(array); } private static void chooseOutput(int[] array) { System.out.println("\n Please choose output data: 1 - to txt file, 2 - to console.\n Default output to console!"); Scanner in = new Scanner(System.in); System.out.print("\n Choose: "); String methodOutput = in.nextLine(); try { if (Integer.parseInt(methodOutput) == 1) { writeToFile(array); } else { consoleOutput(array); } } catch (NumberFormatException e) { consoleOutput(array); } } private static void writeToFile(int[] array) { File file = new File(currentDir, dirFileInProject); try (PrintWriter writer = new PrintWriter(file.getAbsoluteFile())) { for (int i : array) { writer.print(i + " "); } } catch (IOException e) { System.err.println(" Something wrong!"); } } private static void consoleOutput(int[] array) { System.out.println(Arrays.toString(array)); } }
package com.spoqa.battery; public final class Config { static public boolean DEBUG_DUMP_REQUEST = false; static public boolean DEBUG_DUMP_RESPONSE = false; }
package dalicia.rsvp; import static dalicia.rsvp.JsonHelper.newLenientObjectMapper; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Locale; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.appengine.repackaged.com.google.common.base.Throwables; import com.google.common.base.Optional; import dalicia.rsvp.protocol.ErrorResponse; import dalicia.rsvp.protocol.SuccessResponse; public class RsvpServlet extends HttpServlet { private static final Logger log = Logger.getLogger(LoginServlet.class.getName()); private static final ObjectMapper objectMapper = newLenientObjectMapper(); private static final InvitationDao invitationDao = new InvitationDaoImpl(); @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("application/json"); String code = request.getParameter("code"); if (code == null) { response.getWriter().println(objectMapper.writeValueAsString(new ErrorResponse("badRequest", "missing 'code' parameter"))); return; } code = code.toLowerCase(Locale.ENGLISH); Optional<Invitation> invitation = invitationDao.load(code); if (!invitation.isPresent()) { log.info("bad code: '" + code + "'"); response.getWriter().println(objectMapper.writeValueAsString(new ErrorResponse("badCode", "unrecognized code: '" + code + "'"))); return; } log.info("got invitation: " + invitation.get()); String numAttendingStr = request.getParameter("numGuests"); if (numAttendingStr == null) { response.getWriter().println(objectMapper.writeValueAsString(new ErrorResponse("badRequest", "missing 'numAttending' parameter"))); return; } final int numAttending; try { numAttending = Integer.parseInt(numAttendingStr); } catch (NumberFormatException e) { response.getWriter().println(objectMapper.writeValueAsString(new ErrorResponse("badRequest", "'numAttending' must be an integer"))); return; } if (invitation.get().getMaxGuests() < numAttending) { response.getWriter().println(objectMapper.writeValueAsString(new ErrorResponse("badRequest", "'numAttending' must be <= max guests (" + invitation.get().getMaxGuests() + ")"))); return; } invitation.get().setActualGuests(numAttending); try { log.info("Saving response {code='" + code + "' numAttending='" + numAttending + "'}"); invitationDao.saveResponse(code, numAttending); } catch (Exception e) { sendErrorEmail(e); log.log(Level.SEVERE, "failed to save response", e); response.getWriter().println(objectMapper.writeValueAsString(new ErrorResponse("rsvpFailed", "Oops, something went wrong -- sorry about that! If it happens again, please get in touch with us by email at <dnault@mac.com> or by phone at 650-242-8376."))); return; } response.getWriter().println(objectMapper.writeValueAsString(new SuccessResponse(invitation.get()))); sendEmail(invitation.get()); } private void sendErrorEmail(Exception error) { sendEmail("RSVP failure: " + error.getMessage(), Throwables.getStackTraceAsString(error)); } private void sendEmail(String subject, String body) { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress("dnault@gmail.com", "Dave Nault")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress("aradia@gmail.com", "Alicia Ong")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress("dnault@mac.com", "Dave Nault")); msg.setSubject(subject); msg.setText(body); Transport.send(msg); } catch (Exception e) { log.log(Level.SEVERE, "failed to send email", e); } } private void sendEmail(Invitation invitation) { try { String subject = "RSVP: " + invitation.getName() + " (" + invitation.getActualGuests() + ")"; String body = objectMapper.writeValueAsString(invitation.getActualGuests()); sendEmail(subject, body); } catch (Exception e) { log.log(Level.SEVERE, "failed to send email", e); } } }
package de.iani.cubequest; import com.google.common.base.Verify; import de.iani.cubequest.util.ChatAndTextUtil; import de.iani.cubequest.util.ItemStackUtil; import java.sql.SQLException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.logging.Level; import net.md_5.bungee.api.ChatColor; import org.bukkit.Bukkit; import org.bukkit.Sound; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; public class Reward implements ConfigurationSerializable { private int cubes; private int questPoints; private int xp; private ItemStack[] items; public Reward() { this(0, new ItemStack[0]); } public Reward(int cubes) { this(cubes, new ItemStack[0]); } public Reward(ItemStack[] items) { this(0, items); } public Reward(int cubes, ItemStack[] items) { this(cubes, 0, 0, items); } public Reward(int cubes, int questPoints, int xp, ItemStack[] items) { Verify.verify(cubes >= 0); Verify.verify(questPoints >= 0); Verify.verify(xp >= 0); this.cubes = cubes; this.questPoints = questPoints; this.xp = xp; this.items = items == null ? new ItemStack[0] : ItemStackUtil.shrinkItemStack(items); } @SuppressWarnings("unchecked") public Reward(Map<String, Object> serialized) throws InvalidConfigurationException { try { this.cubes = serialized.containsKey("cubes") ? (Integer) serialized.get("cubes") : 0; this.questPoints = serialized.containsKey("questPoints") ? (Integer) serialized.get("questPoints") : 0; this.xp = serialized.containsKey("xp") ? (Integer) serialized.get("xp") : 0; this.items = serialized.containsKey("items") ? ((List<ItemStack>) serialized.get("items")).toArray(new ItemStack[0]) : new ItemStack[0]; } catch (Exception e) { throw new InvalidConfigurationException(e); } } public int getCubes() { return this.cubes; } public int getQuestPoints() { return this.questPoints; } public int getXp() { return this.xp; } public ItemStack[] getItems() { return this.items; } public Reward add(Reward other) { ItemStack newItems[] = new ItemStack[this.items.length + other.items.length]; for (int i = 0; i < this.items.length; i++) { newItems[i] = this.items[i]; } for (int i = 0; i < other.items.length; i++) { newItems[i + this.items.length] = other.items[i]; } return new Reward(this.cubes + other.cubes, this.questPoints + other.questPoints, this.xp + other.xp, newItems); } public void pay(Player player) { if (!CubeQuest.getInstance().isPayRewards()) { ChatAndTextUtil.sendXpAndQuestPointsMessage(player, this.xp, this.questPoints); CubeQuest.getInstance().getPlayerData(player).applyQuestPointsAndXP(this); if (this.cubes != 0 || this.items.length != 0) { addToTreasureChest(player.getUniqueId()); ChatAndTextUtil.sendNormalMessage(player, "Deine Belohnung wurde in deine Schatzkiste gelegt."); } return; } if (this.items.length != 0) { ItemStack[] playerInv = player.getInventory().getContents(); playerInv = Arrays.copyOf(playerInv, 36); Inventory clonedPlayerInventory = Bukkit.createInventory(null, 36); clonedPlayerInventory.setContents(playerInv); int priceCount = this.items == null ? 0 : this.items.length; if (priceCount > 0) { ItemStack[] temp = new ItemStack[priceCount]; for (int i = 0; i < priceCount; i++) { temp[i] = this.items[i].clone(); } if (!clonedPlayerInventory.addItem(temp).isEmpty()) { ChatAndTextUtil.sendWarningMessage(player, "Du hast nicht genügend Platz in deinem Inventar! Deine Belohnung wird in deine Schatzkiste gelegt."); player.updateInventory(); addToTreasureChest(player.getUniqueId()); return; } } if (priceCount > 0) { ItemStack[] temp = new ItemStack[priceCount]; for (int i = 0; i < priceCount; i++) { temp[i] = this.items[i].clone(); } player.getInventory().addItem(temp); for (ItemStack stack: this.items) { StringBuilder t = new StringBuilder(" "); if (stack.getAmount() > 1) { t.append(stack.getAmount()).append(" "); } t.append(ChatAndTextUtil.capitalize(stack.getType().name(), true)); if (stack.getDurability() > 0) { t.append(':').append(stack.getDurability()); } ItemMeta meta = stack.getItemMeta(); if (meta.hasDisplayName()) { t.append(" (").append(meta.getDisplayName()).append(ChatColor.YELLOW) .append(")"); } ChatAndTextUtil.sendMessage(player, t.toString()); } } } ChatAndTextUtil.sendXpAndQuestPointsMessage(player, this.xp, this.questPoints); CubeQuest.getInstance().getPlayerData(player).applyQuestPointsAndXP(this); CubeQuest.getInstance().payCubes(player, this.cubes); if (this.cubes != 0) { ChatAndTextUtil.sendNormalMessage(player, "Du hast " + this.cubes + " Cubes erhalten."); } ChatAndTextUtil.sendMessage(player, ChatColor.GRAY + "Du hast eine Belohnung bekommen!"); player.playSound(player.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1f, 1f); } public void addToTreasureChest(UUID playerId) { if (!CubeQuest.getInstance().addToTreasureChest(playerId, this)) { try { CubeQuest.getInstance().getDatabaseFassade() .addRewardToDeliver(new Reward(getCubes(), getItems()), playerId); } catch (SQLException e) { CubeQuest.getInstance().getLogger().log(Level.SEVERE, "Could not add Quest-Reward to database for player with UUID " + playerId, e); } } } @Override public Map<String, Object> serialize() { HashMap<String, Object> data = new HashMap<>(); data.put("cubes", this.cubes); data.put("questPoints", this.questPoints); data.put("xp", this.xp); data.put("items", this.items); return data; } public boolean isEmpty() { return this.cubes == 0 && this.questPoints == 0 && this.xp == 0 && this.items.length == 0; } public String toNiceString() { if (isEmpty()) { return "Nichts"; } String result = ""; result += this.cubes + " Cubes"; result += ", " + this.questPoints + " Punkte"; result += ", " + this.xp + " XP"; if (this.items.length != 0) { result += ", Items: "; for (ItemStack item: this.items) { result += ItemStackUtil.toNiceString(item) + ", "; } result = result.substring(0, result.length() - ", ".length()); } return result; } }
package edu.jhu.hlt.optimize; import java.util.Date; import org.apache.commons.lang3.mutable.MutableDouble; import org.apache.commons.lang3.mutable.MutableInt; import org.slf4j.LoggerFactory; import edu.jhu.hlt.optimize.BottouSchedule.BottouSchedulePrm; import edu.jhu.hlt.optimize.function.DifferentiableBatchFunction; import edu.jhu.hlt.optimize.function.Function; import edu.jhu.hlt.optimize.function.NonstationaryFunction; import edu.jhu.hlt.optimize.function.SampleFunction; import edu.jhu.hlt.optimize.function.ValueGradient; import edu.jhu.hlt.util.OnOffLogger; import edu.jhu.hlt.util.Prm; import edu.jhu.prim.util.Lambda.FnIntDoubleToDouble; import edu.jhu.prim.util.Timer; import edu.jhu.prim.vector.IntDoubleDenseVector; import edu.jhu.prim.vector.IntDoubleVector; /** * Stochastic gradient descent with minibatches. * * We use the gain schedule suggested in Leon Bottou's (2012) SGD Tricks paper. * * @author mgormley */ public class SGD implements Optimizer<DifferentiableBatchFunction> { /** Options for this optimizer. */ public static class SGDPrm extends Prm { private static final long serialVersionUID = 1L; /** The gain schedule which defines the learning rate at each iteration. */ public GainSchedule sched = new BottouSchedule(new BottouSchedulePrm()); /** Whether to automatically select the learning rate. (Leon Bottou's "secret ingredient".) */ public boolean autoSelectLr = true; /** How many epochs between auto-select runs. */ public int autoSelectFreq = 5; /** The number of passes over the dataset to perform. */ public int numPasses = 10; /** The batch size to use at each step. */ public int batchSize = 15; /** Whether batches should be sampled with replacement. */ public boolean withReplacement = false; /** Date by which to stop. */ public Date stopBy = null; /** Whether to compute the function value on the non-final iterations. */ public boolean computeValueOnNonFinalIter = true; /** Whether to return the point with min validation score. */ public boolean earlyStopping = true; /** Whether to do parameter averaging. */ public boolean averaging = false; /** The pass at which to begin averaging of the parameters. */ public double passToStartAvg = 1.0; public SGDPrm() { } } private static final OnOffLogger log = new OnOffLogger(LoggerFactory.getLogger(SGD.class)); private SGDPrm prm; /** * Constructs an SGD optimizer. */ public SGD(SGDPrm prm) { this.prm = prm; } protected SGD copy() { // Don't copy the bestPoint / bestDevScore. return new SGD(Prm.clonePrm(this.prm)); } /** * Initializes all the parameters for optimization. */ protected void init(DifferentiableBatchFunction function, IntDoubleVector point) { prm.sched.init(function); } /** * Maximize the function starting at the given initial point. */ @Override public boolean maximize(DifferentiableBatchFunction function, IntDoubleVector point) { return optimize(function, point, true, null); } /** * Minimize the function starting at the given initial point. */ public boolean minimize(DifferentiableBatchFunction function, IntDoubleVector point) { return optimize(function, point, false, null); } public boolean optimize(DifferentiableBatchFunction function, final IntDoubleVector point, final boolean maximize, Function devLoss) { init(function, point); final int itersPerEpoch = getItersPerPass(function); log.info("Number of batch gradient iterations: " + prm.numPasses * itersPerEpoch); optimizeWithoutInit(function, point, maximize, itersPerEpoch, 0, devLoss); // We don't test for convergence. return false; } /** Gets the number of (batch) iterations per epoch (i.e. pass through the training data). */ protected int getItersPerPass(DifferentiableBatchFunction function) { return (int) Math.ceil((double) function.getNumExamples() / prm.batchSize); } private double optimizeWithoutInit(DifferentiableBatchFunction function, final IntDoubleVector point, final boolean maximize, final int itersPerPass, int pass, Function devLoss) { final int maxIters = prm.numPasses * itersPerPass; final int startIter = pass * itersPerPass; int iter = startIter; BatchSampler batchSampler = new BatchSampler(prm.withReplacement, function.getNumExamples(), prm.batchSize); Timer passTimer = new Timer(); Timer tuneTimer = new Timer(); double bestDevLoss = Double.MAX_VALUE; IntDoubleVector bestPoint = prm.earlyStopping && devLoss != null ? new IntDoubleDenseVector(function.getNumDimensions()) : null; IntDoubleVector avgPoint = prm.averaging ? new IntDoubleDenseVector(point) : null; assert !prm.averaging || prm.passToStartAvg >= pass; // Setup. if (prm.stopBy != null) { log.debug("Max time alloted (hr): " + (prm.stopBy.getTime() - new Date().getTime()) / 1000. / 3600.); } if (function instanceof NonstationaryFunction) { ((NonstationaryFunction) function).updatateIterAndMax(iter, maxIters); } assert (function.getNumDimensions() >= point.getNumImplicitEntries()); // Optimization. passTimer.start(); passLoop: for (; pass < prm.numPasses; pass++) { if (prm.autoSelectLr && (pass % prm.autoSelectFreq == 0)) { passTimer.stop(); tuneTimer.start(); // Auto select every autoSelecFreq epochs. autoSelectLr(function, point, maximize, pass); log.info("Average time (min) per tuning pass: " + tuneTimer.avgSec() / 60.0); tuneTimer.stop(); passTimer.start(); } if (prm.computeValueOnNonFinalIter) { bestDevLoss = sufferLossAndUpdateBest(function, point, avgPoint, pass, devLoss, startIter, iter, bestDevLoss, bestPoint)[1]; } // Make a full pass through the training data. for (int i=0; i<itersPerPass; i++) { int[] batch = batchSampler.sampleBatch(); if (function instanceof NonstationaryFunction) { ((NonstationaryFunction) function).updatateIterAndMax(iter, maxIters); } // Get the current value and gradient of the function. ValueGradient vg = function.getValueGradient(point, batch); double value = vg.getValue(); final IntDoubleVector gradient = vg.getGradient(); log.trace(String.format("Function value on batch = %g at iteration = %d", value, iter)); prm.sched.takeNoteOfGradient(gradient); // Step in the direction of the gradient (maximization) or opposite it (minimization). takeGradientStep(point, gradient, maximize, iter); logAvgLrAndStepSize(point, gradient, iter); logStatsAboutPoint(point); if (prm.averaging) { // Non-sparse update of averaged parameters. double t0 = prm.passToStartAvg * itersPerPass; int t = iter + 1; double mu_t = 1.0 / Math.max(1, t - t0); for (int m=0; m<function.getNumDimensions(); m++) { avgPoint.set(m, (1 - mu_t) * avgPoint.get(m) + mu_t * point.get(m)); } } if (prm.stopBy != null) { Date now = new Date(); if (now.after(prm.stopBy)) { log.info(String.format("Current time is after stop-by time. now=%s, stopBy=%s", now.toString(), prm.stopBy.toString())); log.info("Stopping training early."); break passLoop; } } iter++; } // Another full pass through the data has been completed. log.debug(String.format("Average time per pass (min): %.2g", passTimer.totSec() / 60.0 / (pass + 1))); } double[] pair = sufferLossAndUpdateBest(function, point, avgPoint, pass, devLoss, startIter, iter, bestDevLoss, bestPoint); double value = pair[0]; bestDevLoss = pair[1]; if (prm.earlyStopping && devLoss != null) { // Return the best point seen so far. log.debug("Early stopping returning point with dev loss: " + bestDevLoss); for (int m=0; m<function.getNumDimensions(); m++) { point.set(m, bestPoint.get(m)); } } else if (prm.averaging) { log.debug("Returning averaged parameters."); for (int m=0; m<function.getNumDimensions(); m++) { point.set(m, avgPoint.get(m)); } } return value; } protected double[] sufferLossAndUpdateBest(DifferentiableBatchFunction function, IntDoubleVector point, IntDoubleVector avgPoint, int pass, Function devLoss, int startIter, int iter, double bestDevLoss, IntDoubleVector bestPoint) { if (prm.averaging) { point = avgPoint; } // Report the value of the function on all the examples. double value = function.getValue(point); log.info(String.format("Function value on all examples = %g at iteration = %d on pass = %d", value, iter, pass)); if (devLoss != null) { // Report the loss on validation data. double devScore = devLoss.getValue(point); log.info(String.format("Dev loss = %g at iteration = %d on pass = %d", devScore, iter, pass)); if (prm.earlyStopping && devScore < bestDevLoss) { // Store the best point seen so far. for (int m=0; m<function.getNumDimensions(); m++) { bestPoint.set(m, point.get(m)); } bestDevLoss = devScore; } } return new double[]{value, bestDevLoss}; } protected void takeGradientStep(final IntDoubleVector point, final IntDoubleVector gradient, final boolean maximize, final int iterCount) { // Scale the gradient by the parameter-specific learning rate. gradient.apply(new FnIntDoubleToDouble() { @Override public double call(int index, double value) { double lr = prm.sched.getLearningRate(iterCount, index); if (maximize) { value = lr * value; } else { value = - lr * value; } assert !Double.isNaN(value); assert !Double.isInfinite(value); return value; } }); // Take a step in the direction of the gradient. point.add(gradient); } private void logAvgLrAndStepSize(final IntDoubleVector point, final IntDoubleVector gradient, final int iterCount) { if (log.isTraceEnabled()) { // Compute the average learning rate and the average step size. final MutableDouble avgLr = new MutableDouble(0.0); final MutableDouble grad2norm = new MutableDouble(0d); final MutableInt numNonZeros = new MutableInt(0); gradient.apply(new FnIntDoubleToDouble() { @Override public double call(int index, double value) { double lr = prm.sched.getLearningRate(iterCount, index); assert !Double.isNaN(point.get(index)); if (value != 0.0) { avgLr.add(lr); double grad_i = gradient.get(index); grad2norm.add(grad_i * grad_i); numNonZeros.increment(); } return value; } }); avgLr.setValue(avgLr.doubleValue() / numNonZeros.doubleValue()); grad2norm.setValue(Math.sqrt(grad2norm.doubleValue())); if (numNonZeros.doubleValue() == 0) { avgLr.setValue(0.0); grad2norm.setValue(0.0); } log.trace("Average learning rate: " + avgLr); log.trace("Step 2-norm: " + grad2norm); } } private void logStatsAboutPoint(IntDoubleVector point) { if (log.isTraceEnabled()) { log.trace(String.format("min=%g max=%g infnorm=%g l2=%g", point.getMin(), point.getMax(), point.getInfNorm(), point.getL2Norm())); } } protected void autoSelectLr(DifferentiableBatchFunction function, final IntDoubleVector point, final boolean maximize, final int pass) { double eta0 = autoSelectLrStatic(function, point, maximize, this, pass); this.setEta0(eta0); } private static double autoSelectLrStatic(DifferentiableBatchFunction function, final IntDoubleVector point, final boolean maximize, SGD orig, int pass) { log.info("Auto-selecting the best learning rate constant at pass " + pass); // Parameters for how we perform auto selection of the initial learning rate. // The max number of iterations. int numEvals = 10; // How to update the learning rate at each iteration (e.g. 2 yeilds doubling, then halving) double factor = 2; // This sample size equates to a single epoch. int sampleSize = (int) Math.ceil((double) function.getNumExamples() / numEvals); SampleFunction sampFunction = new SampleFunction(function, sampleSize); // Get the objective value with no training. double startObj = sampFunction.getValue(point); log.info("Initial sample obj="+startObj); // Initialize the "best" values. double origEta0 = orig.getEta0(); double bestEta = origEta0; double bestObj = startObj; boolean increasing = true; double eta = origEta0; for (int i=0; i<numEvals; i++) { double obj = evaluateInitialLr(sampFunction, point, maximize, orig, eta, pass); log.info(String.format("Evaluated initial learning rate: eta="+eta+" obj="+obj)); if (isBetter(obj, bestObj, maximize)) { bestObj = obj; bestEta = eta; } if (!isBetter(obj, startObj, maximize) && increasing) { // If training caused the objective to worsen, then switch from // increasing the learning rate to decreasing it. increasing = false; eta = origEta0; } if (increasing) { // Increase eta by a factor. eta *= factor; } else { // Decrease eta by a factor. eta /= factor; } } // Conservatively return the value for eta smaller than the best one. bestEta = bestEta / factor; log.info("Chose initial learning rate: eta="+bestEta); return bestEta; } private static double evaluateInitialLr(DifferentiableBatchFunction sampFunction, IntDoubleVector origPoint, boolean maximize, SGD orig, double eta, int pass) { SGD sgd = orig.copy(); if (orig.prm == sgd.prm) { throw new IllegalStateException("Copy must create a new prm."); } IntDoubleVector point = origPoint.copy(); SGDPrm prm = sgd.prm; prm.sched = prm.sched.copy(); sgd.setEta0(eta); prm.numPasses = 1; // Only one epoch. prm.autoSelectLr = false; // Don't recurse. prm.computeValueOnNonFinalIter = false; // Report function value only at end. prm.earlyStopping = false; prm.averaging = false; log.setEnabled(false); sgd.init(sampFunction, point); // Make sure we start off the learning rate schedule at the proper place. final int itersPerPass = sgd.getItersPerPass(sampFunction); double obj; try { obj = sgd.optimizeWithoutInit(sampFunction, point, maximize, itersPerPass, pass, null); } catch (Throwable t) { log.setEnabled(true); String msg = (t.getMessage() == null) ? "": " : " + t.getMessage(); log.error("Failed to evaluate hyperparameter. Caught throwable: " + t.getClass() + msg); log.trace("Stacktrace from previous ERROR:\n", t); obj = worstObjValue(maximize); } log.setEnabled(true); return obj; } protected double getEta0() { return prm.sched.getEta0(); } protected void setEta0(double eta) { prm.sched.setEta0(eta); } private static boolean isBetter(double obj, double bestObj, boolean maximize) { return maximize ? obj > bestObj : obj < bestObj; } private static double worstObjValue(boolean maximize) { return maximize ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; } }
package elegit.treefx; import javafx.application.Platform; import javafx.concurrent.Service; import javafx.concurrent.Task; import java.util.ArrayList; import java.util.List; /** * Handles the layout of cells in a TreeGraph in an appropriate tree structure */ public class TreeLayout{ public static int V_SPACING = Cell.BOX_SIZE + 10; public static int H_SPACING = Cell.BOX_SIZE * 3 + 5; public static int V_PAD = 10; public static int H_PAD = 25; public static int cells_moved = 0; // Service to compute the location of where all cells should go public static class ComputeCellPosService extends Service { private List<Integer> maxColumnUsedInRow; private List<Integer> maxColumnWantedInRow; private List<Cell> allCellsSortedByTime; private boolean isInitialSetupFinished; private int cellLocation; public ComputeCellPosService(List<Cell> allCellsSortedByTime, boolean isInitialSetupFinished) { this.maxColumnUsedInRow = new ArrayList<>(); this.maxColumnWantedInRow = new ArrayList<>(); this.maxColumnWantedInRow.add(0,allCellsSortedByTime.size()); this.cellLocation = allCellsSortedByTime.size()-1; this.allCellsSortedByTime = allCellsSortedByTime; this.isInitialSetupFinished = isInitialSetupFinished; } public void setCellLocation(int cellLocation) { this.cellLocation = cellLocation; } @Override protected synchronized Task createTask() { return new Task() { @Override protected Void call() throws Exception { //cellLocation = allCellsSortedByTime.size()-1 - getCellsMoved(); if (cellLocation > allCellsSortedByTime.size()-1) this.failed(); // Get cell at rightmost location not yet placed Cell c = allCellsSortedByTime.get(allCellsSortedByTime.size()-1-cellLocation); // Get where the cell should go based on which columns have been 'reserved' int x = cellLocation; int y = getRowOfCellInColumn(maxColumnWantedInRow, x); // See whether or not this cell will move int oldColumnLocation = c.columnLocationProperty.get(); int oldRowLocation = c.rowLocationProperty.get(); c.columnLocationProperty.set(x); c.rowLocationProperty.set(y); boolean hasCellMoved = oldColumnLocation >= 0 && oldRowLocation >= 0; boolean willCellMove = oldColumnLocation != x || oldRowLocation != y; // Update where the cell has been placed if (y >= maxColumnUsedInRow.size()) maxColumnUsedInRow.add(x); else maxColumnUsedInRow.set(y, x); // Update the reserved rows for (int i = y+1; y< maxColumnWantedInRow.size(); y++) if (maxColumnWantedInRow.get(i) == i) maxColumnWantedInRow.set(i, maxColumnUsedInRow.get(i)); // Set the animation and use parent properties of the cell c.setAnimate(isInitialSetupFinished && willCellMove); c.setUseParentAsSource(!hasCellMoved); // Move the cell - this will happen in a thread //moveCell(c, isInitialSetupFinished && willCellMove, !hasCellMoved); // Update the reserved columns in rows with the cells parents, oldest to newest List<Cell> list = c.getCellParents(); list.sort((c1, c2) -> Long.compare(c1.getTime(), c2.getTime())); // For each parent, oldest to newest, place its want of row in the highest possible for(Cell parent : list){ int col = allCellsSortedByTime.size() -1- allCellsSortedByTime.indexOf(parent); int row = getRowOfCellInColumn(maxColumnWantedInRow, col); System.out.println(col+" "+row); if (maxColumnWantedInRow.size() > row) maxColumnWantedInRow.set(row, col); else maxColumnWantedInRow.add(row, col); } return null; } }; } } /** * Returns a task that will take care of laying out the given * graph into a tree. Uses a combination of recursion and * iteration to pack cells as far up as possible with each * cell being arranged horizontally based on time * @param g the graph to layout * @return a task that, when executed, does the layout of g */ public static Task getTreeLayoutTask(TreeGraph g){ return new Task<Void>(){ private List<Cell> allCellsSortedByTime; /** * Extracts the TreeGraphModel, sorts its cells by time, then relocates * every cell. When complete, updates the model if necessary to show * it has been through the layout process at least once already */ @Override protected Void call() throws Exception{ TreeGraphModel treeGraphModel = g.treeGraphModel; allCellsSortedByTime = treeGraphModel.allCells; allCellsSortedByTime.sort((c1, c2) -> { int i = Long.compare(c2.getTime(), c1.getTime()); if(i == 0){ if(c2.getCellChildren().contains(c1)){ return -1; }else if(c1.getCellChildren().contains(c2)){ return 1; } } return i; }); ComputeCellPosService mover = new ComputeCellPosService(allCellsSortedByTime, false); mover.setOnFailed(event -> { // Schedule the moving of all cells Task moveCells = new Task() { @Override protected Object call() throws Exception { int max = allCellsSortedByTime.size()-1; int percent=0; for (int i = 0; i < max; i++) { moveCell(allCellsSortedByTime.get(i)); /*if (i>0 && 100-(max*100.0/i%100)>percent) { updateProgress(i, max); percent++; }*/ } return null; } }; Thread th = new Thread(moveCells); th.setDaemon(true); th.setName("Cell Mover"); th.start(); if(!isCancelled()){ treeGraphModel.isInitialSetupFinished = true; } }); mover.setOnSucceeded(event -> { mover.setCellLocation(mover.cellLocation-1); mover.restart(); }); mover.start(); return null; } }; } /** * Calculates the row closest to the top of the screen to place the * given cell based on the cell's column and the maximum heights recorded * for each row * @param maxColumnUsedInRow the map of max columns used in each row * @param cellCol the column the cell to examine is in * @return the lowest indexed row in which to place c */ public static int getRowOfCellInColumn(List<Integer> maxColumnUsedInRow, int cellCol){ int row = 0; while(maxColumnUsedInRow.size() > row && (cellCol > maxColumnUsedInRow.get(row))){ row++; } return row; } /** * Helper method that updates the given cell's position to the coordinates corresponding * to its stored row and column locations * @param c the cell to move */ public static void moveCell(Cell c){ Platform.runLater(new Task<Void>(){ @Override protected Void call(){ boolean animate = c.getAnimate(); boolean useParentPosAsSource = c.getUseParentAsSource(); if(animate && useParentPosAsSource && c.getCellParents().size()>0){ double px = c.getCellParents().get(0).columnLocationProperty.get() * H_SPACING + H_PAD; double py = c.getCellParents().get(0).rowLocationProperty.get() * V_SPACING + V_PAD; c.moveTo(px, py, false, false); } double x = c.columnLocationProperty.get() * H_SPACING + H_PAD; double y = c.rowLocationProperty.get() * V_SPACING + V_PAD; c.moveTo(x, y, animate, animate && useParentPosAsSource); return null; } }); } }
package elegit.treefx; import com.sun.xml.internal.fastinfoset.algorithm.BuiltInEncodingAlgorithm; import javafx.application.Platform; import javafx.concurrent.Service; import javafx.concurrent.Task; import javafx.concurrent.WorkerStateEvent; import javafx.event.EventHandler; import java.util.ArrayList; import java.util.List; /** * Handles the layout of cells in a TreeGraph in an appropriate tree structure */ public class TreeLayout{ public static int V_SPACING = Cell.BOX_SIZE + 10; public static int H_SPACING = Cell.BOX_SIZE * 3 + 5; public static int V_PAD = 10; public static int H_PAD = 25; public static int cells_moved = 0; // Move cell service to move cells public static class MoveCellService extends Service<Integer> { private List<Integer> minColumnUsedInRow; private List<Integer> minColumnWantedInRow; private List<Cell> allCellsSortedByTime; private boolean isInitialSetupFinished; private int cellLocation; public MoveCellService(List<Cell> allCellsSortedByTime, boolean isInitialSetupFinished) { this.minColumnUsedInRow = new ArrayList<>(); this.minColumnWantedInRow = new ArrayList<>(); this.cellLocation = allCellsSortedByTime.size()-1; this.allCellsSortedByTime = allCellsSortedByTime; this.isInitialSetupFinished = isInitialSetupFinished; } @Override protected synchronized Task<Integer> createTask() { return new Task<Integer>() { @Override protected Integer call() throws Exception { cellLocation = allCellsSortedByTime.size()-1 - getCellsMoved(); System.out.println(cellLocation); if (cellLocation > allCellsSortedByTime.size()-1) this.cancelled(); // Get cell at rightmost location not yet placed Cell c = allCellsSortedByTime.get(allCellsSortedByTime.size()-1-cellLocation); // Get where the cell should go based on which columns have been 'reserved' int x = cellLocation; int y = getRowOfCellInColumn(minColumnWantedInRow, x); // See whether or not this cell will move int oldColumnLocation = c.columnLocationProperty.get(); int oldRowLocation = c.rowLocationProperty.get(); c.columnLocationProperty.set(x); c.rowLocationProperty.set(y); boolean hasCellMoved = oldColumnLocation >= 0 && oldRowLocation >= 0; boolean willCellMove = oldColumnLocation != x || oldRowLocation != y; // Update where the cell has been placed if (y >= minColumnUsedInRow.size()) minColumnUsedInRow.add(x); else minColumnUsedInRow.set(y, x); // Update the reserved rows for (int i=y; y<minColumnWantedInRow.size(); y++) if (minColumnWantedInRow.get(i) == i) minColumnWantedInRow.set(i, minColumnUsedInRow.get(i)); // Move the cell moveCell(c, isInitialSetupFinished && willCellMove, !hasCellMoved); // Update the reserved columns in rows with the cells parents, oldest to newest List<Cell> list = c.getCellParents(); list.sort((c1, c2) -> Long.compare(c1.getTime(), c2.getTime())); // For each parent, oldest to newest, place its want of row in the highest possible for(Cell parent : list){ int row = getRowOfCellInColumn(minColumnWantedInRow, getColumnOfCell(allCellsSortedByTime, parent)); if (minColumnWantedInRow.size() > row) minColumnWantedInRow.set(row, getColumnOfCell(allCellsSortedByTime, parent)); else minColumnWantedInRow.add(row, getColumnOfCell(allCellsSortedByTime, parent)); } // Check that the cells have been moved upCellsMoved(); return x; } }; } } /** * Returns a task that will take care of laying out the given * graph into a tree. Uses a combination of recursion and * iteration to pack cells as far up as possible with each * cell being arranged horizontally based on time * @param g the graph to layout * @return a task that, when executed, does the layout of g */ public static Task getTreeLayoutTask(TreeGraph g){ return new Task<Void>(){ private List<Cell> allCellsSortedByTime; /** * Extracts the TreeGraphModel, sorts its cells by time, then relocates * every cell. When complete, updates the model if necessary to show * it has been through the layout process at least once already */ @Override protected Void call() throws Exception{ TreeGraphModel treeGraphModel = g.treeGraphModel; allCellsSortedByTime = treeGraphModel.allCells; allCellsSortedByTime.sort((c1, c2) -> { int i = Long.compare(c2.getTime(), c1.getTime()); if(i == 0){ if(c2.getCellChildren().contains(c1)){ return -1; }else if(c1.getCellChildren().contains(c2)){ return 1; } } return i; }); MoveCellService mover = new MoveCellService(allCellsSortedByTime, false); mover.setOnSucceeded(event -> { mover.restart(); }); mover.start(); if(!isCancelled()){ treeGraphModel.isInitialSetupFinished = true; } return null; } }; } /** * Helper method that updates the given cell's position to the coordinates corresponding * to its stored row and column locations * @param c the cell to move * @param animate whether the given cell should have an animation towards its new position * @param useParentPosAsSource whether the given cell should move to its first parent before * being animated, to prevent animations starting from off screen */ public static void moveCell(Cell c, boolean animate, boolean useParentPosAsSource){ Platform.runLater(new Task<Void>(){ @Override protected Void call(){ if(animate && useParentPosAsSource && c.getCellParents().size()>0){ double px = c.getCellParents().get(0).columnLocationProperty.get() * H_SPACING + H_PAD; double py = c.getCellParents().get(0).rowLocationProperty.get() * V_SPACING + V_PAD; c.moveTo(px, py, false, false); } double x = c.columnLocationProperty.get() * H_SPACING + H_PAD; double y = c.rowLocationProperty.get() * V_SPACING + V_PAD; c.moveTo(x, y, animate, animate && useParentPosAsSource); return null; } }); } /** * Calculates the row closest to the top of the screen to place the * given cell based on the cell's column and the maximum heights recorded * for each row * @param minColumnUsedInRow the map of max columns used in each row * @param cellCol the column the cell to examine is in * @return the lowest indexed row in which to place c */ public static int getRowOfCellInColumn(List<Integer> minColumnUsedInRow, int cellCol){ int row = 0; while(minColumnUsedInRow.size() > row && (cellCol > minColumnUsedInRow.get(row))){ row++; } return row; } /** * Gets the column of the given cell, with column 0 being the right of the screen * and the root cell of the tree being at the bottom * @param allCellsSortedByTime the list of all cells sorted by time * @param c the cell to examine * @return the column index of this cell */ public static int getColumnOfCell(List<Cell> allCellsSortedByTime, Cell c){ return allCellsSortedByTime.size() - 1 - allCellsSortedByTime.indexOf(c); } public static int getCellsMoved() { return cells_moved; } public static void upCellsMoved() { cells_moved++; } }
package it.unitn.bd.bfs; import com.google.common.base.Joiner; import com.google.common.base.Stopwatch; import it.unitn.bd.ServiceConfiguration; import it.unitn.bd.bfs.graph.Color; import it.unitn.bd.bfs.graph.Vertex; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.Function2; import org.apache.spark.api.java.function.PairFlatMapFunction; import scala.Tuple2; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.*; /** * Parallel BFS test with MapReduce on Spark * <p/> * NOTE: Remember to configure the environment in "service.properties" ! * * @see ServiceConfiguration */ public final class BfsSpark { private static final Logger logger = LogManager.getLogger(); private static final Joiner NEW_LINE = Joiner.on("\n"); private static final String APP_NAME = ServiceConfiguration.getAppName(); private static final String IP = ServiceConfiguration.getIp(); private static final int PORT = ServiceConfiguration.getPort(); private static final String JAR = ServiceConfiguration.getJar(); private static final List<String> PROBLEM_FILES = ServiceConfiguration.getProblemFiles(); public static void main(String[] args) throws Exception { String master = "spark://" + IP + ':' + PORT; logger.info("Application name: " + APP_NAME); logger.info("Problem files path: " + PROBLEM_FILES); logger.info("Using JAR file: " + JAR); logger.info("Connecting to: " + master); JavaSparkContext spark = new JavaSparkContext(new SparkConf().setAppName(APP_NAME).setMaster(master)); spark.addJar("target/" + JAR + ".jar"); for (String problemFile : PROBLEM_FILES) { logger.info("Problem file: " + problemFile); GraphFileUtil.convert(problemFile); int index = 0; boolean isGrayVertex = true; Stopwatch stopwatch = Stopwatch.createUnstarted(); // Continue until there is at least one GRAY vertex while (isGrayVertex) { JavaRDD<String> lines = spark.textFile(problemFile + '_' + index++); stopwatch.start(); // Split vertices by their id and all the neighbours it is connected to JavaPairRDD<Integer, Vertex> mapper = lines.flatMapToPair(new PairFlatMapFunction<String, Integer, Vertex>() { @Override public Iterable<Tuple2<Integer, Vertex>> call(String source) throws Exception { Vertex vertex = new Vertex(source); Set<Tuple2<Integer, Vertex>> result = new HashSet<>(); // Emit neighbours of a GRAY vertex if (vertex.getColor() == Color.GRAY) { for (final int neighbour : vertex.getNeighbours()) { List<Integer> path = new LinkedList<Integer>(vertex.getPath()) {{ add(neighbour); }}; result.add(new Tuple2<>(neighbour, new Vertex(neighbour, new HashSet<Integer>(), path, vertex.getDistance() + 1, Color.GRAY))); } vertex.setColor(Color.BLACK); } // Emit the current vertex result.add(new Tuple2<>(vertex.getId(), vertex)); return result; } }); // Combine all vertices by id, while choosing the shortest path with minimal distance JavaPairRDD<Integer, Vertex> reducer = mapper.reduceByKey(new Function2<Vertex, Vertex, Vertex>() { @Override public Vertex call(Vertex vertex1, Vertex vertex2) { // Chose the original vertex with full list of all the neighbours Set<Integer> neighbours = !vertex1.getNeighbours().isEmpty() ? vertex1.getNeighbours() : vertex2.getNeighbours(); // Chose the shortest path from the source to current vertex List<Integer> path = vertex1.getDistance() < vertex2.getDistance() ? vertex1.getPath() : vertex2.getPath(); // Chose the minimum distance int distance = vertex1.getDistance() < vertex2.getDistance() ? vertex1.getDistance() : vertex2.getDistance(); // Chose the darkest color Color color = vertex1.getColor().ordinal() > vertex2.getColor().ordinal() ? vertex1.getColor() : vertex2.getColor(); // Emit the best possible solution found so far for a given vertex id return new Vertex(vertex1.getId(), neighbours, path, distance, color); } }); Collection<Vertex> vertices = reducer.collectAsMap().values(); stopwatch.stop(); logger.info("Elapsed time [" + index + "] ==> " + stopwatch); // Save intermediate results into a text file for the next iteration if GRAY vertex is still present String content = NEW_LINE.join(vertices); Files.write(Paths.get(problemFile + '_' + index), content.getBytes(), StandardOpenOption.CREATE); isGrayVertex = content.contains(Color.GRAY.name()); } } spark.stop(); } }
package javaslang.collection; import javaslang.Function1; import javaslang.Tuple; import javaslang.Tuple2; import javaslang.Tuple3; import javaslang.control.Option; import java.util.Comparator; import java.util.Objects; import java.util.function.*; /** * Interface for immutable sequential data structures. * <p> * Creation: * * <ul> * <li>{@link #unit(Iterable)}</li> * </ul> * * Filtering: * * <ul> * <li>{@link #remove(Object)}</li> * <li>{@link #removeAll(Object)}</li> * <li>{@link #removeAll(Iterable)}</li> * <li>{@link #removeAt(int)}</li> * <li>{@link #removeFirst(Predicate)}</li> * <li>{@link #removeLast(Predicate)}</li> * </ul> * * Mutation: * * <ul> * <li>{@link #append(Object)}</li> * <li>{@link #appendAll(Iterable)}</li> * <li>{@link #insert(int, Object)}</li> * <li>{@link #insertAll(int, Iterable)}</li> * <li>{@link #prepend(Object)}</li> * <li>{@link #prependAll(Iterable)}</li> * <li>{@link #update(int, Object)}</li> * </ul> * * Selection: * * <ul> * <li>{@link #get(int)}</li> * <li>{@link #indexOf(Object)}</li> * <li>{@link #indexOf(Object, int)}</li> * <li>{@link #lastIndexOf(Object)}</li> * <li>{@link #lastIndexOf(Object, int)}</li> * <li>{@link #slice(int, int)}</li> * <li>{@link #subSequence(int)}</li> * <li>{@link #subSequence(int, int)}</li> * </ul> * * Transformation: * * <ul> * <li>{@link #crossProduct()}</li> * <li>{@link #crossProduct(int)}</li> * <li>{@link #crossProduct(Iterable)}</li> * <li>{@link #combinations()}</li> * <li>{@link #combinations(int)}</li> * <li>{@link #intersperse(Object)}</li> * <li>{@link #padTo(int, Object)}</li> * <li>{@link #permutations()}</li> * <li>{@link #reverse()}</li> * <li>{@link #sort()}</li> * <li>{@link #sort(Comparator)}</li> * <li>{@link #splitAt(int)}</li> * <li>{@link #unzip(Function)}</li> * <li>{@link #zip(Iterable)}</li> * <li>{@link #zipAll(Iterable, Object, Object)}</li> * <li>{@link #zipWithIndex()}</li> * </ul> * * Traversal: * * <ul> * <li>{@link #iterator(int)}</li> * </ul> * * @param <T> Component type * @author Daniel Dietrich * @since 1.1.0 */ public interface Seq<T> extends Traversable<T>, Function1<Integer, T> { long serialVersionUID = 1L; /** * Creates a Seq of the given elements. * <p> * The resulting sequence has the same iteration order as the given iterable of elements * if the iteration order of the elements is stable. * * @param <T> Component type of the Seq. * @param elements An Iterable of elements. * @return A sequence containing the given elements in the same order or the * given argument if it is already an instance of Seq. * @throws NullPointerException if {@code elements} is null */ @SuppressWarnings("unchecked") static <T> Seq<T> ofAll(Iterable<? extends T> elements) { Objects.requireNonNull(elements, "elements is null"); if (elements instanceof Seq) { return (Seq<T>) elements; } else { return List.ofAll(elements); } } /** * A {@code Seq} is a partial function which returns the element at the specified index by calling * {@linkplain #get(int)}. * * @param index an index * @return the element at the given index * @throws IndexOutOfBoundsException if this is empty, index &lt; 0 or index &gt;= length() */ @Override default T apply(Integer index) { return get(index); } /** * Appends an element to this. * * @param element An element * @return A new Seq containing the given element appended to this elements */ Seq<T> append(T element); /** * Appends all given elements to this. * * @param elements An Iterable of elements * @return A new Seq containing the given elements appended to this elements * @throws NullPointerException if {@code elements} is null */ Seq<T> appendAll(Iterable<? extends T> elements); /** * Returns the union of all combinations from k = 0 to length(). * <p> * Examples: * <pre> * <code> * [].combinations() = [[]] * * [1,2,3].combinations() = [ * [], // k = 0 * [1], [2], [3], // k = 1 * [1,2], [1,3], [2,3], // k = 2 * [1,2,3] // k = 3 * ] * </code> * </pre> * * @return the combinations of this */ Seq<? extends Seq<T>> combinations(); Seq<? extends Seq<T>> combinations(int k); /** * Tests whether this sequence contains a given sequence as a slice. * <p> * Note: may not terminate for infinite-sized collections. * * @param that the sequence to test * @return true if this sequence contains a slice with the same elements as that, otherwise false. * @throws NullPointerException if {@code that} is null. */ default boolean containsSlice(Iterable<? extends T> that) { Objects.requireNonNull(that, "that is null"); return indexOfSlice(that) >= 0; } /** * Calculates the cross product (, i.e. square) of {@code this x this}. * <p> * Example: * <pre> * <code> * // = List of Tuples (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3) * List.of(1, 2, 3).crossProduct(); * </code> * </pre> * * @return a new Seq containing the square of {@code this} */ Seq<Tuple2<T, T>> crossProduct(); /** * Calculates the n-ary cartesian power (or <em>cross product</em> or simply <em>product</em>) of this. * <p> * Example: * <pre> * <code> * // = ((A,A), (A,B), (A,C), ..., (B,A), (B,B), ..., (Z,Y), (Z,Z)) * CharSeq.rangeClosed('A', 'Z').crossProduct(2); * </code> * </pre> * * @param power the number of cartesian multiplications * @return A new Seq representing the n-ary cartesian power of this */ Seq<? extends Seq<T>> crossProduct(int power); /** * Calculates the cross product {@code this x that}. * <p> * Example: * <pre> * <code> * // = List of Tuples (1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b') * List.of(1, 2, 3).crossProduct(List.of('a', 'b'); * </code> * </pre> * * @param that Another iterable * @param <U> Component type * @return a new Seq containing the cross product {@code this x that} * @throws NullPointerException if that is null */ <U> Seq<Tuple2<T, U>> crossProduct(Iterable<? extends U> that); /** * Tests whether this sequence ends with the given sequence. * <p> * Note: If the both the receiver object this and the argument that are infinite sequences this method may not terminate. * * @param that the sequence to test * @return true if this sequence has that as a suffix, false otherwise.. */ default boolean endsWith(Seq<? extends T> that) { Objects.requireNonNull(that, "that is null"); Iterator<T> i = this.iterator().drop(length() - that.length()); Iterator<? extends T> j = that.iterator(); while (i.hasNext() && j.hasNext()) { if (!Objects.equals(i.next(), j.next())) { return false; } } return !j.hasNext(); } /** * Returns the element at the specified index. * * @param index an index * @return the element at the given index * @throws IndexOutOfBoundsException if this is empty, index &lt; 0 or index &gt;= length() */ T get(int index); /** * Returns the index of the first occurrence of the given element or -1 if this does not contain the given element. * * @param element an element * @return the index of the first occurrence of the given element */ default int indexOf(T element) { return indexOf(element, 0); } /** * Returns the index of the first occurrence of the given element after or at some start index * or -1 if this does not contain the given element. * * @param element an element * @param from start index * @return the index of the first occurrence of the given element */ int indexOf(T element, int from); /** * Finds first index where this sequence contains a given sequence as a slice. * <p> * Note: may not terminate for infinite-sized collections. * * @param that the sequence to test * @return the first index such that the elements of this sequence starting at this index match * the elements of sequence that, or -1 of no such slice exists. * @throws NullPointerException if {@code that} is null. */ default int indexOfSlice(Iterable<? extends T> that) { Objects.requireNonNull(that, "that is null"); return indexOfSlice(that, 0); } /** * Finds first index after or at a start index where this sequence contains a given sequence as a slice. * <p> * Note: may not terminate for infinite-sized collections. * * @param that the sequence to test * @param from the start index * @return the first index &gt;= from such that the elements of this sequence starting at this index match * the elements of sequence that, or -1 of no such slice exists. * @throws NullPointerException if {@code that} is null. */ default int indexOfSlice(Iterable<? extends T> that, int from) { Objects.requireNonNull(that, "that is null"); class Util { int indexOfSlice(Seq<T> t, Seq<T> slice, int from) { if (t.isEmpty()) { return from == 0 && slice.isEmpty() ? 0 : -1; } if (from <= 0 && checkPrefix(t, slice)) { return 0; } int idx = indexOfSlice(t.tail(), slice, from - 1); return idx >= 0 ? idx + 1 : -1; } private boolean checkPrefix(Seq<T> t, Seq<T> prefix) { if (prefix.isEmpty()) { return true; } else { return !t.isEmpty() && java.util.Objects.equals(t.head(), prefix.head()) && checkPrefix(t.tail(), prefix.tail()); } } } return new Util().indexOfSlice(this, unit(that), from); } /** * Finds index of first element satisfying some predicate. * * @param p the predicate used to test elements. * @return the index of the first element of this Seq that satisfies the given * {@code predicate}, or {@code -1}, if none exists. */ default int indexWhere(Predicate<? super T> p) { return indexWhere(p, 0); } /** * Finds index of the first element satisfying some predicate after or at * some start index. * * @param predicate the predicate used to test elements. * @param from the start index * @return the index {@code >= from} of the first element of this Seq that * satisfies the given {@code predicate}, or {@code -1}, if none exists. */ int indexWhere(Predicate<? super T> predicate, int from); /** * Inserts the given element at the specified index. * * @param index an index * @param element an element * @return a new Seq, where the given element is inserted into this at the given index * @throws IndexOutOfBoundsException if this is empty, index &lt; 0 or index &gt;= length() */ Seq<T> insert(int index, T element); /** * Inserts the given elements at the specified index. * * @param index an index * @param elements An Iterable of elements * @return a new Seq, where the given elements are inserted into this at the given index * @throws IndexOutOfBoundsException if this is empty, index &lt; 0 or index &gt;= length() */ Seq<T> insertAll(int index, Iterable<? extends T> elements); /** * Inserts an element between all elements of this Traversable. * * @param element An element. * @return an interspersed version of this */ Seq<T> intersperse(T element); /** * Returns an iterator of this elements starting at the given index. * The result is equivalent to {@code this.subSequence(index).iterator()}. * * @param index an index * @return a new Iterator, starting with the element at the given index or the empty Iterator, if index = length() * @throws IndexOutOfBoundsException if index &lt; 0 or index &gt; length() */ default Iterator<T> iterator(int index) { return subSequence(index).iterator(); } /** * Returns the index of the last occurrence of the given element or -1 if this does not contain the given element. * * @param element an element * @return the index of the last occurrence of the given element */ default int lastIndexOf(T element) { return lastIndexOf(element, Integer.MAX_VALUE); } /** * Finds index of last element satisfying some predicate. * * @param predicate the predicate used to test elements. * @return the index of the last element of this Seq that satisfies the given {@code predicate}, or {@code -1}, * if none exists. */ default int lastIndexWhere(Predicate<? super T> predicate) { return lastIndexWhere(predicate, length() - 1); } /** * Finds index of last element satisfying some predicate before or at given * end index. * * @param predicate the predicate used to test elements. * @param end the maximum index of the search * @return the index {@code <= end} of the last element of this Seq that * satisfies the given {@code predicate}, or {@code -1}, if none exists. */ int lastIndexWhere(Predicate<? super T> predicate, int end); /** * Returns the index of the last occurrence of the given element before or at a given end index * or -1 if this does not contain the given element. * * @param element an element * @param end the end index * @return the index of the last occurrence of the given element */ int lastIndexOf(T element, int end); /** * Finds last index where this sequence contains a given sequence as a slice. * <p> * Note: will not terminate for infinite-sized collections. * * @param that the sequence to test * @return the last index such that the elements of this sequence starting a this index match the elements * of sequence that, or -1 of no such slice exists. * @throws NullPointerException if {@code that} is null. */ default int lastIndexOfSlice(Iterable<? extends T> that) { Objects.requireNonNull(that, "that is null"); return lastIndexOfSlice(that, Integer.MAX_VALUE); } /** * Finds last index before or at a given end index where this sequence contains a given sequence as a slice. * * @param that the sequence to test * @param end the end index * @return the last index &lt;= end such that the elements of this sequence starting at this index match * the elements of sequence that, or -1 of no such slice exists. * @throws NullPointerException if {@code that} is null. */ int lastIndexOfSlice(Iterable<? extends T> that, int end); /** * A copy of this sequence with an element appended until a given target length is reached. * * @param length the target length * @param element the padding element * @return a new sequence consisting of all elements of this sequence followed by the minimal number * of occurrences of <code>element</code> so that the resulting sequence has a length of at least <code>length</code>. */ Seq<T> padTo(int length, T element); /** * Produces a new list where a slice of elements in this list is replaced by another sequence. * * @param from the index of the first replaced element * @param that sequence for replacement * @param replaced the number of elements to drop in the original list * @return a new sequence. */ Seq<T> patch(int from, Iterable<? extends T> that, int replaced); /** * Computes all unique permutations. * <p> * Example: * <pre> * <code> * [].permutations() = [] * * [1,2,3].permutations() = [ * [1,2,3], * [1,3,2], * [2,1,3], * [2,3,1], * [3,1,2], * [3,2,1] * ] * </code> * </pre> * * @return this unique permutations */ Seq<? extends Seq<T>> permutations(); /** * Returns the length of the longest prefix whose elements all satisfy some predicate. * * Note: may not terminate for infinite-sized collections. * * @param predicate the predicate used to test elements. * @return the length of the longest prefix of this general sequence such that every * element of the segment satisfies the predicate p. */ default int prefixLength(Predicate<? super T> predicate) { return segmentLength(predicate, 0); } /** * Prepends an element to this. * * @param element An element * @return A new Seq containing the given element prepended to this elements */ Seq<T> prepend(T element); /** * Prepends all given elements to this. * * @param elements An Iterable of elements * @return A new Seq containing the given elements prepended to this elements */ Seq<T> prependAll(Iterable<? extends T> elements); /** * Removes the first occurrence of the given element. * * @param element An element to be removed from this Seq. * @return a Seq containing all elements of this without the first occurrence of the given element. */ Seq<T> remove(T element); /** * Removes all occurrences of the given element. * * @param element An element to be removed from this Seq. * @return a Seq containing all elements of this but not the given element. */ Seq<T> removeAll(T element); /** * Removes all occurrences of the given elements. * * @param elements Elements to be removed from this Seq. * @return a Seq containing all elements of this but none of the given elements. * @throws NullPointerException if {@code elements} is null */ Seq<T> removeAll(Iterable<? extends T> elements); /** * Removes the element at the specified position in this sequence. Shifts any subsequent elements to the left * (subtracts one from their indices). * * @param index position of element to remove * @return a sequence containing all elements of this without the element at the specified position. * @throws IndexOutOfBoundsException if this is empty, index &lt; 0 or index &gt;= length() */ Seq<T> removeAt(int index); /** * Removes the first occurrence that satisfy predicate * * @param predicate an predicate * @return a new Seq */ Seq<T> removeFirst(Predicate<T> predicate); /** * Removes the last occurrence that satisfy predicate * * @param predicate an predicate * @return a new Seq */ Seq<T> removeLast(Predicate<T> predicate); /** * Reverses the order of elements. * * @return the reversed elements. */ Seq<T> reverse(); /** * An iterator yielding elements in reversed order. * <p> * Note: {@code xs.reverseIterator()} is the same as {@code xs.reverse().iterator()} but might * be more efficient. * * @return an iterator yielding the elements of this Seq in reversed order */ Iterator<T> reverseIterator(); /** * Computes length of longest segment whose elements all satisfy some predicate. * * Note: may not terminate for infinite-sized collections. * * @param predicate the predicate used to test elements. * @param from the index where the search starts. * @return the length of the longest segment of this sequence starting from index * from such that every element of the segment satisfies the predicate p. */ int segmentLength(Predicate<? super T> predicate, int from); /** * Returns a Seq that is a <em>slice</em> of this. The slice begins with the element at the specified * {@code beginIndex} and extends to the element at index {@code endIndex - 1}. * <p> * Examples: * * <pre> * <code> * List.of(1, 2, 3, 4).slice(1, 3); // = (2, 3) * List.of(1, 2, 3, 4).slice(0, 4); // = (1, 2, 3, 4) * List.of(1, 2, 3, 4).slice(2, 2); // = () * List.of(1, 2).slice(1, 0); // = () * List.of(1, 2).slice(-10, 10); // = (1, 2) * </code> * </pre> * * See also {@link #subSequence(int, int)} which throws in some cases instead of returning a sequence. * * @param beginIndex the beginning index, inclusive * @param endIndex the end index, exclusive * @return the specified slice */ Seq<T> slice(int beginIndex, int endIndex); /** * Sorts this elements according to their natural order. If this elements are not * {@code Comparable}, a {@code java.lang.ClassCastException} may be thrown. * * @return A sorted version of this * @throws ClassCastException if this elements are not {@code Comparable} */ Seq<T> sort(); /** * Sorts this elements according to the provided {@code Comparator}. If this elements are not * {@code Comparable}, a {@code java.lang.ClassCastException} may be thrown. * * @param comparator A comparator * @return a sorted version of this */ Seq<T> sort(Comparator<? super T> comparator); /** * Sorts this elements by comparing the elements in a different domain, using the given {@code mapper}. * * @param mapper A mapper * @param <U> The domain where elements are compared * @return a sorted version of this */ <U extends Comparable<? super U>> Seq<T> sortBy(Function<? super T, ? extends U> mapper); /** * Sorts this elements by comparing the elements in a different domain, using the given {@code mapper}. * * @param comparator A comparator * @param mapper A mapper * @param <U> The domain where elements are compared * @return a sorted version of this */ <U> Seq<T> sortBy(Comparator<? super U> comparator, Function<? super T, ? extends U> mapper); /** * Splits a Seq at the specified index. The result of {@code splitAt(n)} is equivalent to * {@code Tuple.of(take(n), drop(n))}. * * @param n An index. * @return A Tuple containing the first n and the remaining elements. */ Tuple2<? extends Seq<T>, ? extends Seq<T>> splitAt(int n); /** * Splits a sequence at the first element which satisfies the {@link Predicate}, e.g. Tuple(init, element+tail). * * @param predicate An predicate * @return A {@link Tuple} containing divided sequences */ Tuple2<? extends Seq<T>, ? extends Seq<T>> splitAt(Predicate<? super T> predicate); /** * Splits a sequence at the first element which satisfies the {@link Predicate}, e.g. Tuple(init+element, tail). * * @param predicate An predicate * @return A {@link Tuple} containing divided sequences */ Tuple2<? extends Seq<T>, ? extends Seq<T>> splitAtInclusive(Predicate<? super T> predicate); /** * Tests whether this list starts with the given sequence. * * @param that the sequence to test * @return true if that is empty or that is prefix of this collection, false otherwise. */ default boolean startsWith(Iterable<? extends T> that) { return startsWith(that, 0); } /** * Tests whether this list contains the given sequence at a given index. * <p> * Note: If the both the receiver object this and the argument that are infinite sequences this method may not terminate. * * @param that the sequence to test * @param offset the index where the sequence is searched. * @return true if that is empty or that is prefix of this collection starting from the given offset, false otherwise. */ default boolean startsWith(Iterable<? extends T> that, int offset) { Objects.requireNonNull(that, "that is null"); if (offset < 0) return false; Iterator<T> i = this.iterator().drop(offset); java.util.Iterator<? extends T> j = that.iterator(); while (i.hasNext() && j.hasNext()) { if (!Objects.equals(i.next(), j.next())) { return false; } } return !j.hasNext(); } /** * Returns a Seq that is a subsequence of this. The subsequence begins with the element at the specified * {@code beginIndex} and extends to the end of this Seq. * <p> * Examples: * * <pre> * <code> * List.of(1, 2).subSequence(0); // = (1, 2) * List.of(1, 2).subSequence(1); // = (2) * List.of(1, 2).subSequence(2); // = () * List.of(1, 2).subSequence(10); // throws IndexOutOfBoundsException * List.of(1, 2).subSequence(-10); // throws IndexOutOfBoundsException * </code> * </pre> * * See also {@link #drop(int)} which is similar but does not throw. * * @param beginIndex the beginning index, inclusive * @return the specified subsequence * @throws IndexOutOfBoundsException if {@code beginIndex} is negative or larger than the length of this * {@code String} object. */ Seq<T> subSequence(int beginIndex); /** * Returns a Seq that is a subsequence of this. The subsequence begins with the element at the specified * {@code beginIndex} and extends to the element at index {@code endIndex - 1}. * <p> * Examples: * * <pre> * <code> * List.of(1, 2, 3, 4).subSequence(1, 3); // = (2, 3) * List.of(1, 2, 3, 4).subSequence(0, 4); // = (1, 2, 3, 4) * List.of(1, 2, 3, 4).subSequence(2, 2); // = () * List.of(1, 2).subSequence(1, 0); // throws IndexOutOfBoundsException * List.of(1, 2).subSequence(-10, 1); // throws IndexOutOfBoundsException * List.of(1, 2).subSequence(0, 10); // throws IndexOutOfBoundsException * </code> * </pre> * * See also {@link #slice(int, int)} which returns an empty sequence instead of throwing. * * @param beginIndex the beginning index, inclusive * @param endIndex the end index, exclusive * @return the specified subsequence * @throws IndexOutOfBoundsException if {@code beginIndex} or {@code endIndex} is negative, * if {@code endIndex} is greater than {@code length()}, * or if {@code beginIndex} is greater than {@code endIndex} */ Seq<T> subSequence(int beginIndex, int endIndex); /** * Transforms this {@code Seq}. * * @param f A transformation * @param <U> Type of transformation result * @return An instance of type {@code U} * @throws NullPointerException if {@code f} is null */ default <U> U transform(Function<? super Seq<? super T>, ? extends U> f) { Objects.requireNonNull(f, "f is null"); return f.apply(this); } /** * Creates an instance of this type of an {@code Iterable}. * * @param <U> Component type * @param iterable an {@code Iterable} * @return A new instance of this collection containing the elements of the given {@code iterable}. */ <U> Seq<U> unit(Iterable<? extends U> iterable); /** * Updates the given element at the specified index. * * @param index an index * @param element an element * @return a new Seq consisting of this elements and the given element is set at the given index * @throws IndexOutOfBoundsException if this is empty, index &lt; 0 or index &gt;= length() */ Seq<T> update(int index, T element); // -- Adjusted return types of Traversable methods @Override Seq<T> clear(); @Override Seq<T> distinct(); @Override Seq<T> distinctBy(Comparator<? super T> comparator); @Override <U> Seq<T> distinctBy(Function<? super T, ? extends U> keyExtractor); @Override Seq<T> drop(int n); @Override Seq<T> dropRight(int n); @Override Seq<T> dropUntil(Predicate<? super T> predicate); @Override Seq<T> dropWhile(Predicate<? super T> predicate); @Override Seq<T> filter(Predicate<? super T> predicate); @Override Seq<T> filterNot(Predicate<? super T> predicate); @Override <U> Seq<U> flatMap(Function<? super T, ? extends Iterable<? extends U>> mapper); @Override default <U> U foldRight(U zero, BiFunction<? super T, ? super U, ? extends U> f) { Objects.requireNonNull(f, "f is null"); return reverse().foldLeft(zero, (xs, x) -> f.apply(x, xs)); } @Override <C> Map<C, ? extends Seq<T>> groupBy(Function<? super T, ? extends C> classifier); @Override Iterator<? extends Seq<T>> grouped(int size); @Override Seq<T> init(); @Override Option<? extends Seq<T>> initOption(); @Override <U> Seq<U> map(Function<? super T, ? extends U> mapper); @Override Tuple2<? extends Seq<T>, ? extends Seq<T>> partition(Predicate<? super T> predicate); @Override Seq<T> peek(Consumer<? super T> action); @Override Seq<T> replace(T currentElement, T newElement); @Override Seq<T> replaceAll(T currentElement, T newElement); @Override Seq<T> retainAll(Iterable<? extends T> elements); @Override Seq<T> scan(T zero, BiFunction<? super T, ? super T, ? extends T> operation); @Override <U> Seq<U> scanLeft(U zero, BiFunction<? super U, ? super T, ? extends U> operation); @Override <U> Seq<U> scanRight(U zero, BiFunction<? super T, ? super U, ? extends U> operation); @Override Iterator<? extends Seq<T>> sliding(int size); @Override Iterator<? extends Seq<T>> sliding(int size, int step); @Override Tuple2<? extends Seq<T>, ? extends Seq<T>> span(Predicate<? super T> predicate); @Override Seq<T> tail(); @Override Option<? extends Seq<T>> tailOption(); @Override Seq<T> take(int n); @Override Seq<T> takeRight(int n); @Override Seq<T> takeUntil(Predicate<? super T> predicate); @Override Seq<T> takeWhile(Predicate<? super T> predicate); @Override <T1, T2> Tuple2<? extends Seq<T1>, ? extends Seq<T2>> unzip(Function<? super T, Tuple2<? extends T1, ? extends T2>> unzipper); @Override <T1, T2, T3> Tuple3<? extends Seq<T1>, ? extends Seq<T2>, ? extends Seq<T3>> unzip3(Function<? super T, Tuple3<? extends T1, ? extends T2, ? extends T3>> unzipper); @Override <U> Seq<Tuple2<T, U>> zip(Iterable<U> that); @Override <U> Seq<Tuple2<T, U>> zipAll(Iterable<U> that, T thisElem, U thatElem); @Override Seq<Tuple2<T, Integer>> zipWithIndex(); }
package javax.time.period; import java.io.Serializable; import javax.time.MathUtils; /** * An immutable period consisting of the standard year, month, day, hour, minute, second and nanosecond units. * <p> * This is used to represent the human-scale description of an amount of time, known as a period. * As an example, "3 months, 4 days and 7 hours" can be stored. * <p> * Period stores just six units - years, months, days, hours, minutes and seconds. * There is an implied relationship between some of these units: * <ul> * <li>12 months in a year</li> * <li>24 hours in a day (ignoring time zones)</li> * <li>60 minutes in an hour</li> * <li>60 seconds in a minute</li> * <li>1,000,000,000 nanoseconds in a second</li> * </ul> * This is exposed in the {@link #normalized()} and {@link #normalizedWith24HourDays()} methods. * Period can be used by any calendar system that makes the same assumptions as shown above. * <p> * Note that beyond the limits specified above, the stored amounts are only descriptive. * For example, a year in two calendar systems may differ in length. * Only when the period is combined with a date/time in a specific calendar system can the * duration of the period be calculated. * <p> * Period is thread-safe and immutable. * * @author Stephen Colebourne */ public final class Period implements PeriodProvider, Serializable { /** * A constant for a period of zero. */ public static final Period ZERO = new Period(0, 0, 0, 0, 0, 0, 0); /** * A serialization identifier for this class. */ private static final long serialVersionUID = 1L; /** * The number of years. */ private final int years; /** * The number of months. */ private final int months; /** * The number of days. */ private final int days; /** * The number of hours. */ private final int hours; /** * The number of minutes. */ private final int minutes; /** * The number of seconds. */ private final int seconds; /** * The number of nanoseconds. */ private final long nanos; /** * The cached toString value. */ private transient volatile String string; /** * Obtains an instance of <code>Period</code> from a provider of periods. * <p> * In addition to calling {@link PeriodProvider#toPeriod()} this method * also checks the validity of the result of the provider. * * @param periodProvider a provider of period information, not null * @return the created period instance, never null */ public static Period period(PeriodProvider periodProvider) { if (periodProvider == null) { throw new NullPointerException("Period provider must not be null"); } Period provided = periodProvider.toPeriod(); if (provided == null) { throw new NullPointerException("The implementation of PeriodProvider must not return null"); } return provided; } /** * Obtains an instance of <code>Period</code> from amounts from years to seconds. * * @param years the amount of years * @param months the amount of months * @param days the amount of days * @param hours the amount of hours * @param minutes the amount of minutes * @param seconds the amount of seconds * @return the created period instance, never null */ public static Period period(int years, int months, int days, int hours, int minutes, int seconds) { if ((years | months | days | hours | minutes | seconds) == 0) { return ZERO; } return new Period(years, months, days, hours, minutes, seconds, 0); } /** * Obtains an instance of <code>Period</code> from amounts from years to nanoseconds. * * @param years the amount of years * @param months the amount of months * @param days the amount of days * @param hours the amount of hours * @param minutes the amount of minutes * @param seconds the amount of seconds * @param nanos the amount of nanos * @return the created period instance, never null */ public static Period period(int years, int months, int days, int hours, int minutes, int seconds, long nanos) { if ((years | months | days | hours | minutes | seconds | nanos) == 0) { return ZERO; } return new Period(years, months, days, hours, minutes, seconds, nanos); } /** * Obtains an instance of <code>Period</code> from years, months and days. * * @param years the amount of years * @param months the amount of months * @return the created period instance, never null */ public static Period yearsMonths(int years, int months) { if ((years | months) == 0) { return ZERO; } return new Period(years, months, 0, 0, 0, 0, 0); } /** * Obtains an instance of <code>Period</code> from years, months and days. * * @param years the amount of years * @param months the amount of months * @param days the amount of days * @return the created period instance, never null */ public static Period yearsMonthsDays(int years, int months, int days) { if ((years | months | days) == 0) { return ZERO; } return new Period(years, months, days, 0, 0, 0, 0); } /** * Obtains an instance of <code>Period</code> from hours, minutes and seconds. * * @param hours the amount of hours * @param minutes the amount of minutes * @param seconds the amount of seconds * @return the created period instance, never null */ public static Period hoursMinutesSeconds(int hours, int minutes, int seconds) { if ((hours | minutes | seconds) == 0) { return ZERO; } return new Period(0, 0, 0, hours, minutes, seconds, 0); } /** * Creates a period of years. * * @param years the amount of years * @return the created period instance, never null */ public static Period years(int years) { if (years == 0) { return ZERO; } return new Period(years, 0, 0, 0, 0, 0, 0); } /** * Creates a period of months. * * @param months the amount of months * @return the created period instance, never null */ public static Period months(int months) { if (months == 0) { return ZERO; } return new Period(0, months, 0, 0, 0, 0, 0); } /** * Creates a period of days. * * @param days the amount of days * @return the created period instance, never null */ public static Period days(int days) { if (days == 0) { return ZERO; } return new Period(0, 0, days, 0, 0, 0, 0); } /** * Creates a period of hours. * * @param hours the amount of hours * @return the created period instance, never null */ public static Period hours(int hours) { if (hours == 0) { return ZERO; } return new Period(0, 0, 0, hours, 0, 0, 0); } /** * Creates a period of minutes. * * @param minutes the amount of minutes * @return the created period instance, never null */ public static Period minutes(int minutes) { if (minutes == 0) { return ZERO; } return new Period(0, 0, 0, 0, minutes, 0, 0); } /** * Creates a period of seconds. * * @param seconds the amount of seconds * @return the created period instance, never null */ public static Period seconds(int seconds) { if (seconds == 0) { return ZERO; } return new Period(0, 0, 0, 0, 0, seconds, 0); } /** * Creates a period of nanoseconds. * * @param nanos the amount of nanos * @return the created period instance, never null */ public static Period nanos(long nanos) { if (nanos == 0) { return ZERO; } return new Period(0, 0, 0, 0, 0, 0, nanos); } /** * Constructor. * * @param years the amount * @param months the amount * @param days the amount * @param hours the amount * @param minutes the amount * @param seconds the amount * @param nanos the amount */ private Period(int years, int months, int days, int hours, int minutes, int seconds, long nanos) { this.years = years; this.months = months; this.days = days; this.hours = hours; this.minutes = minutes; this.seconds = seconds; this.nanos = nanos; } /** * Resolves singletons. * * @return the resolved instance */ private Object readResolve() { if ((years | months | days | hours | minutes | seconds | nanos) == 0) { return ZERO; } return this; } /** * Checks if the period is zero-length. * * @return true if this period is zero-length */ public boolean isZero() { return (this == ZERO); } /** * Gets the amount of years of the overall period, if any. * * @return the amount of years of the overall period */ public int getYears() { return years; } /** * Gets the amount of months of the overall period, if any. * * @return the amount of months of the overall period */ public int getMonths() { return months; } /** * Gets the amount of days of the overall period, if any. * * @return the amount of days of the overall period */ public int getDays() { return days; } /** * Gets the amount of hours of the overall period, if any. * * @return the amount of hours of the overall period */ public int getHours() { return hours; } /** * Gets the amount of minutes of the overall period, if any. * * @return the amount of minutes of the overall period */ public int getMinutes() { return minutes; } /** * Gets the amount of seconds of the overall period, if any. * * @return the amount of seconds of the overall period */ public int getSeconds() { return seconds; } /** * Gets the amount of nanoseconds of the overall period, if any. * * @return the amount of nanoseconds of the overall period */ public long getNanos() { return nanos; } /** * Returns a copy of this period with the specified amount of years. * <p> * This instance is immutable and unaffected by this method call. * * @param years the years to represent * @return a new updated period instance, never null */ public Period withYears(int years) { if (years == this.years) { return this; } return period(years, months, days, hours, minutes, seconds, nanos); } /** * Returns a copy of this period with the specified amount of months. * <p> * This instance is immutable and unaffected by this method call. * * @param months the months to represent * @return a new updated period instance, never null */ public Period withMonths(int months) { if (months == this.months) { return this; } return period(years, months, days, hours, minutes, seconds, nanos); } /** * Returns a copy of this period with the specified amount of days. * <p> * This instance is immutable and unaffected by this method call. * * @param days the days to represent * @return a new updated period instance, never null */ public Period withDays(int days) { if (days == this.days) { return this; } return period(years, months, days, hours, minutes, seconds, nanos); } /** * Returns a copy of this period with the specified amount of hours. * <p> * This instance is immutable and unaffected by this method call. * * @param hours the hours to represent * @return a new updated period instance, never null */ public Period withHours(int hours) { if (hours == this.hours) { return this; } return period(years, months, days, hours, minutes, seconds, nanos); } /** * Returns a copy of this period with the specified amount of minutes. * <p> * This instance is immutable and unaffected by this method call. * * @param minutes the minutes to represent * @return a new updated period instance, never null */ public Period withMinutes(int minutes) { if (minutes == this.minutes) { return this; } return period(years, months, days, hours, minutes, seconds, nanos); } /** * Returns a copy of this period with the specified amount of seconds. * <p> * This instance is immutable and unaffected by this method call. * * @param seconds the seconds to represent * @return a new updated period instance, never null */ public Period withSeconds(int seconds) { if (seconds == this.seconds) { return this; } return period(years, months, days, hours, minutes, seconds, nanos); } /** * Returns a copy of this period with the specified amount of nanoseconds. * <p> * This instance is immutable and unaffected by this method call. * * @param nanos the nanoseconds to represent * @return a new updated period instance, never null */ public Period withNanos(long nanos) { if (nanos == this.nanos) { return this; } return period(years, months, days, hours, minutes, seconds, nanos); } /** * Returns a copy of this period with the specified period added. * <p> * This instance is immutable and unaffected by this method call. * * @param periodProvider the period to add, not null * @return a new updated period instance, never null * @throws NullPointerException if the period to add is null * @throws ArithmeticException if the calculation result overflows */ public Period plus(PeriodProvider periodProvider) { Period other = period(periodProvider); return period( MathUtils.safeAdd(years, other.years), MathUtils.safeAdd(months, other.months), MathUtils.safeAdd(days, other.days), MathUtils.safeAdd(hours, other.hours), MathUtils.safeAdd(minutes, other.minutes), MathUtils.safeAdd(seconds, other.seconds), MathUtils.safeAdd(nanos, other.nanos)); } /** * Returns a copy of this period with the specified number of years added. * <p> * This instance is immutable and unaffected by this method call. * * @param years the years to add, positive or negative * @return a new updated period instance, never null * @throws ArithmeticException if the calculation result overflows */ public Period plusYears(int years) { return withYears(MathUtils.safeAdd(this.years, years)); } /** * Returns a copy of this period with the specified number of months added. * <p> * This instance is immutable and unaffected by this method call. * * @param months the months to add, positive or negative * @return a new updated period instance, never null * @throws ArithmeticException if the calculation result overflows */ public Period plusMonths(int months) { return withMonths(MathUtils.safeAdd(this.months, months)); } /** * Returns a copy of this period with the specified number of days added. * <p> * This instance is immutable and unaffected by this method call. * * @param days the days to add, positive or negative * @return a new updated period instance, never null * @throws ArithmeticException if the calculation result overflows */ public Period plusDays(int days) { return withDays(MathUtils.safeAdd(this.days, days)); } /** * Returns a copy of this period with the specified number of hours added. * <p> * This instance is immutable and unaffected by this method call. * * @param hours the hours to add, positive or negative * @return a new updated period instance, never null * @throws ArithmeticException if the calculation result overflows */ public Period plusHours(int hours) { return withHours(MathUtils.safeAdd(this.hours, hours)); } /** * Returns a copy of this period with the specified number of minutes added. * <p> * This instance is immutable and unaffected by this method call. * * @param minutes the minutes to add, positive or negative * @return a new updated period instance, never null * @throws ArithmeticException if the calculation result overflows */ public Period plusMinutes(int minutes) { return withMinutes(MathUtils.safeAdd(this.minutes, minutes)); } /** * Returns a copy of this period with the specified number of seconds added. * <p> * This instance is immutable and unaffected by this method call. * * @param seconds the seconds to add, positive or negative * @return a new updated period instance, never null * @throws ArithmeticException if the calculation result overflows */ public Period plusSeconds(int seconds) { return withSeconds(MathUtils.safeAdd(this.seconds, seconds)); } /** * Returns a copy of this period with the specified number of nanoseconds added. * <p> * This instance is immutable and unaffected by this method call. * * @param nanos the nanoseconds to add, positive or negative * @return a new updated period instance, never null * @throws ArithmeticException if the calculation result overflows */ public Period plusNanos(long nanos) { return withNanos(MathUtils.safeAdd(this.nanos, nanos)); } /** * Returns a copy of this period with the specified period subtracted. * <p> * This instance is immutable and unaffected by this method call. * * @param periodProvider the period to subtract, not null * @return a new updated period instance, never null * @throws NullPointerException if the period to subtract is null * @throws ArithmeticException if the calculation result overflows */ public Period minus(PeriodProvider periodProvider) { Period other = period(periodProvider); return period( MathUtils.safeSubtract(years, other.years), MathUtils.safeSubtract(months, other.months), MathUtils.safeSubtract(days, other.days), MathUtils.safeSubtract(hours, other.hours), MathUtils.safeSubtract(minutes, other.minutes), MathUtils.safeSubtract(seconds, other.seconds), MathUtils.safeSubtract(nanos, other.nanos)); } /** * Returns a copy of this period with the specified number of years subtracted. * <p> * This instance is immutable and unaffected by this method call. * * @param years the years to subtract, positive or negative * @return a new updated period instance, never null * @throws ArithmeticException if the calculation result overflows */ public Period minusYears(int years) { return withYears(MathUtils.safeSubtract(this.years, years)); } /** * Returns a copy of this period with the specified number of months subtracted. * <p> * This instance is immutable and unaffected by this method call. * * @param months the months to subtract, positive or negative * @return a new updated period instance, never null * @throws ArithmeticException if the calculation result overflows */ public Period minusMonths(int months) { return withMonths(MathUtils.safeSubtract(this.months, months)); } /** * Returns a copy of this period with the specified number of days subtracted. * <p> * This instance is immutable and unaffected by this method call. * * @param days the days to subtract, positive or negative * @return a new updated period instance, never null * @throws ArithmeticException if the calculation result overflows */ public Period minusDays(int days) { return withDays(MathUtils.safeSubtract(this.days, days)); } /** * Returns a copy of this period with the specified number of hours subtracted. * <p> * This instance is immutable and unaffected by this method call. * * @param hours the hours to subtract, positive or negative * @return a new updated period instance, never null * @throws ArithmeticException if the calculation result overflows */ public Period minusHours(int hours) { return withHours(MathUtils.safeSubtract(this.hours, hours)); } /** * Returns a copy of this period with the specified number of minutes subtracted. * <p> * This instance is immutable and unaffected by this method call. * * @param minutes the minutes to subtract, positive or negative * @return a new updated period instance, never null * @throws ArithmeticException if the calculation result overflows */ public Period minusMinutes(int minutes) { return withMinutes(MathUtils.safeSubtract(this.minutes, minutes)); } /** * Returns a copy of this period with the specified number of seconds subtracted. * <p> * This instance is immutable and unaffected by this method call. * * @param seconds the seconds to subtract, positive or negative * @return a new updated period instance, never null * @throws ArithmeticException if the calculation result overflows */ public Period minusSeconds(int seconds) { return withSeconds(MathUtils.safeSubtract(this.seconds, seconds)); } /** * Returns a copy of this period with the specified number of nanoseconds subtracted. * <p> * This instance is immutable and unaffected by this method call. * * @param nanos the nanoseconds to subtract, positive or negative * @return a new updated period instance, never null * @throws ArithmeticException if the calculation result overflows */ public Period minusNanos(long nanos) { return withNanos(MathUtils.safeSubtract(this.nanos, nanos)); } /** * Returns a new instance with each element in this period multiplied * by the specified scalar. * * @param scalar the scalar to multiply by, not null * @return the new updated period instance, never null * @throws ArithmeticException if the calculation result overflows */ public Period multipliedBy(int scalar) { if (this == ZERO || scalar == 1) { return this; } return period( MathUtils.safeMultiply(years, scalar), MathUtils.safeMultiply(months, scalar), MathUtils.safeMultiply(days, scalar), MathUtils.safeMultiply(hours, scalar), MathUtils.safeMultiply(minutes, scalar), MathUtils.safeMultiply(seconds, scalar), MathUtils.safeMultiply(nanos, scalar)); } /** * Returns a new instance with each element in this period divided * by the specified value. * <p> * The implementation simply divides each separate field by the divisor * using integer division. * * @param divisor the value to divide by, not null * @return the new updated period instance, never null * @throws ArithmeticException if dividing by zero */ public Period dividedBy(int divisor) { if (divisor == 0) { throw new ArithmeticException("Cannot divide by zero"); } if (this == ZERO || divisor == 1) { return this; } return period( years / divisor, months / divisor, days / divisor, hours / divisor, minutes / divisor, seconds / divisor, nanos / divisor); } /** * Returns a new instance with each amount in this period negated. * * @return the new updated period instance, never null * @throws ArithmeticException if the calculation result overflows */ public Period negated() { return multipliedBy(-1); } /** * Returns a copy of this period with all amounts normalized to the * standard ranges for date-time fields. * <p> * Two normalizations occur, one for years and months, and one for hours, minutes and seconds. * Days are not normalized, as a day may vary in length at daylight savings cutover. * For example, a period of P1Y15M1DT28H will be normalized to 2Y3M1DT28H. * <p> * Note that this method normalizes using assumptions: * <ul> * <li>12 months in a year</li> * <li>60 minutes in an hour</li> * <li>60 seconds in a minute</li> * <li>1,000,000,000 nanoseconds in a second</li> * </ul> * This method is only appropriate to call if these assumptions are met. * <p> * This instance is immutable and unaffected by this method call. * * @return a new updated period instance, never null * @throws ArithmeticException if the calculation result overflows */ public Period normalized() { if (this == ZERO) { return ZERO; } int years = this.years; int months = this.months; if (months >= 12) { years = MathUtils.safeAdd(years, months / 12); months = months % 12; } long total = (hours * 60L * 60L) + (minutes * 60L) + seconds; // will not overflow total = MathUtils.safeMultiply(total, 1000000000); total = MathUtils.safeAdd(total, nanos); long nanos = total % 1000000000L; total /= 1000000000L; int seconds = (int) (total % 60); total /= 60; int minutes = (int) (total % 60); total /= 60; int hours = MathUtils.safeToInt(total); return period(years, months, days, hours, minutes, seconds, nanos); } /** * Returns a copy of this period with all amounts normalized to the * standard ranges for date-time fields including the assumption that * days are 24 hours long. * <p> * Two normalizations occur, one for years and months, and one for hours, minutes and seconds. * The number of hours may optionally be normalized into days based on an input parameter. * For example, a period of P1Y15M1DT28H will be normalized to 2Y3M2DT4H. * <p> * Note that this method normalizes using assumptions: * <ul> * <li>12 months in a year</li> * <li>24 hours in a day</li> * <li>60 minutes in an hour</li> * <li>60 seconds in a minute</li> * <li>1,000,000,000 nanoseconds in a second</li> * </ul> * This method is only appropriate to call if these assumptions are met. * <p> * This instance is immutable and unaffected by this method call. * * @return a new updated period instance, never null * @throws ArithmeticException if the calculation result overflows */ public Period normalizedWith24HourDays() { if (this == ZERO) { return ZERO; } int years = this.years; int months = this.months; if (months >= 12) { years = MathUtils.safeAdd(years, months / 12); months = months % 12; } long total = (days * 24L * 60L * 60L) + (hours * 60L * 60L) + (minutes * 60L) + seconds; // will not overflow total = MathUtils.safeMultiply(total, 1000000000); total = MathUtils.safeAdd(total, nanos); long nanos = total % 1000000000L; total /= 1000000000L; int seconds = (int) (total % 60); total /= 60; int minutes = (int) (total % 60); total /= 60; int hours = (int) (total % 24); total /= 24; int days = MathUtils.safeToInt(total); return period(years, months, days, hours, minutes, seconds, nanos); } /** * Converts this object to a <code>Period</code>, trivially returning <code>this</code>. * * @return <code>this</code>, never null */ public Period toPeriod() { return this; } /** * Converts this object to a <code>PeriodFields</code> instance. * <p> * The resulting period is always normalized such that it does not contain * zero amounts. * * @return an equivalent period fields instance, never null */ public PeriodFields toPeriodFields() { // TODO: Maybe remove? return PeriodFields.periodFields(this); } /** * Is this period equal to the specified period. * * @param obj the other period to compare to, null returns false * @return true if this instance is equal to the specified period */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof Period) { Period other = (Period) obj; return years == other.years && months == other.months && days == other.days & hours == other.hours && minutes == other.minutes && seconds == other.seconds && nanos == other.nanos; } return false; } /** * Returns the hash code for this period. * * @return a suitable hash code */ @Override public int hashCode() { // SPEC: Require unique hash code for all periods where fields within these inclusive bounds: // years 0-31, months 0-11, days 0-31, hours 0-23, minutes 0-59, seconds 0-59 // IMPL: Ordered such that overflow from one field doesn't immediately affect the next field // years 5 bits, months 4 bits, days 6 bits, hours 5 bits, minutes 6 bits, seconds 6 bits return ((years << 27) | (years >>> 5)) ^ ((hours << 22) | (hours >>> 10)) ^ ((months << 18) | (months >>> 14)) ^ ((minutes << 12) | (minutes >>> 20)) ^ ((days << 6) | (days >>> 26)) ^ seconds ^ (((int) nanos) + 37); } /** * Returns a string representation of the amount of time. * * @return the amount of time in ISO8601 string format */ @Override public String toString() { String s = string; if (s == null) { if (this == ZERO) { s = "PT0S"; } else { StringBuilder buf = new StringBuilder(); buf.append('P'); if (years != 0) { buf.append(years).append('Y'); } if (months != 0) { buf.append(months).append('M'); } if (days != 0) { buf.append(days).append('D'); } if ((hours | minutes | seconds) != 0) { buf.append('T'); if (hours != 0) { buf.append(hours).append('H'); } if (minutes != 0) { buf.append(minutes).append('M'); } if (seconds != 0) { buf.append(seconds).append('S'); } } s = buf.toString(); } string = s; } return s; } }
package kodkod.ast; import static kodkod.ast.operator.IntCastOperator.BITSETCAST; import static kodkod.ast.operator.IntCastOperator.INTCAST; import static kodkod.ast.operator.IntCompOperator.EQ; import static kodkod.ast.operator.IntCompOperator.NEQ; import static kodkod.ast.operator.IntCompOperator.GT; import static kodkod.ast.operator.IntCompOperator.GTE; import static kodkod.ast.operator.IntCompOperator.LT; import static kodkod.ast.operator.IntCompOperator.LTE; import static kodkod.ast.operator.IntOperator.ABS; import static kodkod.ast.operator.IntOperator.AND; import static kodkod.ast.operator.IntOperator.DIVIDE; import static kodkod.ast.operator.IntOperator.MINUS; import static kodkod.ast.operator.IntOperator.MODULO; import static kodkod.ast.operator.IntOperator.MULTIPLY; import static kodkod.ast.operator.IntOperator.NEG; import static kodkod.ast.operator.IntOperator.NOT; import static kodkod.ast.operator.IntOperator.OR; import static kodkod.ast.operator.IntOperator.PLUS; import static kodkod.ast.operator.IntOperator.SGN; import static kodkod.ast.operator.IntOperator.SHA; import static kodkod.ast.operator.IntOperator.SHL; import static kodkod.ast.operator.IntOperator.SHR; import static kodkod.ast.operator.IntOperator.XOR; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import kodkod.ast.operator.IntCastOperator; import kodkod.ast.operator.IntCompOperator; import kodkod.ast.operator.IntOperator; import kodkod.ast.visitor.ReturnVisitor; import kodkod.ast.visitor.VoidVisitor; import kodkod.util.collections.Containers; /** * A Node whose value is an integer * rather than a relational expression. * * @author Emina Torlak */ public abstract class IntExpression extends Node { /** * Constructs an IntExpression. */ IntExpression() {} /** * Returns a formula stating that the given int expression and * this have the same value. The effect * of this method is the same as calling this.compare(EQ, intExpr). * @return this.compare(EQ, intExpr) */ public final Formula eq(IntExpression intExpr) { return this.compare(EQ, intExpr); } /** * Returns a formula stating that the given int expression and * this have a different value. The effect * of this method is the same as calling this.compare(NEQ, intExpr). * @return this.compare(NEQ, intExpr) */ public final Formula neq(IntExpression intExpr) { return this.compare(NEQ, intExpr); } /** * Returns a formula stating that the value of this int expression is less than the * value of the given int expression The effect * of this method is the same as calling this.compare(LT, intExpr). * @return this.compare(LT, intExpr) */ public final Formula lt(IntExpression intExpr) { return this.compare(LT, intExpr); } /** * Returns a formula stating that the value of this int expression is less than * or equal to the value of the given int expression The effect * of this method is the same as calling this.compare(LTE, intExpr). * @return this.compare(LTE, intExpr) */ public final Formula lte(IntExpression intExpr) { return this.compare(LTE, intExpr); } /** * Returns a formula stating that the value of this int expression is greater than the * value of the given int expression The effect * of this method is the same as calling this.compare(GT, intExpr). * @return this.compare(GT, intExpr) */ public final Formula gt(IntExpression intExpr) { return this.compare(GT, intExpr); } /** * Returns a formula stating that the value of this int expression is greater than * or equal to the value of the given int expression The effect * of this method is the same as calling this.compare(GTE, intExpr). * @return this.compare(GTE, intExpr) */ public final Formula gte(IntExpression intExpr) { return this.compare(GTE, intExpr); } /** * Returns a formula comparing this and the given integer expression using the * specified operator. * @return {f: Formula | f.left = this and f.right = intExpr and f.op = op } */ public Formula compare(IntCompOperator op, IntExpression intExpr) { if (op==null || intExpr==null) throw new NullPointerException(); return new IntComparisonFormula(this, op, intExpr); } /** * Returns an integer expression that is the sum of all * values that this integer expression can take given the * provided declarations. * @return {e: IntExpression | e.decls = decls and e.intExpr = this } */ public final IntExpression sum(Decls decls) { return new SumExpression(decls, this); } /** * Returns an IntExpression that represents the sum of this and * the given int node. The effect of this method is the same as calling * this.compose(PLUS, intExpr). * @return this.compose(PLUS, intExpr) */ public final IntExpression plus(IntExpression intExpr) { return compose(PLUS, intExpr); } /** * Returns an IntExpression that represents the difference between this and * the given int node. The effect of this method is the same as calling * this.compose(MINUS, intExpr). * @return this.compose(MINUS, intExpr) */ public final IntExpression minus(IntExpression intExpr) { return compose(MINUS, intExpr); } /** * Returns an IntExpression that represents the product of this and * the given int node. The effect of this method is the same as calling * this.compose(MULTIPLY, intExpr). * @return this.compose(MULTIPLY, intExpr) */ public final IntExpression multiply(IntExpression intExpr) { return compose(MULTIPLY, intExpr); } /** * Returns an IntExpression that represents the quotient of the division * between this and the given int node. The effect of this method is the same as calling * this.compose(DIVIDE, intExpr). * @return this.compose(DIVIDE, intExpr) */ public final IntExpression divide(IntExpression intExpr) { return compose(DIVIDE, intExpr); } /** * Returns an IntExpression that represents the remainder of the division * between this and the given int node. The effect of this method is the same as calling * this.compose(MODULO, intExpr). * @return this.compose(MODULO, intExpr) */ public final IntExpression modulo(IntExpression intExpr) { return compose(MODULO, intExpr); } /** * Returns an IntExpression that represents the bitwise AND of this and * the given int node. The effect of this method is the same as calling * this.compose(AND, intExpr). * @return this.compose(AND, intExpr) */ public final IntExpression and(IntExpression intExpr) { return compose(AND, intExpr); } /** * Returns an IntExpression that represents the bitwise OR of this and * the given int node. The effect of this method is the same as calling * this.compose(OR, intExpr). * @return this.compose(OR, intExpr) */ public final IntExpression or(IntExpression intExpr) { return compose(OR, intExpr); } /** * Returns an IntExpression that represents the bitwise XOR of this and * the given int node. The effect of this method is the same as calling * this.compose(XOR, intExpr). * @return this.compose(XOR, intExpr) */ public final IntExpression xor(IntExpression intExpr) { return compose(XOR, intExpr); } /** * Returns an IntExpression that represents the left shift of this by * the given int node. The effect of this method is the same as calling * this.compose(SHL, intExpr). * @return this.compose(SHL, intExpr) */ public final IntExpression shl(IntExpression intExpr) { return compose(SHL, intExpr); } /** * Returns an IntExpression that represents the right shift of this and * the given int node, with zero extension. The effect of this method is the same as calling * this.compose(SHR, intExpr). * @return this.compose(SHR, intExpr) */ public final IntExpression shr(IntExpression intExpr) { return compose(SHR, intExpr); } /** * Returns an IntExpression that represents the right shift of this and * the given int node, with sign extension. The effect of this method is the same as calling * this.compose(SHA, intExpr). * @return this.compose(SHA, intExpr) */ public final IntExpression sha(IntExpression intExpr) { return compose(SHA, intExpr); } /** * Returns an expression that combines this and the given integer expression using the * specified operator. * @requires op.binary() * @return {e: IntExpression | e.left = this and e.right = intExpr and e.op = op } */ public final IntExpression compose(IntOperator op, IntExpression intExpr) { if (op==null || intExpr==null) throw new NullPointerException(); return new BinaryIntExpression(this, op, intExpr); } /** * Returns the sum of the given int expressions. The effect of this method is the * same as calling compose(PLUS, intExprs). * @return compose(PLUS, intExprs) */ public static IntExpression plus(IntExpression...intExprs) { return compose(PLUS, intExprs); } /** * Returns the plus of the given int expressions. The effect of this method is the * same as calling compose(PLUS, intExprs). * @return compose(PLUS, intExprs) */ public static IntExpression plus(Collection<? extends IntExpression> intExprs) { return compose(PLUS, intExprs); } /** * Returns the product of the given int expressions. The effect of this method is the * same as calling compose(MULTIPLY, intExprs). * @return compose(MULTIPLY, intExprs) */ public static IntExpression multiply(IntExpression...intExprs) { return compose(MULTIPLY, intExprs); } /** * Returns the product of the given int expressions. The effect of this method is the * same as calling compose(MULTIPLY, intExprs). * @return compose(MULTIPLY, intExprs) */ public static IntExpression multiply(Collection<? extends IntExpression> intExprs) { return compose(MULTIPLY, intExprs); } /** * Returns the bitwise and of the given int expressions. The effect of this method is the * same as calling compose(AND, intExprs). * @return compose(AND, intExprs) */ public static IntExpression and(IntExpression...intExprs) { return compose(AND, intExprs); } /** * Returns the bitwise and of the given int expressions. The effect of this method is the * same as calling compose(AND, intExprs). * @return compose(AND, intExprs) */ public static IntExpression and(Collection<? extends IntExpression> intExprs) { return compose(AND, intExprs); } /** * Returns the bitwise or of the given int expressions. The effect of this method is the * same as calling compose(OR, intExprs). * @return compose(OR, intExprs) */ public static IntExpression or(IntExpression...intExprs) { return compose(OR, intExprs); } /** * Returns the bitwise or of the given int expressions. The effect of this method is the * same as calling compose(OR, intExprs). * @return compose(OR, intExprs) */ public static IntExpression or(Collection<? extends IntExpression> intExprs) { return compose(OR, intExprs); } /** * Returns the composition of the given int expressions using the given operator. * @requires intExprs.length = 2 => op.binary(), intExprs.length > 2 => op.nary() * @return intExprs.length=1 => intExprs[0] else {e: IntExpression | e.children = intExprs and e.op = this } */ public static IntExpression compose(IntOperator op, IntExpression...intExprs) { switch(intExprs.length) { case 0 : throw new IllegalArgumentException("Expected at least one argument: " + Arrays.toString(intExprs)); case 1 : return intExprs[0]; case 2 : return new BinaryIntExpression(intExprs[0], op, intExprs[1]); default : return new NaryIntExpression(op, Containers.copy(intExprs, new IntExpression[intExprs.length])); } } /** * Returns the composition of the given int expressions using the given operator. * @requires intExprs.length = 2 => op.binary(), intExprs.length > 2 => op.nary() * @return intExprs.size() = 1 => intExprs.iterator().next() else {e: IntExpression | e.children = intExprs.toArray() and e.op = this } */ public static IntExpression compose(IntOperator op, Collection<? extends IntExpression> intExprs) { switch(intExprs.size()) { case 0 : throw new IllegalArgumentException("Expected at least one argument: " + intExprs); case 1 : return intExprs.iterator().next(); case 2 : final Iterator<? extends IntExpression> itr = intExprs.iterator(); return new BinaryIntExpression(itr.next(), op, itr.next()); default : return new NaryIntExpression(op, intExprs.toArray(new IntExpression[intExprs.size()])); } } /** * Returns an IntExpression that represents the negation of this int expression. * The effect of this method is the same as calling this.apply(NEG). * @return this.apply(NEG) */ public final IntExpression negate() { return apply(NEG); } /** * Returns an IntExpression that represents the bitwise negation of this int expression. * The effect of this method is the same as calling this.apply(NOT). * @return this.apply(NOT) */ public final IntExpression not() { return apply(NOT); } /** * Returns an IntExpression that represents the absolute value of this int expression. * The effect of this method is the same as calling this.apply(ABS). * @return this.apply(ABS) */ public final IntExpression abs() { return apply(ABS); } /** * Returns an IntExpression that represents the sign of this int expression. * The effect of this method is the same as calling this.apply(SGN). * @return this.apply(SGN) */ public final IntExpression signum() { return apply(SGN); } /** * Returns an expression that represents the application of the given unary * operator to this integer expression. * @requires op.unary() * @return {e: IntExpression | e.op = op and e.intExpr = this } */ public final IntExpression apply(IntOperator op) { return new UnaryIntExpression(op, this); } /** * Returns an expression whose meaning is the singleton set containing the atom * that represents the integer given by this integer expression. * The effect of this method is the same as calling this.cast(INTCAST). * @return this.cast(INTCAST) */ public final Expression toExpression() { return cast(INTCAST); } /** * Returns an expression whose meaning is the set containing the atoms * that represent the powers of 2 (bits) present in this integer expression. * The effect of this method is the same as calling this.cast(BITSETCAST). * @return this.cast(BITSETCAST) */ public final Expression toBitset() { return cast(BITSETCAST); } /** * Returns an expression that is the relational representation of this * integer expression specified by the given operator. * @return an expression that is the relational representation of this * integer expression specified by the given operator. */ public final Expression cast(IntCastOperator op) { if (op==null) throw new NullPointerException(); return new IntToExprCast(this, op); } /** * {@inheritDoc} * @see kodkod.ast.Node#accept(kodkod.ast.visitor.ReturnVisitor) */ public abstract <E, F, D, I> I accept(ReturnVisitor<E, F, D, I> visitor) ; /** * {@inheritDoc} * @see kodkod.ast.Node#accept(kodkod.ast.visitor.VoidVisitor) */ public abstract void accept(VoidVisitor visitor); }
package net.coobird.thumbnailator; import java.awt.Dimension; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import net.coobird.thumbnailator.filters.ImageFilter; import net.coobird.thumbnailator.filters.Pipeline; import net.coobird.thumbnailator.filters.Rotation; import net.coobird.thumbnailator.filters.Watermark; import net.coobird.thumbnailator.geometry.Position; import net.coobird.thumbnailator.geometry.Positions; import net.coobird.thumbnailator.name.Rename; import net.coobird.thumbnailator.resizers.BicubicResizer; import net.coobird.thumbnailator.resizers.BilinearResizer; import net.coobird.thumbnailator.resizers.ProgressiveBilinearResizer; import net.coobird.thumbnailator.resizers.Resizer; import net.coobird.thumbnailator.resizers.Resizers; import net.coobird.thumbnailator.resizers.configurations.AlphaInterpolation; import net.coobird.thumbnailator.resizers.configurations.Antialiasing; import net.coobird.thumbnailator.resizers.configurations.Dithering; import net.coobird.thumbnailator.resizers.configurations.Rendering; import net.coobird.thumbnailator.resizers.configurations.ScalingMode; import net.coobird.thumbnailator.tasks.FileThumbnailTask; import net.coobird.thumbnailator.tasks.SourceSinkThumbnailTask; import net.coobird.thumbnailator.tasks.io.BufferedImageSink; import net.coobird.thumbnailator.tasks.io.BufferedImageSource; import net.coobird.thumbnailator.tasks.io.FileImageSink; import net.coobird.thumbnailator.tasks.io.FileImageSource; import net.coobird.thumbnailator.tasks.io.ImageSource; import net.coobird.thumbnailator.tasks.io.InputStreamImageSource; import net.coobird.thumbnailator.tasks.io.OutputStreamImageSink; import net.coobird.thumbnailator.tasks.io.URLImageSource; /** * This class provides a fluent interface to create thumbnails. * <DL> * <DT><B>Usage:</B></DT> * <DD> * The following example code demonstrates how to use the fluent interface * to create a thumbnail from multiple files from a directory, resizing them to * a maximum of 200 pixels by 200 pixels while preserving the aspect ratio of * the original, then saving the resulting thumbnails as JPEG images with file * names having {@code thumbnail.} appended to the beginning of the file name. * <p> * <pre> Thumbnails.of(directory.listFiles()) .size(200, 200) .keepAspectRatio(true) .outputFormat("jpeg") .asFiles(Rename.PREFIX_DOT_THUMBNAIL); * </pre> * </DD> * </DL> * * @author coobird * */ public final class Thumbnails { /** * This class is not intended to be instantiated. */ private Thumbnails() {} private static void validateDimensions(int width, int height) { if (width <= 0 && height <= 0) { throw new IllegalArgumentException( "Destination image dimensions must not be less than " + "0 pixels." ); } else if (width <= 0 || height <= 0) { String dimension = width == 0 ? "width" : "height"; throw new IllegalArgumentException( "Destination image " + dimension + " must not be " + "less than or equal to 0 pixels." ); } } private static void checkForNull(Object o, String message) { if (o == null) { throw new NullPointerException(message); } } private static void checkForEmpty(Object[] o, String message) { if (o.length == 0) { throw new IllegalArgumentException(message); } } private static void checkForEmpty(Collection<?> o, String message) { if (o.size() == 0) { throw new IllegalArgumentException(message); } } public static Builder<File> of(String... files) { checkForNull(files, "Cannot specify null for input files."); checkForEmpty(files, "Cannot specify an empty array for input files."); return Builder.of(files); } public static Builder<File> of(File... files) { checkForNull(files, "Cannot specify null for input files."); checkForEmpty(files, "Cannot specify an empty array for input files."); return Builder.of(files); } public static Builder<URL> of(URL... urls) { checkForNull(urls, "Cannot specify null for input URLs."); checkForEmpty(urls, "Cannot specify an empty array for input URLs."); return Builder.of(urls); } public static Builder<InputStream> of(InputStream... inputStreams) { checkForNull(inputStreams, "Cannot specify null for InputStreams."); checkForEmpty(inputStreams, "Cannot specify an empty array for InputStreams."); return Builder.of(inputStreams); } public static Builder<BufferedImage> of(BufferedImage... images) { checkForNull(images, "Cannot specify null for images."); checkForEmpty(images, "Cannot specify an empty array for images."); return Builder.of(images); } public static Builder<File> fromFilenames(Collection<String> files) { checkForNull(files, "Cannot specify null for input files."); checkForEmpty(files, "Cannot specify an empty collection for input files."); return of(files.toArray(new String[files.size()])); } public static Builder<File> fromFiles(Collection<File> files) { checkForNull(files, "Cannot specify null for input files."); checkForEmpty(files, "Cannot specify an empty collection for input files."); return of(files.toArray(new File[files.size()])); } public static Builder<URL> fromURLs(Collection<URL> urls) { checkForNull(urls, "Cannot specify null for input URLs."); checkForEmpty(urls, "Cannot specify an empty collection for input URLs."); return of(urls.toArray(new URL[urls.size()])); } public static Builder<InputStream> fromInputStreams(Collection<? extends InputStream> inputStreams) { checkForNull(inputStreams, "Cannot specify null for InputStreams."); checkForEmpty(inputStreams, "Cannot specify an empty collection for InputStreams."); return of(inputStreams.toArray(new InputStream[inputStreams.size()])); } public static Builder<BufferedImage> fromImages(Collection<BufferedImage> images) { checkForNull(images, "Cannot specify null for images."); checkForEmpty(images, "Cannot specify an empty collection for images."); return of(images.toArray(new BufferedImage[images.size()])); } /** * A builder interface for Thumbnailator. * <p> * An instance of this class is obtained by calling one of: * <ul> * <li>{@link Thumbnails#of(BufferedImage...)}</li> * <li>{@link Thumbnails#of(File...)}</li> * <li>{@link Thumbnails#of(String...)}</li> * <li>{@link Thumbnails#fromImages(Collection)}</li> * <li>{@link Thumbnails#fromFiles(Collection)}</li> * <li>{@link Thumbnails#fromFilenames(Collection)}</li> * </ul> * * @author coobird * */ public static class Builder<T> { private final List<ImageSource<T>> sources; private Builder(List<ImageSource<T>> sources) { this.sources = sources; statusMap.put(Properties.OUTPUT_FORMAT, Status.OPTIONAL); } private static Builder<File> of(String... filenames) { List<ImageSource<File>> sources = new ArrayList<ImageSource<File>>(); for (String f : filenames) { sources.add(new FileImageSource(f)); } return new Builder<File>(sources); } private static Builder<File> of(File... files) { List<ImageSource<File>> sources = new ArrayList<ImageSource<File>>(); for (File f : files) { sources.add(new FileImageSource(f)); } return new Builder<File>(sources); } private static Builder<URL> of(URL... urls) { List<ImageSource<URL>> sources = new ArrayList<ImageSource<URL>>(); for (URL url : urls) { sources.add(new URLImageSource(url)); } return new Builder<URL>(sources); } private static Builder<InputStream> of(InputStream... inputStreams) { List<ImageSource<InputStream>> sources = new ArrayList<ImageSource<InputStream>>(); for (InputStream is : inputStreams) { sources.add(new InputStreamImageSource(is)); } return new Builder<InputStream>(sources); } private static Builder<BufferedImage> of(BufferedImage... images) { List<ImageSource<BufferedImage>> sources = new ArrayList<ImageSource<BufferedImage>>(); for (BufferedImage img : images) { sources.add(new BufferedImageSource(img)); } return new Builder<BufferedImage>(sources); } private final class BufferedImageIterable implements Iterable<BufferedImage> { public Iterator<BufferedImage> iterator() { return new Iterator<BufferedImage>() { Iterator<ImageSource<T>> sourceIter = sources.iterator(); public boolean hasNext() { return sourceIter.hasNext(); } public BufferedImage next() { ImageSource<T> source = sourceIter.next(); BufferedImageSink destination = new BufferedImageSink(); try { Thumbnailator.createThumbnail( new SourceSinkThumbnailTask<T, BufferedImage>(makeParam(), source, destination) ); } catch (IOException e) { return null; } return destination.getSink(); } public void remove() { throw new UnsupportedOperationException( "Cannot remove elements from this iterator." ); } }; } } /** * Status of each property. * * @author coobird * */ private static enum Status { OPTIONAL, READY, NOT_READY, ALREADY_SET, CANNOT_SET, } /** * Interface used by {@link Properties}. * * @author coobird * */ private static interface Property { public String getName(); } /** * Enum of properties which can be set by this builder. * * @author coobird * */ private static enum Properties implements Property { SIZE("size"), SCALE("scale"), IMAGE_TYPE("imageType"), SCALING_MODE("scalingMode"), ALPHA_INTERPOLATION("alphaInterpolation"), ANTIALIASING("antialiasing"), DITHERING("dithering"), RENDERING("rendering"), KEEP_ASPECT_RATIO("keepAspectRatio"), OUTPUT_FORMAT("outputFormat"), OUTPUT_FORMAT_TYPE("outputFormatType"), OUTPUT_QUALITY("outputQuality"), RESIZER("resizer"), ; private final String name; private Properties(String name) { this.name = name; } public String getName() { return name; } } /** * Map to keep track of whether a property has been properly set or not. */ private final Map<Properties, Status> statusMap = new HashMap<Properties, Status>(); /** * Populates the property map. */ { statusMap.put(Properties.SIZE, Status.NOT_READY); statusMap.put(Properties.SCALE, Status.NOT_READY); statusMap.put(Properties.IMAGE_TYPE, Status.OPTIONAL); statusMap.put(Properties.SCALING_MODE, Status.OPTIONAL); statusMap.put(Properties.ALPHA_INTERPOLATION, Status.OPTIONAL); statusMap.put(Properties.ANTIALIASING, Status.OPTIONAL); statusMap.put(Properties.DITHERING, Status.OPTIONAL); statusMap.put(Properties.RENDERING, Status.OPTIONAL); statusMap.put(Properties.KEEP_ASPECT_RATIO, Status.OPTIONAL); statusMap.put(Properties.OUTPUT_FORMAT, Status.OPTIONAL); statusMap.put(Properties.OUTPUT_FORMAT_TYPE, Status.OPTIONAL); statusMap.put(Properties.OUTPUT_QUALITY, Status.OPTIONAL); statusMap.put(Properties.RESIZER, Status.OPTIONAL); } /** * Updates the property status map. * * @param property The property to update. * @param newStatus The new status. */ private void updateStatus(Properties property, Status newStatus) { if (statusMap.get(property) == Status.ALREADY_SET) { throw new IllegalStateException( property.getName() + " is already set."); } if (statusMap.get(property) == Status.CANNOT_SET) { throw new IllegalStateException( property.getName() + " cannot be set."); } statusMap.put(property, newStatus); } /** * An constant used to indicate that the imageType has not been * specified. When this constant is encountered, one should use the * {@link ThumbnailParameter#DEFAULT_IMAGE_TYPE} as the value for * imageType. */ private static int IMAGE_TYPE_UNSPECIFIED = -1; /* * Defines the fields for the builder interface, and assigns the * default values. */ private int width = -1; private int height = -1; private double scale = Double.NaN; private int imageType = IMAGE_TYPE_UNSPECIFIED; private boolean keepAspectRatio = true; private String outputFormat = ThumbnailParameter.ORIGINAL_FORMAT; private String outputFormatType = ThumbnailParameter.DEFAULT_FORMAT_TYPE; private float outputQuality = ThumbnailParameter.DEFAULT_QUALITY; private ScalingMode scalingMode = ScalingMode.PROGRESSIVE_BILINEAR; private AlphaInterpolation alphaInterpolation = AlphaInterpolation.DEFAULT; private Dithering dithering = Dithering.DEFAULT; private Antialiasing antialiasing = Antialiasing.DEFAULT; private Rendering rendering = Rendering.DEFAULT; private Resizer resizer = Resizers.PROGRESSIVE; /** * The {@link ImageFilter}s that should be applied when creating the * thumbnail. */ private Pipeline filterPipeline = new Pipeline(); public Builder<T> size(int width, int height) { updateStatus(Properties.SIZE, Status.ALREADY_SET); updateStatus(Properties.SCALE, Status.CANNOT_SET); validateDimensions(width, height); this.width = width; this.height = height; return this; } public Builder<T> scale(double scale) { updateStatus(Properties.SCALE, Status.ALREADY_SET); updateStatus(Properties.SIZE, Status.CANNOT_SET); updateStatus(Properties.KEEP_ASPECT_RATIO, Status.CANNOT_SET); if (scale <= 0) { throw new IllegalArgumentException( "The scaling factor is equal to or less than 0." ); } this.scale = scale; return this; } public Builder<T> imageType(int type) { updateStatus(Properties.IMAGE_TYPE, Status.ALREADY_SET); imageType = type; return this; } public Builder<T> scalingMode(ScalingMode config) { checkForNull(config, "Scaling mode is null."); updateStatus(Properties.SCALING_MODE, Status.ALREADY_SET); updateStatus(Properties.RESIZER, Status.CANNOT_SET); scalingMode = config; return this; } public Builder<T> resizer(Resizer resizer) { checkForNull(resizer, "Resizer is null."); updateStatus(Properties.RESIZER, Status.ALREADY_SET); updateStatus(Properties.SCALING_MODE, Status.CANNOT_SET); this.resizer = resizer; return this; } public Builder<T> alphaInterpolation(AlphaInterpolation config) { checkForNull(config, "Alpha interpolation is null."); updateStatus(Properties.ALPHA_INTERPOLATION, Status.ALREADY_SET); alphaInterpolation = config; return this; } public Builder<T> dithering(Dithering config) { checkForNull(config, "Dithering is null."); updateStatus(Properties.DITHERING, Status.ALREADY_SET); dithering = config; return this; } public Builder<T> antialiasing(Antialiasing config) { checkForNull(config, "Antialiasing is null."); updateStatus(Properties.ANTIALIASING, Status.ALREADY_SET); antialiasing = config; return this; } public Builder<T> rendering(Rendering config) { checkForNull(config, "Rendering is null."); updateStatus(Properties.RENDERING, Status.ALREADY_SET); rendering = config; return this; } public Builder<T> keepAspectRatio(boolean keep) { if (statusMap.get(Properties.SCALE) == Status.ALREADY_SET) { throw new IllegalStateException("Cannot specify whether to " + "keep the aspect ratio if the scaling factor has " + "already been specified."); } if (statusMap.get(Properties.SIZE) != Status.ALREADY_SET) { throw new IllegalStateException("Cannot specify whether to " + "keep the aspect ratio unless the size parameter has " + "already been specified."); } updateStatus(Properties.KEEP_ASPECT_RATIO, Status.ALREADY_SET); keepAspectRatio = keep; return this; } public Builder<T> outputQuality(float quality) { if (quality < 0.0f || quality > 1.0f) { throw new IllegalArgumentException( "The quality setting must be in the range 0.0f and " + "1.0f, inclusive." ); } updateStatus(Properties.OUTPUT_QUALITY, Status.ALREADY_SET); outputQuality = quality; return this; } public Builder<T> outputQuality(double quality) { if (quality < 0.0d || quality > 1.0d) { throw new IllegalArgumentException( "The quality setting must be in the range 0.0d and " + "1.0d, inclusive." ); } updateStatus(Properties.OUTPUT_QUALITY, Status.ALREADY_SET); outputQuality = (float)quality; if (outputQuality < 0.0f) { outputQuality = 0.0f; } else if (outputQuality > 1.0f) { outputQuality = 1.0f; } return this; } public Builder<T> outputFormat(String format) { if (!ThumbnailatorUtils.isSupportedOutputFormat(format)) { throw new IllegalArgumentException( "Specified format is not supported: " + format ); } updateStatus(Properties.OUTPUT_FORMAT, Status.ALREADY_SET); outputFormat = format; return this; } public Builder<T> outputFormatType(String formatType) { /* * If the output format is the original format, and the format type * is being specified, it's going to be likely that the specified * type will not be present in all the formats, so we'll disallow * it. (e.g. setting type to "JPEG", and if the original formats * were JPEG and PNG, then we'd have a problem. */ if (formatType != ThumbnailParameter.DEFAULT_FORMAT_TYPE && outputFormat == ThumbnailParameter.ORIGINAL_FORMAT) { throw new IllegalArgumentException( "Cannot set the format type if a specific output " + "format has not been specified." ); } if (!ThumbnailatorUtils.isSupportedOutputFormatType(outputFormat, formatType)) { throw new IllegalArgumentException( "Specified format type (" + formatType + ") is not " + " supported for the format: " + outputFormat ); } /* * If the output format type is set, then we'd better make the * output format unchangeable, or else we'd risk having a type * that is not part of the output format. */ updateStatus(Properties.OUTPUT_FORMAT_TYPE, Status.ALREADY_SET); if (!statusMap.containsKey(Properties.OUTPUT_FORMAT)) { updateStatus(Properties.OUTPUT_FORMAT, Status.CANNOT_SET); } outputFormatType = formatType; return this; } /** * Sets the watermark to apply on the thumbnail. * <p> * This method can be called multiple times to apply multiple * watermarks. * <p> * If multiple watermarks are to be applied, the watermarks will be * applied in the order that this method is called. * <p> * Calling this method to set this parameter is optional. * * @param w The watermark to apply to the thumbnail. * @return Reference to this object. */ public Builder<T> watermark(Watermark w) { if (w == null) { throw new NullPointerException("Watermark is null."); } filterPipeline.add(w); return this; } /** * Sets the image of the watermark to apply on the thumbnail. * <p> * This method is a convenience method for the * {@link #watermark(Position, BufferedImage, float)} method, where * the opacity is 50%, and the position is set to center of the * thumbnail: * <p> * <pre> watermark(Positions.CENTER, image, 0.5f); * </pre> * This method can be called multiple times to apply multiple * watermarks. * <p> * If multiple watermarks are to be applied, the watermarks will be * applied in the order that this method is called. * <p> * Calling this method to set this parameter is optional. * * @param image The image of the watermark. * @return Reference to this object. */ public Builder<T> watermark(BufferedImage image) { return watermark(Positions.CENTER, image, 0.5f); } /** * Sets the image and opacity of the watermark to apply on * the thumbnail. * <p> * This method is a convenience method for the * {@link #watermark(Position, BufferedImage, float)} method, where * the opacity is 50%: * <p> * <pre> watermark(Positions.CENTER, image, opacity); * </pre> * This method can be called multiple times to apply multiple * watermarks. * <p> * If multiple watermarks are to be applied, the watermarks will be * applied in the order that this method is called. * <p> * Calling this method to set this parameter is optional. * * @param image The image of the watermark. * @param opacity The opacity of the watermark. * <p> * The value should be between {@code 0.0f} and * {@code 1.0f}, where {@code 0.0f} is completely * transparent, and {@code 1.0f} is completely * opaque. * @return Reference to this object. */ public Builder<T> watermark(BufferedImage image, float opacity) { return watermark(Positions.CENTER, image, opacity); } /** * Sets the image and opacity and position of the watermark to apply on * the thumbnail. * <p> * This method can be called multiple times to apply multiple * watermarks. * <p> * If multiple watermarks are to be applied, the watermarks will be * applied in the order that this method is called. * <p> * Calling this method to set this parameter is optional. * * @param position The position of the watermark. * @param image The image of the watermark. * @param opacity The opacity of the watermark. * <p> * The value should be between {@code 0.0f} and * {@code 1.0f}, where {@code 0.0f} is completely * transparent, and {@code 1.0f} is completely * opaque. * @return Reference to this object. */ public Builder<T> watermark(Position position, BufferedImage image, float opacity) { filterPipeline.add(new Watermark(position, image, opacity)); return this; } /* * rotation */ /** * Sets the amount of rotation to apply to the thumbnail. * <p> * The thumbnail will be rotated clockwise by the angle specified. * <p> * This method can be called multiple times to apply multiple * rotations. * <p> * If multiple rotations are to be applied, the rotations will be * applied in the order that this method is called. * <p> * Calling this method to set this parameter is optional. * * @param angle Angle in degrees. * @return Reference to this object. */ public Builder<T> rotate(double angle) { filterPipeline.add(Rotation.newRotator(angle)); return this; } /* * other filters */ /** * Adds a {@link ImageFilter} to apply to the thumbnail. * <p> * This method can be called multiple times to apply multiple * filters. * <p> * If multiple filters are to be applied, the filters will be * applied in the order that this method is called. * <p> * Calling this method to set this parameter is optional. * * @param filter An image filter to apply to the thumbnail. * @return Reference to this object. */ public Builder<T> addFilter(ImageFilter filter) { if (filter == null) { throw new NullPointerException("Filter is null."); } filterPipeline.add(filter); return this; } /** * Adds multiple {@link ImageFilter}s to apply to the thumbnail. * <p> * This method can be called multiple times to apply multiple * filters. * <p> * If multiple filters are to be applied, the filters will be * applied in the order that this method is called. * <p> * Calling this method to set this parameter is optional. * * @param filters A list of filters to apply to the thumbnail. * @return Reference to this object. */ public Builder<T> addFilters(List<ImageFilter> filters) { if (filters == null) { throw new NullPointerException("Filters is null."); } filterPipeline.addAll(filters); return this; } private void checkReadiness() { for (Map.Entry<Properties, Status> s : statusMap.entrySet()) { if (s.getValue() == Status.NOT_READY) { throw new IllegalStateException(s.getKey().getName() + " is not set."); } } } /** * Returns a {@link Resizer} which is suitable for the current * builder state. * * @return The {@link Resizer} which is suitable for the * current builder state. */ private Resizer makeResizer() { /* * If the scalingMode has been set, then use scalingMode to obtain * a resizer, else, use the resizer field. */ if (statusMap.get(Properties.SCALING_MODE) == Status.ALREADY_SET) { return makeResizer(scalingMode); } else { return this.resizer; } } /** * Returns a {@link Resizer} which is suitable for the current * builder state. * * @param mode The scaling mode to use to create thumbnails. * @return The {@link Resizer} which is suitable for the * specified scaling mode and builder state. */ private Resizer makeResizer(ScalingMode mode) { Map<RenderingHints.Key, Object> hints = new HashMap<RenderingHints.Key, Object>(); hints.put(RenderingHints.KEY_ALPHA_INTERPOLATION, alphaInterpolation.getValue()); hints.put(RenderingHints.KEY_DITHERING, dithering.getValue()); hints.put(RenderingHints.KEY_ANTIALIASING, antialiasing.getValue()); hints.put(RenderingHints.KEY_RENDERING, rendering.getValue()); if (mode == ScalingMode.BILINEAR) { return new BilinearResizer(hints); } else if (mode == ScalingMode.BICUBIC) { return new BicubicResizer(hints); } else if (mode == ScalingMode.PROGRESSIVE_BILINEAR) { return new ProgressiveBilinearResizer(hints); } else { return new ProgressiveBilinearResizer(hints); } } /** * Returns a {@link ThumbnailParameter} from the current builder state. * * @return A {@link ThumbnailParameter} from the current * builder state. */ private ThumbnailParameter makeParam() { Resizer resizer = makeResizer(); int imageTypeToUse = imageType; if (imageType == IMAGE_TYPE_UNSPECIFIED) { imageTypeToUse = ThumbnailParameter.ORIGINAL_IMAGE_TYPE; } if (Double.isNaN(scale)) { return new ThumbnailParameter( new Dimension(width, height), keepAspectRatio, outputFormat, outputFormatType, outputQuality, imageTypeToUse, filterPipeline.getFilters(), resizer ); } else { return new ThumbnailParameter( scale, keepAspectRatio, outputFormat, outputFormatType, outputQuality, imageTypeToUse, filterPipeline.getFilters(), resizer ); } } /** * Create the thumbnails and return as a {@link Iterable} of * {@link BufferedImage}s. * <p> * For situations where multiple thumbnails are being generated, this * method is preferred over the {@link #asBufferedImages()} method, * as (1) the processing does not have to complete before the method * returns and (2) the thumbnails can be retrieved one at a time, * potentially reducing the number of thumbnails which need to be * retained in the heap memory, potentially reducing the chance of * {@link OutOfMemoryError}s from occurring. * <p> * If an {@link IOException} occurs during the processing of the * thumbnail, the {@link Iterable} will return a {@code null} for that * element. * * @return An {@link Iterable} which will provide an * {@link Iterator} which returns thumbnails as * {@link BufferedImage}s. */ public Iterable<BufferedImage> iterableBufferedImages() { checkReadiness(); /* * TODO To get the precise error information, there would have to * be an event notification mechanism. */ return new BufferedImageIterable(); } /** * Create the thumbnails and return as a {@link List} of * {@link BufferedImage}s. * <p> * <h3>Note about performance</h3> * If there are many thumbnails generated at once, it is possible that * the Java virtual machine's heap space will run out and an * {@link OutOfMemoryError} could result. * <p> * If many thumbnails are being processed at once, then using the * {@link #iterableBufferedImages()} method would be preferable. * * @return A list of thumbnails. * @throws IOException If an problem occurred during * the reading of the original * images. */ public List<BufferedImage> asBufferedImages() throws IOException { checkReadiness(); List<BufferedImage> thumbnails = new ArrayList<BufferedImage>(); // Create thumbnails for (ImageSource<T> source : sources) { BufferedImageSink destination = new BufferedImageSink(); Thumbnailator.createThumbnail( new SourceSinkThumbnailTask<T, BufferedImage>(makeParam(), source, destination) ); thumbnails.add(destination.getSink()); } return thumbnails; } public BufferedImage asBufferedImage() throws IOException { checkReadiness(); if (sources.size() > 1) { throw new IllegalArgumentException("Cannot create one thumbnail from multiple original images."); } BufferedImageSink destination = new BufferedImageSink(); Thumbnailator.createThumbnail( new SourceSinkThumbnailTask<T, BufferedImage>(makeParam(), sources.get(0), destination) ); return destination.getSink(); } /** * Creates the thumbnails and stores them to the files, and returns * a {@link List} of {@link File}s to the thumbnails. * <p> * The file names for the thumbnails are obtained from the given * {@link Iterable}. * * @param iterable An {@link Iterable} which returns an * {@link Iterator} which returns file names * which should be assigned to each thumbnail. * @return A list of {@link File}s of the thumbnails * which were created. * @throws IOException If a problem occurs while reading the * original images or writing the thumbnails * to files. */ public List<File> asFiles(Iterable<File> iterable) throws IOException { checkReadiness(); if (iterable == null) { throw new NullPointerException("File name iterable is null."); } List<File> destinationFiles = new ArrayList<File>(); ThumbnailParameter param = makeParam(); Iterator<File> filenameIter = iterable.iterator(); for (ImageSource<T> source : sources) { if (!filenameIter.hasNext()) { throw new IndexOutOfBoundsException( "Not enough file names provided by iterator." ); } FileImageSink destination = new FileImageSink(filenameIter.next()); Thumbnailator.createThumbnail( new SourceSinkThumbnailTask<T, File>(param, source, destination) ); destinationFiles.add(destination.getSink()); } return destinationFiles; } /** * Creates the thumbnails and stores them to the files. * <p> * The file names for the thumbnails are obtained from the given * {@link Iterable}. * * @param iterable An {@link Iterable} which returns an * {@link Iterator} which returns file names * which should be assigned to each thumbnail. * @throws IOException If a problem occurs while reading the * original images or writing the thumbnails * to files. */ public void toFiles(Iterable<File> iterable) throws IOException { asFiles(iterable); } public List<File> asFiles(Rename rename) throws IOException { checkReadiness(); if (!(sources.get(0) instanceof FileImageSource)) { throw new IllegalStateException("Cannot create thumbnails to files if original images are not from files."); } if (rename == null) { throw new NullPointerException("Rename is null."); } List<File> destinationFiles = new ArrayList<File>(); ThumbnailParameter param = makeParam(); for (ImageSource<T> source : sources) { File f = ((FileImageSource)source).getSource(); File destinationFile = new File(f.getParent(), rename.apply(f.getName())); destinationFiles.add(destinationFile); Thumbnailator.createThumbnail(new FileThumbnailTask(param, f, destinationFile)); } return destinationFiles; } public void toFiles(Rename rename) throws IOException { asFiles(rename); } public void toFile(File outFile) throws IOException { checkReadiness(); if (sources.size() > 1) { throw new IllegalArgumentException("Cannot output multiple thumbnails to one file."); } toFiles(Arrays.asList(outFile)); } public void toFile(String outFilepath) throws IOException { checkReadiness(); if (sources.size() > 1) { throw new IllegalArgumentException("Cannot output multiple thumbnails to one file."); } ImageSource<T> source = sources.get(0); FileImageSink destination = new FileImageSink(outFilepath); Thumbnailator.createThumbnail( new SourceSinkThumbnailTask<T, File>(makeParam(), source, destination) ); } public void toOutputStream(OutputStream os) throws IOException { checkReadiness(); if (sources.size() > 1) { throw new IllegalArgumentException("Cannot output multiple thumbnails to a single OutputStream."); } toOutputStreams(Arrays.asList(os)); } public void toOutputStreams(Iterable<? extends OutputStream> iterable) throws IOException { checkReadiness(); /* * if the image is from a BufferedImage, then we require that the * output format be set. (or else, we can't tell what format to * output as!) */ if (sources.get(0) instanceof BufferedImageSource) { if (outputFormat == ThumbnailParameter.ORIGINAL_FORMAT) { throw new IllegalStateException( "Output format not specified." ); } } if (iterable == null) { throw new NullPointerException("OutputStream iterable is null."); } ThumbnailParameter param = makeParam(); Iterator<? extends OutputStream> osIter = iterable.iterator(); for (ImageSource<T> source : sources) { if (!osIter.hasNext()) { throw new IndexOutOfBoundsException( "Not enough file names provided by iterator." ); } OutputStreamImageSink destination = new OutputStreamImageSink(osIter.next()); Thumbnailator.createThumbnail( new SourceSinkThumbnailTask<T, OutputStream>(param, source, destination) ); } } } }
package net.coobird.thumbnailator; import java.awt.Dimension; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import net.coobird.thumbnailator.filters.ImageFilter; import net.coobird.thumbnailator.filters.Pipeline; import net.coobird.thumbnailator.filters.Rotation; import net.coobird.thumbnailator.filters.Watermark; import net.coobird.thumbnailator.geometry.Position; import net.coobird.thumbnailator.geometry.Positions; import net.coobird.thumbnailator.name.Rename; import net.coobird.thumbnailator.resizers.BicubicResizer; import net.coobird.thumbnailator.resizers.BilinearResizer; import net.coobird.thumbnailator.resizers.ProgressiveBilinearResizer; import net.coobird.thumbnailator.resizers.Resizer; import net.coobird.thumbnailator.resizers.Resizers; import net.coobird.thumbnailator.resizers.configurations.AlphaInterpolation; import net.coobird.thumbnailator.resizers.configurations.Antialiasing; import net.coobird.thumbnailator.resizers.configurations.Dithering; import net.coobird.thumbnailator.resizers.configurations.Rendering; import net.coobird.thumbnailator.resizers.configurations.ScalingMode; import net.coobird.thumbnailator.tasks.FileThumbnailTask; import net.coobird.thumbnailator.tasks.SourceSinkThumbnailTask; import net.coobird.thumbnailator.tasks.io.BufferedImageSink; import net.coobird.thumbnailator.tasks.io.BufferedImageSource; import net.coobird.thumbnailator.tasks.io.FileImageSink; import net.coobird.thumbnailator.tasks.io.FileImageSource; import net.coobird.thumbnailator.tasks.io.ImageSource; import net.coobird.thumbnailator.tasks.io.OutputStreamImageSink; /** * This class provides a fluent interface to create thumbnails. * <DL> * <DT><B>Usage:</B></DT> * <DD> * The following example code demonstrates how to use the fluent interface * to create a thumbnail from multiple files from a directory, resizing them to * a maximum of 200 pixels by 200 pixels while preserving the aspect ratio of * the original, then saving the resulting thumbnails as JPEG images with file * names having {@code thumbnail.} appended to the beginning of the file name. * <p> * <pre> Thumbnails.of(directory.listFiles()) .size(200, 200) .keepAspectRatio(true) .outputFormat("jpeg") .asFiles(Rename.PREFIX_DOT_THUMBNAIL); * </pre> * </DD> * </DL> * * @author coobird * */ public final class Thumbnails { /** * This class is not intended to be instantiated. */ private Thumbnails() {} private static void validateDimensions(int width, int height) { if (width <= 0 && height <= 0) { throw new IllegalArgumentException( "Destination image dimensions must not be less than " + "0 pixels." ); } else if (width <= 0 || height <= 0) { String dimension = width == 0 ? "width" : "height"; throw new IllegalArgumentException( "Destination image " + dimension + " must not be " + "less than or equal to 0 pixels." ); } } private static void checkForNull(Object o, String message) { if (o == null) { throw new NullPointerException(message); } } private static void checkForEmpty(Object[] o, String message) { if (o.length == 0) { throw new IllegalArgumentException(message); } } private static void checkForEmpty(Collection<?> o, String message) { if (o.size() == 0) { throw new IllegalArgumentException(message); } } public static Builder<File> of(String... files) { checkForNull(files, "Cannot specify null for input files."); checkForEmpty(files, "Cannot specify an empty array for input files."); return Builder.of(files); } public static Builder<File> of(File... files) { checkForNull(files, "Cannot specify null for input files."); checkForEmpty(files, "Cannot specify an empty array for input files."); return Builder.of(files); } public static Builder<BufferedImage> of(BufferedImage... images) { checkForNull(images, "Cannot specify null for images."); checkForEmpty(images, "Cannot specify an empty array for images."); return Builder.of(images); } public static Builder<File> fromFilenames(Collection<String> files) { checkForNull(files, "Cannot specify null for input files."); checkForEmpty(files, "Cannot specify an empty collection for input files."); return of(files.toArray(new String[files.size()])); } public static Builder<File> fromFiles(Collection<File> files) { checkForNull(files, "Cannot specify null for input files."); checkForEmpty(files, "Cannot specify an empty collection for input files."); return of(files.toArray(new File[files.size()])); } public static Builder<BufferedImage> fromImages(Collection<BufferedImage> images) { checkForNull(images, "Cannot specify null for images."); checkForEmpty(images, "Cannot specify an empty collection for images."); return of(images.toArray(new BufferedImage[images.size()])); } /** * A builder interface for Thumbnailator. * <p> * An instance of this class is obtained by calling one of: * <ul> * <li>{@link Thumbnails#of(BufferedImage...)}</li> * <li>{@link Thumbnails#of(File...)}</li> * <li>{@link Thumbnails#of(String...)}</li> * <li>{@link Thumbnails#fromImages(Collection)}</li> * <li>{@link Thumbnails#fromFiles(Collection)}</li> * <li>{@link Thumbnails#fromFilenames(Collection)}</li> * </ul> * * @author coobird * */ public static class Builder<T> { private final List<ImageSource<T>> sources; private Builder(List<ImageSource<T>> sources) { this.sources = sources; statusMap.put(Properties.OUTPUT_FORMAT, Status.OPTIONAL); } private static Builder<File> of(String... filenames) { List<ImageSource<File>> sources = new ArrayList<ImageSource<File>>(); for (String f : filenames) { sources.add(new FileImageSource(f)); } return new Builder<File>(sources); } private static Builder<File> of(File... files) { List<ImageSource<File>> sources = new ArrayList<ImageSource<File>>(); for (File f : files) { sources.add(new FileImageSource(f)); } return new Builder<File>(sources); } private static Builder<BufferedImage> of(BufferedImage... images) { List<ImageSource<BufferedImage>> sources = new ArrayList<ImageSource<BufferedImage>>(); for (BufferedImage img : images) { sources.add(new BufferedImageSource(img)); } return new Builder<BufferedImage>(sources); } private final class BufferedImageIterable implements Iterable<BufferedImage> { public Iterator<BufferedImage> iterator() { return new Iterator<BufferedImage>() { Iterator<ImageSource<T>> sourceIter = sources.iterator(); public boolean hasNext() { return sourceIter.hasNext(); } public BufferedImage next() { ImageSource<T> source = sourceIter.next(); BufferedImageSink destination = new BufferedImageSink(); try { Thumbnailator.createThumbnail( new SourceSinkThumbnailTask<T, BufferedImage>(makeParam(), source, destination) ); } catch (IOException e) { return null; } return destination.getSink(); } public void remove() { throw new UnsupportedOperationException( "Cannot remove elements from this iterator." ); } }; } } /** * Status of each property. * * @author coobird * */ private static enum Status { OPTIONAL, READY, NOT_READY, ALREADY_SET, CANNOT_SET, } /** * Interface used by {@link Properties}. * * @author coobird * */ private static interface Property { public String getName(); } /** * Enum of properties which can be set by this builder. * * @author coobird * */ private static enum Properties implements Property { SIZE("size"), SCALE("scale"), IMAGE_TYPE("imageType"), SCALING_MODE("scalingMode"), ALPHA_INTERPOLATION("alphaInterpolation"), ANTIALIASING("antialiasing"), DITHERING("dithering"), RENDERING("rendering"), KEEP_ASPECT_RATIO("keepAspectRatio"), OUTPUT_FORMAT("outputFormat"), OUTPUT_FORMAT_TYPE("outputFormatType"), OUTPUT_QUALITY("outputQuality"), RESIZER("resizer"), ; private final String name; private Properties(String name) { this.name = name; } public String getName() { return name; } } /** * Map to keep track of whether a property has been properly set or not. */ private final Map<Properties, Status> statusMap = new HashMap<Properties, Status>(); /** * Populates the property map. */ { statusMap.put(Properties.SIZE, Status.NOT_READY); statusMap.put(Properties.SCALE, Status.NOT_READY); statusMap.put(Properties.IMAGE_TYPE, Status.OPTIONAL); statusMap.put(Properties.SCALING_MODE, Status.OPTIONAL); statusMap.put(Properties.ALPHA_INTERPOLATION, Status.OPTIONAL); statusMap.put(Properties.ANTIALIASING, Status.OPTIONAL); statusMap.put(Properties.DITHERING, Status.OPTIONAL); statusMap.put(Properties.RENDERING, Status.OPTIONAL); statusMap.put(Properties.KEEP_ASPECT_RATIO, Status.OPTIONAL); statusMap.put(Properties.OUTPUT_FORMAT, Status.OPTIONAL); statusMap.put(Properties.OUTPUT_FORMAT_TYPE, Status.OPTIONAL); statusMap.put(Properties.OUTPUT_QUALITY, Status.OPTIONAL); statusMap.put(Properties.RESIZER, Status.OPTIONAL); } /** * Updates the property status map. * * @param property The property to update. * @param newStatus The new status. */ private void updateStatus(Properties property, Status newStatus) { if (statusMap.get(property) == Status.ALREADY_SET) { throw new IllegalStateException( property.getName() + " is already set."); } if (statusMap.get(property) == Status.CANNOT_SET) { throw new IllegalStateException( property.getName() + " cannot be set."); } statusMap.put(property, newStatus); } /** * An constant used to indicate that the imageType has not been * specified. When this constant is encountered, one should use the * {@link ThumbnailParameter#DEFAULT_IMAGE_TYPE} as the value for * imageType. */ private static int IMAGE_TYPE_UNSPECIFIED = -1; /* * Defines the fields for the builder interface, and assigns the * default values. */ private int width = -1; private int height = -1; private double scale = Double.NaN; private int imageType = IMAGE_TYPE_UNSPECIFIED; private boolean keepAspectRatio = true; private String outputFormat = ThumbnailParameter.ORIGINAL_FORMAT; private String outputFormatType = ThumbnailParameter.DEFAULT_FORMAT_TYPE; private float outputQuality = ThumbnailParameter.DEFAULT_QUALITY; private ScalingMode scalingMode = ScalingMode.PROGRESSIVE_BILINEAR; private AlphaInterpolation alphaInterpolation = AlphaInterpolation.DEFAULT; private Dithering dithering = Dithering.DEFAULT; private Antialiasing antialiasing = Antialiasing.DEFAULT; private Rendering rendering = Rendering.DEFAULT; private Resizer resizer = Resizers.PROGRESSIVE; /** * The {@link ImageFilter}s that should be applied when creating the * thumbnail. */ private Pipeline filterPipeline = new Pipeline(); public Builder<T> size(int width, int height) { updateStatus(Properties.SIZE, Status.ALREADY_SET); updateStatus(Properties.SCALE, Status.CANNOT_SET); validateDimensions(width, height); this.width = width; this.height = height; return this; } public Builder<T> scale(double scale) { updateStatus(Properties.SCALE, Status.ALREADY_SET); updateStatus(Properties.SIZE, Status.CANNOT_SET); updateStatus(Properties.KEEP_ASPECT_RATIO, Status.CANNOT_SET); if (scale <= 0) { throw new IllegalArgumentException( "The scaling factor is equal to or less than 0." ); } this.scale = scale; return this; } public Builder<T> imageType(int type) { updateStatus(Properties.IMAGE_TYPE, Status.ALREADY_SET); imageType = type; return this; } public Builder<T> scalingMode(ScalingMode config) { checkForNull(config, "Scaling mode is null."); updateStatus(Properties.SCALING_MODE, Status.ALREADY_SET); updateStatus(Properties.RESIZER, Status.CANNOT_SET); scalingMode = config; return this; } public Builder<T> resizer(Resizer resizer) { checkForNull(resizer, "Resizer is null."); updateStatus(Properties.RESIZER, Status.ALREADY_SET); updateStatus(Properties.SCALING_MODE, Status.CANNOT_SET); this.resizer = resizer; return this; } public Builder<T> alphaInterpolation(AlphaInterpolation config) { checkForNull(config, "Alpha interpolation is null."); updateStatus(Properties.ALPHA_INTERPOLATION, Status.ALREADY_SET); alphaInterpolation = config; return this; } public Builder<T> dithering(Dithering config) { checkForNull(config, "Dithering is null."); updateStatus(Properties.DITHERING, Status.ALREADY_SET); dithering = config; return this; } public Builder<T> antialiasing(Antialiasing config) { checkForNull(config, "Antialiasing is null."); updateStatus(Properties.ANTIALIASING, Status.ALREADY_SET); antialiasing = config; return this; } public Builder<T> rendering(Rendering config) { checkForNull(config, "Rendering is null."); updateStatus(Properties.RENDERING, Status.ALREADY_SET); rendering = config; return this; } public Builder<T> keepAspectRatio(boolean keep) { if (statusMap.get(Properties.SCALE) == Status.ALREADY_SET) { throw new IllegalStateException("Cannot specify whether to " + "keep the aspect ratio if the scaling factor has " + "already been specified."); } if (statusMap.get(Properties.SIZE) != Status.ALREADY_SET) { throw new IllegalStateException("Cannot specify whether to " + "keep the aspect ratio unless the size parameter has " + "already been specified."); } updateStatus(Properties.KEEP_ASPECT_RATIO, Status.ALREADY_SET); keepAspectRatio = keep; return this; } public Builder<T> outputQuality(float quality) { if (quality < 0.0f || quality > 1.0f) { throw new IllegalArgumentException( "The quality setting must be in the range 0.0f and " + "1.0f, inclusive." ); } updateStatus(Properties.OUTPUT_QUALITY, Status.ALREADY_SET); outputQuality = quality; return this; } public Builder<T> outputQuality(double quality) { if (quality < 0.0d || quality > 1.0d) { throw new IllegalArgumentException( "The quality setting must be in the range 0.0d and " + "1.0d, inclusive." ); } updateStatus(Properties.OUTPUT_QUALITY, Status.ALREADY_SET); outputQuality = (float)quality; if (outputQuality < 0.0f) { outputQuality = 0.0f; } else if (outputQuality > 1.0f) { outputQuality = 1.0f; } return this; } public Builder<T> outputFormat(String format) { if (!ThumbnailatorUtils.isSupportedOutputFormat(format)) { throw new IllegalArgumentException( "Specified format is not supported: " + format ); } updateStatus(Properties.OUTPUT_FORMAT, Status.ALREADY_SET); outputFormat = format; return this; } public Builder<T> outputFormatType(String formatType) { /* * If the output format is the original format, and the format type * is being specified, it's going to be likely that the specified * type will not be present in all the formats, so we'll disallow * it. (e.g. setting type to "JPEG", and if the original formats * were JPEG and PNG, then we'd have a problem. */ if (formatType != ThumbnailParameter.DEFAULT_FORMAT_TYPE && outputFormat == ThumbnailParameter.ORIGINAL_FORMAT) { throw new IllegalArgumentException( "Cannot set the format type if a specific output " + "format has not been specified." ); } if (!ThumbnailatorUtils.isSupportedOutputFormatType(outputFormat, formatType)) { throw new IllegalArgumentException( "Specified format type (" + formatType + ") is not " + " supported for the format: " + outputFormat ); } /* * If the output format type is set, then we'd better make the * output format unchangeable, or else we'd risk having a type * that is not part of the output format. */ updateStatus(Properties.OUTPUT_FORMAT_TYPE, Status.ALREADY_SET); if (!statusMap.containsKey(Properties.OUTPUT_FORMAT)) { updateStatus(Properties.OUTPUT_FORMAT, Status.CANNOT_SET); } outputFormatType = formatType; return this; } /** * Sets the watermark to apply on the thumbnail. * <p> * This method can be called multiple times to apply multiple * watermarks. * <p> * If multiple watermarks are to be applied, the watermarks will be * applied in the order that this method is called. * <p> * Calling this method to set this parameter is optional. * * @param w The watermark to apply to the thumbnail. * @return Reference to this object. */ public Builder<T> watermark(Watermark w) { if (w == null) { throw new NullPointerException("Watermark is null."); } filterPipeline.add(w); return this; } /** * Sets the image of the watermark to apply on the thumbnail. * <p> * This method is a convenience method for the * {@link #watermark(Position, BufferedImage, float)} method, where * the opacity is 50%, and the position is set to center of the * thumbnail: * <p> * <pre> watermark(Positions.CENTER, image, 0.5f); * </pre> * This method can be called multiple times to apply multiple * watermarks. * <p> * If multiple watermarks are to be applied, the watermarks will be * applied in the order that this method is called. * <p> * Calling this method to set this parameter is optional. * * @param image The image of the watermark. * @return Reference to this object. */ public Builder<T> watermark(BufferedImage image) { return watermark(Positions.CENTER, image, 0.5f); } /** * Sets the image and opacity of the watermark to apply on * the thumbnail. * <p> * This method is a convenience method for the * {@link #watermark(Position, BufferedImage, float)} method, where * the opacity is 50%: * <p> * <pre> watermark(Positions.CENTER, image, opacity); * </pre> * This method can be called multiple times to apply multiple * watermarks. * <p> * If multiple watermarks are to be applied, the watermarks will be * applied in the order that this method is called. * <p> * Calling this method to set this parameter is optional. * * @param image The image of the watermark. * @param opacity The opacity of the watermark. * <p> * The value should be between {@code 0.0f} and * {@code 1.0f}, where {@code 0.0f} is completely * transparent, and {@code 1.0f} is completely * opaque. * @return Reference to this object. */ public Builder<T> watermark(BufferedImage image, float opacity) { return watermark(Positions.CENTER, image, opacity); } /** * Sets the image and opacity and position of the watermark to apply on * the thumbnail. * <p> * This method can be called multiple times to apply multiple * watermarks. * <p> * If multiple watermarks are to be applied, the watermarks will be * applied in the order that this method is called. * <p> * Calling this method to set this parameter is optional. * * @param position The position of the watermark. * @param image The image of the watermark. * @param opacity The opacity of the watermark. * <p> * The value should be between {@code 0.0f} and * {@code 1.0f}, where {@code 0.0f} is completely * transparent, and {@code 1.0f} is completely * opaque. * @return Reference to this object. */ public Builder<T> watermark(Position position, BufferedImage image, float opacity) { filterPipeline.add(new Watermark(position, image, opacity)); return this; } /* * rotation */ /** * Sets the amount of rotation to apply to the thumbnail. * <p> * The thumbnail will be rotated clockwise by the angle specified. * <p> * This method can be called multiple times to apply multiple * rotations. * <p> * If multiple rotations are to be applied, the rotations will be * applied in the order that this method is called. * <p> * Calling this method to set this parameter is optional. * * @param angle Angle in degrees. * @return Reference to this object. */ public Builder<T> rotate(double angle) { filterPipeline.add(Rotation.newRotator(angle)); return this; } /* * other filters */ /** * Adds a {@link ImageFilter} to apply to the thumbnail. * <p> * This method can be called multiple times to apply multiple * filters. * <p> * If multiple filters are to be applied, the filters will be * applied in the order that this method is called. * <p> * Calling this method to set this parameter is optional. * * @param filter An image filter to apply to the thumbnail. * @return Reference to this object. */ public Builder<T> addFilter(ImageFilter filter) { if (filter == null) { throw new NullPointerException("Filter is null."); } filterPipeline.add(filter); return this; } /** * Adds multiple {@link ImageFilter}s to apply to the thumbnail. * <p> * This method can be called multiple times to apply multiple * filters. * <p> * If multiple filters are to be applied, the filters will be * applied in the order that this method is called. * <p> * Calling this method to set this parameter is optional. * * @param filters A list of filters to apply to the thumbnail. * @return Reference to this object. */ public Builder<T> addFilters(List<ImageFilter> filters) { if (filters == null) { throw new NullPointerException("Filters is null."); } filterPipeline.addAll(filters); return this; } private void checkReadiness() { for (Map.Entry<Properties, Status> s : statusMap.entrySet()) { if (s.getValue() == Status.NOT_READY) { throw new IllegalStateException(s.getKey().getName() + " is not set."); } } } /** * Returns a {@link Resizer} which is suitable for the current * builder state. * * @return The {@link Resizer} which is suitable for the * current builder state. */ private Resizer makeResizer() { /* * If the scalingMode has been set, then use scalingMode to obtain * a resizer, else, use the resizer field. */ if (statusMap.get(Properties.SCALING_MODE) == Status.ALREADY_SET) { return makeResizer(scalingMode); } else { return this.resizer; } } /** * Returns a {@link Resizer} which is suitable for the current * builder state. * * @param mode The scaling mode to use to create thumbnails. * @return The {@link Resizer} which is suitable for the * specified scaling mode and builder state. */ private Resizer makeResizer(ScalingMode mode) { Map<RenderingHints.Key, Object> hints = new HashMap<RenderingHints.Key, Object>(); hints.put(RenderingHints.KEY_ALPHA_INTERPOLATION, alphaInterpolation.getValue()); hints.put(RenderingHints.KEY_DITHERING, dithering.getValue()); hints.put(RenderingHints.KEY_ANTIALIASING, antialiasing.getValue()); hints.put(RenderingHints.KEY_RENDERING, rendering.getValue()); if (mode == ScalingMode.BILINEAR) { return new BilinearResizer(hints); } else if (mode == ScalingMode.BICUBIC) { return new BicubicResizer(hints); } else if (mode == ScalingMode.PROGRESSIVE_BILINEAR) { return new ProgressiveBilinearResizer(hints); } else { return new ProgressiveBilinearResizer(hints); } } /** * Returns a {@link ThumbnailParameter} from the current builder state. * * @return A {@link ThumbnailParameter} from the current * builder state. */ private ThumbnailParameter makeParam() { Resizer resizer = makeResizer(); int imageTypeToUse = imageType; if (imageType == IMAGE_TYPE_UNSPECIFIED) { imageTypeToUse = ThumbnailParameter.ORIGINAL_IMAGE_TYPE; } if (Double.isNaN(scale)) { return new ThumbnailParameter( new Dimension(width, height), keepAspectRatio, outputFormat, outputFormatType, outputQuality, imageTypeToUse, filterPipeline.getFilters(), resizer ); } else { return new ThumbnailParameter( scale, keepAspectRatio, outputFormat, outputFormatType, outputQuality, imageTypeToUse, filterPipeline.getFilters(), resizer ); } } /** * Create the thumbnails and return as a {@link Iterable} of * {@link BufferedImage}s. * <p> * For situations where multiple thumbnails are being generated, this * method is preferred over the {@link #asBufferedImages()} method, * as (1) the processing does not have to complete before the method * returns and (2) the thumbnails can be retrieved one at a time, * potentially reducing the number of thumbnails which need to be * retained in the heap memory, potentially reducing the chance of * {@link OutOfMemoryError}s from occurring. * <p> * If an {@link IOException} occurs during the processing of the * thumbnail, the {@link Iterable} will return a {@code null} for that * element. * * @return An {@link Iterable} which will provide an * {@link Iterator} which returns thumbnails as * {@link BufferedImage}s. */ public Iterable<BufferedImage> iterableBufferedImages() { checkReadiness(); /* * TODO To get the precise error information, there would have to * be an event notification mechanism. */ return new BufferedImageIterable(); } /** * Create the thumbnails and return as a {@link List} of * {@link BufferedImage}s. * <p> * <h3>Note about performance</h3> * If there are many thumbnails generated at once, it is possible that * the Java virtual machine's heap space will run out and an * {@link OutOfMemoryError} could result. * <p> * If many thumbnails are being processed at once, then using the * {@link #iterableBufferedImages()} method would be preferable. * * @return A list of thumbnails. * @throws IOException If an problem occurred during * the reading of the original * images. */ public List<BufferedImage> asBufferedImages() throws IOException { checkReadiness(); List<BufferedImage> thumbnails = new ArrayList<BufferedImage>(); // Create thumbnails for (ImageSource<T> source : sources) { BufferedImageSink destination = new BufferedImageSink(); Thumbnailator.createThumbnail( new SourceSinkThumbnailTask<T, BufferedImage>(makeParam(), source, destination) ); thumbnails.add(destination.getSink()); } return thumbnails; } public BufferedImage asBufferedImage() throws IOException { checkReadiness(); if (sources.size() > 1) { throw new IllegalArgumentException("Cannot create one thumbnail from multiple original images."); } BufferedImageSink destination = new BufferedImageSink(); Thumbnailator.createThumbnail( new SourceSinkThumbnailTask<T, BufferedImage>(makeParam(), sources.get(0), destination) ); return destination.getSink(); } /** * Creates the thumbnails and stores them to the files, and returns * a {@link List} of {@link File}s to the thumbnails. * <p> * The file names for the thumbnails are obtained from the given * {@link Iterable}. * * @param rename The rename function which is used to * determine the filenames of the thumbnail * files to write. * @return A list of {@link File}s of the thumbnails * which were created. * @throws IOException If a problem occurs while reading the * original images or writing the thumbnails * to files. */ public List<File> asFiles(Iterable<File> files) throws IOException { checkReadiness(); if (files == null) { throw new NullPointerException("Rename is null."); } List<File> destinationFiles = new ArrayList<File>(); ThumbnailParameter param = makeParam(); Iterator<File> filenameIter = files.iterator(); for (ImageSource<T> source : sources) { if (!filenameIter.hasNext()) { throw new IndexOutOfBoundsException("Not enough file names provided by iterator."); } // Determine the destination file name, include it in the resulting list. File destinationFile = filenameIter.next(); destinationFiles.add(destinationFile); FileImageSink destination = new FileImageSink(destinationFile); Thumbnailator.createThumbnail(new SourceSinkThumbnailTask<T, File>(param, source, destination)); } return destinationFiles; } /** * Creates the thumbnails and stores them to the files. * <p> * The file names for the thumbnails are obtained from the given * {@link Iterable}. * * @param iterable An {@link Iterable} which returns an * {@link Iterator} which returns file names * which should be assigned to each thumbnail. * @throws IOException If a problem occurs while reading the * original images or writing the thumbnails * to files. */ public void toFiles(Iterable<File> iterable) throws IOException { asFiles(iterable); } public List<File> asFiles(Rename rename) throws IOException { checkReadiness(); if (!(sources.get(0) instanceof FileImageSource)) { throw new IllegalStateException("Cannot create thumbnails to files if original images are not from files."); } if (rename == null) { throw new NullPointerException("Rename is null."); } List<File> destinationFiles = new ArrayList<File>(); ThumbnailParameter param = makeParam(); for (ImageSource<T> source : sources) { File f = ((FileImageSource)source).getSource(); File destinationFile = new File(f.getParent(), rename.apply(f.getName())); destinationFiles.add(destinationFile); Thumbnailator.createThumbnail(new FileThumbnailTask(param, f, destinationFile)); } return destinationFiles; } public void toFiles(Rename rename) throws IOException { asFiles(rename); } public void toFile(File outFile) throws IOException { checkReadiness(); if (sources.size() > 1) { throw new IllegalArgumentException("Cannot output multiple thumbnails to one file."); } ImageSource<T> source = sources.get(0); FileImageSink destination = new FileImageSink(outFile); Thumbnailator.createThumbnail( new SourceSinkThumbnailTask<T, File>(makeParam(), source, destination) ); } public void toFile(String outFilepath) throws IOException { checkReadiness(); if (sources.size() > 1) { throw new IllegalArgumentException("Cannot output multiple thumbnails to one file."); } ImageSource<T> source = sources.get(0); FileImageSink destination = new FileImageSink(outFilepath); Thumbnailator.createThumbnail( new SourceSinkThumbnailTask<T, File>(makeParam(), source, destination) ); } public void toOutputStream(OutputStream os) throws IOException { checkReadiness(); if (sources.size() > 1) { throw new IllegalArgumentException("Cannot output multiple thumbnails to one stream."); } ImageSource<T> source = sources.get(0); OutputStreamImageSink destination = new OutputStreamImageSink(os); Thumbnailator.createThumbnail( new SourceSinkThumbnailTask<T, OutputStream>(makeParam(), source, destination) ); } } }
package logbook.internal; public enum SeaArea { ("1-1", "", 30), ("1-2", "", 50), ("1-3", "", 80), ("1-4", "", 100), ("1-5", "", 150), ("1-6", ""), ("2-1", "", 120), ("2-2", "", 150), ("2-3", "", 200), ("2-4", "", 300), ("2-5", "", 250), ("3-1", "", 310), ("3-2", "", 320), ("3-3", "", 330), ("3-4", "", 350), AL("3-5", "AL", 400), ("4-1", "", 310), ("4-2", "", 320), ("4-3", "", 330), ("4-4", "", 340), ("4-5", ""), ("5-1", "", 360), ("5-2", "", 380), ("5-3", "", 400), ("5-4", "", 420), ("5-5", "", 450), ("6-1", "", 380), MS("6-2", "MS", 420), ("6-3", ""), ("6-4", ""), (null, "", -1, 1), (null, "", -1, 2), (null, "", -1, 3); private String shortName; private String name; private int seaExp; private int area; SeaArea(String shortName, String name) { this(shortName, name, -1); } SeaArea(String shortName, String name, int seaExp) { this(shortName, name, seaExp, -1); } SeaArea(String shortName, String name, int seaExp, int area) { this.shortName = shortName; this.name = name; this.seaExp = seaExp; this.area = area; } /** * * @return */ public String getShortName() { return this.shortName; } /** * * @return */ public String getName() { return this.name; } /** * * @return */ public int getSeaExp() { return this.seaExp; } /** * () * @return () */ public int getArea() { return this.area; } @Override public String toString() { if (this.shortName != null) { return this.name + " (" + this.shortName + ")"; } else { return this.name; } } /** * * * @param area * @return */ public static SeaArea fromArea(int area) { switch (area) { case 1: return SeaArea.; case 2: return SeaArea.; case 3: return SeaArea.; default: return null; } } }
package lux.saxon; import java.io.IOException; import lux.XPathQuery; import lux.api.LuxException; import lux.api.QueryStats; import lux.lucene.LuxSearcher; import net.sf.saxon.om.Item; import net.sf.saxon.om.SequenceIterator; import net.sf.saxon.s9api.XdmItem; import net.sf.saxon.trans.XPathException; import net.sf.saxon.tree.tiny.TinyDocumentImpl; import org.apache.lucene.search.DocIdSetIterator; import org.apache.lucene.search.Scorer; @SuppressWarnings("rawtypes") public class ResultIterator implements SequenceIterator<Item>{ private final DocIdSetIterator docIter; private final XPathQuery query; private final QueryStats stats; private final LuxSearcher searcher; private final Saxon saxon; private CachingDocReader docCache; private Item current = null; private int position = 0; public ResultIterator (Saxon saxon, XPathQuery query) throws IOException { this.query = query; this.saxon = saxon; this.stats = saxon.getQueryStats(); if (stats != null) { stats.query = query.getQuery().toString(); } searcher = saxon.getContext().getSearcher(); docCache = saxon.getDocReader(); docIter = searcher.searchOrdered(query); } public Item next() throws XPathException { long t = System.nanoTime(); try { int docID = docIter.nextDoc(); //System.out.println ("GET " + docID + " " + query.toString()); if (docID == Scorer.NO_MORE_DOCS) { position = -1; current = null; } else { if (stats != null) { if (docCache.isCached(docID)) { stats.cacheHits ++; } else { stats.cacheMisses ++; } } XdmItem doc = docCache.get(docID); Item item = (Item) doc.getUnderlyingValue(); // assertion for safety if (current != null && ((TinyDocumentImpl)item).getDocumentNumber() <= ((TinyDocumentImpl)current).getDocumentNumber()) { throw new LuxException ("out of order"); } current = item; ++position; stats.retrievalTime += System.nanoTime() - t; } } catch (IOException e) { throw new XPathException(e); } finally { if (stats != null) { if (position >= 0) { stats.docCount = position; } stats.totalTime += System.nanoTime() - t; } } return current; } public Item current() { return current; } public int position() { return position; } public void close() { // Saxon doesn't call this reliably } public SequenceIterator<Item> getAnother() throws XPathException { try { return new ResultIterator (saxon, query); } catch (IOException e) { throw new XPathException (e); } } public int getProperties() { return SequenceIterator.LOOKAHEAD; } }