answer
stringlengths 17
10.2M
|
|---|
package com.matt.forgehax.mods;
import static com.matt.forgehax.Helper.getFileManager;
import static com.matt.forgehax.Helper.getLocalPlayer;
import com.google.common.collect.Lists;
import com.matt.forgehax.Helper;
import com.matt.forgehax.util.SafeConverter;
import com.matt.forgehax.util.command.Setting;
import com.matt.forgehax.util.console.ConsoleIO;
import com.matt.forgehax.util.mod.Category;
import com.matt.forgehax.util.mod.ToggleMod;
import com.matt.forgehax.util.mod.loader.RegisterMod;
import io.netty.buffer.Unpooled;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Collection;
import java.util.Scanner;
import java.util.function.Consumer;
import net.minecraft.client.gui.GuiScreenBook;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemWritableBook;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTTagString;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.play.client.CPacketCustomPayload;
import net.minecraft.util.EnumHand;
@RegisterMod
public class BookBot extends ToggleMod {
private static final int MAX_CHARACTERS_PER_PAGE = 256;
private static final int MAX_PAGES = 50;
public static final String NUMBER_TOKEN = "\\{NUMBER\\}";
public static final String NEW_PAGE = ":PAGE:";
private final Setting<String> name =
getCommandStub()
.builders()
.<String>newSettingBuilder()
.name("name")
.description("Name of the book, use {NUMBER} for the number")
.defaultTo("Book #{NUMBER}")
.build();
private final Setting<String> file =
getCommandStub()
.builders()
.<String>newSettingBuilder()
.name("file")
.description("Name of the file inside the forgehax directory to use")
.defaultTo("")
.build();
private final Setting<Boolean> prettify =
getCommandStub()
.builders()
.<Boolean>newSettingBuilder()
.name("prettify")
.description("Enables word wrapping. Can cause book size to increase dramatically")
.defaultTo(true)
.build();
private final Setting<Long> sleep =
getCommandStub()
.builders()
.<Long>newSettingBuilder()
.name("sleep")
.description("Sleep time in ms")
.defaultTo(10L)
.build();
private Thread writerThread = null;
private BookWriter writer = null;
public BookBot() {
super(Category.MISC, "BookBot", false, "Automatically write books");
}
private static final Collection<Character> CHARS_NO_REPEATING =
Lists.newArrayList(' ', '\n', '\t', '\r');
private static String parseText(String text, boolean wrap) {
text = text.replace('\r', '\n').replace('\t', ' ').replace("\0", "");
StringBuilder builder = new StringBuilder();
char next = '\0', last;
int ls = -1; // last space index
for (int i = 0, p = i; i < text.length(); i++, p++, p %= MAX_CHARACTERS_PER_PAGE) {
// previous character
last = next;
// next character
next = text.charAt(i);
// start a new page at the initial position
if (p == 0) builder.append(NEW_PAGE);
// if this index contains a space, save the index
if (next == ' ') ls = i;
// prevent annoying repeating characters
if (CHARS_NO_REPEATING.contains(next) && CHARS_NO_REPEATING.contains(last)) {
// do not append, go back 1 position to act as if this was never processed
p
continue;
}
// word wrapping logic
if (wrap && ls != -1 && last == ' ') {
// next space index
int ns = text.indexOf(' ', i);
// distance from next space to last space
int d = ns - ls;
// if the word (distance between two spaces) is less than the max chars allowed (to prevent
// words greater than it from causing an infinite loop), and
// the word will not fit onto the current page.
if (d < MAX_CHARACTERS_PER_PAGE && (p + d) > MAX_CHARACTERS_PER_PAGE) {
// insert new page
builder.append(NEW_PAGE);
// start at position 0
p = 0;
}
}
builder.append(next);
}
return builder.toString();
}
private BookWriter loadFile() throws RuntimeException {
if (file.get().isEmpty()) throw new RuntimeException("No file name set");
File f = Helper.getFileManager().getFileInBaseDirectory(file.get());
if (!f.exists()) throw new RuntimeException("File not found");
if (!f.isFile()) throw new RuntimeException("Not a file type");
String text;
try {
text = new String(Files.readAllBytes(f.toPath()), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("Failed to read file");
}
if (f.getName().endsWith(".txt") || f.getName().endsWith(".book")) {
return new BookWriter(
this, f.getName().endsWith(".txt") ? parseText(text, prettify.get()) : text);
} else throw new RuntimeException("File is not of a .txt or .book type");
}
@Override
public String getDisplayText() {
return this.writer == null
? super.getDisplayText()
: super.getDisplayText() + "[" + this.writer.toString() + "]";
}
@Override
protected void onLoad() {
getCommandStub()
.builders()
.newCommandBuilder()
.name("start")
.description("Start book bot. Can optionally set the starting position")
.processor(
data -> {
if (writerThread != null)
throw new RuntimeException("BookBot thread already running!");
Integer page = SafeConverter.toInteger(data.getArgument(0), 0);
if (writer == null) {
writer = loadFile();
data.write(String.format("BookBot file \"%s\" loaded successfully", file.get()));
}
writer.setPage(page);
writerThread = new Thread(writer);
writer.start();
writerThread.start();
data.write("BookBot task started");
})
.build();
getCommandStub()
.builders()
.newCommandBuilder()
.name("reset")
.description("Stop the BookBot task")
.processor(
data -> {
if (writer != null) {
writer.setFinalListener(
o -> ConsoleIO.write("BookBot task stopped at page " + writer.getPage()));
writer.stop();
writerThread = null;
data.write("Stopping BookBot");
} else data.write("No writer present");
})
.build();
getCommandStub()
.builders()
.newCommandBuilder()
.name("resume")
.description("Resume the BookBot task")
.processor(
data -> {
if (writer != null) {
writerThread = new Thread(writer);
writer.start();
writerThread.start();
} else data.write("No writer present");
})
.build();
getCommandStub()
.builders()
.newCommandBuilder()
.name("delete")
.description("Delete the writer bot instance")
.processor(
data -> {
if (writer != null) {
writer.setFinalListener(
o -> ConsoleIO.write("BookBot task stopped at page " + writer.getPage()));
writer.stop();
writer = null;
writerThread = null;
data.write("Shutting down BookBot instance");
} else data.write("No writer present");
})
.build();
getCommandStub()
.builders()
.newCommandBuilder()
.name("load")
.description("Load the file into memory")
.processor(
data -> {
writer = loadFile();
data.write(String.format("BookBot file \"%s\"loaded successfully", file.get()));
})
.build();
getCommandStub()
.builders()
.newCommandBuilder()
.name("save")
.description("Save the contents to a .book file in the forgehax folder")
.processor(
data -> {
String fname = data.getArgument(0);
// optional argument, if not given use name from file variable and rename the
// extension to .book
if (fname == null || fname.isEmpty()) {
fname = file.get();
if (!fname.endsWith(".book")) fname = fname.substring(0, fname.lastIndexOf('.'));
}
if (!fname.endsWith(".book")) fname += ".book"; // append extension type
if (writer != null) {
try {
Files.write(
getFileManager().getFileInBaseDirectory(fname).toPath(),
writer.contents.getBytes());
data.write("Successfully saved book data");
} catch (IOException e) {
data.write("Failed to write file");
}
} else data.write("No writer present");
})
.build();
}
private static class BookWriter implements Runnable {
public enum Status {
INITIALIZED,
FINISHED,
ERROR,
STOPPED,
AWAITING_GUI_CLOSE,
NEED_EMPTY_BOOKS_IN_HOTBAR,
CHANGING_HELD_ITEM,
OPENING_BOOK,
CLOSING_BOOK,
WRITING_BOOK,
}
private final BookBot parent;
private final String contents;
private final int totalPages;
private volatile Status status = Status.INITIALIZED;
private volatile boolean stopped = false;
private Scanner parser;
private int page = 0;
private Consumer<BookWriter> finalListener = null;
public BookWriter(BookBot parent, String contents) {
this.parent = parent;
this.contents = contents;
Scanner scanner = newScanner();
int c = 0;
while (scanner.hasNext()) {
scanner.next();
c++;
}
this.totalPages = c;
}
private Scanner newScanner() {
return new Scanner(contents).useDelimiter(NEW_PAGE);
}
public int getTotalPages() {
return totalPages;
}
public int getTotalBooks() {
return totalPages > 0 ? (int) Math.ceil((double) (totalPages) / (double) (MAX_PAGES)) : 0;
}
public Status getStatus() {
return status;
}
public int getPage() {
return page;
}
public void setPage(int page) {
if (parser != null)
throw new RuntimeException("Cannot set position while task is running or stopped");
this.page = page;
}
public int getBook() {
return page > 0 ? (int) Math.ceil((double) (page) / (double) (MAX_PAGES)) : 0;
}
public void setFinalListener(Consumer<BookWriter> finalListener) {
this.finalListener = finalListener;
}
public boolean isStopped() {
return stopped;
}
public void start() {
if (parser == null) {
parser = newScanner();
// skip pages
for (int i = 0; i < page && parser.hasNext(); i++) parser.next();
}
stopped = false;
finalListener = null;
}
public void stop() {
stopped = true;
}
private void sendBook(ItemStack stack) {
NBTTagList pages = new NBTTagList(); // page tag list
// copy pages into NBT
for (int i = 0; i < MAX_PAGES && parser.hasNext(); i++) {
pages.appendTag(new NBTTagString(parser.next().trim()));
page++;
}
// set our client side book
if (stack.hasTagCompound()) stack.getTagCompound().setTag("pages", pages);
else stack.setTagInfo("pages", pages);
// publish the book
stack.setTagInfo("author", new NBTTagString(getLocalPlayer().getName()));
stack.setTagInfo(
"title",
new NBTTagString(parent.name.get().replaceAll(NUMBER_TOKEN, "" + getBook()).trim()));
PacketBuffer buff = new PacketBuffer(Unpooled.buffer());
buff.writeItemStack(stack);
MC.getConnection().sendPacket(new CPacketCustomPayload("MC|BSign", buff));
}
@Override
public void run() {
try {
while (!stopped) {
// check to see if we've finished the book
if (!parser.hasNext()) {
this.status = Status.FINISHED;
break;
}
sleep();
// wait for screen
if (MC.currentScreen != null) {
this.status = Status.AWAITING_GUI_CLOSE;
continue;
}
// search for empty book
int slot = -1;
ItemStack selected = null;
for (int i = 0; i < InventoryPlayer.getHotbarSize(); i++) {
ItemStack stack = getLocalPlayer().inventory.getStackInSlot(i);
if (stack != null
&& !stack.equals(ItemStack.EMPTY)
&& stack.getItem() instanceof ItemWritableBook) {
slot = i;
selected = stack;
break;
}
}
// make sure we found a book
if (slot == -1) {
this.status = Status.NEED_EMPTY_BOOKS_IN_HOTBAR;
continue;
}
// set selected item to that slot
while (getLocalPlayer().inventory.currentItem != slot) {
getLocalPlayer().inventory.currentItem = slot;
this.status = Status.CHANGING_HELD_ITEM;
sleep();
}
final ItemStack item = selected;
// open the book gui screen
this.status = Status.OPENING_BOOK;
MC.addScheduledTask(() -> getLocalPlayer().openBook(item, EnumHand.MAIN_HAND));
// wait for gui to open
while (!(MC.currentScreen instanceof GuiScreenBook)) sleep();
// send book to server
this.status = Status.WRITING_BOOK;
MC.addScheduledTask(
() -> {
sendBook(item);
MC.displayGuiScreen(null);
});
// wait for screen to close
while (MC.currentScreen != null) sleep();
}
} catch (Throwable t) {
this.status = Status.ERROR;
} finally {
if (finalListener != null) {
finalListener.accept(this);
finalListener = null;
}
// set stopped to true
this.stopped = true;
if (!this.status.equals(Status.FINISHED) && !this.status.equals(Status.ERROR))
this.status = Status.STOPPED;
}
}
@Override
public String toString() {
return String.format(
"Status=%s,P/T=%d/%d,B/T=%d/%d",
status.name(), page, getTotalPages(), getBook(), getTotalBooks());
}
private void sleep() throws InterruptedException {
Thread.sleep(parent.sleep.get());
if (stopped) throw new RuntimeException("Thread stopped");
}
}
}
|
package com.yahoo.container.core.config;
import com.yahoo.config.FileReference;
import com.yahoo.container.Container;
import com.yahoo.filedistribution.fileacquirer.FileAcquirer;
import com.yahoo.osgi.Osgi;
import org.osgi.framework.Bundle;
import org.osgi.framework.wiring.BundleRevision;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import java.util.stream.Collectors;
/**
* Manages the set of installed and active/inactive bundles.
*
* @author gjoranv
* @author Tony Vaagenes
*/
public class ApplicationBundleLoader {
/* Map of file refs of active bundles (not scheduled for uninstall) to the installed bundle.
*
* Used to:
* 1. Avoid installing already installed bundles. Just an optimization, installing the same bundle location is a NOP
* 2. Start bundles (all are started every time)
* 3. Calculate the set of bundles to uninstall
*/
private final Map<FileReference, Bundle> reference2Bundle = new LinkedHashMap<>();
private final Logger log = Logger.getLogger(ApplicationBundleLoader.class.getName());
private final Osgi osgi;
// A custom bundle installer for non-disk bundles, to be used for testing
private BundleInstaller customBundleInstaller = null;
public ApplicationBundleLoader(Osgi osgi) {
this.osgi = osgi;
}
/**
* Installs the given set of bundles and returns the set of bundles that is no longer used
* by the application, and should therefore be scheduled for uninstall.
*/
public synchronized Set<Bundle> useBundles(List<FileReference> newFileReferences) {
Set<FileReference> obsoleteReferences = getObsoleteFileReferences(newFileReferences);
Set<Bundle> bundlesToUninstall = getObsoleteBundles(obsoleteReferences);
log.info("Bundles to schedule for uninstall: " + bundlesToUninstall);
osgi.allowDuplicateBundles(bundlesToUninstall);
removeInactiveFileReferences(obsoleteReferences);
installBundles(newFileReferences);
BundleStarter.startBundles(reference2Bundle.values());
log.info(installedBundlesMessage());
return bundlesToUninstall;
}
private Set<FileReference> getObsoleteFileReferences(List<FileReference> newReferences) {
Set<FileReference> obsoleteReferences = new HashSet<>(reference2Bundle.keySet());
obsoleteReferences.removeAll(newReferences);
return obsoleteReferences;
}
/**
* Returns the bundles that will not be retained by the new application generation.
*/
private Set<Bundle> getObsoleteBundles(Set<FileReference> obsoleteReferences) {
return obsoleteReferences.stream().map(reference2Bundle::get).collect(Collectors.toSet());
}
private void removeInactiveFileReferences(Set<FileReference> fileReferencesToRemove) {
fileReferencesToRemove.forEach(reference2Bundle::remove);
}
private void installBundles(List<FileReference> references) {
Set<FileReference> bundlesToInstall = new HashSet<>(references);
// This is just an optimization, as installing a bundle with the same location id returns the already installed bundle.
bundlesToInstall.removeAll(reference2Bundle.keySet());
if (!bundlesToInstall.isEmpty()) {
FileAcquirer fileAcquirer = Container.get().getFileAcquirer();
boolean hasFileDistribution = (fileAcquirer != null);
if (hasFileDistribution) {
installWithFileDistribution(bundlesToInstall, new FileAcquirerBundleInstaller(fileAcquirer));
} else if (customBundleInstaller != null) {
installWithFileDistribution(bundlesToInstall, customBundleInstaller);
} else {
log.warning("Can't retrieve bundles since file distribution is disabled.");
}
}
}
private void installWithFileDistribution(Set<FileReference> bundlesToInstall, BundleInstaller bundleInstaller) {
for (FileReference reference : bundlesToInstall) {
try {
log.info("Installing bundle with reference '" + reference.value() + "'");
List<Bundle> bundles = bundleInstaller.installBundles(reference, osgi);
// If more than one bundle was installed, and the OSGi framework is the real Felix one,
// it means that the X-JDisc-Preinstall-Bundle header was used.
// However, test osgi frameworks may return multiple bundles when installing a single bundle.
if (bundles.size() > 1 && osgi.hasFelixFramework()) {
// TODO: remove if-statement below when the last model with preinstall has rolled out of hosted
if (! bundles.get(0).getSymbolicName().equals("config-model-fat-amended"))
throw new RuntimeException("Bundle '" + bundles.get(0).getSymbolicName() + "' tried to pre-install bundles from disk.");
}
reference2Bundle.put(reference, bundles.get(0));
}
catch(Exception e) {
throw new RuntimeException("Could not install bundle with reference '" + reference + "'", e);
}
}
}
private String installedBundlesMessage() {
StringBuilder sb = new StringBuilder("Installed bundles: {" );
for (Bundle b : osgi.getBundles())
sb.append("[" + b.getBundleId() + "]" + b.getSymbolicName() + ":" + b.getVersion() + ", ");
sb.setLength(sb.length() - 2);
sb.append("}");
return sb.toString();
}
// Only for testing
void useCustomBundleInstaller(BundleInstaller bundleInstaller) {
customBundleInstaller = bundleInstaller;
}
// Only for testing
List<FileReference> getActiveFileReferences() {
return new ArrayList<>(reference2Bundle.keySet());
}
}
|
package org.springsource.ide.eclipse.commons.livexp.ui;
import static org.springsource.ide.eclipse.commons.livexp.ui.UIConstants.FIELD_TEXT_AREA_WIDTH;
import java.util.Collection;
import java.util.Objects;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.springsource.ide.eclipse.commons.livexp.core.FieldModel;
import org.springsource.ide.eclipse.commons.livexp.core.LiveExpression;
import org.springsource.ide.eclipse.commons.livexp.core.LiveVariable;
import org.springsource.ide.eclipse.commons.livexp.core.SelectionModel;
import org.springsource.ide.eclipse.commons.livexp.core.ValidationResult;
import org.springsource.ide.eclipse.commons.livexp.core.ValueListener;
import org.springsource.ide.eclipse.commons.livexp.util.Parser;
/**
* Wizard section to choose one element from list of elements. Uses a pulldown Combo box to allow selecting
* an element.
*/
public class ChooseOneSectionCombo<T> extends AbstractChooseOneSection<T> {
private boolean DEBUG = true; //(""+Platform.getLocation()).contains("kdvolder");
private void debug(String string) {
if (DEBUG) {
System.out.println("handleModifyText "+string);
}
}
private final SelectionModel<T> selection;
private final String label; //Descriptive Label for this section
private LiveExpression<T[]> options; //The elements to choose from
private boolean useFieldLabelWidthHint = true;
private boolean grabHorizontal = false;
/**
* For a combo that allows text edits, a textInputParser must be provided to convert
* the input text into a selection value.
*/
private Parser<T> inputParser = null;
public ChooseOneSectionCombo(IPageWithSections owner, String label, SelectionModel<T> selection, T[] options) {
this(owner, label, selection, LiveExpression.constant(options));
Assert.isNotNull(options);
}
public ChooseOneSectionCombo<T> useFieldLabelWidthHint(boolean use) {
this.useFieldLabelWidthHint = use;
return this;
}
public ChooseOneSectionCombo<T> grabHorizontal(boolean grab) {
this.grabHorizontal = grab;
return this;
}
public ChooseOneSectionCombo(IPageWithSections owner, String label, SelectionModel<T> selection, LiveExpression<T[]> options) {
super(owner);
DEBUG = DEBUG && "Service URL".equals(label);
this.label = label;
this.selection = selection;
this.options = options;
}
@SuppressWarnings("unchecked")
public ChooseOneSectionCombo(IPageWithSections owner, String label, LiveVariable<T> selection, Collection<T> options) {
this(owner,
label,
new SelectionModel<>(selection),
(T[])options.toArray()
);
}
public ChooseOneSectionCombo(IPageWithSections owner, FieldModel<T> model,
T[] options) {
this(owner, model.getLabel(), new SelectionModel<>(model.getVariable(), model.getValidator()), LiveExpression.constant(options));
}
/**
* Enable's support for 'editable' text widget in the Combo. This means user can perform textual edits
* in addition to using the combo.
* <p>
* To support these 'free form' edits. A inputParser must be provided.
*/
public void allowTextEdits(Parser<T> inputParser) {
this.inputParser = inputParser;
}
@Override
public LiveExpression<ValidationResult> getValidator() {
return selection.validator;
}
public LiveVariable<T> getSelection() {
return selection.selection;
}
@Override
public void createContents(Composite page) {
Composite field = new Composite(page, SWT.NONE);
GridLayout layout = GridLayoutFactory.fillDefaults().numColumns(2).create();
field.setLayout(layout);
GridDataFactory.fillDefaults().grab(true, false).applyTo(field);
Label fieldNameLabel = new Label(field, SWT.NONE);
fieldNameLabel.setText(label);
GridDataFactory labelGridData = GridDataFactory
.fillDefaults()
.align(SWT.BEGINNING, SWT.CENTER);
if (useFieldLabelWidthHint) {
labelGridData.hint(UIConstants.fieldLabelWidthHint(fieldNameLabel), SWT.DEFAULT);
}
labelGridData.applyTo(fieldNameLabel);
final Combo combo = new Combo(field, inputParser==null?SWT.READ_ONLY:SWT.NONE);
options.addListener(new ValueListener<T[]>() {
public void gotValue(org.springsource.ide.eclipse.commons.livexp.core.LiveExpression<T[]> exp, T[] value) {
if (combo!=null) {
String oldText = combo.getText();
combo.setItems(getLabels()); //This will clear the selection sometimes
combo_setText(combo, oldText);
}
};
});
if (inputParser==null) {
GridDataFactory.fillDefaults().applyTo(combo);
// } else if (grabHorizontal) {
// GridDataFactory.fillDefaults().grab(true, false).applyTo(combo);
} else {
GridDataFactory.fillDefaults().hint(FIELD_TEXT_AREA_WIDTH, SWT.DEFAULT).applyTo(combo);
}
combo.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
handleModifyText(combo);
}
});
selection.selection.addListener(new ValueListener<T>() {
public void gotValue(LiveExpression<T> exp, T newSelection) {
if (newSelection!=null) {
//Technically, not entirely correct. This might
// select the wrong element if more than one option
// has the same label text.
String newText = labelProvider.getText(newSelection);
combo_setText(combo, newText);
if (!combo.getText().equals(newText)) {
//widget rejected the selection. To avoid widget state
// and model state getting out-of-sync, refelct current
// widget state back to the model:
handleModifyText(combo);
}
}
}
});
}
private void combo_setText(final Combo combo, String newText) {
if (combo!=null && !combo.isDisposed()) {
String oldText = combo.getText();
if (!Objects.equals(oldText, newText)) {
//Avoid setting the text if its already set to a equal value. This can cause strange effects by
combo.setText(newText);
}
}
}
private void handleModifyText(final Combo combo) {
int selected = combo.getSelectionIndex();
debug("selectedIdx = "+selected);
T[] options = getOptionsArray();
if (options!=null && selected>=0 && selected<options.length) {
debug("setting selection based on idx = "+ options[selected]);
selection.selection.setValue(options[selected]);
} else {
T parsed = parse(combo.getText());
debug("setting selection from combo = "+ parsed);
selection.selection.setValue(parsed);
}
debug("Exiting: "+labelProvider.getText(selection.selection.getValue()) +" == "+combo.getText());
}
private T parse(String text) {
try {
if (inputParser!=null) {
return inputParser.parse(text);
}
} catch (Exception e) {
//ignore unparsable input
}
return null;
}
private String[] getLabels() {
String[] labels = new String[getOptionsArray().length];
for (int i = 0; i < labels.length; i++) {
labels[i] = labelProvider.getText(getOptionsArray()[i]);
}
return labels;
}
private T[] getOptionsArray() {
return options.getValue();
}
public LiveExpression<T[]> getOptions() {
return options;
}
/**
* Convenience method that returns the options cast to LiveVariable. This method
* will throw an {@link ClassCastException} if the options were not provided
* via a LiveVariable.
*/
public LiveVariable<T[]> getOptionsVar() {
return (LiveVariable<T[]>) options;
}
}
|
package flyway.oskari;
import fi.nls.oskari.domain.map.view.Bundle;
import fi.nls.oskari.domain.map.view.View;
import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.map.view.*;
import fi.nls.oskari.map.view.util.ViewHelper;
import fi.nls.oskari.util.ConversionHelper;
import fi.nls.oskari.util.JSONHelper;
import fi.nls.oskari.util.PropertyUtil;
import org.apache.commons.lang.StringUtils;
import org.flywaydb.core.api.migration.jdbc.JdbcMigration;
import org.json.JSONArray;
import org.json.JSONObject;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
/**
* Migrates all views of type "PUBLISHED" and having a bundle with "openlayers" referenced in the startup JSON.
* This targets all the Openlayers 2 based published maps. The views are then programmatically
* "republished" with the current publish template which should be Openlayers 3 based, but the
* doesn't really care about it. You could use it to migrate published maps to any new publish template with
* some modification to the selection of views to migrate.
*/
public class V1_39_2__migrate_published_maps_to_ol3 implements JdbcMigration {
private static final Logger LOG = LogFactory.getLogger(V1_39_2__migrate_published_maps_to_ol3.class);
private ViewService service = null;
private BundleService bundleService = null;
public void migrate(Connection conn)
throws Exception {
if (PropertyUtil.getOptional("flyway.1_39_2.skip", false)) {
LOG.warn("You are skipping published maps migration.",
"All new development is happening for the Openlayers 3 based publish template",
"and having Openlayers 2 based published maps might not work properly anymore.",
"You will have to make an app specific migration since you skipped this one.");
return;
}
service = new ViewServiceIbatisImpl();
bundleService = new BundleServiceIbatisImpl();
// 1. list view uuids that have openlayers2 and of type PUBLISHED
List<String> uuidList = getOL2PublishedUUIDs(conn);
for(String uuid : uuidList) {
// load views like AppSetupHandler.get()
final View oldView = service.getViewWithConfByUuId(uuid);
final JSONObject json = getPayload(oldView);
// republish -> like feed through AppSetupHandler.post() but with less user checks
final View view = getBaseView(oldView);
setupMapState(view, json.optJSONObject("mapfull"));
merge(view, json);
}
}
private List<String> getOL2PublishedUUIDs(Connection conn) throws SQLException {
List<String> list = new ArrayList<>();
String sql = "select uuid from portti_view where type = 'PUBLISHED' and " +
"id in (SELECT id FROM portti_view_bundle_seq where startup like '%openlayers%')";
try(PreparedStatement statement = conn.prepareStatement(sql)) {
try (ResultSet rs = statement.executeQuery()) {
while(rs.next()) {
list.add(rs.getString("uuid"));
}
}
}
return list;
}
private JSONObject getPayload(View view) {
try {
return ViewHelper.getConfiguration(view);
} catch (ViewException ex) {
throw new RuntimeException("Couldn't restore view data for view id: " + view.getId(), ex);
}
}
// code copied from AppSetupHandler to do the republishing
public void merge(View view, JSONObject viewdata) {
// check if we need to add divmanazer
for(String bundleid : BUNDLE_REQUIRES_DIVMANAZER) {
if(viewdata.has(bundleid)) {
// Found bundles that require divmanazer
// add it to the view before handling them
LOG.info("Adding bundle", "divmanazer");
addBundle(view, "divmanazer");
// break so we don't add it more than once
break;
}
}
// setup all the bundles that don't need extra processing
for(String bundleid : SIMPLE_BUNDLES) {
if(viewdata.has(bundleid)) {
setupBundle(view, viewdata, bundleid, ALWAYSON_BUNDLES.contains(bundleid));
//toolbar -> add style info from metadata
if (bundleid.equals("toolbar")) {
setupToolbarStyleInfo(view);
}
}
}
setupBundle(view, viewdata, "publishedmyplaces2", false);
try {
service.updatePublishedView(view);
} catch (ViewException e) {
throw new RuntimeException("Couldn't update view with id:" + view.getId());
}
}
private void setupToolbarStyleInfo(final View view) {
final Bundle toolbarBundle = view.getBundleByName("toolbar");
if (toolbarBundle == null) {
return;
}
JSONObject toolbarConfig = toolbarBundle.getConfigJSON();
JSONHelper.putValue(toolbarConfig, KEY_STYLE, view.getMetadata().optJSONObject(KEY_STYLE));
}
// Simple bundles don't require extra processing
private static final Set<String> SIMPLE_BUNDLES = ConversionHelper.asSet(
"infobox", "toolbar",
"publishedgrid", "featuredata2", "coordinatetool", "statsgrid");
// Bundles that we don't want to remove even if publisher doesn't provide config
private static final Set<String> ALWAYSON_BUNDLES = ConversionHelper.asSet(
"infobox", "toolbar");
// Bundles that require divmanazer to be loaded for them to work
private static final Set<String> BUNDLE_REQUIRES_DIVMANAZER =
ConversionHelper.asSet("featuredata2", "coordinatetool", "statsgrid");
// List of bundles that the user is able to publish
// mapfull not included since it's assumed to be part of publisher template handled anyways
private static final Set<String> BUNDLE_WHITELIST = ConversionHelper.asSet(
"publishedmyplaces2", "divmanazer");
static {
// add all "simple" bundles to the whitelist
BUNDLE_WHITELIST.addAll(SIMPLE_BUNDLES);
}
private Bundle setupBundle(final View view, final JSONObject inputViewData, final String bundleid, final boolean alwaysKeep) {
// Note! Assumes value is a JSON object
final JSONObject bundleData = inputViewData.optJSONObject(bundleid);
if (bundleData != null) {
LOG.info("Config found for", bundleid);
final Bundle bundle = addBundle(view, bundleid);
if(bundle != null) {
mergeBundleConfiguration(bundle, bundleData.optJSONObject(KEY_CONF), bundleData.optJSONObject(KEY_STATE));
}
return bundle;
} else if(!alwaysKeep) {
// Remove bundle since it's not needed
LOG.warn("Config not found for", bundleid, "- removing bundle.");
view.removeBundle(bundleid);
}
return null;
}
private Bundle addBundle(final View view, final String bundleid) {
if(!BUNDLE_WHITELIST.contains(bundleid)) {
LOG.warn("Trying to add bundle that isn't recognized:", bundleid, "- Skipping it!");
return null;
}
Bundle bundle = view.getBundleByName(bundleid);
if (bundle == null) {
LOG.info("Bundle with id:", bundleid, "not found in currentView - adding");
bundle = bundleService.getBundleTemplateByName(bundleid);
view.addBundle(bundle);
}
return bundle;
}
private static final String KEY_PLUGINS = "plugins";
private static final String KEY_LAYERS = "layers";
private static final String KEY_SELLAYERS = "selectedLayers";
private static final String KEY_CROSSHAIR = "crosshair";
private static final String KEY_STATE = "state";
private static final String KEY_CONF = "conf";
private static final String KEY_CONFIG = "config";
private static final String KEY_MAPOPTIONS = "mapOptions";
private static final String KEY_STYLE = "style";
private static final String KEY_ID = "id";
private void setupMapState(final View view, final JSONObject input) throws Exception {
final Bundle mapfullBundle = view.getBundleByName("mapfull");
if (mapfullBundle == null) {
throw new Exception("Could not find mapfull bundle from template view: " + view.getId());
}
if(input == null) {
throw new Exception("Could not get state for mapfull from publisher data");
}
// complete overrride of template mapfull state with the data coming from publisher!
JSONObject mapfullState = input.optJSONObject(KEY_STATE);
if(mapfullState == null) {
throw new Exception("Could not get state for mapfull from publisher data");
}
mapfullBundle.setState(mapfullState.toString());
// setup layers based on user rights (double check for user rights)
final JSONArray selectedLayers = mapfullState.optJSONArray(KEY_SELLAYERS);
// Override template layer selections
final boolean layersUpdated = JSONHelper.putValue(mapfullBundle.getConfigJSON(), KEY_LAYERS, selectedLayers);
final boolean selectedLayersUpdated = JSONHelper.putValue(mapfullBundle.getStateJSON(), KEY_SELLAYERS, selectedLayers);
if (!(layersUpdated && selectedLayersUpdated)) {
// failed to put layers correctly
throw new Exception("Could not override layers selections");
}
final JSONArray plugins = mapfullBundle.getConfigJSON().optJSONArray(KEY_PLUGINS);
if(plugins == null) {
throw new Exception("Could not get default plugins");
}
final JSONObject mapfullConf = input.optJSONObject(KEY_CONF);
if(mapfullConf == null) {
throw new Exception("Could not get map configuration from input");
}
JSONObject finalConfig = mapfullBundle.getConfigJSON();
final JSONArray userConfiguredPlugins = mapfullConf.optJSONArray(KEY_PLUGINS);
if(userConfiguredPlugins == null) {
throw new Exception("Could not get map plugins from input");
}
// merge user configs for template plugins
for(int i = 0; i < plugins.length(); ++i) {
JSONObject plugin = plugins.optJSONObject(i);
//plugins
JSONObject userPlugin = removePlugin(userConfiguredPlugins, plugin.optString(KEY_ID));
if(userPlugin != null) {
// same plugin from template AND user
// merge config using users as base! and override it with template values
// this way terms of use etc cannot be overridden by user
JSONObject mergedConfig = JSONHelper.merge(userPlugin.optJSONObject(KEY_CONFIG), plugin.optJSONObject(KEY_CONFIG));
JSONHelper.putValue(plugin, KEY_CONFIG, sanitizeConfigLocation(mergedConfig));
}
}
// add remaining plugins user has selected on top of template plugins
for (int i = userConfiguredPlugins.length(); --i >= 0; ) {
JSONObject userPlugin = userConfiguredPlugins.optJSONObject(i);
JSONHelper.putValue(userPlugin, KEY_CONFIG, sanitizeConfigLocation(userPlugin.optJSONObject(KEY_CONFIG)));
plugins.put(userPlugin);
}
// replace current plugins
JSONHelper.putValue(finalConfig, KEY_PLUGINS, plugins);
// copy style definition from metadata to mapOptions
JSONObject mapOptions = finalConfig.optJSONObject(KEY_MAPOPTIONS);
if(mapOptions == null) {
// create mapOptions if it doesn't exist
mapOptions = new JSONObject();
JSONHelper.putValue(finalConfig, KEY_MAPOPTIONS, mapOptions);
}
JSONHelper.putValue(mapOptions, KEY_CROSSHAIR, mapOptions.optBoolean(KEY_CROSSHAIR));
// ensure consistency in mapOptions/metadata style block
// NOTE! Need to use mapOptions from input conf to get the original one
final JSONObject style = ensureStyleConsistency(
view.getMetadata().optJSONObject(KEY_STYLE), mapfullConf.optJSONObject(KEY_MAPOPTIONS));
JSONHelper.putValue(mapOptions, KEY_STYLE, style);
view.getMetadata().put(KEY_STYLE, style);
}
private static final String KEY_FONT = "font";
private static final String KEY_TOOLSTYLE = "toolStyle";
/**
* Some views seem to only have style saved to mapOptions and NOT metadata. Options is used for rendering, metadata
* is used for publisher. Metadata should be consistent, but for reason or another isn't in the database. Merge
* the values with metadata as master and mapOptions to fill in missing parts.
* @param metadata
* @param options
* @return
*/
private JSONObject ensureStyleConsistency(JSONObject metadata, JSONObject options) {
if(options == null) {
return metadata;
}
JSONObject style = options.optJSONObject(KEY_STYLE);
if(style == null) {
return metadata;
}
if(!metadata.has(KEY_FONT) && style.has(KEY_FONT)) {
JSONHelper.putValue(metadata, KEY_FONT, style.optString(KEY_FONT));
}
if(!metadata.has(KEY_TOOLSTYLE) && style.has(KEY_TOOLSTYLE)) {
JSONHelper.putValue(metadata, KEY_TOOLSTYLE, style.optString(KEY_TOOLSTYLE));
}
return metadata;
}
private static final Set<String> CLASS_WHITELIST = ConversionHelper.asSet("center", "top", "right", "bottom", "left");
private static final String KEY_LOCATION = "location";
private static final String KEY_CLASSES = "classes";
/**
* Removes the plugin and returns the removed value or null if not found.
* NOTE! Modifies input list
* @param plugins
* @param pluginId
* @return
*/
public static JSONObject removePlugin(final JSONArray plugins, final String pluginId) {
if(pluginId == null || plugins == null) {
return null;
}
for(int i = 0; i < plugins.length(); ++i) {
JSONObject pluginObj = plugins.optJSONObject(i);
if(pluginObj != null && pluginId.equals(pluginObj.optString(KEY_ID))) {
plugins.remove(i);
return pluginObj;
}
}
return null;
}
/**
* Merges user selections to bundles default config/state.
* @param bundle bundle to configure
* @param userConfig overrides for default config
* @param userState overrides for default state
* @return root configuration object containing both config and state
*/
public static void mergeBundleConfiguration(final Bundle bundle, final JSONObject userConfig, final JSONObject userState) {
final JSONObject defaultConfig = bundle.getConfigJSON();
final JSONObject defaultState = bundle.getStateJSON();
final JSONObject mergedConfig = JSONHelper.merge(defaultConfig, userConfig);
final JSONObject mergedState = JSONHelper.merge(defaultState, userState);
bundle.setConfig(mergedConfig.toString());
bundle.setState(mergedState.toString());
}
public static JSONObject sanitizeConfigLocation(final JSONObject config) {
if(config == null) {
return null;
}
// sanitize plugin.config.location.classes
JSONObject location = config.optJSONObject(KEY_LOCATION);
if (location != null) {
String classes = location.optString(KEY_CLASSES);
if (classes != null && classes.length() > 0) {
String[] filteredClasses = filterClasses(classes.split(" "));
JSONHelper.putValue(location, KEY_CLASSES, StringUtils.join(filteredClasses, " "));
}
// Make sure we don't have inline css set
for(String str : CLASS_WHITELIST) {
location.remove(str);
}
}
return config;
}
private static String[] filterClasses(String[] classes) {
Set<String> filteredClasses = new TreeSet<String>();
for (int i = 0; i < classes.length; i++) {
if (CLASS_WHITELIST.contains(classes[i])) {
filteredClasses.add(classes[i]);
}
}
return filteredClasses.toArray(new String[filteredClasses.size()]);
}
private View templateView;
private View getBaseView(final View existingView) {
if(templateView == null) {
templateView = service.getViewWithConf(PropertyUtil.getOptional(ViewService.PROPERTY_PUBLISH_TEMPLATE, -1));
}
// clone a blank view based on template (so template doesn't get updated!!)
final View view = templateView.cloneBasicInfo();
// setup ids for updating a view
view.setId(existingView.getId());
view.setCreator(existingView.getCreator());
view.setUuid(existingView.getUuid());
view.setOldId(existingView.getOldId());
view.setName(existingView.getName());
view.setPubDomain(existingView.getPubDomain());
JSONObject style = existingView.getMetadata().optJSONObject(KEY_STYLE);
if(style != null) {
String value = style.optString("toolStyle");
if ("null".equalsIgnoreCase(value)) {
// previous migration gone wrong -> replace "null" with no style selected
style.remove("toolStyle");
}
}
view.setMetadata(existingView.getMetadata());
view.setDescription(existingView.getDescription());
view.setIsPublic(existingView.isPublic());
view.setOnlyForUuId(existingView.isOnlyForUuId());
return view;
}
}
|
package com.opengamma.engine.view.client.merging;
import static org.mockito.Mockito.mock;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.util.HashSet;
import java.util.Set;
import java.util.Timer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;
import com.opengamma.engine.ComputationTargetSpecification;
import com.opengamma.engine.resource.EngineResourceManagerImpl;
import com.opengamma.engine.test.TestViewResultListener;
import com.opengamma.engine.value.ComputedValueResult;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.engine.view.AggregatedExecutionLog;
import com.opengamma.engine.view.ViewComputationResultModel;
import com.opengamma.engine.view.ViewDeltaResultModel;
import com.opengamma.engine.view.ViewResultEntry;
import com.opengamma.engine.view.compilation.CompiledViewDefinitionWithGraphsImpl;
import com.opengamma.engine.view.impl.InMemoryViewDeltaResultModel;
import com.opengamma.engine.view.listener.ViewResultListener;
import com.opengamma.id.UniqueId;
import com.opengamma.util.test.TestGroup;
import com.opengamma.util.test.Timeout;
import com.opengamma.util.tuple.Pair;
/**
* Tests RateLimitingMergingUpdateProvider
*/
@Test(groups = TestGroup.INTEGRATION)
public class RateLimitingMergingViewProcessListenerTest {
private static final Logger s_logger = LoggerFactory.getLogger(RateLimitingMergingViewProcessListenerTest.class);
@Test
public void testPassThrough() {
final TestViewResultListener testListener = new TestViewResultListener();
final RateLimitingMergingViewProcessListener mergingListener = new RateLimitingMergingViewProcessListener(testListener, mock(EngineResourceManagerImpl.class), new Timer("Custom timer"));
// OK, it doesn't really test the 'synchronous' bit, but it at least checks that no merging has happened.
addCompile(mergingListener);
addResults(mergingListener, 1000);
testListener.assertViewDefinitionCompiled();
testListener.assertMultipleCycleCompleted(1000);
testListener.assertNoCalls();
mergingListener.setPaused(true);
addResults(mergingListener, 1000);
testListener.assertNoCalls();
mergingListener.setPaused(false);
testListener.assertCycleCompleted();
testListener.assertNoCalls();
mergingListener.setPaused(false);
addResults(mergingListener, 1000);
testListener.assertMultipleCycleCompleted(1000);
mergingListener.processTerminated(false);
testListener.assertProcessTerminated();
testListener.assertNoCalls();
mergingListener.processTerminated(false);
}
@Test
public void testMergingWhenRateLimiting() throws InterruptedException {
final TestViewResultListener testListener = new TestViewResultListener();
final RateLimitingMergingViewProcessListener mergingListener = new RateLimitingMergingViewProcessListener(testListener, mock(EngineResourceManagerImpl.class), new Timer("Custom timer"));
mergingListener.setMinimumUpdatePeriodMillis(500);
addResults(mergingListener, 1000);
Thread.sleep(500);
testListener.assertCycleCompleted();
testListener.assertNoCalls();
mergingListener.terminate();
}
@Test
public void testModifiableUpdatePeriod() throws InterruptedException {
final TestViewResultListener testListener = new TestViewResultListener();
final RateLimitingMergingViewProcessListener mergingListener = new RateLimitingMergingViewProcessListener(testListener, mock(EngineResourceManagerImpl.class), new Timer("Custom timer"));
assertCorrectUpdateRate(mergingListener, testListener, 100);
assertCorrectUpdateRate(mergingListener, testListener, 400);
assertCorrectUpdateRate(mergingListener, testListener, 50);
mergingListener.terminate();
}
@Test
public void testCallOrderingAndCollapsing() throws InterruptedException {
final TestViewResultListener testListener = new TestViewResultListener();
final RateLimitingMergingViewProcessListener mergingListener = new RateLimitingMergingViewProcessListener(testListener, mock(EngineResourceManagerImpl.class), new Timer("Custom timer"));
mergingListener.setPaused(true);
testListener.assertNoCalls();
// Begin sequence while paused
addCompile(mergingListener);
addResults(mergingListener, 10);
final CompiledViewDefinitionWithGraphsImpl preCompilation = mock(CompiledViewDefinitionWithGraphsImpl.class);
mergingListener.viewDefinitionCompiled(preCompilation, true);
addResults(mergingListener, 10);
mergingListener.cycleCompleted(mock(ViewComputationResultModel.class), getDeltaResult(1));
final ViewComputationResultModel latestResult = mock(ViewComputationResultModel.class);
mergingListener.cycleCompleted(latestResult, getDeltaResult(2));
final CompiledViewDefinitionWithGraphsImpl postCompilation = mock(CompiledViewDefinitionWithGraphsImpl.class);
mergingListener.viewDefinitionCompiled(postCompilation, true);
mergingListener.processCompleted();
mergingListener.processTerminated(false);
// End of sequence while paused
mergingListener.setPaused(false);
testListener.assertViewDefinitionCompiled(Timeout.standardTimeoutMillis());
testListener.assertViewDefinitionCompiled(Timeout.standardTimeoutMillis(), preCompilation);
final ViewDeltaResultModel mergedDelta = testListener.getCycleCompleted(Timeout.standardTimeoutMillis()).getDeltaResult();
assertEquals(2, mergedDelta.getAllResults().size());
final Set<Pair<String, Integer>> results = new HashSet<Pair<String, Integer>>();
for (final ViewResultEntry deltaItem : mergedDelta.getAllResults()) {
results.add(Pair.of(deltaItem.getComputedValue().getSpecification().getValueName(), (Integer) deltaItem.getComputedValue().getValue()));
}
assertTrue(results.contains(Pair.of("value1", 1)));
assertTrue(results.contains(Pair.of("value2", 2)));
testListener.assertViewDefinitionCompiled(Timeout.standardTimeoutMillis(), postCompilation);
testListener.assertProcessCompleted();
testListener.assertProcessTerminated();
testListener.assertNoCalls();
}
private ViewDeltaResultModel getDeltaResult(final int value) {
final InMemoryViewDeltaResultModel deltaResult = new InMemoryViewDeltaResultModel();
deltaResult.addValue("DEFAULT", getComputedValueResult("value" + value, value));
return deltaResult;
}
private ComputedValueResult getComputedValueResult(final String valueName, final Object value) {
final ComputationTargetSpecification target = ComputationTargetSpecification.of(UniqueId.of("Scheme", valueName));
return new ComputedValueResult(new ValueSpecification(valueName, target, ValueProperties.with(ValuePropertyNames.FUNCTION, "FunctionId").get()), value, AggregatedExecutionLog.EMPTY);
}
private void assertCorrectUpdateRate(final RateLimitingMergingViewProcessListener mergingListener, final TestViewResultListener testListener, final int period) throws InterruptedException {
mergingListener.setMinimumUpdatePeriodMillis(period);
assertUpdateRate(mergingListener, testListener, period);
// If the provider is paused then all updates should be merged regardless of the time elapsed or the rate
mergingListener.setPaused(true);
for (int i = 0; i < 3; i++) {
addResults(mergingListener, 10);
Thread.sleep(period);
}
testListener.assertNoCalls();
mergingListener.setPaused(false);
Thread.sleep(2 * period);
testListener.assertCycleCompleted();
testListener.assertNoCalls();
// Once unpaused, everything should be back to normal
assertUpdateRate(mergingListener, testListener, period);
}
private void assertUpdateRate(final RateLimitingMergingViewProcessListener mergingListener, final TestViewResultListener testListener, final int period) throws InterruptedException {
testListener.resetShortestDelay();
for (int i = 0; i < 100; i++) {
Thread.sleep(10);
addResults(mergingListener, 10);
}
// Wait a couple of periods for any stragglers
Thread.sleep (2 * period);
// Check that the results didn't come any faster than we asked for (give or take 10%), and not too slowly (allow up to twice)
assertTrue ("Expecting results no faster than " + period + " ms, but got a result after " + testListener.getShortestDelay() + " ms", testListener.getShortestDelay() >= (period - period / 10));
assertTrue ("Expecting results no slower than " + (period * 2) + " ms, but got a result after " + testListener.getShortestDelay() + " ms", testListener.getShortestDelay() <= (period * 2));
s_logger.info("Size = {}", testListener.getQueueSize());
testListener.clear();
}
private void addResults(final ViewResultListener listener, final int count) {
for (int i = 0; i < count; i++) {
listener.cycleCompleted(mock(ViewComputationResultModel.class), null);
}
}
private void addCompile(final ViewResultListener listener) {
listener.viewDefinitionCompiled(mock(CompiledViewDefinitionWithGraphsImpl.class), true);
}
}
|
package com.smargav.api.net;
import com.smargav.api.logger.AppLogger;
import com.squareup.okhttp.Authenticator;
import com.squareup.okhttp.Credentials;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Request.Builder;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.internal.Util;
import org.apache.commons.lang3.StringUtils;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Proxy;
import java.net.URLEncoder;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPOutputStream;
import okio.Buffer;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;
public class WebSession {
public interface FileDownloadListener {
void downloadProgress(long total);
}
private static final MediaType JSON = MediaType
.parse("application/json; charset=utf-8");
public static int NET_TIMEOUT = 30;
private int connectionTimeout;
private int readTimeout;
private OkHttpClient client;
private Response lastCallResponse;
private Request lastCallRequest;
public WebSession() {
this(NET_TIMEOUT);
}
public WebSession(int timeOutInSec) {
this(timeOutInSec, timeOutInSec);
}
public WebSession(int connectionTimeout, int readTimeout) {
client = new OkHttpClient();
client.interceptors().add(new LoggingInterceptor());
this.readTimeout = readTimeout;
this.connectionTimeout = connectionTimeout;
client.setConnectTimeout(connectionTimeout, TimeUnit.SECONDS);
client.setReadTimeout(readTimeout, TimeUnit.SECONDS);
}
public void set2gTimeOut() {
readTimeout = NET_TIMEOUT + NET_TIMEOUT / 2;
connectionTimeout = NET_TIMEOUT + NET_TIMEOUT / 2;
client.setConnectTimeout(connectionTimeout, TimeUnit.SECONDS);
client.setReadTimeout(readTimeout, TimeUnit.SECONDS);
}
public void setRegularTimeOut() {
readTimeout = NET_TIMEOUT;
connectionTimeout = NET_TIMEOUT;
client.setConnectTimeout(connectionTimeout, TimeUnit.SECONDS);
client.setReadTimeout(readTimeout, TimeUnit.SECONDS);
}
/**
* new AppAuthenticator(username, password)
*
* @param url
* @param json
* @param authenticator
* @return
* @throws IOException
*/
public String postGzip(String url, String json, Authenticator authenticator) throws IOException {
Builder builder = new Builder();
builder.header("Content-Encoding", "gzip");
// Compress data.
byte[] data = copressData(json);
RequestBody body = RequestBody.create(JSON, data);
builder.url(url).post(body);
Request request = builder.build();
if (authenticator != null) {
client.setAuthenticator(authenticator);
}
lastCallRequest = request;
Response response = client.newCall(request).execute();
lastCallResponse = response;
verifyResponseCode(response);
String resString = response.body().string();
validateResponse(resString);
return resString;
}
public String postGzip(String url, String json) throws IOException {
return postGzip(url, json, null);
}
public String post(String url, String json) throws IOException {
return post(url, json, null);
}
public String get(String url, Map<String, String> params) throws IOException {
return get(url, params, null);
}
public String get(Request request, Authenticator authenticator) throws IOException {
if (authenticator != null) {
client.setAuthenticator(authenticator);
}
lastCallRequest = request;
Response response = client.newCall(request).execute();
lastCallResponse = response;
verifyResponseCode(response);
String resString = response.body().string();
validateResponse(resString);
return resString;
}
public String get(String url, Map<String, String> params, Authenticator authenticator, Map<String, String> headers) throws IOException {
String finalUrl = buildURI(url, params);
Request.Builder builder = new Builder();
for (String key : headers.keySet()) {
builder.addHeader(key, headers.get(key));
}
Request request = builder.url(finalUrl).build();
return get(request, authenticator);
}
public String get(String url, Map<String, String> params, Authenticator authenticator) throws IOException {
String finalUrl = buildURI(url, params);
Request request = new Builder().url(finalUrl).build();
return get(request, authenticator);
}
public String buildURI(String baseUrl, Map<String, String> params)
throws IOException {
if (params != null && params.size() > 0) {
StringBuilder builder = new StringBuilder(baseUrl + "?");
builder.append(parseMap(params));
baseUrl = builder.toString();
}
return baseUrl;
}
public String parseMap(Map<String, String> params) throws IOException {
if (params == null && params.isEmpty()) {
return "";
}
StringBuilder builder = new StringBuilder();
for (String key : params.keySet()) {
String parameterName = URLEncoder.encode(key, "UTF-8");
String parameterValue = params.get(key);
if (StringUtils.isNotBlank(parameterValue)) {
parameterValue = URLEncoder.encode(parameterValue,
"UTF-8");
}
builder.append(parameterName).append("=")
.append(parameterValue).append("&");
}
// remove last '&'
builder.deleteCharAt(builder.length() - 1);
return builder.toString();
}
public String post(Request request, Authenticator authenticator) throws IOException {
if (authenticator != null) {
client.setAuthenticator(authenticator);
}
lastCallRequest = request;
Response response = client.newCall(request).execute();
lastCallResponse = response;
String resString = response.body().string();
validateResponse(resString);
return resString;
}
public String post(String url, String data, Authenticator authenticator, Map<String, String> headers) throws IOException {
RequestBody body = RequestBody.create(JSON, data);
Request.Builder builder = new Builder();
for (String key : headers.keySet()) {
builder.addHeader(key, headers.get(key));
}
builder.url(url).post(body);
Request request = builder.build();
return post(request, authenticator);
}
public String post(String url, String data, Authenticator authenticator) throws IOException {
RequestBody body = RequestBody.create(JSON, data);
Request.Builder builder = new Builder();
builder.url(url).post(body);
Request request = builder.build();
return post(request, authenticator);
}
public String post(String url, Map<String, String> params, Authenticator authenticator) throws IOException {
FormEncodingBuilder formBody = new FormEncodingBuilder();
for (String key : params.keySet()) {
formBody.add(key, params.get(key));
}
RequestBody body = formBody.build();
Request.Builder builder = new Builder();
builder.url(url).post(body);
Request request = builder.build();
return post(request, authenticator);
}
public String post(String url, Map<String, String> params, Authenticator authenticator, Map<String, String> headers) throws IOException {
FormEncodingBuilder formBody = new FormEncodingBuilder();
for (String key : params.keySet()) {
formBody.add(key, params.get(key));
}
RequestBody body = formBody.build();
Request.Builder builder = new Builder();
for (String key : headers.keySet()) {
builder.addHeader(key, headers.get(key));
}
builder.url(url).post(body);
Request request = builder.build();
return post(request, authenticator);
}
public String put(String url, Map<String, String> params, Authenticator authenticator, Map<String, String> headers) throws IOException {
FormEncodingBuilder formBody = new FormEncodingBuilder();
for (String key : params.keySet()) {
formBody.add(key, params.get(key));
}
RequestBody body = formBody.build();
Request.Builder builder = new Builder();
for (String key : headers.keySet()) {
builder.addHeader(key, headers.get(key));
}
builder.url(url).put(body);
Request request = builder.build();
return post(request, authenticator);
}
public Response getLastCallResponse() {
return lastCallResponse;
}
public void setLastCallResponse(Response lastCallResponse) {
this.lastCallResponse = lastCallResponse;
}
public Request getLastCallRequest() {
return lastCallRequest;
}
public void setLastCallRequest(Request lastCallRequest) {
this.lastCallRequest = lastCallRequest;
}
private void verifyResponseCode(Response response) throws IOException {
int code = response.code();
if (code == 404) {
throw new NetIOException(404, "404 - Not found");
}
if (code == 400) {
throw new NetIOException(400,
"400 - The request sent by the client was syntactically incorrect.");
}
if (code == 500) {
AppLogger.e(getClass(), "Server Exception : " + response.body().string());
throw new NetIOException(500,
"500 - Unexpected Server error");
}
}
private byte[] compressData(String body) throws IOException {
byte[] data = body.getBytes("UTF-8");
ByteArrayOutputStream arr = new ByteArrayOutputStream();
OutputStream zipper = new GZIPOutputStream(arr);
zipper.write(data);
zipper.close();
return arr.toByteArray();
}
private void validateResponse(String resString) throws IOException {
if (StringUtils.contains(resString,
"The request sent by the client was syntactically incorrect.")) {
throw new IOException(
"The request sent by the client was syntactically incorrect.");
}
AppLogger.i(getClass(),
"Response : " + StringUtils.substring(resString, 0, 500));
}
public String get(String url) throws IOException {
Request request = new Builder().url(url).build();
lastCallRequest = request;
Response response = client.newCall(request).execute();
lastCallResponse = response;
verifyResponseCode(response);
String resString = response.body().string();
validateResponse(resString);
return resString;
}
public long downloadFile(File folder, String mediaURL, String name, Authenticator authenticator, FileDownloadListener listener) throws IOException {
AppLogger.i(getClass(), "Downloading File - " + mediaURL + " to folder " + folder.getAbsolutePath());
if (authenticator != null) {
client.setAuthenticator(authenticator);
}
Request request = new Request.Builder().url(mediaURL).build();
// OkHttpClient client = getUnsafeOkHttpClient();
Response response = client.newCall(request).execute();
File downloadedFile = new File(folder, name);
InputStream is = response.body().byteStream();
OutputStream output = new FileOutputStream(downloadedFile);
BufferedInputStream input = new BufferedInputStream(is);
byte[] data = new byte[2048];
long total = 0;
int count = 0;
int iteration = 0;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
if (iteration % 100 == 0) {
if (listener != null) {
listener.downloadProgress(total);
}
}
}
output.flush();
output.close();
input.close();
listener.downloadProgress(total);
return total;
}
private class LoggingInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
long contentLength = 0;
String content = "";
if (request.body() != null) {
contentLength = request.body().contentLength();
content = bodyToString(request);
}
AppLogger.d(getClass(), "Request: " + request.url() + " Content-Length: " + contentLength);
AppLogger.d(getClass(), "Params: " + content);
Response response = chain.proceed(request);
long t2 = System.nanoTime();
AppLogger.i(getClass(), String.format(
"Received response for %s in %.1fms%n\tHTTP Status %d",
response.request().url(), (t2 - t1) / 1e6d, response.code()));
return response;
}
}
public static class BasicAuthenticator implements Authenticator {
private String username, password;
public BasicAuthenticator(String u, String p) {
username = u;
password = p;
}
@Override
public Request authenticate(Proxy proxy, Response response)
throws IOException {
String credential = Credentials.basic(username, password);
return response.request().newBuilder()
.header("Authorization", credential).build();
}
@Override
public Request authenticateProxy(Proxy arg0, Response arg1)
throws IOException {
return null;
}
}
public static RequestBody create(final MediaType mediaType,
final InputStream inputStream) {
return new RequestBody() {
@Override
public MediaType contentType() {
return mediaType;
}
@Override
public long contentLength() {
try {
return inputStream.available();
} catch (IOException e) {
return 0;
}
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
Source source = null;
try {
source = Okio.source(inputStream);
sink.writeAll(source);
} finally {
Util.closeQuietly(source);
}
}
};
}
private String bodyToString(final Request request) {
try {
final Request copy = request.newBuilder().build();
final Buffer buffer = new Buffer();
copy.body().writeTo(buffer);
return new String(buffer.readByteArray());
} catch (final IOException e) {
return "did not work";
}
}
}
|
package com.valkryst.VTerminal.misc;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class IntRangeTest {
private IntRange range;
@Before
public void initializeRange() {
range = new IntRange(1, 200);
}
@Test
public void testConstructor() {
final IntRange range = new IntRange(1, 2);
Assert.assertEquals(1, range.getBegin());
Assert.assertEquals(2, range.getEnd());
}
@Test
public void testConstructor_withNegativeBegin() {
final IntRange range = new IntRange(-1, 2);
Assert.assertEquals(-1, range.getBegin());
Assert.assertEquals(2, range.getEnd());
}
@Test
public void testConstructor_withNegativeEnd() {
final IntRange range = new IntRange(-3, -2);
Assert.assertEquals(-3, range.getBegin());
Assert.assertEquals(-2, range.getEnd());
}
@Test(expected = IllegalArgumentException.class)
public void testConstructor_withBeginGreaterThanEnd() {
new IntRange(2, 1);
}
@Test
public void testEquals_withSelf() {
Assert.assertEquals(range, range);
}
@Test
public void testEquals_withEqualRanges() {
final IntRange rangeB = new IntRange(1, 200);
Assert.assertEquals(range, rangeB);
}
@Test
public void testEquals_withNonIntRangeObject() {
Assert.assertNotEquals(range, 7);
}
@Test
public void testEquals_withNonEqualBegin() {
final IntRange rangeB = new IntRange(6, 200);
Assert.assertNotEquals(range, rangeB);
}
@Test
public void testEquals_withNonEqualEnd() {
final IntRange rangeB = new IntRange(1, 300);
Assert.assertNotEquals(range, rangeB);
}
@Test
public void testHashCode_withEqualRanges() {
final IntRange rangeB = new IntRange(1, 200);
Assert.assertEquals(range.hashCode(), rangeB.hashCode());
}
@Test
public void testHashCode_withNonEqualRanges() {
final IntRange rangeB = new IntRange(6, 200);
Assert.assertNotEquals(range.hashCode(), rangeB.hashCode());
}
}
|
package org.eclipse.birt.core.script;
import junit.framework.TestCase;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
public class NativeFinanceTest extends TestCase
{
/**
* Create a Context instance
*/
Context cx;
/**
* Create a Scriptable instance
*/
Scriptable scope;
/**
* Record whether there exists an error
*/
boolean hasException;
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#setUp()
*/
public void setUp( ) throws Exception
{
/*
* Creates and enters a Context. The Context stores information about
* the execution environment of a script.
*/
cx = Context.enter( );
/*
* Initialize the standard objects (Object, Function, etc.) This must be
* done before scripts can be executed. Returns a scope object that we
* use in later calls.
*/
scope = cx.initStandardObjects( );
ScriptableObject.defineClass(scope, NativeFinance.class);
}
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#tearDown()
*/
public void tearDown( )
{
Context.exit( );
}
/**
* Evaluate a JavaScript source string.
*
* @param script
* @return the result
*/
protected double eval( String script )
{
try
{
hasException = false;
Object value = cx.evaluateString( scope, script, "inline", 1, null );
return ( (Double) value ).doubleValue( );
}
catch ( Throwable ex )
{
hasException = true;
return Double.NaN;
}
}
public void testDdb( )
{
//ddb(1400, 200, 10, 1) == 280
double value = eval( "Finance.ddb(1400, '200', '10', '1')" );
assertEquals( 280.0, value, Double.MIN_VALUE );
value = eval( "Finance.ddb( 1400, 200, 10, 1 )" );
assertEquals( 280.0, value, Double.MIN_VALUE );
eval( "Finance.ddb( 1400, 200, -10, 1 )" );
assertTrue(hasException);
}
public void testSln( )
{
//sln(1400, 200, 10) == 120
double value = eval( "Finance.sln( 1400, 200, 10 )" );
assertEquals( 120, value, Double.MIN_VALUE );
value = eval( "Finance.sln( 1400, 200, -10 )" );
assertEquals(-120, value, Double.MIN_VALUE);
}
public void testSyd( )
{
double value = eval( "Finance.syd( 1400, 200, 2, 1 )" );
assertEquals( 800, value, Double.MIN_VALUE );
value = eval( "Finance.syd( -1400, 200, 3, 1 )" );
assertEquals( -800, value, Double.MIN_VALUE );
}
public void testFv( )
{
String script1 = "Finance.fv( 0.057 / 365, 18 * 365, 0, -10000, 1 )";
double value1 = eval( script1 );
assertEquals( 27896.60, value1, 0.01 );
String script2 = "Finance.fv( 0.057 / 12, 18 * 12, -55, -10000, 1 )";
double value2 = eval( script2 );
assertEquals( 48575.82, value2, 0.01 );
assertFalse( hasException );
String script3 = "Finance.fv( 0.057 / 12, 18 * 12, -55, -10000, 3 )";
eval( script3 );
}
public void testPmt( )
{
String script1 = " Finance.pmt( 0.115 / 12, 36, -20000, 0, 1 )";
double value1 = eval( script1 );
assertEquals( 653.26, value1, 0.01 );
assertFalse( hasException );
/*
* If we input the value of parameter due is neither 1 or 0, application
* will also report error.
*/
String script3 = "Finance.pmt( 0.115 / 12, 36, -20000, 0, -1 )";
eval( script3 );
}
public void testIpmt( )
{
String script1 = "Finance.ipmt( 0.115 / 12, 5, 36, -20000, 0, 1 )";
double value1 = eval( script1 );
assertEquals( 171.82, value1, 0.01 );
assertFalse( hasException );
/*
* If any parameter meet the following condition:rate < 0 || nPer < 0 ||
* per > nPer || ( due != 1 && due != 0 ), application will report error
*/
String script2 = "Finance.ipmt( 0.115 / 12, 37, 36, -20000, 0, 1 )";
eval( script2 );
String script3 = "Finance.ipmt( 0.115 / 12, 3, 36, -20000, 0, 8 )";
eval( script3 );
}
public void testPpmt( )
{
String script1 = " Finance.ppmt( 0.115 / 12, 5, 36, -20000, 0, 1 )";
double value1 = eval( script1 );
assertEquals( 481.43, value1, 0.01 );
assertFalse( hasException );
/*
* If any parameter meet the following condition:rate < 0 || nPer < 0 ||
* per > nPer || ( due != 1 && due != 0 ), application will report error
*/
String script2 = "Finance.ppmt( 0.115 / 12, 66, 36, -20000, 0, 1 )";
eval( script2 );
String script3 = "Finance.ppmt( 0.115 / 12, 5, 36, -20000, 0, 7 )";
eval( script3 );
}
public void testNPer( )
{
double value = eval( "Finance.nper( 0.01, -2000, 20000, 0, 1 )" );
assertEquals( 10.478, value, 0.001 );
value = eval( "Finance.nper( 0.01, -2000, 20000, 0, 0 )" );
assertEquals( 10.588, value, 0.001 );
}
public void testPv( )
{
String script1 = "Finance.pv( 0.105 / 12, 3 * 12, -325, 11000, 1 )";
double value1 = eval( script1 );
assertEquals( 2048.06, value1, 0.01 );
/*
* If any parameter meet the following condition:(( nPer < 0 || ( due !=
* 1 && due != 0 ) ), application will report error
*/
String script3 = "Finance.nPer( 0.115 / 12, -4, 20000, 0, 1 )";
eval( script3 );
}
public void testRate( )
{
String script1 = "Finance.rate( 3 * 12, -653.26, 20000, 0, 1, 0.1 ) * 12";
double value1 = eval( script1 );
assertEquals( 0.115, value1, 0.01 );
assertFalse( hasException );
/*
* If any parameter meet the following condition:( nPer <= 0 || ( due !=
* 1 && due != 0 ) ), application will report error
*/
String script2 = "Finance.rate( -3, -653.26, 20000, 0, 1, 0.1 )";
eval( script2 );
}
public void testPercent( )
{
String script1 = "Finance.percent( 20, 50 )";
double value1 = eval( script1 );
assertEquals( 250, value1, Double.MIN_VALUE );
String script2 = "Finance.percent( 50, 0 )";
double value2 = eval( script2 );
assertEquals( 0, value2, Double.MIN_VALUE );
String script3 = "Finance.percent( '20', 50 )";
double value3 = eval( script3 );
assertEquals( 250, value3, Double.MIN_VALUE );
//String script7 = " var a[2]=new String(2);a[0]=new
// String('5');Finance.percent( a, 50 )";
//double value7 = eval( script7 );
//assertEquals( 1000, value7, Double.MIN_VALUE );
}
public void testNpv( )
{
String script1 = "var array=new Array(4);array[0]=-10000;array[1]=3000;array[2]=4200;array[3]=6800;"
+ "Finance.npv( 0.1, array )";
double value1 = eval( script1 );
assertEquals( 1188.44, value1, 0.01 );
}
public void testIrr( )
{
//use double array to test this case
double a[] = new double[]{-70000, 12000, 15000};
Object jsNumber=Context.javaToJS(a,scope);
ScriptableObject.putProperty(scope,"array",jsNumber);
String script4="Finance.irr( array, -0.6 )";
double value4 = eval( script4 );
assertEquals( -0.44, value4, 0.01 );
String script1 = "var array=new Array(6);array[0]=-70000;array[1]=12000;"
+ "array[2]=15000;array[3]=18000;array[4]=21000;array[5]=26000;"
+ "Finance.irr( array, 0.01)";
double value1 = eval( script1 );
assertEquals( 0.0866, value1, 0.0001 );
String script2 = "var array=new Array(5);array[0]=-70000;array[1]=12000;array[2]=15000;array[3]=18000;array[4]=21000;Finance.irr(array, -0.1 )";
double value2 = eval( script2 );
assertEquals( -0.021244848273899997, value2, Double.MIN_VALUE );
String script3 = "var array=new Array(3);array[0]=-70000;array[1]=12000;array[2]=15000;Finance.irr(array, -0.6 )";
double value3 = eval( script3 );
assertEquals( -0.44, value3, 0.01 );
assertFalse( hasException );
}
public void testMirr( )
{
//If the value of the guess is far from the correct answer, application
// can't get the correct result and will report error
String script1 = "var array=new Array(6);array[0]=-120000;array[1]=39000;"
+ "array[2]=30000;array[3]=21000;array[4]=37000;array[5]=46000;"
+ "Finance.mirr( array, 0.1, 0.12 )";
double value1 = eval( script1 );
assertEquals( 0.126, value1, 0.001);
}
}
|
package org.csstudio.platform.security;
import java.util.ArrayList;
import java.util.List;
import org.csstudio.platform.internal.rightsmanagement.RightsManagementService;
import org.csstudio.platform.internal.usermanagement.IUserManagementListener;
import org.csstudio.platform.internal.usermanagement.LoginContext;
import org.csstudio.platform.internal.usermanagement.UserManagementEvent;
public final class SecurityFacade {
/**
* This holds the current LoginContext.
*/
private LoginContext _context;
/**
* The only one instance of this class.
*/
private static SecurityFacade _instance;
/**
* The listeners.
*/
private List<ISecurityListener> _listeners;
private ArrayList<IUserManagementListener> _userListeners;
/**
* Property for the appearence of the CSS login window at system startup.
*/
public static final String PROP_AUTH_LOGIN = "auth_login"; //$NON-NLS-1$
/**
* Private constructor due to singleton pattern.
*/
private SecurityFacade() {
_listeners = new ArrayList<ISecurityListener>();
_userListeners = new ArrayList<IUserManagementListener>();
_context = new LoginContext("PrimaryLoginContext");
}
/**
* @return The singleton instance of this class.
*/
public static SecurityFacade getInstance() {
if (_instance == null) {
_instance = new SecurityFacade();
}
return _instance;
}
public boolean canExecute(final String id) {
return canExecute(id, _context);
}
public boolean canExecute(final String id, final LoginContext context) {
return RightsManagementService.getInstance().hasRights(
context.getUser(), id);
}
public User getCurrentUser() {
return _context.getUser();
}
/**
* Performs the login procedure.
*
*/
public void login(ILoginCallbackHandler handler) {
this._context.login(handler);
for (IUserManagementListener uml : _userListeners) {
uml.handleUserManagementEvent(new UserManagementEvent());
}
}
/**
* Adds the given listener to the internal list.
*
* @param listener
* The ISecurityListener, which sould be added
*/
public void addListener(
final ISecurityListener listener) {
_listeners.add(listener);
}
/**
* Deletes the given ISecurityListener from the internal list.
*
* @param listener
* The ISecurityListener, which should be deleted
*/
public void removeListener(final ISecurityListener listener) {
_listeners.remove(listener);
}
/**
* Informs all registered ISecureContainerListeners.
*
* @param event
* The event that the listeners are interested in.
*/
private void notifyListener(final SecurityEvent event) {
for (ISecurityListener listener : _listeners) {
listener.handleSecurityEvent(event);
}
}
public void addUserManagementListener(IUserManagementListener listener) {
_userListeners.add(listener);
}
public void removeUserManagementListener(IUserManagementListener listener) {
_userListeners.remove(listener);
}
}
|
package dev.kkorolyov.simpleprops;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;
@SuppressWarnings("javadoc")
public class PropertiesTest { // TODO Finish
private static final int NUM_FILES = 5;
private static final File[] ALL_FILES = new File[NUM_FILES];
private static final Properties[] ALL_DEFAULTS = new Properties[NUM_FILES];
@BeforeClass
public static void setUpBeforeClass() throws IOException {
buildFiles();
buildDefaults();
}
@After
public void tearDownAfter() throws IOException {
for (File file : ALL_FILES)
file.delete();
}
@Test
public void testLoadDefaults() throws IOException {
for (int i = 0; i < NUM_FILES; i++) {
Properties currentDefaults = ALL_DEFAULTS[i];
Properties currentInstance = createInstance(i);
assertEquals(currentDefaults.size(), currentInstance.size());
for (String key : currentDefaults.keys()) {
assertEquals(currentDefaults.get(key), currentInstance.get(key));
}
}
}
@Test
public void testAddProperty() throws IOException {
for (int i = 0; i < NUM_FILES; i++) {
Properties currentDefaults = ALL_DEFAULTS[i];
Properties currentInstance = createInstance(i);
String newKey = "NEW-KEY" + i,
newValue = "NEW-VAL" + i;
currentInstance.put(newKey, newValue);
assertTrue(currentInstance.size() == currentDefaults.size() + 1);
assertEquals(newValue, currentInstance.get(newKey));
}
}
@Test
public void testClear() throws IOException {
for (int i = 0; i < NUM_FILES; i++) {
Properties currentDefaults = ALL_DEFAULTS[i];
Properties currentInstance = createInstance(i);
currentInstance.put("Extra", "Extra");
assertEquals(currentDefaults.size() + 1, currentInstance.size());
currentInstance.clear();
assertEquals(0, currentInstance.size());
}
}
@Test
public void testMatchesFile() {
for (int i = 0; i < NUM_FILES; i++) {
Properties currentInstance = createInstance(i);
assertTrue(currentInstance.matchesFile());
currentInstance.put("NoMatch", "NoMatch");
assertFalse(currentInstance.matchesFile());
}
}
@Test
public void testSaveToFile() throws IOException {
for (int i = 0; i < NUM_FILES; i++) {
Properties currentDefaults = ALL_DEFAULTS[i];
Properties currentInstance = createInstance(i);
String changedKey = currentDefaults.keys().get(0), // 1st key
newValue = "NEW-VAL" + i;
currentInstance.put(changedKey, newValue);
currentInstance.saveFile();
assertEquals(currentDefaults.size(), currentInstance.size());
assertFalse(currentInstance.get(changedKey).equals(currentDefaults.get(changedKey)));
currentInstance.loadDefaults();
assertEquals(currentDefaults.size(), currentInstance.size());
assertEquals(currentDefaults.get(changedKey), currentInstance.get(changedKey));
currentInstance.loadFile();
assertEquals(currentDefaults.size(), currentInstance.size());
assertFalse(currentInstance.get(changedKey).equals(currentDefaults.get(changedKey)));
}
}
private static Properties createInstance(int i) {
return new Properties(ALL_FILES[i], ALL_DEFAULTS[i]);
}
private static void buildFiles() {
for (int i = 0; i < NUM_FILES; i++) {
ALL_FILES[i] = new File("TestPropFile" + i + ".txt");
}
}
private static void buildDefaults() {
for (int i = 0; i < ALL_DEFAULTS.length; i++) {
Properties currentDefaults = new Properties();
for (int j = 0; j < i + 1; j++) {
currentDefaults.put("KEY" + j, "VAL" + j);
}
ALL_DEFAULTS[i] = currentDefaults;
}
}
}
|
package curtis.Cobbleworks;
import java.io.File;
import curtis.Cobbleworks.module.cobblegen.BlockCobbleGen;
import curtis.Cobbleworks.module.cobblegen.GuiProxy;
import curtis.Cobbleworks.module.cobblegen.upgrades.CobbleUpgrade;
import curtis.Cobbleworks.module.magic.AncientStaff;
import curtis.Cobbleworks.module.magic.EntityIceBarrage;
import curtis.Cobbleworks.module.magic.RenderIceBarrage;
import curtis.Cobbleworks.module.spawner.BlockPendulumSummoner;
import curtis.Cobbleworks.module.spawner.BoosterPack;
import curtis.Cobbleworks.module.spawner.ItemMobCard;
import curtis.Cobbleworks.module.spawner.MobRegistry;
import curtis.Cobbleworks.module.spawner.SpaceScale;
import curtis.Cobbleworks.module.spawner.TimeScale;
import curtis.Cobbleworks.module.tool.EntityMantaIllusion;
import curtis.Cobbleworks.module.tool.PocketFurnace;
import curtis.Cobbleworks.module.tool.RenderMantaIllusion;
import curtis.Cobbleworks.module.tool.SuperAxe;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.Item.ToolMaterial;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.util.EnumHelper;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.oredict.ShapedOreRecipe;
public class CommonProxy {
private static int packetID = 0;
public static Configuration config;
public static SimpleNetworkWrapper packetHandler = null;
public static CreativeTabs tabcobbleworks = new CreativeTabs(Cobbleworks.MODID) {
@Override
public Item getTabIconItem() {
return Item.getItemFromBlock(Blocks.COBBLESTONE);
}
};
public static final ToolMaterial materialStar = EnumHelper.addToolMaterial(Cobbleworks.MODID +".materialStar", 3, 9000, 12.0F, 0.5F, 1);
//Stuff for cobble gen
public static BlockCobbleGen cobblegen;
public static CobbleUpgrade up1;
//Stuff for tools
public static SoundEvent mantaSuccess;
public static SoundEvent cooldown;
public static SoundEvent illusionDeath;
public static SoundEvent iceBarrageCast;
public static SoundEvent iceBarrageImpact;
//Tools
public static SuperAxe manta;
public static PocketFurnace pf;
public static AncientStaff ancientStaff;
//Spawner
public static ItemMobCard PendulumMonster;
public static MobRegistry pendulumRegistry;
public static BlockPendulumSummoner summoner;
public static BoosterPack booster;
public static TimeScale timeScale;
public static SpaceScale spaceScale;
public static LootHandler lootations;
public void preInit(FMLPreInitializationEvent e) {
packetHandler = NetworkRegistry.INSTANCE.newSimpleChannel(Cobbleworks.MODID);
File cd = new File(e.getModConfigurationDirectory(), Cobbleworks.DOMAIN);
config = new Configuration(new File(cd, "Cobbleworks.cfg"));
Config.load();
if (Config.enableCobblegen) {
cobblegen = new BlockCobbleGen();
up1 = new CobbleUpgrade();
}
if (Config.enableTools) {
manta = new SuperAxe();
EntityRegistry.registerModEntity(EntityMantaIllusion.class, "Illusion", 0, Cobbleworks.instance, 32, 1, true);
//pf = new PocketFurnace();
}
if (Config.enableMagic) {
ancientStaff = new AncientStaff();
EntityRegistry.registerModEntity(EntityIceBarrage.class, "iceBarrage", 1, Cobbleworks.instance, 32, 1, true);
}
if (Config.enableSpawner) {
summoner = new BlockPendulumSummoner();
PendulumMonster = new ItemMobCard();
booster = new BoosterPack();
timeScale = new TimeScale();
spaceScale = new SpaceScale();
pendulumRegistry = new MobRegistry();
}
mantaSuccess = registerSound("MantaStyle");
cooldown = registerSound("cooldown");
illusionDeath = registerSound("illusionDeath");
iceBarrageCast = registerSound("iceBarrageCast");
iceBarrageImpact = registerSound("iceBarrageImpact");
}
public void init(FMLInitializationEvent e) {
NetworkRegistry.INSTANCE.registerGuiHandler(Cobbleworks.instance, new GuiProxy());
if (Config.enableCobblegen) {
GameRegistry.addRecipe(new ShapedOreRecipe(cobblegen, new Object[] {"III", "LDW", "III", 'I', "ingotIron", 'L', Items.LAVA_BUCKET, 'D', Items.DIAMOND_PICKAXE, 'W', Items.WATER_BUCKET}));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(up1, 1, 0), new Object[] {"IGI", "FCP", "IGI", 'I', "ingotIron", 'G', "ingotGold", 'F', Blocks.FURNACE, 'C', Blocks.COAL_BLOCK, 'P', Blocks.PISTON}));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(up1, 1, 1), new Object[] {"GDG", "TUT", "GDG", 'G', "ingotGold", 'D', "gemDiamond", 'T', Blocks.CRAFTING_TABLE, 'U', new ItemStack(up1, 1, 0)}));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(up1, 1, 2), new Object[] {"CDC", "NUN", "CDC", 'C', Items.MAGMA_CREAM, 'D', "gemDiamond", 'N', Blocks.NETHER_BRICK, 'U', new ItemStack(up1, 1, 1)}));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(up1, 1, 3), new Object[] {"QBQ", "LUL", "QBQ", 'Q', Blocks.QUARTZ_BLOCK, 'B', Items.BLAZE_ROD, 'L', Items.LAVA_BUCKET, 'U', new ItemStack(up1, 1, 2)}));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(up1, 1, 4), new Object[] {"DSD", "TUT", "GGG", 'D', "gemDiamond", 'S', Items.NETHER_STAR, 'T', Items.GHAST_TEAR, 'G', "ingotGold", 'U', new ItemStack(up1, 1, 3)}));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(advgen), new Object[] {"GSG", "BDB", "GQG", 'G', "ingotGold", 'S', Items.NETHER_STAR, 'B', Items.WATER_BUCKET, 'D', Items.DIAMOND_PICKAXE, 'Q', Blocks.QUARTZ_BLOCK}));
}
if (Config.enableTools) {
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(manta), new Object[] {"ss ","sd "," i ", 's', Items.NETHER_STAR, 'd', Items.DIAMOND_AXE, 'i', Items.GOLDEN_SWORD}));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ancientStaff), new Object[] {" pe", "pip", "dp ", 'p', "dyePurple", 'e', Items.ENDER_EYE, 'i', "ingotIron", 'd', "gemDiamond"}));
}
if (Config.enableSpawner) {
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(summoner), new Object[] {"OCO", "SRT", "OKO", 'O', Blocks.OBSIDIAN, 'K', Items.END_CRYSTAL, 'S', spaceScale, 'R', Items.NETHER_STAR, 'T', timeScale, 'C', Items.CLOCK}));
lootations = new LootHandler();
MinecraftForge.EVENT_BUS.register(lootations);
}
packetHandler.registerMessage(PacketSync.PacketSyncHandler.class, PacketSync.class, packetID++, Side.SERVER);
}
public void postInit(FMLPostInitializationEvent e) {
if (Config.enableSpawner) {
pendulumRegistry.postInitVanillaMobs();
}
if (config.hasChanged()) {
config.save();
}
}
public SoundEvent registerSound(String name) {
final ResourceLocation resLoc = new ResourceLocation(Cobbleworks.MODID, name);
return GameRegistry.register(new SoundEvent(resLoc).setRegistryName(resLoc));
}
}
|
package cz.jcu.uai.javapract;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class TimeTable {
private HashMap<Integer, HashMap<String,Subject>> content;
public TimeTable(Date date , List<Subject> listSubject) {
// TODO Auto-generated constructor stub
this.content= new HashMap<Integer, HashMap<String, Subject>>();
this.date = date;
}
}
|
package de.alpharogroup.lang;
/**
* The enum {@link ClassType} defines the types a class can have.
*/
public enum ClassType {
ANNOTATION,
ANONYMOUS,
ARRAY,
COLLECTION,
ENUM,
INTERFACE,
LOCAL,
MAP,
MEMBER,
PRIMITIVE,
SYNTHETIC;
}
|
package de.braintags.netrelay;
import java.util.List;
import de.braintags.io.vertx.pojomapper.IDataStore;
import de.braintags.io.vertx.pojomapper.init.IDataStoreInit;
import de.braintags.io.vertx.pojomapper.mapping.IMapperFactory;
import de.braintags.io.vertx.pojomapper.mongo.init.MongoDataStoreInit;
import de.braintags.io.vertx.util.exception.InitException;
import de.braintags.netrelay.controller.BodyController;
import de.braintags.netrelay.controller.CookieController;
import de.braintags.netrelay.controller.FailureController;
import de.braintags.netrelay.controller.FavIconController;
import de.braintags.netrelay.controller.SessionController;
import de.braintags.netrelay.controller.StaticController;
import de.braintags.netrelay.controller.TimeoutController;
import de.braintags.netrelay.init.MailClientSettings;
import de.braintags.netrelay.init.Settings;
import de.braintags.netrelay.mapping.NetRelayMapperFactory;
import de.braintags.netrelay.processor.ProcessorDefinition;
import de.braintags.netrelay.routing.RouterDefinition;
import de.braintags.netrelay.routing.RoutingInit;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.ext.mail.MailClient;
import io.vertx.ext.web.Router;
/**
*
*
* @author Michael Remme
*
*/
public class NetRelay extends AbstractVerticle {
private static final io.vertx.core.logging.Logger LOGGER = io.vertx.core.logging.LoggerFactory
.getLogger(NetRelay.class);
// to be able to handle multiple datastores, an IDatastoreCollection will come from pojo-mapper later
private IDataStore datastore;
private Settings settings;
private Router router;
private MailClient mailClient;
/**
* The mapper factory which translates between the browser and the server
*/
private IMapperFactory mapperFactory;
/*
* (non-Javadoc)
*
* @see io.vertx.core.AbstractVerticle#start()
*/
@Override
public void start(Future<Void> startFuture) {
try {
settings = initSettings();
initDataStore(dsInitResult -> {
if (dsInitResult.failed()) {
startFuture.fail(dsInitResult.cause());
} else {
init(startFuture);
}
});
} catch (Exception e) {
startFuture.fail(e);
}
}
private void init(Future<Void> startFuture) {
try {
router = Router.router(vertx);
mapperFactory = new NetRelayMapperFactory(this);
initMailClient();
initController(router);
initProcessors();
initHttpServer(router, result -> {
if (result.failed()) {
startFuture.fail(result.cause());
} else {
initComplete(startFuture);
}
});
} catch (Exception e) {
startFuture.fail(e);
}
}
/**
* Set the future to be completed
*
* @param startFuture
*/
protected void initComplete(Future<Void> startFuture) {
startFuture.complete();
}
private void initMailClient() {
MailClientSettings ms = settings.getMailClientSettings();
initMailClientSettings(ms);
if (ms.isActive()) {
mailClient = MailClient.createShared(vertx, ms, ms.getName());
LOGGER.info("MailClient startet with configuration " + ms.toJson());
} else {
LOGGER.info("MailClient NOT started, cause not activated in configuration");
}
}
// "-DmailClientUserName=dev-test@braintags.net -DmailClientPassword=thoo4ati "
private void initMailClientSettings(MailClientSettings ms) {
String mailUserName = System.getProperty(MailClientSettings.USERNAME_SYS_PROPERTY);
if (mailUserName != null && mailUserName.hashCode() != 0) {
ms.setUsername(mailUserName);
}
String mailClientPassword = System.getProperty(MailClientSettings.PASSWORD_SYS_PROPERTY);
if (mailClientPassword != null && mailClientPassword.hashCode() != 0) {
ms.setPassword(mailClientPassword);
}
String mailClientHost = System.getProperty(MailClientSettings.HOST_SYS_PROPERTY);
if (mailClientHost != null && mailClientHost.hashCode() != 0) {
ms.setHostname(mailClientHost);
}
String mailClientPort = System.getProperty(MailClientSettings.PORT_SYS_PROPERTY);
if (mailClientPort != null && mailClientPort.hashCode() != 0) {
ms.setPort(Integer.parseInt(mailClientPort));
}
}
/**
* Retrive the {@link IMapperFactory} which translates between the mappers and the browser
*
* @return the {@link IMapperFactory} of NetRelay
*/
public IMapperFactory getNetRelayMapperFactory() {
return mapperFactory;
}
/**
* Get the router, which is used by NetRelay
*
* @return the router
*/
public Router getRouter() {
return router;
}
/**
* Init the definitions inside {@link Settings#getProcessorDefinitons()}
*
* @throws Exception
*/
protected void initProcessors() {
List<ProcessorDefinition> rd = settings.getProcessorDefinitons().getProcessorDefinitions();
for (ProcessorDefinition def : rd) {
def.initProcessorDefinition(vertx, this);
}
}
/**
* Init the definitions inside {@link Settings#getRouterDefinitions()}
*
* @throws Exception
*/
protected void initController(Router router) throws Exception {
List<RouterDefinition> rd = settings.getRouterDefinitions().getRouterDefinitions();
for (RouterDefinition def : rd) {
RoutingInit.initRoutingDefinition(vertx, this, router, def);
}
}
/**
* Initialize the {@link Settings} which are used to init the current instance
*
* @return
*/
protected Settings initSettings() {
try {
Settings st = Settings.loadSettings(this, vertx, context);
if (!st.isEdited()) {
throw new InitException(
"The settings are not yet edited. Change the value of property 'edited' to true inside the appropriate file");
}
return st;
} catch (Exception e) {
LOGGER.error("", e);
throw e;
}
}
public final void initDataStore(Handler<AsyncResult<Void>> handler)
throws InstantiationException, IllegalAccessException {
IDataStoreInit dsInit = settings.getDatastoreSettings().getDatastoreInit().newInstance();
dsInit.initDataStore(vertx, settings.getDatastoreSettings(), dsInitResult -> {
if (dsInitResult.failed()) {
handler.handle(Future.failedFuture(dsInitResult.cause()));
} else {
datastore = dsInitResult.result();
handler.handle(Future.succeededFuture());
}
});
}
private void initHttpServer(Router router, Handler<AsyncResult<Void>> handler) {
HttpServerOptions options = new HttpServerOptions().setPort(settings.getServerPort());
HttpServer server = vertx.createHttpServer(options);
server.requestHandler(router::accept).listen(result -> {
if (result.failed()) {
handler.handle(Future.failedFuture(result.cause()));
} else {
handler.handle(Future.succeededFuture());
}
});
}
/*
* (non-Javadoc)
*
* @see io.vertx.core.AbstractVerticle#stop(io.vertx.core.Future)
*/
@Override
public void stop(Future<Void> stopFuture) throws Exception {
getDatastore().shutdown(result -> {
if (result.failed()) {
stopFuture.fail(new RuntimeException(result.cause()));
} else {
stopFuture.complete();
}
});
}
/**
* The default instance is requested, when there was no saved instance found
*
* @return
*/
public Settings createDefaultSettings() {
Settings st = new Settings();
addDefaultRouterDefinitions(st);
addDefaultProcessorDefinitions(st);
st.setDatastoreSettings(MongoDataStoreInit.createDefaultSettings());
return st;
}
protected void addDefaultProcessorDefinitions(Settings settings) {
ProcessorDefinition def = new ProcessorDefinition();
def.setActive(false);
def.setName("dummyprocessor");
def.getProcessorProperties().put("demoKey", "demoValue");
def.setTimeDef("60000");
settings.getProcessorDefinitons().add(def);
}
protected void addDefaultRouterDefinitions(Settings settings) {
settings.getRouterDefinitions().add(FavIconController.createDefaultRouterDefinition());
settings.getRouterDefinitions().add(CookieController.createDefaultRouterDefinition());
settings.getRouterDefinitions().add(SessionController.createDefaultRouterDefinition());
settings.getRouterDefinitions().add(TimeoutController.createDefaultRouterDefinition());
settings.getRouterDefinitions().add(BodyController.createDefaultRouterDefinition());
settings.getRouterDefinitions().add(StaticController.createDefaultRouterDefinition());
settings.getRouterDefinitions().add(FailureController.createDefaultRouterDefinition());
}
/**
* Get the {@link IDataStore} for the current instance
*
* @return the datastore
*/
public final IDataStore getDatastore() {
return datastore;
}
/**
* Get the {@link Settings} which are configuring NetRelay
*
* @return the settings
*/
public Settings getSettings() {
return settings;
}
/**
* Resets and rebuilds the routes by using the {@link Settings#getRouterDefinitions()}
*
* @throws Exception
*/
public void resetRoutes() throws Exception {
getRouter().clear();
initController(router);
}
/**
* If {@link MailClientSettings#isActive()} from the {@link Settings}, then this will return
* the initialized instance of {@link MailClient}
*
* @return the mailClient
*/
public final MailClient getMailClient() {
return mailClient;
}
}
|
package de.gymnew.sudoku.gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import de.gymnew.sudoku.core.Solver;
import de.gymnew.sudoku.model.Sudoku;
import static de.gymnew.sudoku.gui.SudokuPanel.*;
@SuppressWarnings("serial")
public class MainFrame extends JFrame {
private MainFrameHandler handler;
private SudokuPanel panel;
private int scale;
private Solver solver;
public MainFrame() {
// The Basics
handler = new MainFrameHandler(this);
setSize(800, 600);
setResizable(false);
setScale(5);
setTitle("SudokuSolver");
panel = new SudokuPanel(this);
panel.addMouseListener(handler);
panel.setOpaque(true);
setContentPane(panel);
addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(WindowEvent event) {
handler.onMenuQuit();
}
});
// The Menu
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menuSudoku = new JMenu("Sudoku");
menuBar.add(menuSudoku);
JMenuItem itemLoad = new JMenuItem("Laden");
itemLoad.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent event) {
handler.onMenuLoad();
}
});
menuSudoku.add(itemLoad);
JMenuItem itemSave = new JMenuItem("Speichern");
itemSave.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent event) {
handler.onMenuSave();
}
});
menuSudoku.add(itemSave);
menuSudoku.addSeparator();
JMenuItem itemCredits = new JMenuItem("Credits");
itemCredits.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent event) {
handler.onMenuCredits();
}
});
menuSudoku.add(itemCredits);
menuSudoku.addSeparator();
JMenuItem itemQuit = new JMenuItem("Beenden");
itemQuit.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent event) {
handler.onMenuQuit();
}
});
menuSudoku.add(itemQuit);
JMenu menuSolve = new JMenu("L\u00F6sen");
menuBar.add(menuSolve);
JMenuItem itemSolverStart = new JMenuItem("L\u00F6ser starten");
itemSolverStart.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent event) {
handler.onMenuStartSolver();
}
});
menuSolve.add(itemSolverStart);
JMenuItem itemSolverStop = new JMenuItem("L\u00F6ser stoppen");
itemSolverStop.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent event) {
handler.onMenuStopSolver();
}
});
menuSolve.add(itemSolverStop);
menuSolve.addSeparator();
JMenu menuAlgorithm = new JMenu("Algorithmus");
menuSolve.add(menuAlgorithm);
}
public int getScale() {
return scale;
}
public void setScale(int scale) {
this.scale = scale;
int height = (OFFSET_TOP + OFFSET_BOTTOM + 9*FIELD_SIZE + 4*BLOCK_SEPARATOR_WIDTH) * scale + 50;
int width = (2*OFFSET_SIDE + 9*FIELD_SIZE + 4*BLOCK_SEPARATOR_WIDTH) * scale;
this.setSize(width, height);
repaint();
}
public Sudoku getSudoku(){
return panel.getSudoku();
}
public void setSudoku(Sudoku sudoku){
panel.setSudoku(sudoku);
panel.repaint();
}
public Solver getSolver() {
return solver;
}
public void setSolver(Solver solver) {
this.solver = solver;
}
}
|
package gl8080.lifegame.logic;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import gl8080.lifegame.logic.exception.IllegalParameterException;
/**
*
* <p>
* <br>
* {@link Position#equals(Object) equals()}
* {@code true}
* <p>
* {@code 0}
*/
@Embeddable
public class Position {
@Column(name="VERTICAL_POSITION")
private int vertical;
@Column(name="HORIZONTAL_POSITION")
private int horizontal;
public Position(int vertical, int horizontal) {
if (vertical < 0 || horizontal < 0) {
throw new IllegalParameterException(" (" + vertical + ", " + horizontal + ")");
}
this.vertical = vertical;
this.horizontal = horizontal;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Position)) return false;
Position other = (Position) o;
return this.vertical == other.vertical && this.horizontal == other.horizontal;
}
@Override
public int hashCode() {
return Objects.hash(this.vertical, this.horizontal);
}
@Override
public String toString() {
return Position.class.getSimpleName() + " (" + this.vertical + ", " + this.horizontal + ")";
}
/**
*
* <p>
*
*
* @return
*/
public List<Position> getNeighborPositions() {
List<Position> neighbors = new ArrayList<>();
for (int v=this.vertical-1; v<this.vertical+2; v++) {
for (int h=this.horizontal-1; h<this.horizontal+2; h++) {
if ((0<=v && 0<=h) && !(this.vertical==v && this.horizontal==h)) {
neighbors.add(new Position(v, h));
}
}
}
return neighbors;
}
@Deprecated @SuppressWarnings("unused")
private Position() {}
public int getHorizontalPosition() {
return this.horizontal;
}
public int getVerticalPosition() {
return this.vertical;
}
}
|
package com.natepaulus.dailyemail.web.service.impl;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.luckycatlabs.sunrisesunset.SunriseSunsetCalculator;
import com.luckycatlabs.sunrisesunset.dto.Location;
import com.natepaulus.dailyemail.repository.*;
import com.natepaulus.dailyemail.repository.entity.*;
import com.natepaulus.dailyemail.web.domain.EmailData;
import com.natepaulus.dailyemail.web.domain.NewsFeed;
import com.natepaulus.dailyemail.web.domain.NewsStory;
import com.natepaulus.dailyemail.web.service.interfaces.EmailService;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.velocity.app.VelocityEngine;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.ui.velocity.VelocityEngineUtils;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import org.xml.sax.InputSource;
import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.*;
// TODO: Auto-generated Javadoc
/**
* The Class EmailServiceImpl checks every minute to see if any users have requested their email at that time. If it finds any users it
* then builds and sends them an email with their requested data.
*/
@Service
@PropertySource("classpath:emailConfig.properties")
public class EmailServiceImpl implements EmailService {
public static final String N_A = "NA";
public static final double METERS_IN_MILE = 1609.344;
public static final double METERS_SECOND_TO_MPH = 0.44704;
@Resource
private Environment environment;
private final static String[] COMPASS_DIRECTIONS = {"N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW","N"};
/** The email addresses to use: */
private final static String ADMINISTRATOR = "administrator.email";
private final static String DAILY_EMAIL_ADDRESS = "dailyemail.from.email";
/** The logger. */
final Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);
/** The delivery schedule repository. */
@Resource
DeliveryScheduleRepository deliveryScheduleRepository;
/** The Rss Feeds Repository. */
@Resource
RssFeedsRepository rssFeedsRepository;
/** The User Rss Feeds Repository. */
@Resource
RssNewsLinksRepository rssNewsLinksRepository;
@Resource
UserRssFeedsRepository userRssFeedsRepository;
/** The user repository. */
@Resource
UserRepository userRepository;
/** The failed messages repository. */
@Resource
FailedMessagesRepository failedMessagesRepository;
/** The java mail sender for sending email. */
@Autowired
private JavaMailSender sender;
/** The velocity engine. */
@Autowired
private VelocityEngine velocityEngine;
/*
* (non-Javadoc)
*
* @see com.natepaulus.dailyemail.web.service.interfaces.EmailService# generateQuickView(java.lang.String)
*/
@Override
public EmailData generateQuickView(final String code) {
final User user = this.userRepository.findByUrlCode(code);
EmailData data = new EmailData();
data = this.getWeatherDataForEmail(data, user);
this.getRssLinksForEmail(data, user);
return data;
}
/**
* Returns weather forecast based on GPS coordinates using new weather.gov api.
*
* @param data
* @param user
* @return
*/
private EmailData getWeatherForecast(final EmailData data, final User user) throws ResourceAccessException{
final String uri = "https://api.weather.gov/points/"
+ user.getWeather().getLatitude() + "," + user.getWeather().getLongitude() + "/forecast";
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(uri, String.class);
JsonParser jsonParser = new JsonParser();
JsonElement jsonElement = jsonParser.parse(result);
JsonObject forecastData = jsonElement.getAsJsonObject();
JsonObject forecastProperties = forecastData.getAsJsonObject("properties");
JsonArray forecastPeriods = forecastProperties.getAsJsonArray("periods");
for(int index = 0; index < 3; index++){
JsonObject forecast = forecastPeriods.get(index).getAsJsonObject();
data.getWeatherForecast().getPeriodForecast().put(forecast.get("name").getAsString(),
forecast.get("detailedForecast").getAsString());
}
return data;
}
private EmailData getCurrentWeatherConditions(final EmailData data, final User user) throws ResourceAccessException{
final String uriPointForCityState = "https://api.weather.gov/points/"
+ user.getWeather().getLatitude() + "," + user.getWeather().getLongitude();
final String uriStations = "https://api.weather.gov/points/"
+ user.getWeather().getLatitude() + "," + user.getWeather().getLongitude() + "/stations";
final RestTemplate restTemplate = new RestTemplate();
final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
final HttpClient httpClient = HttpClientBuilder.create()
.setRedirectStrategy(new LaxRedirectStrategy())
.build();
factory.setHttpClient(httpClient);
restTemplate.setRequestFactory(factory);
final String stationListResult = restTemplate.getForObject(uriStations, String.class);
final JsonParser jsonParser = new JsonParser();
final JsonElement stationList = jsonParser.parse(stationListResult);
final JsonObject stationsJson = stationList.getAsJsonObject();
final JsonArray stations = stationsJson.getAsJsonArray("observationStations");
final String uriWeatherStation = stations.get(0).getAsString();
final String stationDetails = restTemplate.getForObject(uriWeatherStation, String.class);
final JsonElement stationInformation = jsonParser.parse(stationDetails);
final JsonElement stationProperties = stationInformation.getAsJsonObject().get("properties");
data.getWxCurCond().setWeatherStation(stationProperties.getAsJsonObject().get("name").getAsString());
data.getWxCurCond().setCityState(user.getWeather().getLocation_name());
final String pointInformation = restTemplate.getForObject(uriPointForCityState, String.class);
final JsonElement cityStateResponse = jsonParser.parse(pointInformation);
final JsonObject cityState = cityStateResponse.getAsJsonObject().get("properties").getAsJsonObject().get("relativeLocation").getAsJsonObject().get("properties").getAsJsonObject();
data.getWxCurCond().setCityState(cityState.get("city").getAsString() + ", " + cityState.get("state").getAsString());
final String currentWxResponse = restTemplate.getForObject(uriWeatherStation + "/observations", String.class);
final JsonObject allWxObservationsResponse = jsonParser.parse(currentWxResponse).getAsJsonObject();
final JsonArray allWxObservations = allWxObservationsResponse.getAsJsonArray("features");
final JsonObject currentWxObservation = allWxObservations.get(0).getAsJsonObject().get("properties").getAsJsonObject();
final DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");
final DateTime obsUTCTime = fmt.withOffsetParsed().parseDateTime(currentWxObservation.get("timestamp").getAsString());
final DateTime localTime = new DateTime(obsUTCTime).withZone(DateTimeZone.forID(user.getDeliveryTimes().iterator().next().getTz()));
final DateTimeFormatter outFmt = DateTimeFormat.forPattern("MMM dd',' yyyy h:mm a");
this.logger.info("Printing Local Time with printer: " + outFmt.print(localTime));
data.getWxCurCond().setLatestObDateTime(outFmt.print(localTime));
data.getWxCurCond().setCurWx(currentWxObservation.get("textDescription").getAsString());
if(!currentWxObservation.get("temperature").getAsJsonObject().get("value").isJsonNull()){
data.getWxCurCond().setCurrentTemp(String.valueOf(
Math.round(currentWxObservation.get("temperature").getAsJsonObject().get("value").getAsDouble() * 9 / 5 + 32)));
} else {
data.getWxCurCond().setCurrentTemp(N_A);
}
if(!currentWxObservation.get("dewpoint").getAsJsonObject().get("value").isJsonNull()){
data.getWxCurCond().setDewPoint(String.valueOf(
Math.round(currentWxObservation.get("dewpoint").getAsJsonObject().get("value").getAsDouble() * 9 / 5 + 32)));
} else {
data.getWxCurCond().setDewPoint(N_A);
}
if(!currentWxObservation.get("relativeHumidity").getAsJsonObject().get("value").isJsonNull()){
data.getWxCurCond().setHumidity(String.valueOf(Math.round(currentWxObservation.get("relativeHumidity").getAsJsonObject().get("value").getAsDouble())));
} else {
data.getWxCurCond().setHumidity(N_A);
}
if(!currentWxObservation.get("visibility").getAsJsonObject().get("value").isJsonNull()) {
DecimalFormat visbilityFormatter = new DecimalFormat("
data.getWxCurCond().setVisibility(String.valueOf(visbilityFormatter.format(currentWxObservation.get("visibility").getAsJsonObject().get("value").getAsDouble() / METERS_IN_MILE)));
} else {
data.getWxCurCond().setVisibility(N_A);
}
logger.info("Wind speed: " + currentWxObservation.get("windSpeed").getAsJsonObject().toString());
if(!currentWxObservation.get("windSpeed").getAsJsonObject().get("value").isJsonNull()){
data.getWxCurCond().setWindSpeed(String.valueOf(Math.round(currentWxObservation.get("windSpeed").getAsJsonObject().get("value").getAsDouble() / METERS_SECOND_TO_MPH)));
} else {
data.getWxCurCond().setWindSpeed("0");
}
logger.info("Wind gust: " + currentWxObservation.get("windGust").getAsJsonObject().toString());
if(!currentWxObservation.get("windGust").getAsJsonObject().get("value").isJsonNull()){
data.getWxCurCond().setWindGust(String.valueOf(Math.round(currentWxObservation.get("windGust").getAsJsonObject().get("value").getAsDouble() / METERS_SECOND_TO_MPH)));
} else {
data.getWxCurCond().setWindGust(N_A);
}
logger.info("Wind direction: " + currentWxObservation.get("windDirection").getAsJsonObject().toString());
if(!currentWxObservation.get("windDirection").getAsJsonObject().get("value").isJsonNull()) {
setWindDirection(data, currentWxObservation.get("windDirection").getAsJsonObject().get("value").getAsDouble());
} else {
data.getWxCurCond().setWindDirection("");
}
final DateTimeZone dtz = localTime.getZone();
this.logger.info("TimeZone: " + dtz.toString());
final Location location = new Location(user.getWeather().getLatitude(), user.getWeather().getLongitude());
final SunriseSunsetCalculator calculator = new SunriseSunsetCalculator(location, dtz.toString());
final Calendar officialSunrise = calculator.getOfficialSunriseCalendarForDate(Calendar.getInstance());
final Calendar officialSunset = calculator.getOfficialSunsetCalendarForDate(Calendar.getInstance());
final DateTimeFormatter dtfSunriseset = DateTimeFormat.forPattern("h:mm a");
final DateTime dtSunrise = new DateTime(officialSunrise);
final DateTime dtSunset = new DateTime(officialSunset);
final DateTime dtSunriseLocal = dtSunrise.withZone(DateTimeZone.forID(dtz.toString()));
final DateTime dtSunsetLocal = dtSunset.withZone(DateTimeZone.forID(dtz.toString()));
data.getWxCurCond().setSunRise(dtfSunriseset.print(dtSunriseLocal));
data.getWxCurCond().setSunSet(dtfSunriseset.print(dtSunsetLocal));
return data;
}
/**
* Gets the weather conditions from the National Weather Service experimental forecast feed.
*
* @param data the EmailData object to add the weather conditions to
* @param user the user
* @return the weather conditions
*/
private EmailData getWeatherDataForEmail(final EmailData data, final User user) {
switch (user.getWeather().getDeliver_pref()) {
case 1:
try {
getCurrentWeatherConditions(data, user);
} catch (ResourceAccessException e){
data.getWxCurCond().setCityState(null); // this sets error condition in email
logger.error("SSL Error is still occurring", e);
}
break;
case 2:
try {
getWeatherForecast(data, user);
} catch (ResourceAccessException e){
data.getWxCurCond().setCityState(null);
logger.error("SSL Error is still occurring", e);
}
break;
case 3:
try {
getWeatherForecast(data, user);
getCurrentWeatherConditions(data, user);
} catch (ResourceAccessException e){
data.getWxCurCond().setCityState(null);
logger.error("SSL Error is still occurring", e);
}
break;
}
return data;
}
/*
* (non-Javadoc)
*
* @see com.natepaulus.dailyemail.web.service.interfaces.EmailService# retrieveUserListForEmails()
*/
@Override
@Scheduled(cron = "0 0/1 * * * ?")
public void retrieveUserListForEmails() {
// logger.info("Retrieving List of users to email");
int dayOfWeek = -1;
final DateTime currentTime = new DateTime();
final List<DeliverySchedule> allDeliverySchedules = this.deliveryScheduleRepository.findAll();
final List<User> users = new ArrayList<User>();
for (final DeliverySchedule d : allDeliverySchedules) {
// get current time in user's local date & time
final DateTime currentLocalTime =
currentTime.withSecondOfMinute(0).withMillisOfSecond(0).withZone(DateTimeZone.forID(d.getTz()));
final int currentDayOfWeek = currentLocalTime.getDayOfWeek();
if (currentDayOfWeek == 7 || currentDayOfWeek == 6) {
dayOfWeek = 1;
} else {
dayOfWeek = 0;
}
final LocalTime userSetTime = d.getTime(); // user's set time
// convert local time to today's time & date and user's local time &
// date
final DateTime userSetTimeDateTime = userSetTime.toDateTimeToday().withZone(DateTimeZone.UTC);
DateTime userLocalSetTime = userSetTimeDateTime.withZone(DateTimeZone.forID(d.getTz()));
// Adjust for daylight savings since times saved to db remove the DST offset
final DateTimeZone dayLightSavingsCheck = DateTimeZone.forID(d.getTz());
if(!dayLightSavingsCheck.isStandardOffset(System.currentTimeMillis())){
userLocalSetTime = userLocalSetTime.minusHours(1);
}
/*
* logger.info("before IF userLocalSetTime: " + userLocalSetTime.toString()); logger.info("before IF currentLocalTime: " +
* currentLocalTime.toString());
*/
// check if current time equals user set time for today's date
if (userLocalSetTime.equals(currentLocalTime)) {
// logger.info("User's local set time is equal to current local time.");
// if the delivery day (weekend or weekday) equals the delivery
// day in the schedule add user to list
if (d.getDeliveryDay() == dayOfWeek) {
users.add(d.getUser());
// logger.info("Added user: " + d.getUser().getEmail());
}
}
}
final Iterator<User> userIterator = users.iterator();
while (userIterator.hasNext()) {
final User user = userIterator.next();
this.sendEmail(user);
}
}
/*
* (non-Javadoc)
*
* @see com.natepaulus.dailyemail.web.service.interfaces.EmailService# retrySendingFailedMessages()
*/
@Override
@Scheduled(cron = "0 0/5 * * * ?")
public void retrySendingFailedMessages() {
// logger.info("retry sending failed messages");
final List<FailedMessages> failedMessages = this.failedMessagesRepository.findAll();
for (final FailedMessages failedMsg : failedMessages) {
final MimeMessagePreparator preparator = new MimeMessagePreparator() {
@Override
public void prepare(final MimeMessage mimeMessage) throws Exception {
final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
message.setTo(failedMsg.getToAddress());
message.setFrom(EmailServiceImpl.this.environment.getRequiredProperty(DAILY_EMAIL_ADDRESS));
message.setSubject("Daily News & Weather");
message.setText(failedMsg.getMessage(), true);
}
};
try {
this.sender.send(preparator);
this.failedMessagesRepository.delete(failedMsg);
// logger.info("Successfully resent");
} catch (final MailException e) {
final int failedAttempts = failedMsg.getNumberFailedAttempts() + 1;
failedMsg.setNumberFailedAttempts(failedAttempts);
this.failedMessagesRepository.save(failedMsg);
// logger.info("Failed again and incremented counter");
}
}
}
/**
* Send email to the user with the data they have requested.
*
* @param user the user
*/
private void sendEmail(final User user) {
EmailData emailData = new EmailData();
emailData.setToAddress(user.getEmail());
emailData.setToName(user.getFirstName() + " " + user.getLastName());
emailData = this.getWeatherDataForEmail(emailData, user);
this.getRssLinksForEmail(emailData, user);
final EmailData data = emailData;
final Map<String, Object> model = new HashMap<String, Object>();
model.put("data", data);
@SuppressWarnings("deprecation")
final String messageText = VelocityEngineUtils.mergeTemplateIntoString(this.velocityEngine, "email.vm", model);
final MimeMessagePreparator preparator = new MimeMessagePreparator() {
@Override
public void prepare(final MimeMessage mimeMessage) throws Exception {
final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
message.setTo(data.getToAddress());
message.setFrom(EmailServiceImpl.this.environment.getRequiredProperty(DAILY_EMAIL_ADDRESS));
message.setSubject("Daily News & Weather");
message.setText(messageText, true);
}
};
try {
this.sender.send(preparator);
this.logger.info("Message sent to: " + data.getToAddress());
} catch (final MailException e) {
final FailedMessages fm = new FailedMessages();
fm.setToAddress(data.getToAddress());
fm.setToName(data.getToName());
fm.setMessage(messageText);
fm.setErrorMessage(e.getMessage());
fm.setNumberFailedAttempts(1);
this.failedMessagesRepository.save(fm);
this.logger.info("Email errored occured. Saved to Database.");
}
}
/**
* Send error email.
*
* @param errorMessage the error message
*/
private void sendErrorEmail(final String errorMessage) {
final MimeMessagePreparator preparator = new MimeMessagePreparator() {
@Override
public void prepare(final MimeMessage mimeMessage) throws Exception {
final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
message.setTo(EmailServiceImpl.this.environment.getRequiredProperty(ADMINISTRATOR));
message.setFrom(EmailServiceImpl.this.environment.getRequiredProperty(DAILY_EMAIL_ADDRESS));
message.setSubject("Error - Daily News & Weather");
message.setText(errorMessage, true);
}
};
this.sender.send(preparator);
this.logger.info("Error Message sent!");
}
private void getRssLinksForEmail(EmailData data, User user){
// grab first 5 news items from rss feeds and add to email data
for(UserRssFeeds userFeed : user.getUserRssFeeds()){
if(userFeed.getDeliver() == 1) {
RssFeeds rssFeed = rssFeedsRepository.findOne(userFeed.getFeedId());
try {
final URLConnection connection = new URL(rssFeed.getUrl()).openConnection();
connection
.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
connection.connect();
final InputStream is = connection.getInputStream();
final InputSource source = new InputSource(is);
final SyndFeedInput input = new SyndFeedInput();
final SyndFeed feed = input.build(source);
@SuppressWarnings("rawtypes")
final Iterator iFeed = feed.getEntries().iterator();
final int numLinks = 5;
int counter = 0;
final NewsFeed newsFeed = new NewsFeed();
newsFeed.setFeedTitle(userFeed.getFeedName());
while (iFeed.hasNext() && counter < numLinks) {
SyndEntry entry = (SyndEntry) iFeed.next();
if(null == entry.getDescription()){
entry.setDescription(new SyndContentImpl());
entry.getDescription().setValue(new String());
}
final NewsStory newsStory = new NewsStory(entry.getTitle(), entry.getLink(),
entry.getDescription().getValue().replaceAll("\\<.*?>", ""));
newsFeed.getNewsStories().add(newsStory);
counter++;
}
data.getNewsFeeds().add(newsFeed);
} catch (MalformedURLException e) {
logger.error("URL is bad: " + e.getStackTrace());
} catch (IOException e) {
logger.error("IO Exception Occurred: " + e.getStackTrace());
} catch (FeedException e) {
logger.error("Something is wrong with the feed: " + e.getStackTrace());
}
}
}
}
private void setWindDirection(EmailData data, Double windDirectionInDegrees){
if(windDirectionInDegrees == 999){
data.getWxCurCond().setWindDirection("Variable");
} else if(windDirectionInDegrees == 0 && data.getWxCurCond().getWindSpeed().equals("NA")){
data.getWxCurCond().setWindDirection("Calm");
} else {
final int sector = (int) Math.round((windDirectionInDegrees % 360) / 22.5);
data.getWxCurCond().setWindDirection(COMPASS_DIRECTIONS[sector]);
}
}
}
|
package org.inceptus.debug;
import edu.wpi.first.wpilibj.DriverStationLCD;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.image.ColorImage;
import edu.wpi.first.wpilibj.image.NIVisionException;
/**
*
* @author innoying
*/
public class Debug {
//Print an error without a message
public static void fatal(Exception ex){
//Call self
fatal(ex, "");
}
//Print an error
public static void fatal(Exception ex, String msg){
//Output to console
System.out.println( "(inceptus) FATAL Exception in " + ex.getClass().getName() + " :" );
//Print the exception
ex.printStackTrace();
//If a message is found
if(!msg.equals("")){
//Print to console
System.out.println( "(inceptus) FATAL Exception Message: " + msg );
}
//Send message to driverstation
DriverStationLCD.getInstance().println( DriverStationLCD.Line.kUser3, 1,
"FATAL:" + msg );
//Display
DriverStationLCD.getInstance().updateLCD();
}
//Log a message
public static void log(String msg){
//Output to console
System.out.println( "(inceptus) Log Message:" + msg );
//Send message to driverstation
DriverStationLCD.getInstance().println( DriverStationLCD.Line.kUser2, 1,
"Log:" + msg );
//Display
DriverStationLCD.getInstance().updateLCD();
}
public static void logImage(ColorImage im) throws NIVisionException{
//Save to file
im.write("inceptus-"+Timer.getFPGATimestamp()+".jpg");
}
}
|
package hackerrank;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Set;
public class PrimsSpecialSubtree {
private static int mst(Map<Integer, List<Edge>> adjList, int source) {
PriorityQueue<Edge> queue = new PriorityQueue<>();
Set<Integer> marked = new HashSet<>();
List<Edge> mst = new ArrayList<>();
visit(adjList, source, marked, queue);
while (!queue.isEmpty()) {
Edge edge = queue.remove();
int v1 = edge.either();
int v2 = edge.other(v1);
if (marked.contains(v1) && marked.contains(v2)) {
continue;
}
mst.add(edge);
if (!marked.contains(v1)) {
visit(adjList, v1, marked, queue);
}
if (!marked.contains(v2)) {
visit(adjList, v2, marked, queue);
}
}
int totalWeight = 0;
for (Edge edge : mst) {
totalWeight += edge.weight;
}
return totalWeight;
}
private static void visit(Map<Integer, List<Edge>> adjList, int source,
Set<Integer> marked, PriorityQueue<Edge> queue) {
marked.add(source);
for (Edge edge : adjList.get(source)) {
if (!marked.contains(edge.other(source))) {
queue.add(edge);
}
}
}
private static class Edge implements Comparable<Edge> {
private final int v1;
private final int v2;
private final int weight;
public Edge(int v1, int v2, int weight) {
this.v1 = v1;
this.v2 = v2;
this.weight = weight;
}
public int either() {
return v1;
}
public int other(int v) {
if (v == v1) {
return v2;
}
return v1;
}
@Override
public int compareTo(Edge o) {
return Integer.compare(weight, o.weight);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
Map<Integer, List<Edge>> adjList = new HashMap<>();
for (int vertex = 1; vertex <= n; vertex++) {
adjList.put(vertex, new ArrayList<>());
}
for (int i = 0; i < m; i++) {
int x = in.nextInt();
int y = in.nextInt();
int r = in.nextInt();
adjList.get(x).add(new Edge(x, y, r));
adjList.get(y).add(new Edge(x, y, r));
}
int s = in.nextInt();
System.out.println(mst(adjList, s));
}
}
|
package org.mapyrus;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.StringTokenizer;
import javax.imageio.ImageIO;
import org.mapyrus.font.AdobeFontMetricsManager;
import org.mapyrus.font.PostScriptFont;
import org.mapyrus.font.StringDimension;
import org.mapyrus.font.TrueTypeFont;
import org.mapyrus.io.ASCII85Writer;
import org.mapyrus.io.WildcardFile;
import org.mapyrus.ps.PostScriptFile;
/**
* Abstraction of a graphics format. Provides methods to create new
* output files and then draw to them, independent of the graphics
* format.
*/
public class OutputFormat
{
/*
* Type of output currently being generated.
*/
private static final int INTERNAL_IMAGE = 1;
private static final int IMAGE_FILE = 2;
/*
* PostScript output can be created as either moveto-lineto-stroke
* commands to draw shapes on page or as an single image covering
* the whole page containing all drawn shapes.
*/
private static final int POSTSCRIPT_GEOMETRY = 3;
private static final int POSTSCRIPT_IMAGE = 4;
/*
* Type of justification for labels on page, as used
* in a word processor and in HTML tags.
*/
public static final int JUSTIFY_LEFT = 1;
public static final int JUSTIFY_CENTER = 2;
public static final int JUSTIFY_RIGHT = 4;
public static final int JUSTIFY_TOP = 8;
public static final int JUSTIFY_MIDDLE = 16;
public static final int JUSTIFY_BOTTOM = 32;
/*
* File or image that drawing commands are
* writing to.
*/
private int mOutputType;
private String mFormatName;
private BufferedImage mImage;
private String mFilename;
private PrintWriter mWriter;
private OutputStream mOutputStream;
private Graphics2D mGraphics2D;
private boolean mIsPipedOutput;
private boolean mIsStandardOutput;
private boolean mIsUpdatingFile;
private Process mOutputProcess;
private File mTempFile;
/*
* Frequently used fonts.
*/
private FontCache mFontCache;
/*
* List of font definitions included in this PostScript file and list of fonts
* used in this file but not defined.
*/
private HashSet mSuppliedFontResources;
private HashSet mNeededFontResources;
/*
* Fonts which are to be re-encoded to ISOLatin1 in PostScript file.
* This is normally done so that extended symbols (such as degree symbol)
* can be used.
*/
private HashSet mEncodeAsISOLatin1;
/*
* Adobe Font Metrics files containing character width information for all fonts.
*/
private AdobeFontMetricsManager mAdobeFontMetrics;
private ArrayList mAfmFiles;
/*
* List of TrueType fonts to load using Java Font.createFont() method.
*/
private HashMap mTTFFonts;
/*
* Page dimensions and resolution.
*/
private double mPageWidth;
private double mPageHeight;
private double mResolution;
/*
* Justification for labels as fraction of string height and width
* to move string in X and Y direction to achieve correct justification.
*/
private double mJustificationShiftX;
private double mJustificationShiftY;
/*
* Rotation of current font in radians, with 0 horizontal,
* measured counter-clockwise.
*/
private double mFontRotation;
/*
* If non-zero, gives linewidth to use for drawing outlines of
* each character of labels.
*/
private double mFontOutlineWidth;
private Font mBaseFont;
/*
* Mask containing protected areas of the page.
*/
private PageMask mPageMask;
/**
* Write PostScript file header, including document structuring conventions (DSC).
* @param width width of page in mm.
* @param height height of page in mm.
* @param resolution resolution of page in DPI.
* @param turnPage flag true when page is to be rotated 90 degrees.
* @param fontList list of PostScript fonts to include in header.
* @param backgroundColor background color for page, or null if no background.
*/
private void writePostScriptHeader(double width, double height,
int resolution, boolean turnPage, ArrayList fontList, Color backgroundColor)
throws IOException, MapyrusException
{
long widthInPoints = Math.round(width / Constants.MM_PER_INCH *
Constants.POINTS_PER_INCH);
long heightInPoints = Math.round(height / Constants.MM_PER_INCH *
Constants.POINTS_PER_INCH);
mWriter.print("%!PS-Adobe-3.0");
if (mFormatName.equals("eps") || mFormatName.equals("epsimage"))
mWriter.print(" EPSF-3.0");
mWriter.println("");
if (turnPage)
mWriter.println("%%BoundingBox: 0 0 " + heightInPoints + " " + widthInPoints);
else
mWriter.println("%%BoundingBox: 0 0 " + widthInPoints + " " + heightInPoints);
if ((!mFormatName.equals("eps")) && (!mFormatName.equals("epsimage")))
mWriter.println("%%Pages: 1");
mWriter.println("%%DocumentData: Clean7Bit");
mWriter.println("%%LanguageLevel: 2");
mWriter.println("%%Creator: (" + Constants.PROGRAM_NAME +
" " + Constants.getVersion() + ")");
mWriter.println("%%OperatorMessage: (Mapyrus Output...)");
Date now = new Date();
mWriter.println("%%CreationDate: (" + now.toString() + ")");
String username = System.getProperty("user.name");
if (username != null)
mWriter.println("%%For: (" + username + ")");
/*
* List fonts included in this PostScript file.
*/
mWriter.println("%%DocumentRequiredResources: (atend)");
if (fontList.size() > 0)
{
mWriter.print("%%DocumentSuppliedResources: font");
Iterator it = fontList.iterator();
while (it.hasNext())
{
PostScriptFont psFont = (PostScriptFont)(it.next());
mWriter.print(" " + psFont.getName());
mSuppliedFontResources.add(psFont.getName());
}
mWriter.println("");
}
mWriter.println("%%EndComments");
mWriter.println("");
mWriter.println("% Resolution " + resolution + " DPI");
/*
* Inline font definitions.
*/
mWriter.println("%%BeginSetup");
Iterator it = fontList.iterator();
while (it.hasNext())
{
PostScriptFont psFont = (PostScriptFont)(it.next());
mWriter.println("%%BeginResource: font " + psFont.getName());
String fontDefinition = psFont.getFontDefinition();
mWriter.println(fontDefinition);
mWriter.println("%%EndResource");
}
mWriter.println("%%EndSetup");
/*
* Set color and linestyle to reasonable default values.
* Taken from 'initgraphics' operator example in PostScript Language
* Reference Manual.
*/
mWriter.println("1 setlinewidth 0 setlinecap 0 setlinejoin");
mWriter.println("[] 0 setdash 0 setgray 10 setmiterlimit");
if (turnPage)
{
/*
* Turn page 90 degrees so that a landscape orientation page appears
* on a portrait page.
*/
mWriter.println("% Turn page 90 degrees.");
mWriter.println("90 rotate 0 " + heightInPoints + " neg translate");
}
/*
* Prevent anything being displayed outside bounding box we've just defined.
*/
mWriter.println("0 0 " + widthInPoints + " " + heightInPoints + " rectclip");
/*
* Set background color for page.
*/
if (backgroundColor != null)
{
float c[] = backgroundColor.getRGBColorComponents(null);
mWriter.println("gsave");
mWriter.println(c[0] + " " + c[1] + " " + c[2] + " setrgbcolor");
mWriter.println("0 0 " + widthInPoints + " " + heightInPoints + " rectfill");
mWriter.println("grestore");
}
/*
* Define shorter names for most commonly used operations.
* Bind all operators names to improve performance (see 3.11 of
* PostScript Language Reference Manual).
*/
mWriter.println("/m { moveto } bind def /l { lineto } bind def");
mWriter.println("/s { stroke } bind def /f { fill } bind def");
mWriter.println("/j { /fjy exch def /fjx exch def } bind def");
/*
* Define font and dictionary entries for font size and justification.
* Don't bind these as font loading operators may be overridden in interpreter.
*/
mWriter.println("/font {");
mWriter.println("/foutline exch def");
mWriter.println("/frot exch radtodeg def");
mWriter.println("/fsize exch def findfont fsize scalefont setfont } def");
mWriter.println("/radtodeg { 180 mul 3.1415629 div } bind def");
/*
* Draw text string, after setting correct position, rotation,
* justifying it horizontally and vertically for current font size
* and shifting it down a number of lines if it is part of a multi-line
* string.
*
* Line number (starting at 0) and string to show are passed to this procedure.
*/
mWriter.println("/t { gsave currentpoint translate frot rotate");
mWriter.println("dup stringwidth pop fjx mul");
mWriter.println("3 -1 roll neg fjy add fsize mul");
mWriter.println("rmoveto foutline 0 gt");
mWriter.println("{false charpath foutline 0 0 2 sl stroke} {show} ifelse");
mWriter.println("grestore newpath } bind def");
mWriter.println("/rgb { setrgbcolor } bind def");
mWriter.println("/sl { setmiterlimit setlinejoin setlinecap");
mWriter.println("setlinewidth } bind def");
/*
* Use new dictionary in saved state so that variables we define
* do not overwrite variables in parent state.
*/
mWriter.println("/gs { gsave 4 dict begin } bind def");
mWriter.println("/gr { end grestore } bind def");
mWriter.println("");
}
/*
* Set scale in PostScript file so that we can give all coordinate
* positions in millimetres.
*/
private void writePostScriptScaling()
{
/*
* Set plotting units to millimetres.
*/
mWriter.println("% Set scaling so that (x, y) coordinates are given in millimetres");
mWriter.println(Constants.POINTS_PER_INCH + " " + Constants.MM_PER_INCH +
" div dup scale");
}
/**
* Sets correct rendering hints and transformation
* for buffered image we will plot to.
* @param resolution resolution for page in DPI.
* @param backgroundColor background color for page, or null if no background.
* @param lineAliasing flag true if lines should be drawn with anti-aliasing.
* @param labelAliasing flag true if labels should be drawn with anti-aliasing.
*/
private void setupBufferedImage(double resolution, Color backgroundColor,
boolean lineAntiAliasing, boolean labelAntiAliasing)
{
double scale;
scale = resolution / Constants.MM_PER_INCH;
/*
* Set background of entire image to desired color.
*/
if (backgroundColor != null)
{
Color originalColor = mGraphics2D.getColor();
mGraphics2D.setColor(backgroundColor);
mGraphics2D.fillRect(0, 0, mImage.getWidth(), mImage.getHeight());
mGraphics2D.setColor(originalColor);
}
/*
* Set transform with origin in lower-left corner and
* Y axis increasing upwards.
*/
mGraphics2D.translate(0, mImage.getHeight());
mGraphics2D.scale(scale, -scale);
/*
* Set anti-aliasing for labels and lines if the user wants it.
*/
if (lineAntiAliasing)
{
mGraphics2D.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON));
}
else
{
mGraphics2D.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF));
}
if (labelAntiAliasing)
{
mGraphics2D.addRenderingHints(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON));
}
else
{
mGraphics2D.addRenderingHints(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF));
}
}
/**
* Indicates whether an image format is supported or not.
* @param formatName
* @return true if creation of images in given format is supported.
*/
private boolean isSupportedImageFormat(String formatName)
{
boolean found = false;
String knownFormats[] = ImageIO.getWriterFormatNames();
for (int i = 0; i < knownFormats.length && found == false; i++)
{
if (formatName.equalsIgnoreCase(knownFormats[i]))
{
found = true;
}
}
return(found);
}
/**
* Return PostScript commands to re-encode a font in ISOLatin1 encoding.
* @param fontName name of font to re-encode.
* @return string containing PostScript commands to re-encode font.
*/
private String isoLatinEncode(String fontName)
{
/*
* Re-encoding commands taken from section 5.6.1 of Adobe PostScript
* Language Reference Manual (2nd Edition).
*/
return("/" + fontName + " findfont" + Constants.LINE_SEPARATOR +
"dup length dict begin" + Constants.LINE_SEPARATOR +
"{1 index /FID ne {def} {pop pop} ifelse} forall" + Constants.LINE_SEPARATOR +
"/Encoding ISOLatin1Encoding def" + Constants.LINE_SEPARATOR +
"currentdict" + Constants.LINE_SEPARATOR +
"end" + Constants.LINE_SEPARATOR +
"/" + fontName + " exch definefont pop");
}
private void setOutput(String filename, double width, double height,
String extras, PrintStream stdoutStream)
throws IOException, MapyrusException
{
/*
* Parse list of additional options given by caller.
*/
ArrayList fontList = new ArrayList();
mEncodeAsISOLatin1 = new HashSet();
mTTFFonts = new HashMap();
mAfmFiles = new ArrayList();
mIsUpdatingFile = false;
int resolution;
boolean turnPage = false;
Color backgroundColor = null;
boolean labelAntiAliasing = true;
boolean lineAntiAliasing = false;
Rectangle2D existingBoundingBox = null;
if (mOutputType == POSTSCRIPT_GEOMETRY)
resolution = 300;
else
resolution = Constants.getScreenResolution();
/*
* Reading all font metrics information takes some time.
* Wait until we really need it before loading it.
*/
mAdobeFontMetrics = null;
StringTokenizer st = new StringTokenizer(extras);
while (st.hasMoreTokens())
{
String token = st.nextToken();
if (token.startsWith("pfafiles="))
{
/*
* Build list of font filenames user wants
* to include in this PostScript file.
*/
StringTokenizer st2 = new StringTokenizer(token.substring(9), ",");
while (st2.hasMoreTokens())
{
String pfaFilename = st2.nextToken();
if (pfaFilename.length() > 0)
{
/*
* Accept wildcards in filenames.
*/
WildcardFile wildcard = new WildcardFile(pfaFilename);
Iterator it = wildcard.getMatchingFiles().iterator();
while (it.hasNext())
fontList.add(new PostScriptFont((String)it.next()));
}
}
}
if (token.startsWith("afmfiles="))
{
StringTokenizer st2 = new StringTokenizer(token.substring(9), ",");
while (st2.hasMoreTokens())
{
String afmFilename = st2.nextToken();
if (afmFilename.length() > 0)
{
/*
* Accept wildcards in filenames.
*/
WildcardFile wildcard = new WildcardFile(afmFilename);
Iterator it = wildcard.getMatchingFiles().iterator();
while (it.hasNext())
{
mAfmFiles.add(it.next());
}
}
}
}
else if (token.startsWith("isolatinfonts="))
{
/*
* Build list of fonts to encode in ISOLatin1.
*/
StringTokenizer st2 = new StringTokenizer(token.substring(14), ",");
while (st2.hasMoreTokens())
{
String fontName = st2.nextToken();
if (fontName.length() > 0)
mEncodeAsISOLatin1.add(fontName);
}
}
else if (token.startsWith("resolution="))
{
String r = token.substring(11);
try
{
resolution = Integer.parseInt(r);
}
catch (NumberFormatException e)
{
throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.INVALID_PAGE_RESOLUTION) +
": " + r);
}
if (resolution < 1)
{
throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.INVALID_PAGE_RESOLUTION) +
": " + r);
}
}
else if (token.startsWith("ttffiles="))
{
/*
* Build list of TrueType font filenames user wants
* to open with Java methods.
*/
StringTokenizer st2 = new StringTokenizer(token.substring(9), ",");
while (st2.hasMoreTokens())
{
String ttfFilename = st2.nextToken();
/*
* Accept wildcards in filenames.
*/
if (ttfFilename.length() > 0)
{
WildcardFile wildcard = new WildcardFile(ttfFilename);
Iterator it = wildcard.getMatchingFiles().iterator();
while (it.hasNext())
{
String s = (String)it.next();
TrueTypeFont ttf = new TrueTypeFont(s);
mTTFFonts.put(ttf.getName(), ttf);
}
}
}
}
else if (token.startsWith("turnpage="))
{
String flag = token.substring(9);
turnPage = flag.equalsIgnoreCase("true");
}
else if (token.startsWith("labelantialiasing="))
{
String flag = token.substring(18);
labelAntiAliasing = flag.equalsIgnoreCase("true");
}
else if (token.startsWith("lineantialiasing="))
{
String flag = token.substring(17);
lineAntiAliasing = flag.equalsIgnoreCase("true");
}
else if (token.startsWith("update="))
{
String flag = token.substring(7);
mIsUpdatingFile = flag.equalsIgnoreCase("true");
}
else if (token.startsWith("background="))
{
String colorName = token.substring(11);
backgroundColor = ColorDatabase.getColor(colorName, 255);
if (backgroundColor == null)
{
throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.COLOR_NOT_FOUND) +
": " + colorName);
}
}
}
if ((mOutputType == POSTSCRIPT_GEOMETRY || mOutputType == POSTSCRIPT_IMAGE ||
mOutputType == IMAGE_FILE) && (!mIsUpdatingFile))
{
/*
* Should we pipe the output to another program
* instead of writing a file?
*/
mIsPipedOutput = filename.startsWith("|");
/*
* Are we writing to standard output instead of to a file?
*/
mIsStandardOutput = filename.equals("-");
if (mIsPipedOutput)
{
String pipeCommand = filename.substring(1).trim();
mOutputProcess = Runtime.getRuntime().exec(pipeCommand);
mOutputStream = mOutputProcess.getOutputStream();
}
else
{
if (mIsStandardOutput)
mOutputStream = stdoutStream;
else
mOutputStream = new FileOutputStream(filename);
}
}
File f = new File(filename);
if (mIsUpdatingFile)
{
if (!f.canWrite())
{
throw new IOException(MapyrusMessages.get(MapyrusMessages.READ_ONLY) + ": " + filename);
}
}
/*
* Setup file we are writing to.
*/
if (mOutputType == POSTSCRIPT_GEOMETRY || mOutputType == POSTSCRIPT_IMAGE)
{
if (mIsUpdatingFile)
{
PostScriptFile ps = new PostScriptFile(filename);
if (ps.getNumberOfPages() > 1)
{
throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.NOT_PS_FILE) + ": " + filename);
}
/*
* Use size of existing PostScript file as size for new page.
*/
existingBoundingBox = ps.getBoundingBox();
width = existingBoundingBox.getMaxX() / Constants.POINTS_PER_INCH *
Constants.MM_PER_INCH;
height = existingBoundingBox.getMaxY() / Constants.POINTS_PER_INCH *
Constants.MM_PER_INCH;
/*
* Start writing to a temporary file in same directory. We'll replace the
* original file at the end when the file is successfully completed.
*/
mTempFile = File.createTempFile(Constants.PROGRAM_NAME, null,
new File(filename).getAbsoluteFile().getParentFile());
mOutputStream = new FileOutputStream(mTempFile);
}
mWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(mOutputStream)));
mSuppliedFontResources = new HashSet();
writePostScriptHeader(width, height, resolution, turnPage, fontList, backgroundColor);
mNeededFontResources = new HashSet();
if (mIsUpdatingFile)
{
/*
* Append contents of existing file as an included document
* to the new file we are creating.
*/
writePostScriptLine("save");
writePostScriptLine("/showpage {} def");
writePostScriptLine("%%BeginDocument: " + filename);
BufferedReader r = null;
try
{
r = new BufferedReader(new FileReader(filename));
String line;
while ((line = r.readLine()) != null)
{
writePostScriptLine(line);
}
}
finally
{
try
{
if (r != null)
r.close();
}
catch (IOException e)
{
}
}
writePostScriptLine("%%EndDocument");
writePostScriptLine("restore");
}
writePostScriptScaling();
}
if (mOutputType != POSTSCRIPT_GEOMETRY)
{
/*
* Create image to draw into.
*/
if (mOutputType == IMAGE_FILE || mOutputType == POSTSCRIPT_IMAGE)
{
if (mIsUpdatingFile && mOutputType == IMAGE_FILE)
{
/*
* Read existing image for editing.
* Set page width and height to size of existing image.
*/
mImage = ImageIO.read(f);
if (mImage == null)
{
throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.INVALID_FORMAT) + ": " + filename);
}
width = mImage.getWidth() / (resolution / Constants.MM_PER_INCH);
height = mImage.getHeight() / (resolution / Constants.MM_PER_INCH);
}
else
{
/*
* Create a BufferedImage to draw into. We'll save it to a file
* when user has finished drawing to it.
*/
int widthInPixels = (int)Math.round(width / Constants.MM_PER_INCH * resolution);
int heightInPixels = (int)Math.round(height / Constants.MM_PER_INCH * resolution);
int imageType;
/*
* Create images with transparency for all formats except
* JPEG (which does not support it).
*/
if (mFormatName.equals("jpg") || mFormatName.equals("jpeg"))
imageType = BufferedImage.TYPE_3BYTE_BGR;
else
imageType = BufferedImage.TYPE_INT_ARGB;
mImage = new BufferedImage(widthInPixels, heightInPixels,
imageType);
}
}
else if (mOutputType == INTERNAL_IMAGE)
{
/*
* Calculate width of page, based on image and resolution given
* by user.
*/
width = mImage.getWidth() / (resolution / Constants.MM_PER_INCH);
height = mImage.getHeight() / (resolution / Constants.MM_PER_INCH);
}
mGraphics2D = (Graphics2D)(mImage.getGraphics());
setupBufferedImage(resolution, backgroundColor, lineAntiAliasing, labelAntiAliasing);
}
mFilename = filename;
mPageWidth = width;
mPageHeight = height;
mResolution = Constants.MM_PER_INCH / resolution;
mFontCache = new FontCache();
mJustificationShiftX = mJustificationShiftY = 0.0;
mFontOutlineWidth = 0.0;
/*
* Set impossible current font rotation so first font
* accessed will be loaded.
*/
mFontRotation = Double.MAX_VALUE;
/*
* Do not allocate page mask until needed to save memory.
*/
mPageMask = null;
}
/**
* Creates new graphics file, ready for drawing to.
* @param filename name of image file output will be saved to.
* If filename begins with '|' character then output is piped as
* input to that command.
* @param format is the graphics format to use.
* @param width is the page width (in mm).
* @param height is the page height (in mm).
* @param extras contains extra settings for this output.
* @param stdoutStream standard output stream for program.
*/
public OutputFormat(String filename, String format,
double width, double height, String extras,
PrintStream stdoutStream)
throws IOException, MapyrusException
{
mFormatName = format.toLowerCase();
/*
* Check that Java can write this image format to a file.
*/
if (mFormatName.equals("ps") ||
mFormatName.equals("postscript") ||
mFormatName.equals("application/postscript"))
{
mFormatName = "ps";
mOutputType = POSTSCRIPT_GEOMETRY;
}
else if (mFormatName.equals("eps"))
{
mOutputType = POSTSCRIPT_GEOMETRY;
}
else if (mFormatName.equals("epsimage"))
{
mOutputType = POSTSCRIPT_IMAGE;
}
else
{
if (mFormatName.startsWith("image/"))
mFormatName = mFormatName.substring(6);
if (!isSupportedImageFormat(mFormatName))
{
throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.INVALID_FORMAT) +
": " + format);
}
mOutputType = IMAGE_FILE;
}
setOutput(filename, width, height, extras, stdoutStream);
}
/**
* Sets image for drawing into.
* @param image is buffered image to draw into.
* @param extras contains extra settings for this output.
*/
public OutputFormat(BufferedImage image, String extras)
throws IOException, MapyrusException
{
mOutputType = INTERNAL_IMAGE;
mImage = image;
mFormatName = "png";
PrintStream dummyStdout = new PrintStream(new ByteArrayOutputStream());
setOutput("", 0, 0, extras, dummyStdout);
}
/**
* Return page width.
* @return width in millimetres.
*/
public double getPageWidth()
{
return(mPageWidth);
}
/**
* Return page height.
* @return height in millimetres.
*/
public double getPageHeight()
{
return(mPageHeight);
}
/**
* Return file format of page.
* @return file format of page in lowercase.
*/
public String getPageFormat()
{
return(mFormatName);
}
/**
* Return resolution of page as a distance measurement.
* @return distance in millimetres between centres of adjacent pixels.
*/
public double getResolution()
{
return(mResolution);
}
/**
* Returns height and width of a string, drawn to current page.
* @param s string to calculate width for.
* @param fontName name of font to calculate dimensions for.
* @param fontSize size of characters in millimetres.
* @return height and width of string in millimetres.
*/
public StringDimension getStringDimension(String s, String fontName, double fontSize)
throws IOException, MapyrusException
{
StringDimension retval = new StringDimension();
BufferedReader stringReader = new BufferedReader(new StringReader(s));
double width = 0, height = 0;
String token;
double tokenWidth;
/*
* Break multi-line strings into separate lines so we
* can find the width of the longest line.
*/
while ((token = stringReader.readLine()) != null)
{
if (mOutputType == POSTSCRIPT_GEOMETRY)
{
/*
* Load Font Metrics information only when it is needed.
*/
if (mAdobeFontMetrics == null)
mAdobeFontMetrics = new AdobeFontMetricsManager(mAfmFiles, mEncodeAsISOLatin1);
double pointSize = fontSize / Constants.MM_PER_INCH * Constants.POINTS_PER_INCH;
tokenWidth = mAdobeFontMetrics.getStringWidth(fontName, pointSize, token);
tokenWidth = tokenWidth / Constants.POINTS_PER_INCH * Constants.MM_PER_INCH;
if (tokenWidth > width)
width = tokenWidth;
height += fontSize;
}
else
{
/*
* Use Java2D calculation for bounding box of string displayed with
* horizontal font.
*/
FontRenderContext frc = mGraphics2D.getFontRenderContext();
Rectangle2D bounds = mBaseFont.getStringBounds(token, frc);
tokenWidth = bounds.getWidth();
if (tokenWidth > width)
width = tokenWidth;
height += bounds.getHeight();
}
}
retval.setSize(width, height);
return(retval);
}
/**
* Return mask for this page.
* @return page mask.
*/
public PageMask getPageMask()
{
if (mPageMask == null)
{
mPageMask = new PageMask((int)Math.round(mPageWidth),
(int)Math.round(mPageHeight));
}
return(mPageMask);
}
/*
* Write a line to PostScript file. Line is indented to show
* saving and restoring of state more clearly.
*/
private void writePostScriptLine(String line)
{
mWriter.println(line);
}
/**
* Write image to PostScript file.
* @param image image to write.
* @param x center position on page for image.
* @param y center position on page for image.
* @param width width of image in millimetres.
* @param height height of image in millimetres.
* @param rotation rotation angle for image.
*/
private void writePostScriptImage(BufferedImage image, double x, double y,
double width, double height, double rotation)
throws IOException, MapyrusException
{
int j;
int pixelWidth, pixelHeight;
pixelWidth = image.getWidth();
pixelHeight = image.getHeight();
/*
* Check if image is a single color.
* Draw single color images with transparent background
* using PostScript 'imagemask' operator.
* Draw other images as RGB images using 'image' operator.
*/
Color singleColor = getSingleImageColor(image);
/*
* Write PostScript image directionary entry to draw image.
* Taken from Adobe PostScript Language Reference Manual
* (2nd Edition), p. 234.
*/
writePostScriptLine("gs");
writePostScriptLine("/DeviceRGB setcolorspace");
writePostScriptLine(x + " " + y + " translate");
writePostScriptLine(rotation + " radtodeg rotate");
writePostScriptLine(width + " " + height + " scale");
/*
* Image is centred at each point.
* Shift image left and down half it's size so that it is displayed centred.
*/
writePostScriptLine("-0.5 -0.5 translate");
/*
* Set color for drawing single color images.
*/
if (singleColor != null)
{
float []c = singleColor.getColorComponents(null);
writePostScriptLine(c[0] + " " + c[1] + " " + c[2] + " rgb");
}
writePostScriptLine("<<");
writePostScriptLine("/ImageType 1");
writePostScriptLine("/Width " + pixelWidth);
writePostScriptLine("/Height " + pixelHeight);
if (singleColor != null)
{
writePostScriptLine("/BitsPerComponent 1");
writePostScriptLine("/Decode [0 1]");
}
else
{
writePostScriptLine("/BitsPerComponent 8");
writePostScriptLine("/Decode [0 1 0 1 0 1]");
}
writePostScriptLine("/ImageMatrix [" + pixelWidth + " 0 0 " +
-pixelHeight + " 0 " + pixelHeight + "]");
writePostScriptLine("/DataSource currentfile /ASCII85Decode filter");
writePostScriptLine(">>");
if (singleColor != null)
writePostScriptLine("imagemask");
else
writePostScriptLine("image");
/*
* Write ASCII85 encoded string containing all pixel values.
*/
ASCII85Writer ascii85 = new ASCII85Writer(mWriter);
int byteValue = 0;
int bitCounter = 0;
for (j = 0; j < pixelWidth * pixelHeight; j++)
{
int pixel = image.getRGB(j % pixelWidth, j / pixelWidth);
if (singleColor != null)
{
/*
* Pixel is set in PostScript image if it is transparent.
*/
int nextBit = ((pixel >> 24) == 0) ? 1 : 0;
/*
* Store next pixel value as a single bit in a byte.
* If we've completed a byte or reached the end of a row
* then write byte out and begin next byte.
*/
nextBit <<= (7 - bitCounter);
byteValue |= nextBit;
bitCounter++;
if (bitCounter == 8 || (j + 1) % pixelWidth == 0)
{
ascii85.write(byteValue);
byteValue = bitCounter = 0;
}
}
else
{
/*
* Ignore transparency, we want only red, green, blue components
* of pixel.
*/
int blue = (pixel & 0xff);
int green = ((pixel >> 8) & 0xff);
int red = ((pixel >> 16) & 0xff);
ascii85.write(red);
ascii85.write(green);
ascii85.write(blue);
}
}
ascii85.close();
/*
* Write ASCII85 end-of-data marker.
*/
writePostScriptLine("~>");
writePostScriptLine("gr");
}
/**
* Save state, protecting color, linestyle, transform of output.
* This state can be restored later with restoreState().
*/
public void saveState()
{
if (mOutputType == POSTSCRIPT_GEOMETRY)
{
writePostScriptLine("gs");
}
}
/**
* Restore state saved with saveState().
* @return true if saved state was successfully restored.
* Only PostScript format can be successfully restored, caller
* will have to reset values for other formats.
*/
public boolean restoreState()
{
boolean retval;
if (mOutputType == POSTSCRIPT_GEOMETRY)
{
writePostScriptLine("gr");
retval = true;
}
else
{
/*
* Can't restore state when drawing to an image. Caller
* must set everything to correct values again.
*/
retval = false;
}
return(retval);
}
/**
* Writes trailing and buffered information, then closes output file.
*/
public void closeOutputFormat() throws IOException, MapyrusException
{
if (mOutputType == POSTSCRIPT_GEOMETRY || mOutputType == POSTSCRIPT_IMAGE)
{
if (mOutputType == POSTSCRIPT_IMAGE)
{
/*
* Write image file containing page.
*/
writePostScriptImage(mImage, mPageWidth / 2, mPageHeight / 2,
mPageWidth, mPageHeight, 0);
}
/*
* Finish off PostScript file.
*/
if (mFormatName.equals("ps"))
{
/*
* showpage is not included in Encapsulated PostScript files.
*/
mWriter.println("showpage");
}
mWriter.println("%%Trailer");
/*
* Included list of fonts we used in this file but did
* not include in the header.
*/
mWriter.println("%%DocumentNeededResources:");
Iterator it = mNeededFontResources.iterator();
while (it.hasNext())
{
String fontName = (String)(it.next());
if (!mSuppliedFontResources.contains(fontName))
mWriter.println("%%+ font " + fontName);
}
mWriter.println("%%EOF");
if (mIsStandardOutput)
mWriter.flush();
else
mWriter.close();
if (mWriter.checkError())
{
throw new MapyrusException(mFilename +
": " + MapyrusMessages.get(MapyrusMessages.ERROR_PS));
}
/*
* If updating file then replace existing file with completed
* temporary file now.
*/
if (mTempFile != null)
{
if ((!new File(mFilename).delete()) || (!mTempFile.renameTo(new File(mFilename))))
{
mTempFile.delete();
throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.READ_ONLY) + ": " + mFilename);
}
}
}
else if (mOutputType == IMAGE_FILE)
{
/*
* If updating file then overwrite it now with new image.
*/
if (mIsUpdatingFile)
mOutputStream = new FileOutputStream(mFilename);
/*
* Write image buffer to file.
*/
ImageIO.write(mImage, mFormatName, mOutputStream);
if (mIsStandardOutput)
mOutputStream.flush();
else
mOutputStream.close();
}
mImage = null;
mGraphics2D = null;
if (mOutputType != INTERNAL_IMAGE)
{
/*
* If we are piping output to another program then wait for
* that program to finish. Then check that it succeeded.
*/
if (mIsPipedOutput)
{
int retval = 0;
try
{
retval = mOutputProcess.waitFor();
}
catch (InterruptedException e)
{
throw new MapyrusException(mFilename + ": " + e.getMessage());
}
if (retval != 0)
{
throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.PROCESS_ERROR) +
": " + retval + ": " + mFilename);
}
}
}
}
/**
* Set font for labelling in output format.
* @param fontName is name of font as defined in java.awt.Font class.
* @param fontSize is size for labelling in millimetres.
* @param fontRotation is rotation angle for font, in degrees,
* measured counter-clockwise.
* @param outlineWidth if non-zero, labels will drawn as character outlines
* with this width.
*/
public void setFontAttribute(String fontName, double fontSize, double fontRotation, double outlineWidth)
throws IOException, MapyrusException
{
if (mOutputType == POSTSCRIPT_GEOMETRY)
{
if (mEncodeAsISOLatin1.contains(fontName))
{
/*
* Re-encode font from StandardEncoding to ISOLatin1Encoding
* before it is used.
*/
writePostScriptLine(isoLatinEncode(fontName));
mEncodeAsISOLatin1.remove(fontName);
}
/*
* Set font and size for labelling.
*/
writePostScriptLine("/" + fontName + " " +
fontSize + " " +
fontRotation + " " +
outlineWidth + " font");
mNeededFontResources.add(fontName);
}
else
{
/*
* Split font name into font and style.
*/
int style = Font.PLAIN;
if (fontName.endsWith("-Bold"))
{
style = Font.BOLD;
fontName = fontName.substring(0, fontName.length() - 5);
}
else if (fontName.endsWith("-Italic"))
{
style = Font.ITALIC;
fontName = fontName.substring(0, fontName.length() - 7);
}
else if (fontName.endsWith("-BoldItalic"))
{
style = Font.BOLD|Font.ITALIC;
fontName = fontName.substring(0, fontName.length() - 11);
}
/*
* Continually opening and deriving fonts is probably expensive.
* Check that new font is actually different to current font
* before defining it.
*/
Font currentFont = mGraphics2D.getFont();
int newSize = (int)Math.round(fontSize);
if (newSize != currentFont.getSize() ||
style != currentFont.getStyle() ||
(!fontName.equals(currentFont.getFontName())) ||
fontRotation != mFontRotation)
{
/*
* We need a base font that is not rotated for calculating
* string widths for justifying text.
* Get base font from cache, or create it if we don't find it there.
*/
mBaseFont = mFontCache.get(fontName, style, newSize, 0);
if (mBaseFont == null)
{
/*
* If this is a font for which user provided a TTF file then
* use that, else expect the operating system to be able to
* open the font.
*/
TrueTypeFont ttf = (TrueTypeFont)mTTFFonts.get(fontName);
if (ttf != null)
mBaseFont = ttf.getFont().deriveFont(style, (float)newSize);
else
mBaseFont = new Font(fontName, style, newSize);
mFontCache.put(fontName, style, newSize, 0, mBaseFont);
}
/*
* The real font used for labelling must be mirrored in Y axis
* (to reverse the transform we use on Graphics2D objects) and
* rotated to the angle the user wants.
*
* Look it up in cache too.
*/
Font font = mFontCache.get(fontName, style, -newSize, fontRotation);
if (font == null)
{
AffineTransform fontTransform;
fontTransform = AffineTransform.getRotateInstance(fontRotation);
fontTransform.scale(1, -1);
font = mBaseFont.deriveFont(fontTransform);
mFontCache.put(fontName, style, -newSize, fontRotation, font);
}
mGraphics2D.setFont(font);
}
}
/*
* Font rotation and outlining not easily held in a Graphics2D
* object so keep track of it's current value ourselves.
*/
mFontRotation = fontRotation;
mFontOutlineWidth = outlineWidth;
}
/**
* Set label justification in output format.
* @param justify is label justification value, combination of JUSTIFY_* bit flags.
*/
public void setJustifyAttribute(int justify)
{
/*
* Calculate fraction of string height and width to move text to get required
* justification.
*/
if ((justify & JUSTIFY_LEFT) != 0)
mJustificationShiftX = 0.0;
else if ((justify & JUSTIFY_CENTER) != 0)
mJustificationShiftX = -0.5;
else
mJustificationShiftX = -1.0;
if ((justify & JUSTIFY_BOTTOM) != 0)
mJustificationShiftY = 0.0;
else if ((justify & JUSTIFY_MIDDLE) != 0)
mJustificationShiftY = -0.5;
else
mJustificationShiftY = -1.0;
if (mOutputType == POSTSCRIPT_GEOMETRY)
{
/*
* Define dictionary entries for justification settings for PostScript
* procedure to use for aligning text correctly itself.
*/
writePostScriptLine(mJustificationShiftX + " " + mJustificationShiftY + " j");
}
}
/**
* Set color in output format.
* @param color is color to draw in.
*/
public void setColorAttribute(Color color)
{
if (mOutputType == POSTSCRIPT_GEOMETRY)
{
float c[] = color.getRGBColorComponents(null);
writePostScriptLine(c[0] + " " + c[1] + " " + c[2] + " rgb");
}
else
{
mGraphics2D.setColor(color);
}
}
/**
* Set linestyle in output format.
* @param linestyle is Java2D line width, cap and join style, dash pattern.
*/
public void setLinestyleAttribute(BasicStroke linestyle)
{
if (mOutputType == POSTSCRIPT_GEOMETRY)
{
/*
* Convert BasicStroke end cap and line join values to PostScript.
*/
int cap = linestyle.getEndCap();
if (cap == BasicStroke.CAP_BUTT)
cap = 0;
else if (cap == BasicStroke.CAP_ROUND)
cap = 1;
else /* SQUARE */
cap = 2;
int join = linestyle.getLineJoin();
if (join == BasicStroke.JOIN_MITER)
join = 0;
else if (join == BasicStroke.JOIN_ROUND)
join = 1;
else /* BEVEL */
join = 2;
writePostScriptLine(linestyle.getLineWidth() + " " +
cap + " " + join + " " +
linestyle.getMiterLimit() + " sl");
/*
* If there a dash pattern then set that too.
*/
float dashes[] = linestyle.getDashArray();
if (dashes != null)
{
StringBuffer s = new StringBuffer("[");
for (int i = 0; i < dashes.length; i++)
{
if (i > 0)
s.append(" ");
s.append(dashes[i]);
}
s.append("] ");
s.append(linestyle.getDashPhase());
s.append(" setdash");
writePostScriptLine(s.toString());
}
else
{
/*
* Remove any dashed line previously defined.
*/
writePostScriptLine("[] 0 setdash");
}
}
else
{
mGraphics2D.setStroke(linestyle);
}
}
/**
* Set clip path for output format.
* @param clipPaths are polygons to clip against, or null if there are no clip polygons.
*/
public void setClipAttribute(ArrayList clipPaths)
{
if (mOutputType != POSTSCRIPT_GEOMETRY)
{
mGraphics2D.setClip(null);
if (clipPaths != null)
{
for (int i = 0; i < clipPaths.size(); i++)
{
GeometricPath clipPath = (GeometricPath)(clipPaths.get(i));
mGraphics2D.clip(clipPath.getShape());
}
}
}
}
/*
* Walk through path, converting it to PostScript.
*/
private void writePostScriptShape(Shape shape)
{
PathIterator pi = shape.getPathIterator(null);
float coords[] = new float[6];
float lastX = 0.0f, lastY = 0.0f;
float x = 0.0f, y = 0.0f;
float distSquared;
float resolutionSquared = (float)(mResolution * mResolution);
int segmentType;
boolean skippedLastSegment = false;
while (!pi.isDone())
{
segmentType = pi.currentSegment(coords);
switch (segmentType)
{
case PathIterator.SEG_MOVETO:
lastX = coords[0];
lastY = coords[1];
writePostScriptLine(lastX + " " + lastY + " m");
skippedLastSegment = false;
break;
case PathIterator.SEG_LINETO:
x = coords[0];
y = coords[1];
distSquared = (lastX - x) * (lastX - x) + (lastY - y) * (lastY - y);
if (distSquared >= resolutionSquared)
{
lastX = x;
lastY = y;
writePostScriptLine(lastX + " " + lastY + " l");
skippedLastSegment = false;
}
else
{
/*
* Skip segments that are less than one unit of resolution in length.
*/
skippedLastSegment = true;
}
break;
case PathIterator.SEG_CLOSE:
if (skippedLastSegment)
writePostScriptLine(x + " " + y + " l");
writePostScriptLine("closepath");
skippedLastSegment = false;
break;
case PathIterator.SEG_CUBICTO:
writePostScriptLine(coords[0] + " " +
coords[1] + " " +
coords[2] + " " +
coords[3] + " " +
coords[4] + " " +
coords[5] + " " +
"curveto");
lastX = coords[4];
lastY = coords[5];
skippedLastSegment = false;
break;
}
pi.next();
}
if (skippedLastSegment)
{
/*
* Always include last point in lines and polygons,
* never skip it.
*/
writePostScriptLine(x + " " + y + " l");
}
}
/**
* Determines single color used in an image.
* @param image image to check.
* @return single non-transparent color used in an image, or null if
* image has many colors.
*/
private Color getSingleImageColor(BufferedImage image)
{
Color singleColor = Color.BLACK;
boolean foundDifferentColors = false;
boolean foundFirstColor = false;
int i = 0;
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
/*
* Check if all pixels are the same color, or transparent.
*/
int y = 0;
while (y < imageHeight && (!foundDifferentColors))
{
int x = 0;
while (x < imageWidth && (!foundDifferentColors))
{
int pixel = image.getRGB(x, y);
if ((pixel & 0xff000000) != 0)
{
/*
* Pixel is not transparent.
*/
if (!foundFirstColor)
{
foundFirstColor = true;
singleColor = new Color(pixel & 0xffffff);
}
else
{
foundDifferentColors = (pixel != singleColor.getRGB());
}
}
x++;
}
y++;
}
if (foundDifferentColors)
singleColor = null;
return(singleColor);
}
/**
* Draw icon at points on page.
* @param pointList is list of Point2D objects at which to draw icon.
* @param icon image to draw.
* @param size is size of icon in millimeters, or zero for screen size.
* @param rotation rotation angle for icon.
* @param scaling scale factor for icon.
*/
public void drawIcon(ArrayList pointList, BufferedImage image, double size,
double rotation, double scaling)
throws IOException, MapyrusException
{
int pixelWidth = image.getWidth();
int pixelHeight = image.getHeight();
Point2D pt;
int i, j;
double x, y, mmWidth, mmHeight;
/*
* If size not given then make icon about as large as it would appear
* on the screen in an image viewer, with one image pixel in one screen
* pixel.
*/
if (size <= 0.0)
{
size = Math.max(pixelWidth, pixelHeight) * (Constants.MM_PER_INCH /
Constants.getScreenResolution());
}
size *= scaling;
/*
* Calculate width and height for non-square images.
*/
if (pixelWidth > pixelHeight)
{
mmWidth = size;
mmHeight = size * ((double)pixelHeight / pixelWidth);
}
else
{
mmHeight = size;
mmWidth = size * ((double)pixelWidth / pixelHeight);
}
if (mOutputType == POSTSCRIPT_GEOMETRY)
{
/*
* Draw icon at each position in list.
*/
for (i = 0; i < pointList.size(); i++)
{
pt = (Point2D)(pointList.get(i));
x = pt.getX();
y = pt.getY();
/*
* Skip points that are outside page.
*/
if (x + mmWidth >= 0 && x - mmWidth <= mPageWidth &&
y + mmHeight >= 0.0 && y - mmHeight <= mPageHeight)
{
writePostScriptImage(image, x, y, mmWidth, mmHeight, rotation);
}
}
}
else
{
for (i = 0; i < pointList.size(); i++)
{
pt = (Point2D)(pointList.get(i));
x = pt.getX();
y = pt.getY();
AffineTransform affine = AffineTransform.getTranslateInstance(x, y);
/*
* Scale transformation so that units are in pixels.
*/
double mmPerPixel = Constants.MM_PER_INCH / Constants.getScreenResolution();
affine.scale(mmPerPixel, mmPerPixel * -1);
/*
* Rotate clockwise around point (x, y).
*/
affine.rotate(-rotation);
/*
* Scale image to requested size.
*/
double xScale = (mmWidth / mmPerPixel) / pixelWidth;
double yScale = (mmHeight / mmPerPixel) / pixelHeight;
affine.scale(xScale, yScale);
/*
* Shift origin so that middle of image is at point (x, y).
*/
affine.translate(-pixelWidth / 2.0, -pixelHeight / 2.0);
try
{
/*
* Sun JVM throws NullPointerException if image is
* too big to fit in memory.
*/
mGraphics2D.drawImage(image, affine, null);
}
catch (NullPointerException e)
{
throw new OutOfMemoryError("Failed loading icon.");
}
}
}
}
/**
* Draw currently defined path to output page.
*/
public void stroke(Shape shape)
{
if (mOutputType == POSTSCRIPT_GEOMETRY)
{
if (shape.intersects(0.0, 0.0, mPageWidth, mPageHeight))
{
writePostScriptShape(shape);
writePostScriptLine("s");
}
}
else
{
/*
* Draw path into image.
*/
mGraphics2D.draw(shape);
}
}
/**
* Fill currently defined path on output page.
*/
public void fill(Shape shape)
{
if (mOutputType == POSTSCRIPT_GEOMETRY)
{
if (shape.intersects(0.0, 0.0, mPageWidth, mPageHeight))
{
writePostScriptShape(shape);
writePostScriptLine("f");
}
}
else
{
/*
* Fill path in image.
*/
mGraphics2D.fill(shape);
}
}
/**
* Set clip region to inside of currently defined path on output page.
*/
public void clip(Shape shape)
{
if (mOutputType == POSTSCRIPT_GEOMETRY)
{
/*
* Set clip path now, then it stays in effect until previous
* state is restored.
*/
if (shape.intersects(0.0, 0.0, mPageWidth, mPageHeight))
{
writePostScriptShape(shape);
}
else
{
/*
* Clip region is outside page. Clip to simple rectangle
* outside page instead so that nothing is shown.
*/
writePostScriptShape(new Rectangle2D.Float(-1.0f, -1.0f, 0.1f, 0.1f));
}
writePostScriptLine("clip newpath");
}
}
/**
* Convert a string to PostScript format, escaping special characters and
* write it to PostScript file.
* @param s is string to convert and write.
*/
private void writePostScriptString(String s)
{
char c;
StringBuffer buffer = new StringBuffer("(");
for (int i = 0; i < s.length(); i++)
{
/*
* Wrap strings that get too long.
*/
if (buffer.length() > 72)
{
buffer.append('\\');
mWriter.println(buffer.toString());
buffer.setLength(0);
}
/*
* Convert backslashes to '\\' and other special characters to octal code.
*/
c = s.charAt(i);
if (c == '\\')
{
buffer.append("\\\\");
}
else if (c == '(' || c == ')' || c == '%' || c < ' ' || c > 'z')
{
int extendedChar = c;
int b1 = extendedChar / (8 * 8);
extendedChar -= b1 * (8 * 8);
int b2 = extendedChar / 8;
extendedChar -= b2 * 8;
int b3 = extendedChar;
buffer.append('\\');
buffer.append(b1);
buffer.append(b2);
buffer.append(b3);
}
else
{
buffer.append(c);
}
}
buffer.append(")");
mWriter.println(buffer.toString());
}
/**
* Draw label positioned at (or along) currently defined path.
* @param pointList is list of Point2D objects at which to draw label.
* @param label is string to draw on path.
*/
public void label(ArrayList pointList, String label)
{
Point2D pt, startPt;
double x, y;
String nextLine;
StringTokenizer st;
int lineNumber;
AffineTransform affine;
FontRenderContext frc = null;
Stroke originalStroke = null;
if (mOutputType != POSTSCRIPT_GEOMETRY)
{
frc = mGraphics2D.getFontRenderContext();
if (mFontOutlineWidth > 0)
{
/*
* Save existing linestyle and create new one for drawing outlines of each letter.
*/
originalStroke = mGraphics2D.getStroke();
BasicStroke outlineStroke = new BasicStroke((float)mFontOutlineWidth,
BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 2.0f);
mGraphics2D.setStroke(outlineStroke);
}
}
/*
* Draw label at each position in list.
*/
for (int i = 0; i < pointList.size(); i++)
{
pt = (Point2D)(pointList.get(i));
x = pt.getX();
y = pt.getY();
/*
* Draw each line of label below the one above.
*/
st = new StringTokenizer(label, Constants.LINE_SEPARATOR);
lineNumber = 0;
while (st.hasMoreTokens())
{
nextLine = st.nextToken();
if (mOutputType == POSTSCRIPT_GEOMETRY)
{
writePostScriptLine(x + " " + y + " m");
/*
* Pass counter and line to PostScript procedure for
* drawing each line of the label.
*/
writePostScriptLine(Integer.toString(lineNumber));
writePostScriptString(nextLine);
writePostScriptLine("t");
}
else
{
/*
* Reposition label from original point so it has correct justification.
*/
if (mJustificationShiftX != 0.0 || mJustificationShiftY != 0.0 || lineNumber > 0)
{
Rectangle2D bounds = mBaseFont.getStringBounds(nextLine, frc);
affine = AffineTransform.getTranslateInstance(x, y);
affine.rotate(mFontRotation);
startPt = new Point2D.Double(bounds.getWidth() * mJustificationShiftX,
bounds.getHeight() * (mJustificationShiftY - lineNumber));
affine.transform(startPt, startPt);
}
else
{
startPt = pt;
}
float fx = (float)startPt.getX();
float fy = (float)startPt.getY();
if (mFontOutlineWidth > 0)
{
/*
* Draw only outline of letters in label as lines.
*/
GlyphVector glyphs = mGraphics2D.getFont().createGlyphVector(frc, nextLine);
Shape outline = glyphs.getOutline(fx, fy);
mGraphics2D.draw(outline);
}
else
{
/*
* Draw plain label.
*/
mGraphics2D.drawString(nextLine, fx, fy);
}
}
lineNumber++;
}
}
if (originalStroke != null)
{
/*
* Restore line style.
*/
mGraphics2D.setStroke(originalStroke);
}
}
}
|
package jp.dip.oyasirazu.artags;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* Artags
*/
public class Artags {
private Artags() { }
/**
* arxml
*
* @param baseDirectories arxml
* @param excludePattern (null )
*
* @return arxml
*/
public static List<Arxml> findArxmls(List<String> baseDirectories, String excludePattern)
throws IOException {
// TODO:
List<Arxml> arxmls = new ArrayList<>();
if (excludePattern == null) {
for (String baseDirectory : baseDirectories) {
arxmls.addAll(findArxmls(baseDirectory));
}
} else {
for (String baseDirectory : baseDirectories) {
arxmls.addAll(findArxmlsWithExclude(baseDirectory, excludePattern));
}
}
return arxmls;
}
/**
* arxml
*
* @param baseDirectory arxml
*
* @return arxml
*/
private static List<Arxml> findArxmls(String baseDirectory)
throws IOException {
// arxml arxmls
List<Arxml> arxmls = new ArrayList<>();
// arxml
Files.walkFileTree(Paths.get(baseDirectory),
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(
Path filePath,
BasicFileAttributes attr) throws IOException {
// arxml
if (filePath.toString().endsWith("arxml")) {
arxmls.add(new Arxml(filePath));
}
return FileVisitResult.CONTINUE;
}
});
return arxmls;
}
/**
* arxml
*
* @param baseDirectory arxml
* @param excludePattern
*
* @return arxml
*/
private static List<Arxml> findArxmlsWithExclude(String baseDirectory, String excludePattern)
throws IOException {
Pattern pattern = Pattern.compile(excludePattern);
// arxml arxmls
List<Arxml> arxmls = new ArrayList<>();
// arxml
Files.walkFileTree(Paths.get(baseDirectory),
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(
Path dir,
BasicFileAttributes attrs) throws IOException {
// excludePattern
Matcher m = pattern.matcher(dir.toString());
boolean isMatch = m.matches();
if (isMatch) {
return FileVisitResult.SKIP_SUBTREE;
} else {
return FileVisitResult.CONTINUE;
}
}
@Override
public FileVisitResult visitFile(
Path filePath,
BasicFileAttributes attr) throws IOException {
// excludePattern
Matcher m = pattern.matcher(filePath.toString());
boolean isMatch = m.matches();
if (isMatch) {
return FileVisitResult.CONTINUE;
}
// arxml
if (filePath.toString().endsWith("arxml")) {
arxmls.add(new Arxml(filePath));
}
return FileVisitResult.CONTINUE;
}
});
return arxmls;
}
/**
* arxml
*
* @param arxml arxml
*
* @return
*/
private static List<Node> searchRefNodes(Arxml arxml) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException {
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
// get reference node list
NodeList refNodeList = (NodeList)xpath.evaluate(
/**
*
*
* @param referredArxml arxml ()
* @param avarableArxmls arxml
*
* @return
*/
public static Set<Record> createTagsString(
Arxml referredArxml,
List<Arxml> avarableArxmls)
throws SAXException,
XPathExpressionException,
TransformerException,
ParserConfigurationException,
IOException {
List<Node> refNodes = searchRefNodes(referredArxml);
// avarableArxmls refNode
Set<Record> tags = refNodes.parallelStream()
.map((n) -> searchNodeElementFromAvarableArxmls(n, avarableArxmls))
.flatMap(v -> v.stream()).collect(Collectors.toSet());
return tags;
}
/**
* arHierarchyPath XPath
*
* @param arHierarchyPath
*
* @return XPath
*/
private static String buildEntitySearchXPath(String arHierarchyPath) {
List<String> splitedArHierarchyPath = Arrays.asList(arHierarchyPath.split("/"));
StringBuilder sb = new StringBuilder();
sb.append("//SHORT-NAME[text()=\"");
int depth = splitedArHierarchyPath.size();
for (int i = 1; i < depth - 1; i++) {
sb.append(splitedArHierarchyPath.get(i));
sb.append("\"]/..//SHORT-NAME[text()=\"");
}
sb.append(splitedArHierarchyPath.get(depth - 1));
sb.append("\"]/..");
return sb.toString();
}
/**
*
*
* 1
* Artags#getPrologLineNumber
*
* @see Artags#getPrologLineNumber
*/
private static long getLineNumber(Node node) {
String beforeLineTextContents = buildBeforeLineTextContents(node);
// 1 +1.
long count = 1;
for (int i = 0; i < beforeLineTextContents.length(); i++) {
if (beforeLineTextContents.charAt(i) == '\n') {
count++;
}
}
return count;
}
private static String buildBeforeLineTextContents(Node node) {
StringBuilder sb = new StringBuilder();
Node parent = node.getParentNode();
if (parent.getNodeType() == Node.DOCUMENT_NODE) {
return sb.toString();
}
sb.append(buildBeforeLineTextContents(parent));
Node loopTarget = node.getPreviousSibling();
while (loopTarget != null) {
sb.append(loopTarget.getTextContent());
loopTarget = loopTarget.getPreviousSibling();
}
return sb.toString();
}
/**
* arxml Document
*
* @param arxmlFilePath arxml
*
* @return arxml Document
*/
private static Document createDocument(Path arxmlFilePath)
throws SAXException,
ParserConfigurationException,
IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(arxmlFilePath.toString());
}
/**
*
* ctags
*
* @param n
* @param avarableArxmls ARXML
*
* @return ctags
*/
public static Set<Record> searchNodeElementFromAvarableArxmls(Node n,
List<Arxml> avarableArxmls) {
String arHierarchyPath = n.getTextContent();
String[] arHierarchyArray = arHierarchyPath.split("/");
String symbol = arHierarchyArray[arHierarchyArray.length - 1];
// XPath
String entitySearchXPath = buildEntitySearchXPath(arHierarchyPath);
// arxml XPath
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
Set<Record> t = new HashSet<>();
for (Arxml arxml : avarableArxmls) {
try {
// prolog
// prolog
long prologLines = getPrologLineNumber(arxml);
NodeList targetNodeList = (NodeList)xpath.evaluate(
entitySearchXPath,
createDocument(arxml.getFilePath()),
XPathConstants.NODESET);
// Set
int targetNodeSize = targetNodeList.getLength();
for (int i = 0; i < targetNodeSize; i++) {
Node targetNode = targetNodeList.item(i);
String lineNumber = String.valueOf(
prologLines + getLineNumber(targetNode));
t.add(new Record(
symbol,
arxml.getFilePath(),
lineNumber,
targetNode.getNodeName(),
arHierarchyPath));
}
} catch (ParserConfigurationException
|SAXException
|XPathExpressionException
|IOException e) {
throw new RuntimeException("filePath : " + arxml.getFilePath() + ".", e);
}
}
return t;
}
/**
* ARXML
*
* @param ARXML
*
* @return ARXML
*/
private static long getPrologLineNumber(Arxml arxml)
throws SAXException, ParserConfigurationException, IOException {
Path arxmlFilePath = arxml.getFilePath();
Document document = createDocument(arxmlFilePath);
String docEncoding = document.getXmlEncoding();
Charset charset;
if (docEncoding != null) {
charset = Charset.forName(docEncoding);
} else {
charset = Charset.forName("UTF-8");
}
// "<AUTOSAR "
Iterator<String> lines = Files.lines(arxmlFilePath, charset).iterator();
long prologLines = 0;
while (lines.hasNext()) {
String line = lines.next();
if (line.contains("<AUTOSAR ")) {
break;
}
prologLines++;
}
return prologLines;
}
// SYMBO\\t.\\PATH\\TO\\FILE\\tSEARCH_STR/;"\\tTYPE\\tAR_HIERARCHY_PATH\\tfile:
@AllArgsConstructor
@Data
public static class Record {
private String symbol;
private Path filePath;
private String searchStr;
private String type;
private String arHierarchyPath;
/**
* 1
*
* @return 1
*/
public String buildRecordString() {
return symbol + "\t" + filePath.toString() + "\t" + searchStr + ";\"\t\t" + arHierarchyPath + " (" + type + ")\tfile:";
}
/**
* 1
*
* basePath
*
* @param basePath basePath
* @return 1
*/
public String buildRecordString(Path basePath) {
Path relativePath = basePath.toAbsolutePath().getParent().relativize(filePath.toAbsolutePath());
return symbol + "\t" + relativePath.toString() + "\t" + searchStr + ";\"\t\t" + arHierarchyPath + " (" + type + ")\tfile:";
}
}
/**
* Artags arxml
*/
@AllArgsConstructor
@Data
public static class Arxml {
private Path filePath;
}
}
|
package instructions;
public class AThrow {
public static void main(String[] args) {
try {
throw new RuntimeException("**RE!");
} catch (RuntimeException e) {
System.out.println(e.getMessage());
}
// RuntimeException e = new RuntimeException();
// System.out.println("OK!");
// e.fillInStackTrace();
}
}
|
package lemming.context.inbound;
import lemming.context.Context;
import java.io.Serializable;
/**
* A triple of context, inbound context, and the distance between them.
*/
public class Triple implements Serializable {
/**
* Context.
*/
private Context context;
/**
* Context index.
*/
private InboundContext inboundContext;
/**
* Index of context.
*/
private Integer contextIndex;
/**
* Index of inbound context.
*/
private Integer inboundContextIndex;
/**
* Distance between context and inbound.
*/
private Integer distance;
/**
* Creates a triple.
*
* @param context context
* @param contextIndex index of context
* @param distance distance between context and inbound context
* @param inboundContext inbound context
* @param inboundContextIndex index of inbound context
* @see MatchHelper
*/
public Triple(Context context, Integer contextIndex, Integer distance,
InboundContext inboundContext, Integer inboundContextIndex) {
this.context = context;
this.contextIndex = contextIndex;
this.distance = distance;
this.inboundContext = inboundContext;
this.inboundContextIndex = inboundContextIndex;
}
/**
* Returns a context.
*
* @return A context.
*/
public Context getContext() {
return context;
}
/**
* Returns an inbound context.
*
* @return An inbound context.
*/
public InboundContext getInboundContext() {
return inboundContext;
}
/**
* Returns index of contex.
*
* @return A context index.
*/
public Integer getContextIndex() {
return contextIndex;
}
/**
* Returns index of inbound context.
*
* @return An inbound context index.
*/
public Integer getInboundContextIndex() {
return inboundContextIndex;
}
/**
* Returns the distance between context and inbound context.
*
* @return A distance as integer.
*/
public Integer getDistance() {
return distance;
}
}
|
package ncku.hpds.hadoop.fedhdfs.shell;
import java.io.ObjectInputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URI;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.Set;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import ncku.hpds.hadoop.fedhdfs.GlobalNamespaceObject;
public class LsTableInfo {
private String address = "127.0.0.1";
private int port = 8764;
public void GlobalNamespaceClient() {
String Uri = "/";
Socket client = new Socket();
ObjectInputStream ObjectIn;
InetSocketAddress isa = new InetSocketAddress(this.address, this.port);
try {
client.connect(isa, 10000);
ObjectIn = new ObjectInputStream(client.getInputStream());
//received object
GlobalNamespaceObject GN = new GlobalNamespaceObject();
try {
GN = (GlobalNamespaceObject) ObjectIn.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("physicalDrive : " + GN.getGlobalNamespace().getLogicalDrive().getLogicalHashTable());
/*for (int i = 0; i < GN.getGlobalNamespace().getLogicalDrive().getLogicalMappingTable().get(Uri).size(); i++) {
if ("VirtualDrive".equalsIgnoreCase(GN.getGlobalNamespace().getLogicalDrive().getLogicalMappingTable().get(Uri).)) {
show.DirFileInfo(status[i].getPath().toString(), conf);
printFilesRecursively(status[i].getPath().toString(), conf);
} else {
try {
show.DirFileInfo(status[i].getPath().toString(), conf);
} catch (Exception e) {
System.err.println(e.toString());
}
}
}*/
System.out.println("fedUserGet2 : " + GN.getGlobalNamespace().getPhysicalDrive().getPhysicalMappingTable().size());
System.out.println("fedUserGet3 : " + GN.showLogicalMapping());
/*System.out.println(GN.getGlobalNamespace().getLogicalDrive().TestgetLogicalMappingTable().get("FedRDD").get("c34").get(1)
+ String.format("%4d", GN.getGlobalNamespace().getLogicalDrive().TestgetLogicalMappingTable().get("FedRDD").get("c34").get(2))
+ " "
+ GN.getGlobalNamespace().getLogicalDrive().TestgetLogicalMappingTable().get("FedRDD").get("c34").get(3)
+ " "
+ GN.getGlobalNamespace().getLogicalDrive().TestgetLogicalMappingTable().get("FedRDD").get("c34").get(4)
+ String.format("%11d", GN.getGlobalNamespace().getLogicalDrive().TestgetLogicalMappingTable().get("FedRDD").get("c34").get(5))
+ " "
+ GN.getGlobalNamespace().getLogicalDrive().TestgetLogicalMappingTable().get("FedRDD").get("c34").get(6)
+ " " + GN.getGlobalNamespace().getLogicalDrive().TestgetLogicalMappingTable().get("FedRDD").get("c34").get(0));
int VirtualSize = GN.getGlobalNamespace().getLogicalDrive().TestgetLogicalMappingTable().size();
Set<String> keySet = GN.getGlobalNamespace().getLogicalDrive().TestgetLogicalMappingTable().keySet();
Iterator<String> it = keySet.iterator();
while(it.hasNext()){
String key = it.next();
LsTableInfo.showInfo(GN, key);
}
for (int i = 0; i < VirtualSize ; i++) {
GN.getGlobalNamespace().getLogicalDrive().TestgetLogicalMappingTable();
}*/
ObjectIn.close();
ObjectIn = null;
client.close();
} catch (java.io.IOException e) {
System.out.println("Socket connection error");
System.out.println("IOException :" + e.toString());
}
}
/*public static void showInfo(GlobalNamespaceObject GN, String key) {
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm");
System.out.println(GN.getGlobalNamespace().getLogicalDrive().TestgetLogicalMappingTable().get(key).get("c34").get(1)
+ String.format("%4d", GN.getGlobalNamespace().getLogicalDrive().TestgetLogicalMappingTable().get(key).get("c34").get(2))
+ " "
+ GN.getGlobalNamespace().getLogicalDrive().TestgetLogicalMappingTable().get(key).get("c34").get(3)
+ " "
+ GN.getGlobalNamespace().getLogicalDrive().TestgetLogicalMappingTable().get(key).get("c34").get(4)
+ String.format("%11d", GN.getGlobalNamespace().getLogicalDrive().TestgetLogicalMappingTable().get(key).get("c34").get(5))
+ " "
+ GN.getGlobalNamespace().getLogicalDrive().TestgetLogicalMappingTable().get(key).get("c34").get(6)
+ " " + GN.getGlobalNamespace().getLogicalDrive().TestgetLogicalMappingTable().get(key).get("c34").get(0));
}*/
}
|
package org.redkale.util;
public final class Redkale {
private Redkale() {
}
public static String getDotedVersion() {
return "1.8.8";
}
public static int getMajorVersion() {
return 1;
}
public static int getMinorVersion() {
return 8;
}
}
|
package org.xwiki.tool.xar;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
/**
* Perform various verifications of the XAR files in this project. Namely:
* <ul>
* <li>ensure that pages all have a parent (except for Main.WebHome)</li>
* <li>ensure that the author/contentAuthor/creator is {@code xwiki:XWiki.Admin}</li>
* <li>ensure that the version is {@code 1.1}</li>
* </ul>
*
* @version $Id$
* @goal verify
* @phase verify
* @requiresProject
* @requiresDependencyResolution compile
* @threadSafe
*/
public class VerifyMojo extends AbstractVerifyMojo
{
/**
* Disables the plugin execution.
*
* @parameter expression="${xar.verify.skip}" default-value="false"
* @since 4.3M1
*/
private boolean skip;
@Override
public void execute() throws MojoExecutionException, MojoFailureException
{
if (this.skip) {
return;
}
// Only format XAR modules or when forced
if (!getProject().getPackaging().equals("xar") && !this.force) {
getLog().info("Not a XAR module, skipping validity check...");
return;
}
getLog().info("Checking validity of XAR XML files...");
boolean hasErrors = false;
for (File file : getXARXMLFiles()) {
String parentName = file.getParentFile().getName();
XWikiDocument xdoc = getDocFromXML(file);
List<String> errors = new ArrayList<String>();
// Verification 1: Verify Encoding is UTF8
if (!xdoc.getEncoding().equals("UTF-8")) {
errors.add(String.format("Encoding must be [UTF-8] but was [%s]", xdoc.getEncoding()));
}
// Verification 2: Verify authors
verifyAuthor(errors, xdoc.getAuthor(), String.format("Author must be [%s] but was [%s]",
AUTHOR, xdoc.getAuthor()));
verifyAuthor(errors, xdoc.getContentAuthor(),
String.format("Content Author must be [%s] but was [%s]",
AUTHOR, xdoc.getContentAuthor()));
verifyAuthor(errors, xdoc.getCreator(), String.format("Creator must be [%s] but was [%s]",
AUTHOR, xdoc.getCreator()));
// Verification 3: Check for orphans, except for Main.WebHome since it's the topmost document
if (StringUtils.isEmpty(xdoc.getParent())
&& !(xdoc.getSpace().equals("Main") && xdoc.getName().equals("WebHome")))
{
errors.add("Parent must not be empty");
}
// Verification 4: Check for version
if (!xdoc.getVersion().equals(VERSION)) {
errors.add(String.format("Version must be [%s] but was [%s]", VERSION, xdoc.getVersion()));
}
// Verification 5: Check for empty comment
if (xdoc.getComment().length() != 0) {
errors.add(String.format("Comment must be empty but was [%s]", xdoc.getComment()));
}
// Verification 6: Check for minor edit is always "false"
if (!xdoc.getMinorEdit().equals("false")) {
errors.add(String.format("Minor edit must always be [false] but was [%s]", xdoc.getMinorEdit()));
}
// Verification 7: Check that default language is empty
if (xdoc.getDefaultLanguage().length() != 0) {
errors.add(String.format("Default Language must be empty but was [%s]", xdoc.getDefaultLanguage()));
}
if (errors.isEmpty()) {
getLog().info(String.format(" Verifying [%s/%s]... ok", parentName, file.getName()));
} else {
getLog().info(String.format(" Verifying [%s/%s]... errors", parentName, file.getName()));
for (String error : errors) {
getLog().info(String.format(" - %s", error));
}
hasErrors = true;
}
}
if (hasErrors) {
throw new MojoFailureException("There are errors in the XAR XML files!");
}
}
private void verifyAuthor(List<String> errors, String author, String message)
{
if (!author.equals(AUTHOR)) {
errors.add(message);
}
}
}
|
package org.jboss.as.domain.management.parsing;
import static javax.xml.stream.XMLStreamConstants.END_ELEMENT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ACCESS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADVANCED_FILTER;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.APPLICATION_CLASSIFICATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.AUDIT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.AUTHENTICATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.AUTHORIZATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CLASSIFICATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CONSTRAINT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CORE_SERVICE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXCLUDE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ENABLED_CIPHER_SUITES;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ENABLED_PROTOCOLS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.GROUP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.GROUP_SEARCH;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.GROUP_TO_PRINCIPAL;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST_SCOPED_ROLE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST_SCOPED_ROLES;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HTTP_INTERFACE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.LDAP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.LDAP_CONNECTION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MANAGEMENT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MANAGEMENT_INTERFACE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MAP_GROUPS_TO_ROLES;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NATIVE_INTERFACE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NATIVE_REMOTING_INTERFACE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PLAIN_TEXT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PRINCIPAL_TO_GROUP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROPERTIES;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REALM;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ROLE_MAPPING;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SECRET;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SENSITIVITY_CLASSIFICATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_GROUP_SCOPED_ROLE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_IDENTITY;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SSL;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.TRUSTSTORE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.TYPE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.USER;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.USERNAME_FILTER;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.USERNAME_IS_DN;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.USERNAME_TO_DN;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.USERS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VAULT_EXPRESSION;
import static org.jboss.as.controller.parsing.ParseUtils.invalidAttributeValue;
import static org.jboss.as.controller.parsing.ParseUtils.isNoNamespaceAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.missingOneOf;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequired;
import static org.jboss.as.controller.parsing.ParseUtils.missingRequiredElement;
import static org.jboss.as.controller.parsing.ParseUtils.readStringAttributeElement;
import static org.jboss.as.controller.parsing.ParseUtils.requireNamespace;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoAttributes;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoContent;
import static org.jboss.as.controller.parsing.ParseUtils.requireSingleAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute;
import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement;
import static org.jboss.as.domain.management.ModelDescriptionConstants.BY_ACCESS_TIME;
import static org.jboss.as.domain.management.ModelDescriptionConstants.BY_SEARCH_TIME;
import static org.jboss.as.domain.management.ModelDescriptionConstants.CACHE;
import static org.jboss.as.domain.management.ModelDescriptionConstants.DEFAULT_DEFAULT_USER;
import static org.jboss.as.domain.management.ModelDescriptionConstants.DEFAULT_USER;
import static org.jboss.as.domain.management.ModelDescriptionConstants.JAAS;
import static org.jboss.as.domain.management.ModelDescriptionConstants.JKS;
import static org.jboss.as.domain.management.ModelDescriptionConstants.KERBEROS;
import static org.jboss.as.domain.management.ModelDescriptionConstants.KEYSTORE_PROVIDER;
import static org.jboss.as.domain.management.ModelDescriptionConstants.KEYTAB;
import static org.jboss.as.domain.management.ModelDescriptionConstants.LOCAL;
import static org.jboss.as.domain.management.ModelDescriptionConstants.PLUG_IN;
import static org.jboss.as.domain.management.ModelDescriptionConstants.PROPERTY;
import static org.jboss.as.domain.management.ModelDescriptionConstants.SECURITY_REALM;
import static org.jboss.as.domain.management.logging.DomainManagementLogger.ROOT_LOGGER;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.ListAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.controller.parsing.Attribute;
import org.jboss.as.controller.parsing.Element;
import org.jboss.as.controller.parsing.Namespace;
import org.jboss.as.controller.parsing.ParseUtils;
import org.jboss.as.domain.management.access.AccessAuthorizationResourceDefinition;
import org.jboss.as.domain.management.access.ApplicationClassificationConfigResourceDefinition;
import org.jboss.as.domain.management.access.ApplicationClassificationTypeResourceDefinition;
import org.jboss.as.domain.management.access.HostScopedRolesResourceDefinition;
import org.jboss.as.domain.management.access.PrincipalResourceDefinition;
import org.jboss.as.domain.management.access.RoleMappingResourceDefinition;
import org.jboss.as.domain.management.access.SensitivityClassificationTypeResourceDefinition;
import org.jboss.as.domain.management.access.SensitivityResourceDefinition;
import org.jboss.as.domain.management.access.ServerGroupScopedRoleResourceDefinition;
import org.jboss.as.domain.management.connections.ldap.LdapConnectionPropertyResourceDefinition;
import org.jboss.as.domain.management.connections.ldap.LdapConnectionResourceDefinition;
import org.jboss.as.domain.management.security.AbstractPlugInAuthResourceDefinition;
import org.jboss.as.domain.management.security.AdvancedUserSearchResourceDefintion;
import org.jboss.as.domain.management.security.BaseLdapGroupSearchResource;
import org.jboss.as.domain.management.security.BaseLdapUserSearchResource;
import org.jboss.as.domain.management.security.GroupToPrincipalResourceDefinition;
import org.jboss.as.domain.management.security.JaasAuthenticationResourceDefinition;
import org.jboss.as.domain.management.security.KerberosAuthenticationResourceDefinition;
import org.jboss.as.domain.management.security.KeystoreAttributes;
import org.jboss.as.domain.management.security.KeytabResourceDefinition;
import org.jboss.as.domain.management.security.LdapAuthenticationResourceDefinition;
import org.jboss.as.domain.management.security.LdapAuthorizationResourceDefinition;
import org.jboss.as.domain.management.security.LdapCacheResourceDefinition;
import org.jboss.as.domain.management.security.LocalAuthenticationResourceDefinition;
import org.jboss.as.domain.management.security.PlugInAuthenticationResourceDefinition;
import org.jboss.as.domain.management.security.PrincipalToGroupResourceDefinition;
import org.jboss.as.domain.management.security.PropertiesAuthenticationResourceDefinition;
import org.jboss.as.domain.management.security.PropertiesAuthorizationResourceDefinition;
import org.jboss.as.domain.management.security.PropertyResourceDefinition;
import org.jboss.as.domain.management.security.SSLServerIdentityResourceDefinition;
import org.jboss.as.domain.management.security.SecretServerIdentityResourceDefinition;
import org.jboss.as.domain.management.security.SecurityRealmResourceDefinition;
import org.jboss.as.domain.management.security.UserIsDnResourceDefintion;
import org.jboss.as.domain.management.security.UserResourceDefinition;
import org.jboss.as.domain.management.security.UserSearchResourceDefintion;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.jboss.staxmapper.XMLExtendedStreamReader;
import org.jboss.staxmapper.XMLExtendedStreamWriter;
public class ManagementXml {
/** Handles config-file specific aspects of parsing and marshalling {@code <management>} elements */
public abstract static class Delegate {
/**
* Parse {@link Element#SECURITY_REALMS} content.
* <p>This default implementation does standard parsing; override to disable.</p>
* @param reader the xml reader
* @param address the address of the parent resource for any added resources
* @param expectedNs the expected namespace for any children
* @param operationsList list to which any operations should be added
* @throws XMLStreamException
*/
protected void parseSecurityRealms(XMLExtendedStreamReader reader, ModelNode address, Namespace expectedNs, List<ModelNode> operationsList) throws XMLStreamException {
ManagementXml.parseSecurityRealms(reader, address, expectedNs, operationsList);
}
/**
* Parse {@link Element#OUTBOUND_CONNECTIONS} content.
* <p>This default implementation does standard parsing; override to disable.</p>
*
* @param reader the xml reader
* @param address the address of the parent resource for any added resources
* @param expectedNs the expected namespace for any children
* @param operationsList list to which any operations should be added
* @throws XMLStreamException
*/
protected void parseOutboundConnections(XMLExtendedStreamReader reader, ModelNode address, Namespace expectedNs, List<ModelNode> operationsList) throws XMLStreamException {
ManagementXml.parseOutboundConnections(reader, address, expectedNs, operationsList);
}
/**
* Parse {@link Element#MANAGEMENT_INTERFACES} content.
* <p>This default implementation throws {@code UnsupportedOperationException}; override to support.</p>
*
* @param reader the xml reader
* @param address the address of the parent resource for any added resources
* @param expectedNs the expected namespace for any children
* @param operationsList list to which any operations should be added
* @throws XMLStreamException
*/
protected void parseManagementInterfaces(XMLExtendedStreamReader reader, ModelNode address, Namespace expectedNs, List<ModelNode> operationsList) throws XMLStreamException {
throw new UnsupportedOperationException();
}
/**
* Parse {@link Element#ACCESS_CONTROL} content.
* <p>This default implementation throws {@code UnsupportedOperationException}; override to support.</p>
*
* @param reader the xml reader
* @param address the address of the parent resource for any added resources
* @param expectedNs the expected namespace for any children
* @param operationsList list to which any operations should be added
* @throws XMLStreamException
*/
protected void parseAccessControl(final XMLExtendedStreamReader reader, final ModelNode address, final Namespace expectedNs,
final List<ModelNode> operationsList) throws XMLStreamException {
// Must override if supported
throw new UnsupportedOperationException();
}
protected void parseAuditLog(final XMLExtendedStreamReader reader, final ModelNode address, final Namespace expectedNs, final List<ModelNode> list) throws XMLStreamException {
//Must override if supported
throw new UnsupportedOperationException();
}
/**
* Write the {@link Element#NATIVE_INTERFACE} element.
* <p>This default implementation does standard writing</p>
*
* @param writer the xml writer
* @param accessAuthorization the access=authorization configuration
* @throws XMLStreamException
*/
protected void writeAccessControl(XMLExtendedStreamWriter writer, ModelNode accessAuthorization) throws XMLStreamException {
ManagementXml.writeAccessControl(writer, accessAuthorization);
}
/**
* Write the {@link Element#NATIVE_INTERFACE} element.
* <p>This default implementation throws {@code UnsupportedOperationException}; override to support.</p>
*
* @param writer the xml writer
* @param protocol the interface configuration
* @throws XMLStreamException
*/
protected void writeNativeManagementProtocol(XMLExtendedStreamWriter writer, ModelNode protocol) throws XMLStreamException {
// Must override if supported
throw new UnsupportedOperationException();
}
/**
* Write the {@link Element#HTTP_INTERFACE} element.
* <p>This default implementation throws {@code UnsupportedOperationException}; override to support.</p>
*
* @param writer the xml writer
* @param protocol the interface configuration
* @throws XMLStreamException
*/
protected void writeHttpManagementProtocol(XMLExtendedStreamWriter writer, ModelNode protocol) throws XMLStreamException {
// Must override if supported
throw new UnsupportedOperationException();
}
protected void writeAuditLog(XMLExtendedStreamWriter writer, ModelNode auditLog) throws XMLStreamException {
// Must override if supported
throw new UnsupportedOperationException();
}
}
private final Delegate delegate;
public ManagementXml(Delegate delegate) {
this.delegate = delegate;
}
public void parseManagement(final XMLExtendedStreamReader reader, final ModelNode address, final Namespace expectedNs,
final List<ModelNode> list, boolean requireNativeInterface) throws XMLStreamException {
switch (expectedNs) {
case DOMAIN_1_0:
case DOMAIN_1_1:
case DOMAIN_1_2:
case DOMAIN_1_3:
case DOMAIN_1_4:
parseManagement_1_0(reader, address, expectedNs, list, requireNativeInterface);
break;
default:
parseManagement_1_5(reader, address, expectedNs, list, requireNativeInterface);
}
}
private void parseManagement_1_0(final XMLExtendedStreamReader reader, final ModelNode address, final Namespace expectedNs,
final List<ModelNode> list, boolean requireNativeInterface) throws XMLStreamException {
int securityRealmsCount = 0;
int connectionsCount = 0;
int managementInterfacesCount = 0;
final ModelNode managementAddress = address.clone().add(CORE_SERVICE, MANAGEMENT);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case SECURITY_REALMS: {
if (++securityRealmsCount > 1) {
throw unexpectedElement(reader);
}
delegate.parseSecurityRealms(reader, managementAddress, expectedNs, list);
break;
}
case OUTBOUND_CONNECTIONS: {
if (++connectionsCount > 1) {
throw unexpectedElement(reader);
}
delegate.parseOutboundConnections(reader, managementAddress, expectedNs, list);
break;
}
case MANAGEMENT_INTERFACES: {
if (++managementInterfacesCount > 1) {
throw unexpectedElement(reader);
}
delegate.parseManagementInterfaces(reader, managementAddress, expectedNs, list);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
if (requireNativeInterface && managementInterfacesCount < 1) {
throw missingRequiredElement(reader, EnumSet.of(Element.MANAGEMENT_INTERFACES));
}
}
private void parseManagement_1_5(final XMLExtendedStreamReader reader, final ModelNode address, final Namespace expectedNs,
final List<ModelNode> list, boolean requireNativeInterface) throws XMLStreamException {
int securityRealmsCount = 0;
int connectionsCount = 0;
int managementInterfacesCount = 0;
final ModelNode managementAddress = address.clone().add(CORE_SERVICE, MANAGEMENT);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case SECURITY_REALMS: {
if (++securityRealmsCount > 1) {
throw unexpectedElement(reader);
}
delegate.parseSecurityRealms(reader, managementAddress, expectedNs, list);
break;
}
case OUTBOUND_CONNECTIONS: {
if (++connectionsCount > 1) {
throw unexpectedElement(reader);
}
delegate.parseOutboundConnections(reader, managementAddress, expectedNs, list);
break;
}
case MANAGEMENT_INTERFACES: {
if (++managementInterfacesCount > 1) {
throw unexpectedElement(reader);
}
delegate.parseManagementInterfaces(reader, managementAddress, expectedNs, list);
break;
}
case AUDIT_LOG: {
delegate.parseAuditLog(reader, managementAddress, expectedNs, list);
break;
}
case ACCESS_CONTROL: {
delegate.parseAccessControl(reader, managementAddress, expectedNs, list);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
if (requireNativeInterface && managementInterfacesCount < 1) {
throw missingRequiredElement(reader, EnumSet.of(Element.MANAGEMENT_INTERFACES));
}
}
private static void parseOutboundConnections(final XMLExtendedStreamReader reader, final ModelNode address, final Namespace expectedNs,
final List<ModelNode> list) throws XMLStreamException {
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case LDAP: {
switch (expectedNs) {
case DOMAIN_1_0:
case DOMAIN_1_1:
case DOMAIN_1_2:
case DOMAIN_1_3:
parseLdapConnection_1_0(reader, address, list);
break;
case DOMAIN_1_4:
case DOMAIN_1_5:
parseLdapConnection_1_4(reader, address, list);
break;
case DOMAIN_2_0:
parseLdapConnection_2_0(reader, address, expectedNs, list);
break;
default:
// Most recent versions for 1.x, 2.x and 3.x streams converge at this point.
parseLdapConnection_1_6_and_2_1(reader, address, expectedNs, list);
break;
}
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parseLdapConnection_1_0(final XMLExtendedStreamReader reader, final ModelNode address, final List<ModelNode> list)
throws XMLStreamException {
final ModelNode add = new ModelNode();
add.get(OP).set(ADD);
list.add(add);
Set<Attribute> required = EnumSet.of(Attribute.NAME, Attribute.URL, Attribute.SEARCH_DN, Attribute.SEARCH_CREDENTIAL);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME: {
add.get(OP_ADDR).set(address).add(LDAP_CONNECTION, value);
break;
}
case URL: {
LdapConnectionResourceDefinition.URL.parseAndSetParameter(value, add, reader);
break;
}
case SEARCH_DN: {
LdapConnectionResourceDefinition.SEARCH_DN.parseAndSetParameter(value, add, reader);
break;
}
case SEARCH_CREDENTIAL: {
LdapConnectionResourceDefinition.SEARCH_CREDENTIAL.parseAndSetParameter(value, add, reader);
break;
}
case INITIAL_CONTEXT_FACTORY: {
LdapConnectionResourceDefinition.INITIAL_CONTEXT_FACTORY.parseAndSetParameter(value, add, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (required.size() > 0) {
throw missingRequired(reader, required);
}
requireNoContent(reader);
}
private static void parseLdapConnection_1_4(final XMLExtendedStreamReader reader, final ModelNode address, final List<ModelNode> list)
throws XMLStreamException {
final ModelNode add = new ModelNode();
add.get(OP).set(ADD);
list.add(add);
Set<Attribute> required = EnumSet.of(Attribute.NAME, Attribute.URL);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME: {
add.get(OP_ADDR).set(address).add(LDAP_CONNECTION, value);
break;
}
case URL: {
LdapConnectionResourceDefinition.URL.parseAndSetParameter(value, add, reader);
break;
}
case SEARCH_DN: {
LdapConnectionResourceDefinition.SEARCH_DN.parseAndSetParameter(value, add, reader);
break;
}
case SEARCH_CREDENTIAL: {
LdapConnectionResourceDefinition.SEARCH_CREDENTIAL.parseAndSetParameter(value, add, reader);
break;
}
case SECURITY_REALM: {
LdapConnectionResourceDefinition.SECURITY_REALM.parseAndSetParameter(value, add, reader);
break;
}
case INITIAL_CONTEXT_FACTORY: {
LdapConnectionResourceDefinition.INITIAL_CONTEXT_FACTORY.parseAndSetParameter(value, add, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (required.size() > 0) {
throw missingRequired(reader, required);
}
requireNoContent(reader);
}
private static void parseLdapConnection_2_0(final XMLExtendedStreamReader reader, final ModelNode address, final Namespace expectedNs, final List<ModelNode> list)
throws XMLStreamException {
final ModelNode add = new ModelNode();
add.get(OP).set(ADD);
list.add(add);
ModelNode connectionAddress = null;
Set<Attribute> required = EnumSet.of(Attribute.NAME, Attribute.URL);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME: {
connectionAddress = address.clone().add(LDAP_CONNECTION, value);
add.get(OP_ADDR).set(connectionAddress);
break;
}
case URL: {
LdapConnectionResourceDefinition.URL.parseAndSetParameter(value, add, reader);
break;
}
case SEARCH_DN: {
LdapConnectionResourceDefinition.SEARCH_DN.parseAndSetParameter(value, add, reader);
break;
}
case SEARCH_CREDENTIAL: {
LdapConnectionResourceDefinition.SEARCH_CREDENTIAL.parseAndSetParameter(value, add, reader);
break;
}
case SECURITY_REALM: {
LdapConnectionResourceDefinition.SECURITY_REALM.parseAndSetParameter(value, add, reader);
break;
}
case INITIAL_CONTEXT_FACTORY: {
LdapConnectionResourceDefinition.INITIAL_CONTEXT_FACTORY.parseAndSetParameter(value, add, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (required.size() > 0) {
throw missingRequired(reader, required);
}
boolean propertiesFound = false;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case PROPERTIES: {
if (propertiesFound) {
throw unexpectedElement(reader);
}
propertiesFound = true;
parseLdapConnectionProperties(reader, connectionAddress, expectedNs, list);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parseLdapConnection_1_6_and_2_1(final XMLExtendedStreamReader reader, final ModelNode address, final Namespace expectedNs, final List<ModelNode> list)
throws XMLStreamException {
final ModelNode add = new ModelNode();
add.get(OP).set(ADD);
list.add(add);
ModelNode connectionAddress = null;
Set<Attribute> required = EnumSet.of(Attribute.NAME, Attribute.URL);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME: {
connectionAddress = address.clone().add(LDAP_CONNECTION, value);
add.get(OP_ADDR).set(connectionAddress);
break;
}
case URL: {
LdapConnectionResourceDefinition.URL.parseAndSetParameter(value, add, reader);
break;
}
case SEARCH_DN: {
LdapConnectionResourceDefinition.SEARCH_DN.parseAndSetParameter(value, add, reader);
break;
}
case SEARCH_CREDENTIAL: {
LdapConnectionResourceDefinition.SEARCH_CREDENTIAL.parseAndSetParameter(value, add, reader);
break;
}
case SECURITY_REALM: {
LdapConnectionResourceDefinition.SECURITY_REALM.parseAndSetParameter(value, add, reader);
break;
}
case INITIAL_CONTEXT_FACTORY: {
LdapConnectionResourceDefinition.INITIAL_CONTEXT_FACTORY.parseAndSetParameter(value, add, reader);
break;
}
case REFERRALS: {
LdapConnectionResourceDefinition.REFERRALS.parseAndSetParameter(value, add, reader);
break;
}
case HANDLES_REFERRALS_FOR: {
for (String url : reader.getListAttributeValue(i)) {
LdapConnectionResourceDefinition.HANDLES_REFERRALS_FOR.parseAndAddParameterElement(url, add, reader);
}
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (required.size() > 0) {
throw missingRequired(reader, required);
}
boolean propertiesFound = false;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case PROPERTIES: {
if (propertiesFound) {
throw unexpectedElement(reader);
}
propertiesFound = true;
parseLdapConnectionProperties(reader, connectionAddress, expectedNs, list);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parseLdapConnectionProperties(final XMLExtendedStreamReader reader, final ModelNode address,
final Namespace expectedNs, final List<ModelNode> list) throws XMLStreamException {
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case PROPERTY: {
Set<Attribute> required = EnumSet.of(Attribute.NAME, Attribute.VALUE);
final ModelNode add = new ModelNode();
add.get(OP).set(ADD);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME: {
add.get(OP_ADDR).set(address.clone()).add(PROPERTY, value);
break;
}
case VALUE: {
LdapConnectionPropertyResourceDefinition.VALUE.parseAndSetParameter(value, add, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (required.size() > 0) {
throw missingRequired(reader, required);
}
requireNoContent(reader);
list.add(add);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parseSecurityRealms(final XMLExtendedStreamReader reader, final ModelNode address, final Namespace expectedNs, final List<ModelNode> list)
throws XMLStreamException {
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case SECURITY_REALM: {
switch (expectedNs) {
case DOMAIN_1_0:
parseSecurityRealm_1_0(reader, address, expectedNs, list);
break;
case DOMAIN_1_1:
case DOMAIN_1_2:
parseSecurityRealm_1_1(reader, address, expectedNs, list);
break;
default:
parseSecurityRealm_1_3(reader, address, expectedNs, list);
break;
}
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parseSecurityRealm_1_0(final XMLExtendedStreamReader reader, final ModelNode address, final Namespace expectedNs, final List<ModelNode> list)
throws XMLStreamException {
requireSingleAttribute(reader, Attribute.NAME.getLocalName());
// After double checking the name of the only attribute we can retrieve it.
final String realmName = reader.getAttributeValue(0);
final ModelNode realmAddress = address.clone();
realmAddress.add(SECURITY_REALM, realmName);
final ModelNode add = new ModelNode();
add.get(OP_ADDR).set(realmAddress);
add.get(OP).set(ADD);
list.add(add);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case SERVER_IDENTITIES:
parseServerIdentities_1_0(reader, expectedNs, realmAddress, list);
break;
case AUTHENTICATION: {
parseAuthentication_1_0(reader, expectedNs, realmAddress, list);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parseSecurityRealm_1_1(final XMLExtendedStreamReader reader, final ModelNode address, final Namespace expectedNs, final List<ModelNode> list)
throws XMLStreamException {
requireSingleAttribute(reader, Attribute.NAME.getLocalName());
// After double checking the name of the only attribute we can retrieve it.
final String realmName = reader.getAttributeValue(0);
final ModelNode realmAddress = address.clone();
realmAddress.add(SECURITY_REALM, realmName);
final ModelNode add = new ModelNode();
add.get(OP_ADDR).set(realmAddress);
add.get(OP).set(ADD);
list.add(add);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case SERVER_IDENTITIES:
parseServerIdentities_1_0(reader, expectedNs, realmAddress, list);
break;
case AUTHENTICATION: {
parseAuthentication_1_1(reader, expectedNs, realmAddress, list);
break;
}
case AUTHORIZATION:
parseAuthorization_1_1(reader, expectedNs, add, list);
break;
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parseSecurityRealm_1_3(final XMLExtendedStreamReader reader, final ModelNode address, final Namespace expectedNs, final List<ModelNode> list)
throws XMLStreamException {
requireSingleAttribute(reader, Attribute.NAME.getLocalName());
// After double checking the name of the only attribute we can retrieve it.
final String realmName = reader.getAttributeValue(0);
final ModelNode realmAddress = address.clone();
realmAddress.add(SECURITY_REALM, realmName);
final ModelNode add = new ModelNode();
add.get(OP_ADDR).set(realmAddress);
add.get(OP).set(ADD);
list.add(add);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case PLUG_INS:
parsePlugIns(reader, expectedNs, realmAddress, list);
break;
case SERVER_IDENTITIES:
switch (expectedNs.getMajorVersion()) {
case 1:
case 2:
parseServerIdentities_1_0(reader, expectedNs, realmAddress, list);
break;
default:
parseServerIdentities_3_0(reader, expectedNs, realmAddress, list);
}
break;
case AUTHENTICATION: {
switch (expectedNs.getMajorVersion()) {
case 1:
case 2:
parseAuthentication_1_3(reader, expectedNs, realmAddress, list);
break;
default:
parseAuthentication_3_0(reader, expectedNs, realmAddress, list);
}
break;
}
case AUTHORIZATION:
switch (expectedNs) {
case DOMAIN_1_3:
case DOMAIN_1_4:
parseAuthorization_1_3(reader, expectedNs, realmAddress, list);
break;
default:
parseAuthorization_1_5_and_2_0(reader, expectedNs, add, list);
}
break;
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parsePlugIns(final XMLExtendedStreamReader reader, final Namespace expectedNs, final ModelNode realmAddress, final List<ModelNode> list)
throws XMLStreamException {
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case PLUG_IN: {
ModelNode plugIn = new ModelNode();
plugIn.get(OP).set(ADD);
String moduleValue = readStringAttributeElement(reader, Attribute.MODULE.getLocalName());
final ModelNode newAddress = realmAddress.clone();
newAddress.add(PLUG_IN, moduleValue);
plugIn.get(OP_ADDR).set(newAddress);
list.add(plugIn);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parseServerIdentities_1_0(final XMLExtendedStreamReader reader, final Namespace expectedNs, final ModelNode realmAddress, final List<ModelNode> list)
throws XMLStreamException {
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case SECRET: {
parseSecret(reader, realmAddress, list);
break;
}
case SSL: {
if (expectedNs.getMajorVersion() == 1) {
// This is only needed until we port version 1.7 of the schema from EAP to here
// and then the 1.x versions will also be listed in the switch below.
parseSSL_1_0(reader, expectedNs, realmAddress, list);
} else {
switch (expectedNs) {
case DOMAIN_2_0:
case DOMAIN_2_1:
parseSSL_1_0(reader, expectedNs, realmAddress, list);
break;
default:
parseSSL_2_2(reader, expectedNs, realmAddress, list);
break;
}
}
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parseServerIdentities_3_0(final XMLExtendedStreamReader reader, final Namespace expectedNs, final ModelNode realmAddress, final List<ModelNode> list)
throws XMLStreamException {
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case SECRET: {
parseSecret(reader, realmAddress, list);
break;
}
case SSL: {
parseSSL_2_2(reader, expectedNs, realmAddress, list);
break;
}
case KERBEROS: {
parseKerberosIdentity(reader, expectedNs, realmAddress, list);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parseSecret(final XMLExtendedStreamReader reader, final ModelNode realmAddress, final List<ModelNode> list)
throws XMLStreamException {
ModelNode secret = new ModelNode();
secret.get(OP).set(ADD);
secret.get(OP_ADDR).set(realmAddress).add(SERVER_IDENTITY, SECRET);
String secretValue = readStringAttributeElement(reader, Attribute.VALUE.getLocalName());
SecretServerIdentityResourceDefinition.VALUE.parseAndSetParameter(secretValue, secret, reader);
list.add(secret);
}
private static void parseSSL_1_0(final XMLExtendedStreamReader reader, final Namespace expectedNs, final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException {
ModelNode ssl = new ModelNode();
ssl.get(OP).set(ADD);
ssl.get(OP_ADDR).set(realmAddress).add(SERVER_IDENTITY, SSL);
list.add(ssl);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case PROTOCOL: {
SSLServerIdentityResourceDefinition.PROTOCOL.parseAndSetParameter(value, ssl, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case KEYSTORE: {
switch (expectedNs) {
case DOMAIN_1_0:
case DOMAIN_1_1:
case DOMAIN_1_2:
parseKeystore_1_0(reader, ssl);
break;
case DOMAIN_1_3:
case DOMAIN_1_4:
case DOMAIN_1_5:
case DOMAIN_2_0:
parseKeystore_1_3(reader, ssl, true);
break;
default:
// Most recent versions for 1.x, 2.x and 3.x streams converge at this point.
parseKeystore_1_6_and_2_1(reader, ssl, true);
}
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parseSSL_2_2(final XMLExtendedStreamReader reader, final Namespace expectedNs, final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException {
ModelNode ssl = new ModelNode();
ssl.get(OP).set(ADD);
ssl.get(OP_ADDR).set(realmAddress).add(SERVER_IDENTITY, SSL);
list.add(ssl);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case PROTOCOL: {
SSLServerIdentityResourceDefinition.PROTOCOL.parseAndSetParameter(value, ssl, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case ENGINE: {
parseEngine(reader, ssl);
break;
}
case KEYSTORE: {
// Most recent versions for 1.x, 2.x and 3.x streams converge at this point.
parseKeystore_1_6_and_2_1(reader, ssl, true);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parseEngine(final XMLExtendedStreamReader reader, final ModelNode addOperation)
throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case ENABLED_CIPHER_SUITES:
for (String value : reader.getListAttributeValue(i)) {
SSLServerIdentityResourceDefinition.ENABLED_CIPHER_SUITES.parseAndAddParameterElement(value, addOperation, reader);
}
break;
case ENABLED_PROTOCOLS: {
for (String value : reader.getListAttributeValue(i)) {
SSLServerIdentityResourceDefinition.ENABLED_PROTOCOLS.parseAndAddParameterElement(value, addOperation, reader);
}
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
requireNoContent(reader);
}
private static void parseKeystore_1_0(final XMLExtendedStreamReader reader, final ModelNode addOperation)
throws XMLStreamException {
Set<Attribute> required = EnumSet.of(Attribute.PATH, Attribute.PASSWORD);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case PATH:
KeystoreAttributes.KEYSTORE_PATH.parseAndSetParameter(value, addOperation, reader);
break;
case PASSWORD: {
KeystoreAttributes.KEYSTORE_PASSWORD.parseAndSetParameter(value, addOperation, reader);
break;
}
case RELATIVE_TO: {
KeystoreAttributes.KEYSTORE_RELATIVE_TO.parseAndSetParameter(value, addOperation, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (required.size() > 0) {
throw missingRequired(reader, required);
}
requireNoContent(reader);
}
private static void parseKeystore_1_3(final XMLExtendedStreamReader reader, final ModelNode addOperation, final boolean extended)
throws XMLStreamException {
Set<Attribute> required = EnumSet.of(Attribute.PATH, Attribute.KEYSTORE_PASSWORD);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case PATH:
KeystoreAttributes.KEYSTORE_PATH.parseAndSetParameter(value, addOperation, reader);
break;
case PASSWORD: {
// TODO - Support for this attribute can later be removed, would suggest removing at the
// start of AS 8 development.
ROOT_LOGGER.passwordAttributeDeprecated();
required.remove(Attribute.KEYSTORE_PASSWORD);
KeystoreAttributes.KEYSTORE_PASSWORD.parseAndSetParameter(value, addOperation, reader);
break;
}
case KEYSTORE_PASSWORD: {
KeystoreAttributes.KEYSTORE_PASSWORD.parseAndSetParameter(value, addOperation, reader);
break;
}
case RELATIVE_TO: {
KeystoreAttributes.KEYSTORE_RELATIVE_TO.parseAndSetParameter(value, addOperation, reader);
break;
}
/*
* The 'extended' attributes when a true keystore and not just a keystore acting as a truststore.
*/
case ALIAS: {
if (extended) {
KeystoreAttributes.ALIAS.parseAndSetParameter(value, addOperation, reader);
} else {
throw unexpectedAttribute(reader, i);
}
break;
}
case KEY_PASSWORD: {
if (extended) {
KeystoreAttributes.KEY_PASSWORD.parseAndSetParameter(value, addOperation, reader);
} else {
throw unexpectedAttribute(reader, i);
}
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (required.size() > 0) {
throw missingRequired(reader, required);
}
requireNoContent(reader);
}
private static void parseKeystore_1_6_and_2_1(final XMLExtendedStreamReader reader, final ModelNode addOperation, final boolean extended)
throws XMLStreamException {
boolean keystorePasswordSet = false;
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case PROVIDER:
KeystoreAttributes.KEYSTORE_PROVIDER.parseAndSetParameter(value, addOperation, reader);
break;
case PATH:
KeystoreAttributes.KEYSTORE_PATH.parseAndSetParameter(value, addOperation, reader);
break;
case KEYSTORE_PASSWORD: {
KeystoreAttributes.KEYSTORE_PASSWORD.parseAndSetParameter(value, addOperation, reader);
keystorePasswordSet = true;
break;
}
case RELATIVE_TO: {
KeystoreAttributes.KEYSTORE_RELATIVE_TO.parseAndSetParameter(value, addOperation, reader);
break;
}
/*
* The 'extended' attributes when a true keystore and not just a keystore acting as a truststore.
*/
case ALIAS: {
if (extended) {
KeystoreAttributes.ALIAS.parseAndSetParameter(value, addOperation, reader);
} else {
throw unexpectedAttribute(reader, i);
}
break;
}
case KEY_PASSWORD: {
if (extended) {
KeystoreAttributes.KEY_PASSWORD.parseAndSetParameter(value, addOperation, reader);
} else {
throw unexpectedAttribute(reader, i);
}
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
/*
* The only mandatory attribute now is the KEYSTORE_PASSWORD.
*/
if (keystorePasswordSet == false) {
throw missingRequired(reader, EnumSet.of(Attribute.KEYSTORE_PASSWORD));
}
requireNoContent(reader);
}
private static void parseKerberosIdentity(final XMLExtendedStreamReader reader, final Namespace expectedNs,
final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException {
ModelNode kerberos = new ModelNode();
kerberos.get(OP).set(ADD);
ModelNode kerberosAddress = realmAddress.clone().add(SERVER_IDENTITY, KERBEROS);
kerberos.get(OP_ADDR).set(kerberosAddress);
list.add(kerberos);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case KEYTAB:
parseKeyTab(reader, expectedNs, kerberosAddress, list);
break;
default:
throw unexpectedElement(reader);
}
}
}
private static void parseKeyTab(final XMLExtendedStreamReader reader, final Namespace expectedNs,
final ModelNode parentAddress, final List<ModelNode> list) throws XMLStreamException {
ModelNode keytab = new ModelNode();
keytab.get(OP).set(ADD);
list.add(keytab);
Set<Attribute> requiredAttributes = EnumSet.of(Attribute.PRINCIPAL, Attribute.PATH);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
requiredAttributes.remove(attribute);
switch (attribute) {
case PRINCIPAL:
keytab.get(OP_ADDR).set(parentAddress).add(KEYTAB, value);
break;
case PATH:
KeytabResourceDefinition.PATH.parseAndSetParameter(value, keytab, reader);
break;
case RELATIVE_TO:
KeytabResourceDefinition.RELATIVE_TO.parseAndSetParameter(value, keytab, reader);
break;
case FOR_HOSTS:
for (String host : reader.getListAttributeValue(i)) {
KeytabResourceDefinition.FOR_HOSTS.parseAndAddParameterElement(host, keytab, reader);
}
break;
case DEBUG:
KeytabResourceDefinition.DEBUG.parseAndSetParameter(value, keytab, reader);
break;
default:
throw unexpectedAttribute(reader, i);
}
}
}
// This would pick up if the address for the operation has not yet been set.
if (requiredAttributes.isEmpty() == false) {
throw missingRequired(reader, requiredAttributes);
}
requireNoContent(reader);
}
private static void parseAuthentication_1_0(final XMLExtendedStreamReader reader, final Namespace expectedNs, final ModelNode realmAddress, final List<ModelNode> list)
throws XMLStreamException {
int userCount = 0;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
// Only a single user element within the authentication element is currently supported.
if (++userCount > 1) {
throw unexpectedElement(reader);
}
switch (element) {
case LDAP: {
parseLdapAuthentication_1_0(reader, realmAddress, list);
break;
}
case PROPERTIES: {
parsePropertiesAuthentication_1_0(reader, realmAddress, list);
break;
}
case USERS: {
parseUsersAuthentication(reader, expectedNs, realmAddress, list);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
addLegacyLocalAuthentication(realmAddress, list);
}
private static void parseAuthentication_1_1(final XMLExtendedStreamReader reader, final Namespace expectedNs,
final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException {
// Only one truststore can be defined.
boolean trustStoreFound = false;
// Only one of ldap, properties or users can be defined.
boolean usernamePasswordFound = false;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case JAAS: {
if (usernamePasswordFound) {
throw unexpectedElement(reader);
}
parseJaasAuthentication_1_1(reader, realmAddress, list);
usernamePasswordFound = true;
break;
}
case LDAP: {
if (usernamePasswordFound) {
throw unexpectedElement(reader);
}
parseLdapAuthentication_1_1(reader, expectedNs, realmAddress, list);
usernamePasswordFound = true;
break;
}
case PROPERTIES: {
if (usernamePasswordFound) {
throw unexpectedElement(reader);
}
parsePropertiesAuthentication_1_1(reader, realmAddress, list);
usernamePasswordFound = true;
break;
}
case TRUSTSTORE: {
if (trustStoreFound) {
throw unexpectedElement(reader);
}
parseTruststore(reader, expectedNs, realmAddress, list);
trustStoreFound = true;
break;
}
case USERS: {
if (usernamePasswordFound) {
throw unexpectedElement(reader);
}
parseUsersAuthentication(reader, expectedNs, realmAddress, list);
usernamePasswordFound = true;
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
addLegacyLocalAuthentication(realmAddress, list);
}
private static void parseAuthentication_1_3(final XMLExtendedStreamReader reader, final Namespace expectedNs,
final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException {
// Only one truststore can be defined.
boolean trustStoreFound = false;
// Only one local can be defined.
boolean localFound = false;
// Only one of ldap, properties or users can be defined.
boolean usernamePasswordFound = false;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case JAAS: {
if (usernamePasswordFound) {
throw unexpectedElement(reader);
}
switch (expectedNs) {
case DOMAIN_1_3:
case DOMAIN_1_4:
case DOMAIN_1_5:
parseJaasAuthentication_1_1(reader, realmAddress, list);
break;
default:
switch (expectedNs.getMajorVersion()) {
case 2: // i.e. 2.0 up to but not including 3.0
parseJaasAuthentication_1_1(reader, realmAddress, list);
break;
default: // i.e. 1 and 3, most specifically 1.6 and onwards and 3.0 and onwards.
parseJaasAuthentication_1_6_and_3_0(reader, realmAddress, list);
break;
}
}
usernamePasswordFound = true;
break;
}
case LDAP: {
if (usernamePasswordFound) {
throw unexpectedElement(reader);
}
// This method is specific to version 1.3 of the schema and beyond - no need to
// consider namespaces before this point.
switch (expectedNs) {
case DOMAIN_1_3:
parseLdapAuthentication_1_1(reader, expectedNs, realmAddress, list);
break;
default:
switch (expectedNs.getMajorVersion()) {
case 1:
parseLdapAuthentication_1_4(reader, expectedNs, realmAddress, list);
break;
default:
parseLdapAuthentication_2_0(reader, expectedNs, realmAddress, list);
break;
}
}
usernamePasswordFound = true;
break;
}
case PROPERTIES: {
if (usernamePasswordFound) {
throw unexpectedElement(reader);
}
parsePropertiesAuthentication_1_1(reader, realmAddress, list);
usernamePasswordFound = true;
break;
}
case TRUSTSTORE: {
if (trustStoreFound) {
throw unexpectedElement(reader);
}
parseTruststore(reader, expectedNs, realmAddress, list);
trustStoreFound = true;
break;
}
case USERS: {
if (usernamePasswordFound) {
throw unexpectedElement(reader);
}
parseUsersAuthentication(reader, expectedNs, realmAddress, list);
usernamePasswordFound = true;
break;
}
case PLUG_IN: {
if (usernamePasswordFound) {
throw unexpectedElement(reader);
}
ModelNode parentAddress = realmAddress.clone().add(AUTHENTICATION);
parsePlugIn_Authentication(reader, expectedNs, parentAddress, list);
usernamePasswordFound = true;
break;
}
case LOCAL: {
if (localFound) {
throw unexpectedElement(reader);
}
switch (expectedNs) {
case DOMAIN_2_0:
parseLocalAuthentication_1_3(reader, expectedNs, realmAddress, list);
break;
default:
switch (expectedNs.getMajorVersion()) {
case 1:
// 1.3 up to but not including 2.0.
parseLocalAuthentication_1_3(reader, expectedNs, realmAddress, list);
break;
default:
parseLocalAuthentication_2_1(reader, expectedNs, realmAddress, list);
break;
}
}
localFound = true;
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parseAuthentication_3_0(final XMLExtendedStreamReader reader, final Namespace expectedNs,
final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException {
// Only one truststore can be defined.
boolean trustStoreFound = false;
// Only one local can be defined.
boolean localFound = false;
// Only one kerberos can be defined.
boolean kerberosFound = false;
// Only one of ldap, properties or users can be defined.
boolean usernamePasswordFound = false;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case JAAS: {
if (usernamePasswordFound) {
throw unexpectedElement(reader);
}
parseJaasAuthentication_1_6_and_3_0(reader, realmAddress, list);
usernamePasswordFound = true;
break;
}
case KERBEROS: {
if (kerberosFound) {
throw unexpectedElement(reader);
}
parseKerberosAuthentication_3_0(reader, realmAddress, list);
kerberosFound = true;
break;
}
case LDAP: {
if (usernamePasswordFound) {
throw unexpectedElement(reader);
}
parseLdapAuthentication_2_0(reader, expectedNs, realmAddress, list);
usernamePasswordFound = true;
break;
}
case PROPERTIES: {
if (usernamePasswordFound) {
throw unexpectedElement(reader);
}
parsePropertiesAuthentication_1_1(reader, realmAddress, list);
usernamePasswordFound = true;
break;
}
case TRUSTSTORE: {
if (trustStoreFound) {
throw unexpectedElement(reader);
}
parseTruststore(reader, expectedNs, realmAddress, list);
trustStoreFound = true;
break;
}
case USERS: {
if (usernamePasswordFound) {
throw unexpectedElement(reader);
}
parseUsersAuthentication(reader, expectedNs, realmAddress, list);
usernamePasswordFound = true;
break;
}
case PLUG_IN: {
if (usernamePasswordFound) {
throw unexpectedElement(reader);
}
ModelNode parentAddress = realmAddress.clone().add(AUTHENTICATION);
parsePlugIn_Authentication(reader, expectedNs, parentAddress, list);
usernamePasswordFound = true;
break;
}
case LOCAL: {
if (localFound) {
throw unexpectedElement(reader);
}
parseLocalAuthentication_2_1(reader, expectedNs, realmAddress, list);
localFound = true;
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parseKerberosAuthentication_3_0(final XMLExtendedStreamReader reader,
final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException {
ModelNode addr = realmAddress.clone().add(AUTHENTICATION, KERBEROS);
ModelNode kerberos = Util.getEmptyOperation(ADD, addr);
list.add(kerberos);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case REMOVE_REALM:
KerberosAuthenticationResourceDefinition.REMOVE_REALM.parseAndSetParameter(value, kerberos, reader);
break;
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
requireNoContent(reader);
}
private static void parseJaasAuthentication_1_1(final XMLExtendedStreamReader reader,
final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException {
ModelNode addr = realmAddress.clone().add(AUTHENTICATION, JAAS);
ModelNode jaas = Util.getEmptyOperation(ADD, addr);
list.add(jaas);
boolean nameFound = false;
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case NAME:
if (nameFound) {
throw unexpectedAttribute(reader, i);
}
nameFound = true;
JaasAuthenticationResourceDefinition.NAME.parseAndSetParameter(value, jaas, reader);
break;
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (nameFound == false) {
throw missingRequired(reader, Collections.singleton(Attribute.NAME));
}
requireNoContent(reader);
}
private static void parseJaasAuthentication_1_6_and_3_0(final XMLExtendedStreamReader reader,
final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException {
ModelNode addr = realmAddress.clone().add(AUTHENTICATION, JAAS);
ModelNode jaas = Util.getEmptyOperation(ADD, addr);
list.add(jaas);
boolean nameFound = false;
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case NAME:
if (nameFound) {
throw unexpectedAttribute(reader, i);
}
nameFound = true;
JaasAuthenticationResourceDefinition.NAME.parseAndSetParameter(value, jaas, reader);
break;
case ASSIGN_GROUPS:
JaasAuthenticationResourceDefinition.ASSIGN_GROUPS.parseAndSetParameter(value, jaas, reader);
break;
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (nameFound == false) {
throw missingRequired(reader, Collections.singleton(Attribute.NAME));
}
requireNoContent(reader);
}
private static void parseLdapAuthentication_1_0(final XMLExtendedStreamReader reader, final ModelNode realmAddress, final List<ModelNode> list)
throws XMLStreamException {
ModelNode addr = realmAddress.clone().add(AUTHENTICATION, LDAP);
ModelNode ldapAuthentication = Util.getEmptyOperation(ADD, addr);
list.add(ldapAuthentication);
Set<Attribute> required = EnumSet.of(Attribute.CONNECTION, Attribute.BASE_DN, Attribute.USERNAME_ATTRIBUTE);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case CONNECTION: {
LdapAuthenticationResourceDefinition.CONNECTION.parseAndSetParameter(value, ldapAuthentication, reader);
break;
}
case BASE_DN: {
LdapAuthenticationResourceDefinition.BASE_DN.parseAndSetParameter(value, ldapAuthentication, reader);
break;
}
case USERNAME_ATTRIBUTE: {
LdapAuthenticationResourceDefinition.USERNAME_FILTER.parseAndSetParameter(value, ldapAuthentication, reader);
break;
}
case RECURSIVE: {
LdapAuthenticationResourceDefinition.RECURSIVE.parseAndSetParameter(value, ldapAuthentication, reader);
break;
}
case USER_DN: {
LdapAuthenticationResourceDefinition.USER_DN.parseAndSetParameter(value, ldapAuthentication, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (required.size() > 0)
throw missingRequired(reader, required);
requireNoContent(reader);
}
private static void parseLdapAuthentication_1_1(final XMLExtendedStreamReader reader, final Namespace expectedNs,
final ModelNode realmAddress, final List<ModelNode> list)
throws XMLStreamException {
ModelNode addr = realmAddress.clone().add(AUTHENTICATION, LDAP);
ModelNode ldapAuthentication = Util.getEmptyOperation(ADD, addr);
list.add(ldapAuthentication);
Set<Attribute> required = EnumSet.of(Attribute.CONNECTION, Attribute.BASE_DN);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case CONNECTION: {
LdapAuthenticationResourceDefinition.CONNECTION.parseAndSetParameter(value, ldapAuthentication, reader);
break;
}
case BASE_DN: {
LdapAuthenticationResourceDefinition.BASE_DN.parseAndSetParameter(value, ldapAuthentication, reader);
break;
}
case RECURSIVE: {
LdapAuthenticationResourceDefinition.RECURSIVE.parseAndSetParameter(value, ldapAuthentication, reader);
break;
}
case USER_DN: {
LdapAuthenticationResourceDefinition.USER_DN.parseAndSetParameter(value, ldapAuthentication, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (required.size() > 0) {
throw missingRequired(reader, required);
}
boolean choiceFound = false;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
if (choiceFound) {
throw unexpectedElement(reader);
}
choiceFound = true;
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case ADVANCED_FILTER:
String filter = readStringAttributeElement(reader, Attribute.FILTER.getLocalName());
LdapAuthenticationResourceDefinition.ADVANCED_FILTER.parseAndSetParameter(filter, ldapAuthentication, reader);
break;
case USERNAME_FILTER: {
String usernameAttr = readStringAttributeElement(reader, Attribute.ATTRIBUTE.getLocalName());
LdapAuthenticationResourceDefinition.USERNAME_FILTER.parseAndSetParameter(usernameAttr, ldapAuthentication, reader);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
if (!choiceFound) {
throw missingOneOf(reader, EnumSet.of(Element.ADVANCED_FILTER, Element.USERNAME_FILTER));
}
}
private static void parseLdapAuthentication_1_4(final XMLExtendedStreamReader reader, final Namespace expectedNs,
final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException {
ModelNode addr = realmAddress.clone().add(AUTHENTICATION, LDAP);
ModelNode ldapAuthentication = Util.getEmptyOperation(ADD, addr);
list.add(ldapAuthentication);
Set<Attribute> required = EnumSet.of(Attribute.CONNECTION, Attribute.BASE_DN);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case CONNECTION: {
LdapAuthenticationResourceDefinition.CONNECTION.parseAndSetParameter(value, ldapAuthentication, reader);
break;
}
case BASE_DN: {
LdapAuthenticationResourceDefinition.BASE_DN.parseAndSetParameter(value, ldapAuthentication, reader);
break;
}
case RECURSIVE: {
LdapAuthenticationResourceDefinition.RECURSIVE.parseAndSetParameter(value, ldapAuthentication, reader);
break;
}
case USER_DN: {
LdapAuthenticationResourceDefinition.USER_DN.parseAndSetParameter(value, ldapAuthentication, reader);
break;
}
case ALLOW_EMPTY_PASSWORDS: {
LdapAuthenticationResourceDefinition.ALLOW_EMPTY_PASSWORDS.parseAndSetParameter(value, ldapAuthentication, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (required.size() > 0) {
throw missingRequired(reader, required);
}
boolean choiceFound = false;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
if (choiceFound) {
throw unexpectedElement(reader);
}
choiceFound = true;
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case ADVANCED_FILTER:
String filter = readStringAttributeElement(reader, Attribute.FILTER.getLocalName());
LdapAuthenticationResourceDefinition.ADVANCED_FILTER.parseAndSetParameter(filter, ldapAuthentication,
reader);
break;
case USERNAME_FILTER: {
String usernameAttr = readStringAttributeElement(reader, Attribute.ATTRIBUTE.getLocalName());
LdapAuthenticationResourceDefinition.USERNAME_FILTER.parseAndSetParameter(usernameAttr, ldapAuthentication,
reader);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
if (!choiceFound) {
throw missingOneOf(reader, EnumSet.of(Element.ADVANCED_FILTER, Element.USERNAME_FILTER));
}
}
private static void parseLdapAuthentication_2_0(final XMLExtendedStreamReader reader, final Namespace expectedNs,
final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException {
ModelNode addr = realmAddress.clone().add(AUTHENTICATION, LDAP);
ModelNode ldapAuthentication = Util.getEmptyOperation(ADD, addr);
list.add(ldapAuthentication);
Set<Attribute> required = EnumSet.of(Attribute.CONNECTION, Attribute.BASE_DN);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case CONNECTION: {
LdapAuthenticationResourceDefinition.CONNECTION.parseAndSetParameter(value, ldapAuthentication, reader);
break;
}
case BASE_DN: {
LdapAuthenticationResourceDefinition.BASE_DN.parseAndSetParameter(value, ldapAuthentication, reader);
break;
}
case RECURSIVE: {
LdapAuthenticationResourceDefinition.RECURSIVE.parseAndSetParameter(value, ldapAuthentication, reader);
break;
}
case USER_DN: {
LdapAuthenticationResourceDefinition.USER_DN.parseAndSetParameter(value, ldapAuthentication, reader);
break;
}
case ALLOW_EMPTY_PASSWORDS: {
LdapAuthenticationResourceDefinition.ALLOW_EMPTY_PASSWORDS.parseAndSetParameter(value, ldapAuthentication, reader);
break;
}
case USERNAME_LOAD: {
LdapAuthenticationResourceDefinition.USERNAME_LOAD.parseAndSetParameter(value, ldapAuthentication, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (required.size() > 0) {
throw missingRequired(reader, required);
}
ModelNode addLdapCache = null;
boolean choiceFound = false;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
if (choiceFound) {
throw unexpectedElement(reader);
}
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case CACHE:
if (addLdapCache != null) {
throw unexpectedElement(reader);
}
addLdapCache = parseLdapCache(reader);
break;
case ADVANCED_FILTER:
choiceFound = true;
String filter = readStringAttributeElement(reader, Attribute.FILTER.getLocalName());
LdapAuthenticationResourceDefinition.ADVANCED_FILTER.parseAndSetParameter(filter, ldapAuthentication,
reader);
break;
case USERNAME_FILTER: {
choiceFound = true;
String usernameAttr = readStringAttributeElement(reader, Attribute.ATTRIBUTE.getLocalName());
LdapAuthenticationResourceDefinition.USERNAME_FILTER.parseAndSetParameter(usernameAttr, ldapAuthentication,
reader);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
if (!choiceFound) {
throw missingOneOf(reader, EnumSet.of(Element.ADVANCED_FILTER, Element.USERNAME_FILTER));
}
if (addLdapCache != null) {
correctCacheAddress(ldapAuthentication, addLdapCache);
list.add(addLdapCache);
}
}
private static ModelNode parseLdapCache(final XMLExtendedStreamReader reader) throws XMLStreamException {
ModelNode addr = new ModelNode();
ModelNode addCacheOp = Util.getEmptyOperation(ADD, addr);
String type = BY_SEARCH_TIME;
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case TYPE: {
if (BY_ACCESS_TIME.equals(value) || BY_SEARCH_TIME.equals(value)) {
type = value;
} else {
throw invalidAttributeValue(reader, i);
}
break;
}
case EVICTION_TIME: {
LdapCacheResourceDefinition.EVICTION_TIME.parseAndSetParameter(value, addCacheOp, reader);
break;
}
case CACHE_FAILURES: {
LdapCacheResourceDefinition.CACHE_FAILURES.parseAndSetParameter(value, addCacheOp, reader);
break;
}
case MAX_CACHE_SIZE: {
LdapCacheResourceDefinition.MAX_CACHE_SIZE.parseAndSetParameter(value, addCacheOp, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
requireNoContent(reader);
addCacheOp.get(OP_ADDR).add(CACHE, type);
return addCacheOp;
}
private static void correctCacheAddress(ModelNode parentAdd, ModelNode cacheAdd) {
List<Property> addressList = cacheAdd.get(OP_ADDR).asPropertyList();
ModelNode cacheAddress = parentAdd.get(OP_ADDR).clone();
for (Property current : addressList) {
cacheAddress.add(current.getName(), current.getValue().asString());
}
cacheAdd.get(OP_ADDR).set(cacheAddress);
}
private static void addLegacyLocalAuthentication(final ModelNode realmAddress, final List<ModelNode> list) {
/*
* Before version 1.3 of the domain schema there was no configuration for the local mechanism, however it was always
* enabled - this adds an arbitrary add local op to recreate this behaviour in the older schema versions.
*/
ModelNode addr = realmAddress.clone().add(AUTHENTICATION, LOCAL);
ModelNode local = Util.getEmptyOperation(ADD, addr);
local.get(DEFAULT_USER).set(DEFAULT_DEFAULT_USER);
list.add(local);
}
private static void parseLocalAuthentication_1_3(final XMLExtendedStreamReader reader, final Namespace expectedNs,
final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException {
ModelNode addr = realmAddress.clone().add(AUTHENTICATION, LOCAL);
ModelNode local = Util.getEmptyOperation(ADD, addr);
list.add(local);
final int count = reader.getAttributeCount();
Set<Attribute> attributesFound = new HashSet<Attribute>(count);
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
if (attributesFound.contains(attribute)) {
throw unexpectedAttribute(reader, i);
}
attributesFound.add(attribute);
switch (attribute) {
case DEFAULT_USER:
LocalAuthenticationResourceDefinition.DEFAULT_USER.parseAndSetParameter(value, local, reader);
break;
case ALLOWED_USERS:
LocalAuthenticationResourceDefinition.ALLOWED_USERS.parseAndSetParameter(value, local, reader);
break;
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
// All attributes are optional.
requireNoContent(reader);
}
private static void parseLocalAuthentication_2_1(final XMLExtendedStreamReader reader, final Namespace expectedNs,
final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException {
ModelNode addr = realmAddress.clone().add(AUTHENTICATION, LOCAL);
ModelNode local = Util.getEmptyOperation(ADD, addr);
list.add(local);
final int count = reader.getAttributeCount();
Set<Attribute> attributesFound = new HashSet<Attribute>(count);
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
if (attributesFound.contains(attribute)) {
throw unexpectedAttribute(reader, i);
}
attributesFound.add(attribute);
switch (attribute) {
case DEFAULT_USER:
LocalAuthenticationResourceDefinition.DEFAULT_USER.parseAndSetParameter(value, local, reader);
break;
case ALLOWED_USERS:
LocalAuthenticationResourceDefinition.ALLOWED_USERS.parseAndSetParameter(value, local, reader);
break;
case SKIP_GROUP_LOADING:
LocalAuthenticationResourceDefinition.SKIP_GROUP_LOADING.parseAndSetParameter(value, local, reader);
break;
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
// All attributes are optional.
requireNoContent(reader);
}
private static void parsePropertiesAuthentication_1_0(final XMLExtendedStreamReader reader,
final ModelNode realmAddress, final List<ModelNode> list)
throws XMLStreamException {
ModelNode addr = realmAddress.clone().add(AUTHENTICATION, PROPERTIES);
ModelNode properties = Util.getEmptyOperation(ADD, addr);
list.add(properties);
String path = null;
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case PATH:
path = value;
PropertiesAuthenticationResourceDefinition.PATH.parseAndSetParameter(value, properties, reader);
break;
case RELATIVE_TO: {
PropertiesAuthenticationResourceDefinition.RELATIVE_TO.parseAndSetParameter(value, properties, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (path == null)
throw missingRequired(reader, Collections.singleton(Attribute.PATH));
requireNoContent(reader);
// This property was not supported in version 1.0 of the schema, however it is set to true here to ensure
// the default behaviour if a document based on 1.0 of the schema is parsed, 1.1 now defaults this to false.
properties.get(PLAIN_TEXT).set(true);
}
private static void parsePropertiesAuthentication_1_1(final XMLExtendedStreamReader reader,
final ModelNode realmAddress, final List<ModelNode> list)
throws XMLStreamException {
ModelNode addr = realmAddress.clone().add(AUTHENTICATION, PROPERTIES);
ModelNode properties = Util.getEmptyOperation(ADD, addr);
list.add(properties);
String path = null;
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case PATH:
path = value;
PropertiesAuthenticationResourceDefinition.PATH.parseAndSetParameter(value, properties, reader);
break;
case RELATIVE_TO: {
PropertiesAuthenticationResourceDefinition.RELATIVE_TO.parseAndSetParameter(value, properties, reader);
break;
}
case PLAIN_TEXT: {
PropertiesAuthenticationResourceDefinition.PLAIN_TEXT.parseAndSetParameter(value, properties, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (path == null)
throw missingRequired(reader, Collections.singleton(Attribute.PATH));
requireNoContent(reader);
}
// The users element defines users within the domain model, it is a simple authentication for some out of the box users.
private static void parseUsersAuthentication(final XMLExtendedStreamReader reader, final Namespace expectedNs,
final ModelNode realmAddress, final List<ModelNode> list)
throws XMLStreamException {
final ModelNode usersAddress = realmAddress.clone().add(AUTHENTICATION, USERS);
list.add(Util.getEmptyOperation(ADD, usersAddress));
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case USER: {
parseUser(reader, expectedNs, usersAddress, list);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parseUser(final XMLExtendedStreamReader reader, final Namespace expectedNs,
final ModelNode usersAddress, final List<ModelNode> list) throws XMLStreamException {
requireSingleAttribute(reader, Attribute.USERNAME.getLocalName());
// After double checking the name of the only attribute we can retrieve it.
final String userName = reader.getAttributeValue(0);
final ModelNode userAddress = usersAddress.clone().add(USER, userName);
ModelNode user = Util.getEmptyOperation(ADD, userAddress);
list.add(user);
String password = null;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case PASSWORD: {
password = reader.getElementText();
UserResourceDefinition.PASSWORD.parseAndSetParameter(password, user, reader);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
if (password == null) {
throw missingRequiredElement(reader, EnumSet.of(Element.PASSWORD));
}
}
private static void parseTruststore(final XMLExtendedStreamReader reader, final Namespace expectedNs, final ModelNode realmAddress,
final List<ModelNode> list) throws XMLStreamException {
final ModelNode op = new ModelNode();
op.get(OP).set(ADD);
op.get(OP_ADDR).set(realmAddress).add(ModelDescriptionConstants.AUTHENTICATION, ModelDescriptionConstants.TRUSTSTORE);
switch (expectedNs) {
case DOMAIN_1_0:
case DOMAIN_1_1:
case DOMAIN_1_2:
parseKeystore_1_0(reader, op);
break;
case DOMAIN_1_3:
case DOMAIN_1_4:
case DOMAIN_1_5:
case DOMAIN_2_0:
parseKeystore_1_3(reader, op, false);
break;
default:
// Most recent versions for 1.x, 2.x and 3.x streams converge at this point.
parseKeystore_1_6_and_2_1(reader, op, false);
}
list.add(op);
}
private static void parseAuthorization_1_1(final XMLExtendedStreamReader reader, final Namespace expectedNs,
final ModelNode realmAdd, final List<ModelNode> list) throws XMLStreamException {
ModelNode realmAddress = realmAdd.get(OP_ADDR);
boolean authzFound = false;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
// Only a single element within the authorization element is currently supported.
if (authzFound) {
throw unexpectedElement(reader);
}
switch (element) {
case PROPERTIES: {
parsePropertiesAuthorization(reader, realmAddress, list);
authzFound = true;
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parseAuthorization_1_3(final XMLExtendedStreamReader reader, final Namespace expectedNs,
final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException {
boolean authzFound = false;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
// Only a single element within the authorization element is currently supported.
if (authzFound) {
throw unexpectedElement(reader);
}
switch (element) {
case PROPERTIES: {
parsePropertiesAuthorization(reader, realmAddress, list);
authzFound = true;
break;
}
case PLUG_IN: {
ModelNode parentAddress = realmAddress.clone().add(AUTHORIZATION);
parsePlugIn_Authorization(reader, expectedNs, parentAddress, list);
authzFound = true;
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parseAuthorization_1_5_and_2_0(final XMLExtendedStreamReader reader, final Namespace expectedNs,
final ModelNode realmAdd, final List<ModelNode> list) throws XMLStreamException {
ModelNode realmAddress = realmAdd.get(OP_ADDR);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case MAP_GROUPS_TO_ROLES:
SecurityRealmResourceDefinition.MAP_GROUPS_TO_ROLES.parseAndSetParameter(value, realmAdd, reader);
break;
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
boolean authzFound = false;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
// Only a single element within the authorization element is currently supported.
if (authzFound) {
throw unexpectedElement(reader);
}
switch (element) {
case PROPERTIES: {
parsePropertiesAuthorization(reader, realmAddress, list);
authzFound = true;
break;
}
case PLUG_IN: {
ModelNode parentAddress = realmAddress.clone().add(AUTHORIZATION);
parsePlugIn_Authorization(reader, expectedNs, parentAddress, list);
authzFound = true;
break;
}
case LDAP: {
parseLdapAuthorization_1_5(reader, expectedNs, realmAddress, list);
authzFound = true;
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parseLdapAuthorization_1_5(final XMLExtendedStreamReader reader, final Namespace expectedNs,
final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException {
ModelNode addr = realmAddress.clone().add(AUTHORIZATION, LDAP);
ModelNode ldapAuthorization = Util.getEmptyOperation(ADD, addr);
list.add(ldapAuthorization);
Set<Attribute> required = EnumSet.of(Attribute.CONNECTION);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case CONNECTION: {
LdapAuthorizationResourceDefinition.CONNECTION.parseAndSetParameter(value, ldapAuthorization, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (required.isEmpty() == false) {
throw missingRequired(reader, required);
}
Set<Element> foundElements = new HashSet<Element>();
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
if (foundElements.add(element) == false) {
throw unexpectedElement(reader); // Only one of each allowed.
}
switch (element) {
case USERNAME_TO_DN: {
switch (expectedNs.getMajorVersion()) {
case 1: // 1.5 up to but not including 2.0
parseUsernameToDn_1_5(reader, expectedNs, addr, list);
break;
default: // 2.0 and onwards
parseUsernameToDn_2_0(reader, expectedNs, addr, list);
break;
}
break;
}
case GROUP_SEARCH: {
switch (expectedNs.getMajorVersion()) {
case 1: // 1.5 up to but not including 2.0
parseGroupSearch_1_5(reader, expectedNs, addr, list);
break;
default: // 2.0 and onwards
parseGroupSearch_2_0(reader, expectedNs, addr, list);
break;
}
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parseUsernameToDn_1_5(final XMLExtendedStreamReader reader, final Namespace expectedNs,
final ModelNode ldapAddress, final List<ModelNode> list) throws XMLStreamException {
// Add operation to be defined by parsing a child element, however the attribute FORCE is common here.
final ModelNode childAdd = new ModelNode();
childAdd.get(OP).set(ADD);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case FORCE:
BaseLdapUserSearchResource.FORCE.parseAndSetParameter(value, childAdd, reader);
break;
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
boolean filterFound = false;
ModelNode address = ldapAddress.clone().add(USERNAME_TO_DN);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
if (filterFound) {
throw unexpectedElement(reader);
}
switch (element) {
case USERNAME_IS_DN:
filterFound = true;
parseUsernameIsDn(reader, address, childAdd);
break;
case USERNAME_FILTER:
filterFound = true;
parseUsernameFilter(reader, address, childAdd);
break;
case ADVANCED_FILTER:
filterFound = true;
parseAdvancedFilter(reader, address, childAdd);
break;
default: {
throw unexpectedElement(reader);
}
}
}
if (filterFound == false) {
throw missingOneOf(reader, EnumSet.of(Element.USERNAME_IS_DN, Element.USERNAME_FILTER, Element.ADVANCED_FILTER));
}
list.add(childAdd);
}
private static void parseUsernameToDn_2_0(final XMLExtendedStreamReader reader, final Namespace expectedNs,
final ModelNode ldapAddress, final List<ModelNode> list) throws XMLStreamException {
// Add operation to be defined by parsing a child element, however the attribute FORCE is common here.
final ModelNode childAdd = new ModelNode();
childAdd.get(OP).set(ADD);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case FORCE:
BaseLdapUserSearchResource.FORCE.parseAndSetParameter(value, childAdd, reader);
break;
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
boolean filterFound = false;
ModelNode cacheAdd = null;
ModelNode address = ldapAddress.clone().add(USERNAME_TO_DN);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
if (filterFound) {
throw unexpectedElement(reader);
}
switch (element) {
case CACHE:
if (cacheAdd != null) {
throw unexpectedElement(reader);
}
cacheAdd = parseLdapCache(reader);
break;
case USERNAME_IS_DN:
filterFound = true;
parseUsernameIsDn(reader, address, childAdd);
break;
case USERNAME_FILTER:
filterFound = true;
parseUsernameFilter(reader, address, childAdd);
break;
case ADVANCED_FILTER:
filterFound = true;
parseAdvancedFilter(reader, address, childAdd);
break;
default: {
throw unexpectedElement(reader);
}
}
}
if (filterFound == false) {
throw missingOneOf(reader, EnumSet.of(Element.USERNAME_IS_DN, Element.USERNAME_FILTER, Element.ADVANCED_FILTER));
}
list.add(childAdd);
if (cacheAdd != null) {
correctCacheAddress(childAdd, cacheAdd);
list.add(cacheAdd);
}
}
private static void parseUsernameIsDn(final XMLExtendedStreamReader reader,
final ModelNode parentAddress, final ModelNode addOp) throws XMLStreamException {
requireNoAttributes(reader);
requireNoContent(reader);
addOp.get(OP_ADDR).set(parentAddress.clone().add(USERNAME_IS_DN));
}
private static void parseUsernameFilter(final XMLExtendedStreamReader reader, final ModelNode parentAddress,
final ModelNode addOp) throws XMLStreamException {
boolean baseDnFound = false;
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case BASE_DN: {
baseDnFound = true;
UserSearchResourceDefintion.BASE_DN.parseAndSetParameter(value, addOp, reader);
break;
}
case RECURSIVE: {
UserSearchResourceDefintion.RECURSIVE.parseAndSetParameter(value, addOp, reader);
break;
}
case USER_DN_ATTRIBUTE: {
UserSearchResourceDefintion.USER_DN_ATTRIBUTE.parseAndSetParameter(value, addOp, reader);
break;
}
case ATTRIBUTE: {
UserSearchResourceDefintion.ATTRIBUTE.parseAndSetParameter(value, addOp, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (baseDnFound == false) {
throw missingRequired(reader, Collections.singleton(Attribute.BASE_DN));
}
requireNoContent(reader);
addOp.get(OP_ADDR).set(parentAddress.clone().add(USERNAME_FILTER));
}
private static void parseAdvancedFilter(final XMLExtendedStreamReader reader, final ModelNode parentAddress,
final ModelNode addOp) throws XMLStreamException {
boolean baseDnFound = false;
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case BASE_DN: {
baseDnFound = true;
AdvancedUserSearchResourceDefintion.BASE_DN.parseAndSetParameter(value, addOp, reader);
break;
}
case RECURSIVE: {
AdvancedUserSearchResourceDefintion.RECURSIVE.parseAndSetParameter(value, addOp, reader);
break;
}
case USER_DN_ATTRIBUTE: {
UserSearchResourceDefintion.USER_DN_ATTRIBUTE.parseAndSetParameter(value, addOp, reader);
break;
}
case FILTER: {
AdvancedUserSearchResourceDefintion.FILTER.parseAndSetParameter(value, addOp, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (baseDnFound == false) {
throw missingRequired(reader, Collections.singleton(Attribute.BASE_DN));
}
requireNoContent(reader);
addOp.get(OP_ADDR).set(parentAddress.clone().add(ADVANCED_FILTER));
}
private static void parseGroupSearch_1_5(final XMLExtendedStreamReader reader, final Namespace expectedNs,
final ModelNode ldapAddress, final List<ModelNode> list) throws XMLStreamException {
// Add operation to be defined by parsing a child element, however the attribute FORCE is common here.
final ModelNode childAdd = new ModelNode();
childAdd.get(OP).set(ADD);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case GROUP_NAME:
BaseLdapGroupSearchResource.GROUP_NAME.parseAndSetParameter(value, childAdd, reader);
break;
case ITERATIVE:
BaseLdapGroupSearchResource.ITERATIVE.parseAndSetParameter(value, childAdd, reader);
break;
case GROUP_DN_ATTRIBUTE:
BaseLdapGroupSearchResource.GROUP_DN_ATTRIBUTE.parseAndSetParameter(value, childAdd, reader);
break;
case GROUP_NAME_ATTRIBUTE:
BaseLdapGroupSearchResource.GROUP_NAME_ATTRIBUTE.parseAndSetParameter(value, childAdd, reader);
break;
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
boolean filterFound = false;
ModelNode address = ldapAddress.clone().add(GROUP_SEARCH);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
if (filterFound) {
throw unexpectedElement(reader);
}
switch (element) {
case GROUP_TO_PRINCIPAL:
filterFound = true;
parseGroupToPrincipal(reader, expectedNs, address, childAdd);
break;
case PRINCIPAL_TO_GROUP:
filterFound = true;
switch (expectedNs) {
case DOMAIN_1_5:
parsePrincipalToGroup_1_5(reader, expectedNs, address, childAdd);
break;
default:
// 1.6 and 2.1 converge at this point.
parsePrincipalToGroup_1_6_and_2_1(reader, expectedNs, address, childAdd);
break;
}
break;
default: {
throw unexpectedElement(reader);
}
}
}
if (filterFound == false) {
throw missingOneOf(reader, EnumSet.of(Element.GROUP_TO_PRINCIPAL, Element.PRINCIPAL_TO_GROUP));
}
list.add(childAdd);
}
private static void parseGroupSearch_2_0(final XMLExtendedStreamReader reader, final Namespace expectedNs,
final ModelNode ldapAddress, final List<ModelNode> list) throws XMLStreamException {
// Add operation to be defined by parsing a child element, however the attribute FORCE is common here.
final ModelNode childAdd = new ModelNode();
childAdd.get(OP).set(ADD);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case GROUP_NAME:
BaseLdapGroupSearchResource.GROUP_NAME.parseAndSetParameter(value, childAdd, reader);
break;
case ITERATIVE:
BaseLdapGroupSearchResource.ITERATIVE.parseAndSetParameter(value, childAdd, reader);
break;
case GROUP_DN_ATTRIBUTE:
BaseLdapGroupSearchResource.GROUP_DN_ATTRIBUTE.parseAndSetParameter(value, childAdd, reader);
break;
case GROUP_NAME_ATTRIBUTE:
BaseLdapGroupSearchResource.GROUP_NAME_ATTRIBUTE.parseAndSetParameter(value, childAdd, reader);
break;
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
boolean filterFound = false;
ModelNode cacheAdd = null;
ModelNode address = ldapAddress.clone().add(GROUP_SEARCH);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
if (filterFound) {
throw unexpectedElement(reader);
}
switch (element) {
case CACHE:
if (cacheAdd != null) {
throw unexpectedElement(reader);
}
cacheAdd = parseLdapCache(reader);
break;
case GROUP_TO_PRINCIPAL:
filterFound = true;
parseGroupToPrincipal(reader, expectedNs, address, childAdd);
break;
case PRINCIPAL_TO_GROUP:
filterFound = true;
switch (expectedNs) {
case DOMAIN_2_0:
parsePrincipalToGroup_1_5(reader, expectedNs, address, childAdd);
break;
default:
switch (expectedNs.getMajorVersion()) {
case 1:
case 2:
parsePrincipalToGroup_1_6_and_2_1(reader, expectedNs, address, childAdd);
break;
default:
parsePrincipalToGroup_3_0(reader, expectedNs, address, childAdd);
break;
}
}
break;
default: {
throw unexpectedElement(reader);
}
}
}
if (filterFound == false) {
throw missingOneOf(reader, EnumSet.of(Element.GROUP_TO_PRINCIPAL, Element.PRINCIPAL_TO_GROUP));
}
list.add(childAdd);
if (cacheAdd != null) {
correctCacheAddress(childAdd, cacheAdd);
list.add(cacheAdd);
}
}
private static void parseGroupToPrincipalAttributes_1_5_and_2_0(final XMLExtendedStreamReader reader, final ModelNode addOp) throws XMLStreamException {
boolean baseDnFound = false;
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case BASE_DN: {
baseDnFound = true;
GroupToPrincipalResourceDefinition.BASE_DN.parseAndSetParameter(value, addOp, reader);
break;
}
case RECURSIVE: {
GroupToPrincipalResourceDefinition.RECURSIVE.parseAndSetParameter(value, addOp, reader);
break;
}
case SEARCH_BY:
GroupToPrincipalResourceDefinition.SEARCH_BY.parseAndSetParameter(value, addOp, reader);
break;
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (baseDnFound == false) {
throw missingRequired(reader, Collections.singleton(Attribute.BASE_DN));
}
}
private static void parseGroupToPrincipalAttributes_3_0(final XMLExtendedStreamReader reader, final ModelNode addOp) throws XMLStreamException {
boolean baseDnFound = false;
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case BASE_DN: {
baseDnFound = true;
GroupToPrincipalResourceDefinition.BASE_DN.parseAndSetParameter(value, addOp, reader);
break;
}
case RECURSIVE: {
GroupToPrincipalResourceDefinition.RECURSIVE.parseAndSetParameter(value, addOp, reader);
break;
}
case SEARCH_BY:
GroupToPrincipalResourceDefinition.SEARCH_BY.parseAndSetParameter(value, addOp, reader);
break;
case PREFER_ORIGINAL_CONNECTION:
GroupToPrincipalResourceDefinition.PREFER_ORIGINAL_CONNECTION.parseAndSetParameter(value, addOp, reader);
break;
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (baseDnFound == false) {
throw missingRequired(reader, Collections.singleton(Attribute.BASE_DN));
}
}
private static void parseGroupToPrincipal(final XMLExtendedStreamReader reader, final Namespace expectedNs, final ModelNode parentAddress,
final ModelNode addOp) throws XMLStreamException {
// NOTE: Should be wrapped in a switch(expectedNS) if minor version differences need to be accounted for.
switch (expectedNs.getMajorVersion()) {
case 1:
case 2:
parseGroupToPrincipalAttributes_1_5_and_2_0(reader, addOp);
break;
default:
parseGroupToPrincipalAttributes_3_0(reader, addOp);
break;
}
boolean elementFound = false;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
if (elementFound) {
throw unexpectedElement(reader);
}
elementFound = true;
switch (element) {
case MEMBERSHIP_FILTER:
parseMembershipFilter(reader, addOp);
break;
default: {
throw unexpectedElement(reader);
}
}
}
addOp.get(OP_ADDR).set(parentAddress.clone().add(GROUP_TO_PRINCIPAL));
}
private static void parseMembershipFilter(final XMLExtendedStreamReader reader,
final ModelNode addOp) throws XMLStreamException {
boolean principalAttribute = false;
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case PRINCIPAL_ATTRIBUTE: {
principalAttribute = true;
GroupToPrincipalResourceDefinition.PRINCIPAL_ATTRIBUTE.parseAndSetParameter(value, addOp, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (principalAttribute == false) {
throw missingRequired(reader, Collections.singleton(Attribute.PRINCIPAL_ATTRIBUTE));
}
requireNoContent(reader);
}
private static void parsePrincipalToGroup_1_5(final XMLExtendedStreamReader reader, final Namespace expectedNs, final ModelNode parentAddress,
final ModelNode addOp) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case GROUP_ATTRIBUTE: {
PrincipalToGroupResourceDefinition.GROUP_ATTRIBUTE.parseAndSetParameter(value, addOp, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
requireNoContent(reader);
addOp.get(OP_ADDR).set(parentAddress.clone().add(PRINCIPAL_TO_GROUP));
}
private static void parsePrincipalToGroup_1_6_and_2_1(final XMLExtendedStreamReader reader, final Namespace expectedNs, final ModelNode parentAddress,
final ModelNode addOp) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case GROUP_ATTRIBUTE: {
PrincipalToGroupResourceDefinition.GROUP_ATTRIBUTE.parseAndSetParameter(value, addOp, reader);
break;
}
case PREFER_ORIGINAL_CONNECTION: {
PrincipalToGroupResourceDefinition.PREFER_ORIGINAL_CONNECTION.parseAndSetParameter(value, addOp, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
requireNoContent(reader);
addOp.get(OP_ADDR).set(parentAddress.clone().add(PRINCIPAL_TO_GROUP));
}
private static void parsePrincipalToGroup_3_0(final XMLExtendedStreamReader reader, final Namespace expectedNs, final ModelNode parentAddress,
final ModelNode addOp) throws XMLStreamException {
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case GROUP_ATTRIBUTE: {
PrincipalToGroupResourceDefinition.GROUP_ATTRIBUTE.parseAndSetParameter(value, addOp, reader);
break;
}
case PREFER_ORIGINAL_CONNECTION: {
PrincipalToGroupResourceDefinition.PREFER_ORIGINAL_CONNECTION.parseAndSetParameter(value, addOp, reader);
break;
}
case SKIP_MISSING_GROUPS: {
PrincipalToGroupResourceDefinition.SKIP_MISSING_GROUPS.parseAndSetParameter(value, addOp, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
requireNoContent(reader);
addOp.get(OP_ADDR).set(parentAddress.clone().add(PRINCIPAL_TO_GROUP));
}
private static void parsePropertiesAuthorization(final XMLExtendedStreamReader reader, final ModelNode realmAddress,
final List<ModelNode> list) throws XMLStreamException {
ModelNode addr = realmAddress.clone().add(AUTHORIZATION, PROPERTIES);
ModelNode properties = Util.getEmptyOperation(ADD, addr);
list.add(properties);
String path = null;
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case PATH:
path = value;
PropertiesAuthorizationResourceDefinition.PATH.parseAndSetParameter(value, properties, reader);
break;
case RELATIVE_TO: {
PropertiesAuthorizationResourceDefinition.RELATIVE_TO.parseAndSetParameter(value, properties, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (path == null)
throw missingRequired(reader, Collections.singleton(Attribute.PATH));
requireNoContent(reader);
}
private static void parsePlugIn_Authentication(final XMLExtendedStreamReader reader, final Namespace expectedNs,
final ModelNode parentAddress, final List<ModelNode> list) throws XMLStreamException {
ModelNode addr = parentAddress.clone().add(PLUG_IN);
ModelNode plugIn = Util.getEmptyOperation(ADD, addr);
list.add(plugIn);
boolean nameFound = false;
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case NAME:
PlugInAuthenticationResourceDefinition.NAME.parseAndSetParameter(value, plugIn, reader);
nameFound = true;
break;
case MECHANISM: {
PlugInAuthenticationResourceDefinition.MECHANISM.parseAndSetParameter(value, plugIn, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (nameFound == false) {
throw missingRequired(reader, Collections.singleton(Attribute.NAME));
}
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case PROPERTIES: {
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element propertyElement = Element.forName(reader.getLocalName());
switch (propertyElement) {
case PROPERTY:
parseProperty(reader, addr, list);
break;
default:
throw unexpectedElement(reader);
}
}
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parsePlugIn_Authorization(final XMLExtendedStreamReader reader, final Namespace expectedNs,
final ModelNode parentAddress, final List<ModelNode> list) throws XMLStreamException {
ModelNode addr = parentAddress.clone().add(PLUG_IN);
ModelNode plugIn = Util.getEmptyOperation(ADD, addr);
list.add(plugIn);
requireSingleAttribute(reader, Attribute.NAME.getLocalName());
// After double checking the name of the only attribute we can retrieve it.
final String plugInName = reader.getAttributeValue(0);
plugIn.get(NAME).set(plugInName);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case PROPERTIES: {
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element propertyElement = Element.forName(reader.getLocalName());
switch (propertyElement) {
case PROPERTY:
parseProperty(reader, addr, list);
break;
default:
throw unexpectedElement(reader);
}
}
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parseProperty(final XMLExtendedStreamReader reader, final ModelNode parentAddress, final List<ModelNode> list)
throws XMLStreamException {
final ModelNode add = new ModelNode();
add.get(OP).set(ADD);
list.add(add);
boolean addressFound = false;
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case NAME:
add.get(OP_ADDR).set(parentAddress).add(PROPERTY, value);
addressFound = true;
break;
case VALUE: {
PropertyResourceDefinition.VALUE.parseAndSetParameter(value, add, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (addressFound == false) {
throw missingRequired(reader, Collections.singleton(Attribute.NAME));
}
requireNoContent(reader);
}
public static void parseAccessControlRoleMapping(final XMLExtendedStreamReader reader, final ModelNode accContAddr,
final Namespace expectedNs, final List<ModelNode> list) throws XMLStreamException {
requireNoAttributes(reader);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
if (element == Element.ROLE) {
parseRole(reader, accContAddr, expectedNs, list);
} else {
throw unexpectedElement(reader);
}
}
}
private static void parseRole(final XMLExtendedStreamReader reader, final ModelNode address, final Namespace expectedNs,
final List<ModelNode> list) throws XMLStreamException {
final ModelNode add = new ModelNode();
list.add(add);
String name = null;
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case NAME:
name = value;
break;
case INCLUDE_ALL: {
RoleMappingResourceDefinition.INCLUDE_ALL.parseAndSetParameter(value, add, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (name == null) {
throw missingRequired(reader, Collections.singleton(Attribute.NAME));
}
ModelNode addr = address.clone().add(ROLE_MAPPING, name);
add.get(OP_ADDR).set(addr);
add.get(OP).set(ADD);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case INCLUDE: {
parseIncludeExclude(reader, addr, INCLUDE, expectedNs, list);
break;
}
case EXCLUDE: {
parseIncludeExclude(reader, addr, EXCLUDE, expectedNs, list);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parseIncludeExclude(final XMLExtendedStreamReader reader, final ModelNode parentAddress, final String incExcType, final Namespace expectedNs,
final List<ModelNode> list) throws XMLStreamException {
ParseUtils.requireNoAttributes(reader);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case GROUP: {
parsePrincipal(reader, parentAddress, incExcType, GROUP, expectedNs, list);
break;
}
case USER: {
parsePrincipal(reader, parentAddress, incExcType, USER, expectedNs, list);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parsePrincipal(final XMLExtendedStreamReader reader, final ModelNode parentAddress, final String incExcType, final String principalType,
final Namespace expectedNs, final List<ModelNode> list) throws XMLStreamException {
String alias = null;
String realm = null;
String name = null;
ModelNode addOp = new ModelNode();
addOp.get(OP).set(ADD);
addOp.get(TYPE).set(principalType);
int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case ALIAS: {
alias = value;
break;
}
case NAME: {
name = value;
PrincipalResourceDefinition.NAME.parseAndSetParameter(value, addOp, reader);
break;
}
case REALM: {
realm = value;
PrincipalResourceDefinition.REALM.parseAndSetParameter(value, addOp, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (name == null) {
throw ParseUtils.missingRequired(reader, Collections.singleton(Attribute.NAME));
}
String addrValue = alias == null ? generateAlias(principalType, name, realm) : alias;
ModelNode addAddr = parentAddress.clone().add(incExcType, addrValue);
addOp.get(OP_ADDR).set(addAddr);
list.add(addOp);
ParseUtils.requireNoContent(reader);
}
private static String generateAlias(final String type, final String name, final String realm) {
return type + "-" + name + (realm != null ? "@" + realm : "");
}
public static void parseAccessControlConstraints(final XMLExtendedStreamReader reader, final ModelNode accAuthzAddr, final Namespace expectedNs,
final List<ModelNode> list) throws XMLStreamException {
ParseUtils.requireNoAttributes(reader);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case VAULT_EXPRESSION_SENSITIVITY: {
ModelNode vaultAddr = accAuthzAddr.clone().add(CONSTRAINT, VAULT_EXPRESSION);
parseClassificationType(reader, vaultAddr, expectedNs, list, true);
break;
}
case SENSITIVE_CLASSIFICATIONS: {
ModelNode sensAddr = accAuthzAddr.clone().add(CONSTRAINT, SENSITIVITY_CLASSIFICATION);
parseSensitiveClassifications(reader, sensAddr, expectedNs, list);
break;
}
case APPLICATION_CLASSIFICATIONS: {
ModelNode applAddr = accAuthzAddr.clone().add(CONSTRAINT, APPLICATION_CLASSIFICATION);
parseApplicationClassifications(reader, applAddr, expectedNs, list);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parseSensitiveClassifications(final XMLExtendedStreamReader reader, final ModelNode address, final Namespace expectedNs,
final List<ModelNode> list) throws XMLStreamException {
ParseUtils.requireNoAttributes(reader);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case SENSITIVE_CLASSIFICATION: {
parseSensitivityClassification(reader, address, expectedNs, list);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parseSensitivityClassification(final XMLExtendedStreamReader reader, final ModelNode address, final Namespace expectedNs,
final List<ModelNode> list) throws XMLStreamException {
parseClassificationType(reader, address, expectedNs, list, false);
// String name = null;
// final int count = reader.getAttributeCount();
// for (int i = 0; i < count; i++) {
// final String value = reader.getAttributeValue(i);
// if (!isNoNamespaceAttribute(reader, i)) {
// throw unexpectedAttribute(reader, i);
// } else {
// final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
// switch (attribute) {
// case NAME:
// name = value;
// break;
// default: {
// throw unexpectedAttribute(reader, i);
// if (name == null) {
// throw ParseUtils.missingRequired(reader, Collections.singleton(NAME));
// ModelNode newAddress = address.clone().add(SensitivityClassificationTypeResourceDefinition.PATH_ELEMENT.getKey(), name);
// while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
// requireNamespace(reader, expectedNs);
// final Element element = Element.forName(reader.getLocalName());
// String name = null;
// switch (element) {
// case TYPE: {
// parseClassificationType(reader, newAddress, expectedNs, list, false);
// break;
// default: {
// throw unexpectedElement(reader);
}
private static void parseClassificationType(final XMLExtendedStreamReader reader, final ModelNode address, final Namespace expectedNs,
final List<ModelNode> list, boolean vault) throws XMLStreamException {
final int count = reader.getAttributeCount();
String name = null;
String type = null;
Map<String, ModelNode> values = new HashMap<String, ModelNode>();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case NAME: {
name = value;
break;
}
case TYPE: {
type = value;
break;
}
case REQUIRES_READ: {
values.put(SensitivityResourceDefinition.CONFIGURED_REQUIRES_READ.getName(),
SensitivityResourceDefinition.CONFIGURED_REQUIRES_READ.parse(value, reader));
break;
}
case REQUIRES_WRITE: {
values.put(SensitivityResourceDefinition.CONFIGURED_REQUIRES_WRITE.getName(),
SensitivityResourceDefinition.CONFIGURED_REQUIRES_WRITE.parse(value, reader));
break;
}
case REQUIRES_ADDRESSABLE: {
if (!vault) {
values.put(SensitivityResourceDefinition.CONFIGURED_REQUIRES_ADDRESSABLE.getName(),
SensitivityResourceDefinition.CONFIGURED_REQUIRES_ADDRESSABLE.parse(value, reader));
break;
}
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (name == null && !vault) {
throw ParseUtils.missingRequired(reader, Collections.singleton(Attribute.NAME));
}
if (type == null && !vault) {
throw ParseUtils.missingRequired(reader, Collections.singleton(Attribute.TYPE));
}
final ModelNode newAddress = vault ? address :
address.clone()
.add(SensitivityClassificationTypeResourceDefinition.PATH_ELEMENT.getKey(), type)
.add(SensitivityResourceDefinition.PATH_ELEMENT.getKey(), name);
for (Map.Entry<String, ModelNode> entry : values.entrySet()) {
list.add(Util.getWriteAttributeOperation(newAddress, entry.getKey(), entry.getValue()));
}
ParseUtils.requireNoContent(reader);
}
private static void parseApplicationClassifications(final XMLExtendedStreamReader reader, final ModelNode address, final Namespace expectedNs,
final List<ModelNode> list) throws XMLStreamException {
ParseUtils.requireNoAttributes(reader);
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case APPLICATION_CLASSIFICATION: {
parseApplicationClassification(reader, address, expectedNs, list);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parseApplicationClassification(final XMLExtendedStreamReader reader, final ModelNode address, final Namespace expectedNs,
final List<ModelNode> list) throws XMLStreamException {
String name = null;
String type = null;
Boolean applicationValue = null;
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case NAME:
name = value;
break;
case TYPE:
type = value;
break;
case APPLICATION:
applicationValue = Boolean.valueOf(value);
break;
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (name == null) {
throw ParseUtils.missingRequired(reader, Collections.singleton(NAME));
}
if (type == null) {
throw ParseUtils.missingRequired(reader, Collections.singleton(Attribute.TYPE));
}
if (applicationValue == null) {
throw ParseUtils.missingRequired(reader, Collections.singleton(Attribute.APPLICATION));
}
ModelNode newAddress = address.clone()
.add(ApplicationClassificationTypeResourceDefinition.PATH_ELEMENT.getKey(), type)
.add(ApplicationClassificationConfigResourceDefinition.PATH_ELEMENT.getKey(), name);
list.add(Util.getWriteAttributeOperation(newAddress, ApplicationClassificationConfigResourceDefinition.CONFIGURED_APPLICATION.getName(), applicationValue.toString()));
ParseUtils.requireNoContent(reader);
}
public static void parseServerGroupScopedRoles(final XMLExtendedStreamReader reader, final ModelNode address, final Namespace expectedNs, final List<ModelNode> list) throws XMLStreamException {
ParseUtils.requireNoAttributes(reader);
String scopedRoleType = ServerGroupScopedRoleResourceDefinition.PATH_ELEMENT.getKey();
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case ROLE: {
parseScopedRole(reader, address, expectedNs, list, scopedRoleType, Element.SERVER_GROUP,
ServerGroupScopedRoleResourceDefinition.BASE_ROLE, ServerGroupScopedRoleResourceDefinition.SERVER_GROUPS, true);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
public static void parseHostScopedRoles(final XMLExtendedStreamReader reader, final ModelNode address, final Namespace expectedNs, final List<ModelNode> list) throws XMLStreamException {
ParseUtils.requireNoAttributes(reader);
String scopedRoleType = HostScopedRolesResourceDefinition.PATH_ELEMENT.getKey();
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
switch (element) {
case ROLE: {
parseScopedRole(reader, address, expectedNs, list, scopedRoleType, Element.HOST,
HostScopedRolesResourceDefinition.BASE_ROLE, HostScopedRolesResourceDefinition.HOSTS, false);
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
}
private static void parseScopedRole(XMLExtendedStreamReader reader, ModelNode address, Namespace expectedNs,
List<ModelNode> ops, String scopedRoleType, final Element listElement,
SimpleAttributeDefinition baseRoleDefinition, ListAttributeDefinition listDefinition,
boolean requireChildren) throws XMLStreamException {
final ModelNode addOp = Util.createAddOperation();
ops.add(addOp);
final ModelNode ourAddress = addOp.get(OP_ADDR).set(address);
final Set<Attribute> required = EnumSet.of(Attribute.NAME, Attribute.BASE_ROLE);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
}
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case NAME:
ourAddress.add(scopedRoleType, value);
break;
case BASE_ROLE:
baseRoleDefinition.parseAndSetParameter(value, addOp, reader);
break;
default: {
throw unexpectedAttribute(reader, i);
}
}
}
if (!required.isEmpty()) {
throw missingRequired(reader, required);
}
boolean missingChildren = requireChildren;
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
boolean named = false;
requireNamespace(reader, expectedNs);
final Element element = Element.forName(reader.getLocalName());
if (element == listElement) {
missingChildren = false;
final int groupCount = reader.getAttributeCount();
for (int i = 0; i < groupCount; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
}
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
if (attribute == Attribute.NAME) {
named = true;
listDefinition.parseAndAddParameterElement(value, addOp, reader);
} else {
throw unexpectedAttribute(reader, i);
}
}
} else {
throw unexpectedElement(reader);
}
if (!named) {
throw missingRequired(reader, EnumSet.of(Attribute.NAME));
}
requireNoContent(reader);
}
if (missingChildren) {
throw missingRequired(reader, EnumSet.of(listElement));
}
}
public void writeManagement(final XMLExtendedStreamWriter writer, final ModelNode management, boolean allowInterfaces)
throws XMLStreamException {
boolean hasSecurityRealm = management.hasDefined(SECURITY_REALM);
boolean hasConnection = management.hasDefined(LDAP_CONNECTION);
boolean hasInterface = allowInterfaces && management.hasDefined(MANAGEMENT_INTERFACE);
// TODO - These checks are going to become a source of bugs in certain cases - what we really need is a way to allow writing to continue and
// if an element is empty by the time it is closed then undo the write of that element.
ModelNode accessAuthorization = management.hasDefined(ACCESS) ? management.get(ACCESS, AUTHORIZATION) : null;
boolean accessAuthorizationDefined = accessAuthorization != null && accessAuthorization.isDefined();
boolean hasServerGroupRoles = accessAuthorizationDefined && accessAuthorization.hasDefined(SERVER_GROUP_SCOPED_ROLE);
boolean hasHostRoles = accessAuthorizationDefined && (accessAuthorization.hasDefined(HOST_SCOPED_ROLE) || accessAuthorization.hasDefined(HOST_SCOPED_ROLES));
boolean hasRoleMapping = accessAuthorizationDefined && accessAuthorization.hasDefined(ROLE_MAPPING);
Map<String, Map<String, Set<String>>> configuredAccessConstraints = getConfiguredAccessConstraints(accessAuthorization);
boolean hasProvider = accessAuthorizationDefined && accessAuthorization.hasDefined(AccessAuthorizationResourceDefinition.PROVIDER.getName());
boolean hasCombinationPolicy = accessAuthorizationDefined && accessAuthorization.hasDefined(AccessAuthorizationResourceDefinition.PERMISSION_COMBINATION_POLICY.getName());
ModelNode auditLog = management.hasDefined(ACCESS) ? management.get(ACCESS, AUDIT) : new ModelNode();
if (!hasSecurityRealm && !hasConnection && !hasInterface && !hasServerGroupRoles
&& !hasHostRoles && !hasRoleMapping && configuredAccessConstraints.size() == 0
&& !hasProvider && !hasCombinationPolicy && !auditLog.isDefined()) {
return;
}
writer.writeStartElement(Element.MANAGEMENT.getLocalName());
if (hasSecurityRealm) {
writeSecurityRealm(writer, management);
}
if (hasConnection) {
writeOutboundConnections(writer, management);
}
if (auditLog.isDefined()) {
delegate.writeAuditLog(writer, auditLog);
}
if (allowInterfaces && hasInterface) {
writeManagementInterfaces(writer, management);
}
if (accessAuthorizationDefined) {
delegate.writeAccessControl(writer, accessAuthorization);
}
writer.writeEndElement();
}
private static void writeAccessControl(final XMLExtendedStreamWriter writer, final ModelNode accessAuthorization) throws XMLStreamException {
if (accessAuthorization == null || accessAuthorization.isDefined()==false) {
return; // All subsequent checks are based on this being defined.
}
boolean hasServerGroupRoles = accessAuthorization.hasDefined(SERVER_GROUP_SCOPED_ROLE);
boolean hasHostRoles = accessAuthorization.hasDefined(HOST_SCOPED_ROLE) || accessAuthorization.hasDefined(HOST_SCOPED_ROLES);
boolean hasRoleMapping = accessAuthorization.hasDefined(ROLE_MAPPING);
Map<String, Map<String, Set<String>>> configuredAccessConstraints = getConfiguredAccessConstraints(accessAuthorization);
boolean hasProvider = accessAuthorization.hasDefined(AccessAuthorizationResourceDefinition.PROVIDER.getName());
boolean hasCombinationPolicy = accessAuthorization.hasDefined(AccessAuthorizationResourceDefinition.PERMISSION_COMBINATION_POLICY.getName());
if (!hasProvider && !hasCombinationPolicy && !hasServerGroupRoles && !hasHostRoles
&& !hasRoleMapping && configuredAccessConstraints.size() == 0) {
return;
}
writer.writeStartElement(Element.ACCESS_CONTROL.getLocalName());
AccessAuthorizationResourceDefinition.PROVIDER.marshallAsAttribute(accessAuthorization, writer);
AccessAuthorizationResourceDefinition.PERMISSION_COMBINATION_POLICY.marshallAsAttribute(accessAuthorization, writer);
if (hasServerGroupRoles) {
ModelNode serverGroupRoles = accessAuthorization.get(SERVER_GROUP_SCOPED_ROLE);
if (serverGroupRoles.asInt() > 0) {
writeServerGroupScopedRoles(writer, serverGroupRoles);
}
}
if (hasHostRoles) {
ModelNode serverGroupRoles = accessAuthorization.get(HOST_SCOPED_ROLE);
if (serverGroupRoles.asInt() > 0) {
writeHostScopedRoles(writer, serverGroupRoles);
}
}
if (hasRoleMapping) {
writeRoleMapping(writer, accessAuthorization);
}
if (configuredAccessConstraints.size() > 0) {
writeAccessConstraints(writer, accessAuthorization, configuredAccessConstraints);
}
writer.writeEndElement();
}
private void writeSecurityRealm(XMLExtendedStreamWriter writer, ModelNode management) throws XMLStreamException {
ModelNode securityRealms = management.get(SECURITY_REALM);
writer.writeStartElement(Element.SECURITY_REALMS.getLocalName());
for (Property variable : securityRealms.asPropertyList()) {
writer.writeStartElement(Element.SECURITY_REALM.getLocalName());
writeAttribute(writer, Attribute.NAME, variable.getName());
ModelNode realm = variable.getValue();
if (realm.hasDefined(PLUG_IN)) {
writePlugIns(writer, realm.get(PLUG_IN));
}
if (realm.hasDefined(SERVER_IDENTITY)) {
writeServerIdentities(writer, realm);
}
if (realm.hasDefined(AUTHENTICATION)) {
writeAuthentication(writer, realm);
}
writeAuthorization(writer, realm);
writer.writeEndElement();
}
writer.writeEndElement();
}
private void writePlugIns(XMLExtendedStreamWriter writer, ModelNode plugIns) throws XMLStreamException {
writer.writeStartElement(Element.PLUG_INS.getLocalName());
for (Property variable : plugIns.asPropertyList()) {
writer.writeEmptyElement(Element.PLUG_IN.getLocalName());
writer.writeAttribute(Attribute.MODULE.getLocalName(), variable.getName());
}
writer.writeEndElement();
}
private void writeServerIdentities(XMLExtendedStreamWriter writer, ModelNode realm) throws XMLStreamException {
writer.writeStartElement(Element.SERVER_IDENTITIES.getLocalName());
ModelNode serverIdentities = realm.get(SERVER_IDENTITY);
if (serverIdentities.hasDefined(KERBEROS)) {
writer.writeStartElement(Element.KERBEROS.getLocalName());
ModelNode kerberos = serverIdentities.require(KERBEROS);
if (kerberos.hasDefined(KEYTAB)) {
List<Property> keytabList = kerberos.get(KEYTAB).asPropertyList();
for (Property current : keytabList) {
ModelNode currentNode = current.getValue();
writer.writeEmptyElement(KEYTAB);
writer.writeAttribute(Attribute.PRINCIPAL.getLocalName(), current.getName());
KeytabResourceDefinition.PATH.marshallAsAttribute(currentNode, writer);
KeytabResourceDefinition.RELATIVE_TO.marshallAsAttribute(currentNode, writer);
KeytabResourceDefinition.FOR_HOSTS.marshallAsElement(currentNode, writer);
KeytabResourceDefinition.DEBUG.marshallAsAttribute(currentNode, writer);
}
}
writer.writeEndElement();
}
if (serverIdentities.hasDefined(SSL)) {
writer.writeStartElement(Element.SSL.getLocalName());
ModelNode ssl = serverIdentities.get(SSL);
SSLServerIdentityResourceDefinition.PROTOCOL.marshallAsAttribute(ssl, writer);
if (ssl.hasDefined(ENABLED_CIPHER_SUITES) || ssl.hasDefined(ENABLED_PROTOCOLS)) {
writer.writeEmptyElement(Element.ENGINE.getLocalName());
SSLServerIdentityResourceDefinition.ENABLED_CIPHER_SUITES.marshallAsElement(ssl, writer);
SSLServerIdentityResourceDefinition.ENABLED_PROTOCOLS.marshallAsElement(ssl, writer);
}
boolean hasProvider = ssl.hasDefined(KEYSTORE_PROVIDER)
&& (JKS.equals(ssl.require(KEYSTORE_PROVIDER).asString()) == false);
if (hasProvider || ssl.hasDefined(KeystoreAttributes.KEYSTORE_PATH.getName())) {
writer.writeEmptyElement(Element.KEYSTORE.getLocalName());
KeystoreAttributes.KEYSTORE_PROVIDER.marshallAsAttribute(ssl, writer);
KeystoreAttributes.KEYSTORE_PATH.marshallAsAttribute(ssl, writer);
KeystoreAttributes.KEYSTORE_RELATIVE_TO.marshallAsAttribute(ssl, writer);
KeystoreAttributes.KEYSTORE_PASSWORD.marshallAsAttribute(ssl, writer);
KeystoreAttributes.ALIAS.marshallAsAttribute(ssl, writer);
KeystoreAttributes.KEY_PASSWORD.marshallAsAttribute(ssl, writer);
}
writer.writeEndElement();
}
if (serverIdentities.hasDefined(SECRET)) {
ModelNode secret = serverIdentities.get(SECRET);
writer.writeEmptyElement(Element.SECRET.getLocalName());
SecretServerIdentityResourceDefinition.VALUE.marshallAsAttribute(secret, writer);
}
writer.writeEndElement();
}
private void writeLdapCacheIfDefined(XMLExtendedStreamWriter writer, ModelNode parent) throws XMLStreamException {
if (parent.hasDefined(CACHE)) {
ModelNode cacheHolder = parent.require(CACHE);
final ModelNode cache;
final String type;
if (cacheHolder.hasDefined(BY_ACCESS_TIME)) {
cache = cacheHolder.require(BY_ACCESS_TIME);
type = BY_ACCESS_TIME;
} else if (cacheHolder.hasDefined(BY_SEARCH_TIME)) {
cache = cacheHolder.require(BY_SEARCH_TIME);
type = BY_SEARCH_TIME;
} else {
return;
}
writer.writeStartElement(Element.CACHE.getLocalName());
if (type.equals(BY_SEARCH_TIME) == false) {
writer.writeAttribute(Attribute.TYPE.getLocalName(), type);
}
LdapCacheResourceDefinition.EVICTION_TIME.marshallAsAttribute(cache, writer);
LdapCacheResourceDefinition.CACHE_FAILURES.marshallAsAttribute(cache, writer);
LdapCacheResourceDefinition.MAX_CACHE_SIZE.marshallAsAttribute(cache, writer);
writer.writeEndElement();
}
}
private void writeAuthentication(XMLExtendedStreamWriter writer, ModelNode realm) throws XMLStreamException {
writer.writeStartElement(Element.AUTHENTICATION.getLocalName());
ModelNode authentication = realm.require(AUTHENTICATION);
if (authentication.hasDefined(TRUSTSTORE)) {
ModelNode truststore = authentication.require(TRUSTSTORE);
writer.writeEmptyElement(Element.TRUSTSTORE.getLocalName());
KeystoreAttributes.KEYSTORE_PROVIDER.marshallAsAttribute(truststore, writer);
KeystoreAttributes.KEYSTORE_PATH.marshallAsAttribute(truststore, writer);
KeystoreAttributes.KEYSTORE_RELATIVE_TO.marshallAsAttribute(truststore, writer);
KeystoreAttributes.KEYSTORE_PASSWORD.marshallAsAttribute(truststore, writer);
}
if (authentication.hasDefined(LOCAL)) {
ModelNode local = authentication.require(LOCAL);
writer.writeStartElement(Element.LOCAL.getLocalName());
LocalAuthenticationResourceDefinition.DEFAULT_USER.marshallAsAttribute(local, writer);
LocalAuthenticationResourceDefinition.ALLOWED_USERS.marshallAsAttribute(local, writer);
LocalAuthenticationResourceDefinition.SKIP_GROUP_LOADING.marshallAsAttribute(local, writer);
writer.writeEndElement();
}
if (authentication.hasDefined(KERBEROS)) {
ModelNode kerberos = authentication.require(KERBEROS);
writer.writeEmptyElement(Element.KERBEROS.getLocalName());
KerberosAuthenticationResourceDefinition.REMOVE_REALM.marshallAsAttribute(kerberos, writer);
}
if (authentication.hasDefined(JAAS)) {
ModelNode jaas = authentication.get(JAAS);
writer.writeStartElement(Element.JAAS.getLocalName());
JaasAuthenticationResourceDefinition.NAME.marshallAsAttribute(jaas, writer);
JaasAuthenticationResourceDefinition.ASSIGN_GROUPS.marshallAsAttribute(jaas, writer);
writer.writeEndElement();
} else if (authentication.hasDefined(LDAP)) {
ModelNode userLdap = authentication.get(LDAP);
writer.writeStartElement(Element.LDAP.getLocalName());
LdapAuthenticationResourceDefinition.CONNECTION.marshallAsAttribute(userLdap, writer);
LdapAuthenticationResourceDefinition.BASE_DN.marshallAsAttribute(userLdap, writer);
LdapAuthenticationResourceDefinition.RECURSIVE.marshallAsAttribute(userLdap, writer);
LdapAuthenticationResourceDefinition.USER_DN.marshallAsAttribute(userLdap, writer);
LdapAuthenticationResourceDefinition.ALLOW_EMPTY_PASSWORDS.marshallAsAttribute(userLdap, writer);
LdapAuthenticationResourceDefinition.USERNAME_LOAD.marshallAsAttribute(userLdap, writer);
writeLdapCacheIfDefined(writer, userLdap);
if (LdapAuthenticationResourceDefinition.USERNAME_FILTER.isMarshallable(userLdap)) {
writer.writeEmptyElement(Element.USERNAME_FILTER.getLocalName());
LdapAuthenticationResourceDefinition.USERNAME_FILTER.marshallAsAttribute(userLdap, writer);
} else if (LdapAuthenticationResourceDefinition.ADVANCED_FILTER.isMarshallable(userLdap)) {
writer.writeEmptyElement(Element.ADVANCED_FILTER.getLocalName());
LdapAuthenticationResourceDefinition.ADVANCED_FILTER.marshallAsAttribute(userLdap, writer);
}
writer.writeEndElement();
} else if (authentication.hasDefined(PROPERTIES)) {
ModelNode properties = authentication.require(PROPERTIES);
writer.writeEmptyElement(Element.PROPERTIES.getLocalName());
PropertiesAuthenticationResourceDefinition.PATH.marshallAsAttribute(properties, writer);
PropertiesAuthenticationResourceDefinition.RELATIVE_TO.marshallAsAttribute(properties, writer);
PropertiesAuthenticationResourceDefinition.PLAIN_TEXT.marshallAsAttribute(properties, writer);
} else if (authentication.has(USERS)) {
ModelNode userDomain = authentication.get(USERS);
ModelNode users = userDomain.hasDefined(USER) ? userDomain.require(USER) : new ModelNode().setEmptyObject();
writer.writeStartElement(Element.USERS.getLocalName());
for (Property userProps : users.asPropertyList()) {
String userName = userProps.getName();
ModelNode currentUser = userProps.getValue();
writer.writeStartElement(Element.USER.getLocalName());
writer.writeAttribute(Attribute.USERNAME.getLocalName(), userName);
UserResourceDefinition.PASSWORD.marshallAsElement(currentUser, writer);
writer.writeEndElement();
}
writer.writeEndElement();
} else if (authentication.hasDefined(PLUG_IN)) {
writePlugIn_Authentication(writer, authentication.get(PLUG_IN));
}
writer.writeEndElement();
}
private void writePlugIn_Authentication(XMLExtendedStreamWriter writer, ModelNode plugIn) throws XMLStreamException {
writer.writeStartElement(Element.PLUG_IN.getLocalName());
AbstractPlugInAuthResourceDefinition.NAME.marshallAsAttribute(plugIn, writer);
PlugInAuthenticationResourceDefinition.MECHANISM.marshallAsAttribute(plugIn, writer);
if (plugIn.hasDefined(PROPERTY)) {
writer.writeStartElement(PROPERTIES);
for (Property current : plugIn.get(PROPERTY).asPropertyList()) {
writer.writeEmptyElement(PROPERTY);
writer.writeAttribute(Attribute.NAME.getLocalName(), current.getName());
PropertyResourceDefinition.VALUE.marshallAsAttribute(current.getValue(), writer);
}
writer.writeEndElement();
}
writer.writeEndElement();
}
private void writeAuthorization(XMLExtendedStreamWriter writer, ModelNode realm) throws XMLStreamException {
// A String comparison in-case it is an expression.
String defaultMapGroupsToRoles = Boolean.toString(SecurityRealmResourceDefinition.MAP_GROUPS_TO_ROLES.getDefaultValue().asBoolean());
String mapGroupsToRoles = realm.hasDefined(MAP_GROUPS_TO_ROLES) ? realm.require(MAP_GROUPS_TO_ROLES).asString() : defaultMapGroupsToRoles;
if (realm.hasDefined(AUTHORIZATION) || defaultMapGroupsToRoles.equals(mapGroupsToRoles) == false) {
writer.writeStartElement(Element.AUTHORIZATION.getLocalName());
SecurityRealmResourceDefinition.MAP_GROUPS_TO_ROLES.marshallAsAttribute(realm, writer);
if (realm.hasDefined(AUTHORIZATION)) {
ModelNode authorization = realm.require(AUTHORIZATION);
if (authorization.hasDefined(PROPERTIES)) {
ModelNode properties = authorization.require(PROPERTIES);
writer.writeEmptyElement(Element.PROPERTIES.getLocalName());
PropertiesAuthorizationResourceDefinition.PATH.marshallAsAttribute(properties, writer);
PropertiesAuthorizationResourceDefinition.RELATIVE_TO.marshallAsAttribute(properties, writer);
} else if (authorization.hasDefined(PLUG_IN)) {
writePlugIn_Authorization(writer, authorization.get(PLUG_IN));
} else if (authorization.hasDefined(LDAP)) {
writeLdapAuthorization(writer, authorization.get(LDAP));
}
}
writer.writeEndElement();
}
}
private void writeLdapAuthorization(XMLExtendedStreamWriter writer, ModelNode ldapNode) throws XMLStreamException {
writer.writeStartElement(Element.LDAP.getLocalName());
LdapAuthorizationResourceDefinition.CONNECTION.marshallAsAttribute(ldapNode, writer);
if (ldapNode.hasDefined(USERNAME_TO_DN)) {
ModelNode usenameToDn = ldapNode.require(USERNAME_TO_DN);
if (usenameToDn.hasDefined(USERNAME_IS_DN) || usenameToDn.hasDefined(USERNAME_FILTER)
|| usenameToDn.hasDefined(ADVANCED_FILTER)) {
writer.writeStartElement(Element.USERNAME_TO_DN.getLocalName());
if (usenameToDn.hasDefined(USERNAME_IS_DN)) {
ModelNode usernameIsDn = usenameToDn.require(USERNAME_IS_DN);
UserIsDnResourceDefintion.FORCE.marshallAsAttribute(usernameIsDn, writer);
writeLdapCacheIfDefined(writer, usernameIsDn);
writer.writeEmptyElement(Element.USERNAME_IS_DN.getLocalName());
} else if (usenameToDn.hasDefined(USERNAME_FILTER)) {
ModelNode usernameFilter = usenameToDn.require(USERNAME_FILTER);
UserSearchResourceDefintion.FORCE.marshallAsAttribute(usernameFilter, writer);
writeLdapCacheIfDefined(writer, usernameFilter);
writer.writeStartElement(Element.USERNAME_FILTER.getLocalName());
UserSearchResourceDefintion.BASE_DN.marshallAsAttribute(usernameFilter, writer);
UserSearchResourceDefintion.RECURSIVE.marshallAsAttribute(usernameFilter, writer);
UserSearchResourceDefintion.USER_DN_ATTRIBUTE.marshallAsAttribute(usernameFilter, writer);
UserSearchResourceDefintion.ATTRIBUTE.marshallAsAttribute(usernameFilter, writer);
writer.writeEndElement();
} else {
ModelNode advancedFilter = usenameToDn.require(ADVANCED_FILTER);
AdvancedUserSearchResourceDefintion.FORCE.marshallAsAttribute(advancedFilter, writer);
writeLdapCacheIfDefined(writer, advancedFilter);
writer.writeStartElement(Element.ADVANCED_FILTER.getLocalName());
AdvancedUserSearchResourceDefintion.BASE_DN.marshallAsAttribute(advancedFilter, writer);
AdvancedUserSearchResourceDefintion.RECURSIVE.marshallAsAttribute(advancedFilter, writer);
AdvancedUserSearchResourceDefintion.USER_DN_ATTRIBUTE.marshallAsAttribute(advancedFilter, writer);
AdvancedUserSearchResourceDefintion.FILTER.marshallAsAttribute(advancedFilter, writer);
writer.writeEndElement();
}
writer.writeEndElement();
}
}
if (ldapNode.hasDefined(GROUP_SEARCH)) {
ModelNode groupSearch = ldapNode.require(GROUP_SEARCH);
if (groupSearch.hasDefined(GROUP_TO_PRINCIPAL) || groupSearch.hasDefined(PRINCIPAL_TO_GROUP)) {
writer.writeStartElement(Element.GROUP_SEARCH.getLocalName());
if (groupSearch.hasDefined(GROUP_TO_PRINCIPAL)) {
ModelNode groupToPrincipal = groupSearch.require(GROUP_TO_PRINCIPAL);
GroupToPrincipalResourceDefinition.GROUP_NAME.marshallAsAttribute(groupToPrincipal, writer);
GroupToPrincipalResourceDefinition.ITERATIVE.marshallAsAttribute(groupToPrincipal, writer);
GroupToPrincipalResourceDefinition.GROUP_DN_ATTRIBUTE.marshallAsAttribute(groupToPrincipal, writer);
GroupToPrincipalResourceDefinition.GROUP_NAME_ATTRIBUTE.marshallAsAttribute(groupToPrincipal, writer);
writeLdapCacheIfDefined(writer, groupToPrincipal);
writer.writeStartElement(Element.GROUP_TO_PRINCIPAL.getLocalName());
GroupToPrincipalResourceDefinition.SEARCH_BY.marshallAsAttribute(groupToPrincipal, writer);
GroupToPrincipalResourceDefinition.BASE_DN.marshallAsAttribute(groupToPrincipal, writer);
GroupToPrincipalResourceDefinition.RECURSIVE.marshallAsAttribute(groupToPrincipal, writer);
GroupToPrincipalResourceDefinition.PREFER_ORIGINAL_CONNECTION.marshallAsAttribute(groupToPrincipal, writer);
writer.writeStartElement(Element.MEMBERSHIP_FILTER.getLocalName());
GroupToPrincipalResourceDefinition.PRINCIPAL_ATTRIBUTE.marshallAsAttribute(groupToPrincipal, writer);
writer.writeEndElement();
writer.writeEndElement();
} else {
ModelNode principalToGroup = groupSearch.require(PRINCIPAL_TO_GROUP);
PrincipalToGroupResourceDefinition.GROUP_NAME.marshallAsAttribute(principalToGroup, writer);
PrincipalToGroupResourceDefinition.ITERATIVE.marshallAsAttribute(principalToGroup, writer);
PrincipalToGroupResourceDefinition.GROUP_DN_ATTRIBUTE.marshallAsAttribute(principalToGroup, writer);
PrincipalToGroupResourceDefinition.GROUP_NAME_ATTRIBUTE.marshallAsAttribute(principalToGroup, writer);
writeLdapCacheIfDefined(writer, principalToGroup);
writer.writeStartElement(Element.PRINCIPAL_TO_GROUP.getLocalName());
PrincipalToGroupResourceDefinition.GROUP_ATTRIBUTE.marshallAsAttribute(principalToGroup, writer);
PrincipalToGroupResourceDefinition.PREFER_ORIGINAL_CONNECTION.marshallAsAttribute(principalToGroup, writer);
PrincipalToGroupResourceDefinition.SKIP_MISSING_GROUPS.marshallAsAttribute(principalToGroup, writer);
writer.writeEndElement();
}
writer.writeEndElement();
}
}
writer.writeEndElement();
}
private void writePlugIn_Authorization(XMLExtendedStreamWriter writer, ModelNode plugIn) throws XMLStreamException {
writer.writeStartElement(Element.PLUG_IN.getLocalName());
AbstractPlugInAuthResourceDefinition.NAME.marshallAsAttribute(plugIn, writer);
if (plugIn.hasDefined(PROPERTY)) {
writer.writeStartElement(PROPERTIES);
for (Property current : plugIn.get(PROPERTY).asPropertyList()) {
writer.writeEmptyElement(PROPERTY);
writer.writeAttribute(Attribute.NAME.getLocalName(), current.getName());
PropertyResourceDefinition.VALUE.marshallAsAttribute(current.getValue(), writer);
}
writer.writeEndElement();
}
writer.writeEndElement();
}
private void writeOutboundConnections(XMLExtendedStreamWriter writer, ModelNode management) throws XMLStreamException {
writer.writeStartElement(Element.OUTBOUND_CONNECTIONS.getLocalName());
for (Property variable : management.get(LDAP_CONNECTION).asPropertyList()) {
ModelNode connection = variable.getValue();
writer.writeStartElement(Element.LDAP.getLocalName());
writer.writeAttribute(Attribute.NAME.getLocalName(), variable.getName());
LdapConnectionResourceDefinition.URL.marshallAsAttribute(connection, writer);
LdapConnectionResourceDefinition.SEARCH_DN.marshallAsAttribute(connection, writer);
LdapConnectionResourceDefinition.SEARCH_CREDENTIAL.marshallAsAttribute(connection, writer);
LdapConnectionResourceDefinition.SECURITY_REALM.marshallAsAttribute(connection, writer);
LdapConnectionResourceDefinition.INITIAL_CONTEXT_FACTORY.marshallAsAttribute(connection, writer);
LdapConnectionResourceDefinition.REFERRALS.marshallAsAttribute(connection, writer);
LdapConnectionResourceDefinition.HANDLES_REFERRALS_FOR.marshallAsElement(connection, writer);
if (connection.hasDefined(PROPERTY)) {
List<Property> propertyList = connection.get(PROPERTY).asPropertyList();
if (propertyList.size() > 0) {
writer.writeStartElement(PROPERTIES);
for (Property current : propertyList) {
writer.writeEmptyElement(PROPERTY);
writer.writeAttribute(Attribute.NAME.getLocalName(), current.getName());
LdapConnectionPropertyResourceDefinition.VALUE.marshallAsAttribute(current.getValue(), writer);
}
writer.writeEndElement();
}
}
writer.writeEndElement();
}
writer.writeEndElement();
}
private void writeManagementInterfaces(XMLExtendedStreamWriter writer, ModelNode management) throws XMLStreamException {
writer.writeStartElement(Element.MANAGEMENT_INTERFACES.getLocalName());
ModelNode managementInterfaces = management.get(MANAGEMENT_INTERFACE);
if (managementInterfaces.hasDefined(NATIVE_REMOTING_INTERFACE)) {
writer.writeEmptyElement(Element.NATIVE_REMOTING_INTERFACE.getLocalName());
}
if (managementInterfaces.hasDefined(NATIVE_INTERFACE)) {
delegate.writeNativeManagementProtocol(writer, managementInterfaces.get(NATIVE_INTERFACE));
}
if (managementInterfaces.hasDefined(HTTP_INTERFACE)) {
delegate.writeHttpManagementProtocol(writer, managementInterfaces.get(HTTP_INTERFACE));
}
writer.writeEndElement();
}
private static Map<String, Map<String, Set<String>>> getConfiguredAccessConstraints(ModelNode accessAuthorization) {
Map<String, Map<String, Set<String>>> configuredConstraints = new HashMap<String, Map<String, Set<String>>>();
if (accessAuthorization != null && accessAuthorization.hasDefined(CONSTRAINT)) {
ModelNode constraint = accessAuthorization.get(CONSTRAINT);
configuredConstraints.putAll(getVaultConstraints(constraint));
configuredConstraints.putAll(getSensitivityClassificationConstraints(constraint));
configuredConstraints.putAll(getApplicationClassificationConstraints(constraint));
}
return configuredConstraints;
}
private static Map<String, Map<String, Set<String>>> getVaultConstraints(final ModelNode constraint) {
Map<String, Map<String, Set<String>>> configuredConstraints = new HashMap<String, Map<String, Set<String>>>();
if (constraint.hasDefined(VAULT_EXPRESSION)) {
ModelNode classification = constraint.require(VAULT_EXPRESSION);
if (classification.hasDefined(SensitivityResourceDefinition.CONFIGURED_REQUIRES_WRITE.getName())
|| classification.hasDefined(SensitivityResourceDefinition.CONFIGURED_REQUIRES_READ.getName())) {
configuredConstraints.put(SensitivityResourceDefinition.VAULT_ELEMENT.getKey(),
Collections.<String, Set<String>> emptyMap());
}
}
return configuredConstraints;
}
private static Map<String, Map<String, Set<String>>> getSensitivityClassificationConstraints(final ModelNode constraint) {
Map<String, Map<String, Set<String>>> configuredConstraints = new HashMap<String, Map<String, Set<String>>>();
if (constraint.hasDefined(SENSITIVITY_CLASSIFICATION)) {
ModelNode sensitivityParent = constraint.require(SENSITIVITY_CLASSIFICATION);
if (sensitivityParent.hasDefined(TYPE)) {
for (Property typeProperty : sensitivityParent.get(TYPE).asPropertyList()) {
if (typeProperty.getValue().hasDefined(CLASSIFICATION)) {
for (Property sensitivityProperty : typeProperty.getValue().get(CLASSIFICATION).asPropertyList()) {
ModelNode classification = sensitivityProperty.getValue();
if (classification.hasDefined(SensitivityResourceDefinition.CONFIGURED_REQUIRES_ADDRESSABLE.getName())
|| classification.hasDefined(SensitivityResourceDefinition.CONFIGURED_REQUIRES_WRITE
.getName())
|| classification.hasDefined(SensitivityResourceDefinition.CONFIGURED_REQUIRES_READ
.getName())) {
Map<String, Set<String>> constraintMap = configuredConstraints.get(SENSITIVITY_CLASSIFICATION);
if (constraintMap == null) {
constraintMap = new TreeMap<String, Set<String>>();
configuredConstraints.put(SENSITIVITY_CLASSIFICATION, constraintMap);
}
Set<String> types = constraintMap.get(typeProperty.getName());
if (types == null) {
types = new TreeSet<String>();
constraintMap.put(typeProperty.getName(), types);
}
types.add(sensitivityProperty.getName());
}
}
}
}
}
}
return configuredConstraints;
}
private static Map<String, Map<String, Set<String>>> getApplicationClassificationConstraints(final ModelNode constraint) {
Map<String, Map<String, Set<String>>> configuredConstraints = new HashMap<String, Map<String, Set<String>>>();
if (constraint.hasDefined(APPLICATION_CLASSIFICATION)) {
ModelNode appTypeParent = constraint.require(APPLICATION_CLASSIFICATION);
if (appTypeParent.hasDefined(TYPE)) {
for (Property typeProperty : appTypeParent.get(TYPE).asPropertyList()) {
if (typeProperty.getValue().hasDefined(CLASSIFICATION)) {
for (Property applicationProperty : typeProperty.getValue().get(CLASSIFICATION).asPropertyList()) {
ModelNode applicationType = applicationProperty.getValue();
if (applicationType.hasDefined(ApplicationClassificationConfigResourceDefinition.CONFIGURED_APPLICATION.getName())) {
Map<String, Set<String>> constraintMap = configuredConstraints.get(APPLICATION_CLASSIFICATION);
if (constraintMap == null) {
constraintMap = new TreeMap<String, Set<String>>();
configuredConstraints.put(APPLICATION_CLASSIFICATION, constraintMap);
}
Set<String> types = constraintMap.get(typeProperty.getName());
if (types == null) {
types = new TreeSet<String>();
constraintMap.put(typeProperty.getName(), types);
}
types.add(applicationProperty.getName());
}
}
}
}
}
}
return configuredConstraints;
}
private static void writeRoleMapping(XMLExtendedStreamWriter writer, ModelNode accessAuthorization)
throws XMLStreamException {
writer.writeStartElement(Element.ROLE_MAPPING.getLocalName());
if (accessAuthorization.hasDefined(ROLE_MAPPING)) {
ModelNode roleMappings = accessAuthorization.get(ROLE_MAPPING);
for (Property variable : roleMappings.asPropertyList()) {
writer.writeStartElement(Element.ROLE.getLocalName());
writeAttribute(writer, Attribute.NAME, variable.getName());
ModelNode role = variable.getValue();
RoleMappingResourceDefinition.INCLUDE_ALL.marshallAsAttribute(role, writer);
if (role.hasDefined(INCLUDE)) {
writeIncludeExclude(writer, Element.INCLUDE.getLocalName(), role.get(INCLUDE));
}
if (role.hasDefined(EXCLUDE)) {
writeIncludeExclude(writer, Element.EXCLUDE.getLocalName(), role.get(EXCLUDE));
}
writer.writeEndElement();
}
}
writer.writeEndElement();
}
private static void writeIncludeExclude(XMLExtendedStreamWriter writer, String elementName, ModelNode includeExclude)
throws XMLStreamException {
List<Property> list = includeExclude.asPropertyList();
if (list.isEmpty()) {
return;
}
writer.writeStartElement(elementName);
for (Property current : list) {
// The names where only arbitrary to allow unique referencing.
writePrincipal(writer, current.getName(), current.getValue());
}
writer.writeEndElement();
}
private static void writePrincipal(XMLExtendedStreamWriter writer, String alias, ModelNode principal) throws XMLStreamException {
String elementName = principal.require(TYPE).asString().equalsIgnoreCase(GROUP) ? Element.GROUP.getLocalName() : Element.USER.getLocalName();
writer.writeStartElement(elementName);
String realm = principal.get(REALM).isDefined() ? principal.require(REALM).asString() : null;
String name = principal.require(NAME).asString();
String expectedAlias = generateAlias(elementName, name, realm);
if (alias.equals(expectedAlias)==false) {
writeAttribute(writer, Attribute.ALIAS, alias);
}
PrincipalResourceDefinition.REALM.marshallAsAttribute(principal, writer);
PrincipalResourceDefinition.NAME.marshallAsAttribute(principal, writer);
writer.writeEndElement();
}
private static void writeAccessConstraints(XMLExtendedStreamWriter writer, ModelNode accessAuthorization, Map<String, Map<String, Set<String>>> configuredConstraints) throws XMLStreamException {
writer.writeStartElement(Element.CONSTRAINTS.getLocalName());
if (configuredConstraints.containsKey(SensitivityResourceDefinition.VAULT_ELEMENT.getKey())){
writer.writeEmptyElement(Element.VAULT_EXPRESSION_SENSITIVITY.getLocalName());
ModelNode model = accessAuthorization.get(SensitivityResourceDefinition.VAULT_ELEMENT.getKey(),
SensitivityResourceDefinition.VAULT_ELEMENT.getValue());
SensitivityResourceDefinition.CONFIGURED_REQUIRES_READ.marshallAsAttribute(model, writer);
SensitivityResourceDefinition.CONFIGURED_REQUIRES_WRITE.marshallAsAttribute(model, writer);
}
if (configuredConstraints.containsKey(SENSITIVITY_CLASSIFICATION)) {
writer.writeStartElement(Element.SENSITIVE_CLASSIFICATIONS.getLocalName());
Map<String, Set<String>> constraints = configuredConstraints.get(SENSITIVITY_CLASSIFICATION);
for (Map.Entry<String, Set<String>> entry : constraints.entrySet()) {
for (String classification : entry.getValue()) {
writer.writeEmptyElement(Element.SENSITIVE_CLASSIFICATION.getLocalName());
ModelNode model = accessAuthorization.get(CONSTRAINT, SENSITIVITY_CLASSIFICATION, TYPE, entry.getKey(), CLASSIFICATION, classification);
writeAttribute(writer, Attribute.TYPE, entry.getKey());
writeAttribute(writer, Attribute.NAME, classification);
SensitivityResourceDefinition.CONFIGURED_REQUIRES_ADDRESSABLE.marshallAsAttribute(model, writer);
SensitivityResourceDefinition.CONFIGURED_REQUIRES_READ.marshallAsAttribute(model, writer);
SensitivityResourceDefinition.CONFIGURED_REQUIRES_WRITE.marshallAsAttribute(model, writer);
}
}
writer.writeEndElement();
}
if (configuredConstraints.containsKey(APPLICATION_CLASSIFICATION)) {
writer.writeStartElement(Element.APPLICATION_CLASSIFICATIONS.getLocalName());
Map<String, Set<String>> constraints = configuredConstraints.get(APPLICATION_CLASSIFICATION);
for (Map.Entry<String, Set<String>> entry : constraints.entrySet()) {
for (String classification : entry.getValue()) {
writer.writeEmptyElement(Element.APPLICATION_CLASSIFICATION.getLocalName());
ModelNode model = accessAuthorization.get(CONSTRAINT, APPLICATION_CLASSIFICATION, TYPE, entry.getKey(), CLASSIFICATION, classification);
writeAttribute(writer, Attribute.TYPE, entry.getKey());
writeAttribute(writer, Attribute.NAME, classification);
ApplicationClassificationConfigResourceDefinition.CONFIGURED_APPLICATION.marshallAsAttribute(model, writer);
}
}
writer.writeEndElement();
}
writer.writeEndElement();
}
private static void writeServerGroupScopedRoles(XMLExtendedStreamWriter writer, ModelNode scopedRoles) throws XMLStreamException {
writer.writeStartElement(Element.SERVER_GROUP_SCOPED_ROLES.getLocalName());
for (Property property : scopedRoles.asPropertyList()) {
writer.writeStartElement(Element.ROLE.getLocalName());
writer.writeAttribute(Attribute.NAME.getLocalName(), property.getName());
ModelNode value = property.getValue();
ServerGroupScopedRoleResourceDefinition.BASE_ROLE.marshallAsAttribute(value, writer);
ServerGroupScopedRoleResourceDefinition.SERVER_GROUPS.marshallAsElement(value, writer);
writer.writeEndElement();
}
writer.writeEndElement();
}
private static void writeHostScopedRoles(XMLExtendedStreamWriter writer, ModelNode scopedRoles) throws XMLStreamException {
writer.writeStartElement(Element.HOST_SCOPED_ROLES.getLocalName());
for (Property property : scopedRoles.asPropertyList()) {
writer.writeStartElement(Element.ROLE.getLocalName());
writer.writeAttribute(Attribute.NAME.getLocalName(), property.getName());
ModelNode value = property.getValue();
HostScopedRolesResourceDefinition.BASE_ROLE.marshallAsAttribute(value, writer);
HostScopedRolesResourceDefinition.HOSTS.marshallAsElement(value, writer);
writer.writeEndElement();
}
writer.writeEndElement();
}
private static void writeAttribute(XMLExtendedStreamWriter writer, Attribute attribute, String value)
throws XMLStreamException {
writer.writeAttribute(attribute.getLocalName(), value);
}
}
|
package me.atrox.haikunator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class Haikunator {
private Random rnd = new Random();
private String[] ADJECTIVES = {
"autumn", "hidden", "bitter", "misty", "silent", "empty", "dry", "dark",
"summer", "icy", "delicate", "quiet", "white", "cool", "spring", "winter",
"patient", "twilight", "dawn", "crimson", "wispy", "weathered", "blue",
"billowing", "broken", "cold", "damp", "falling", "frosty", "green",
"long", "late", "lingering", "bold", "little", "morning", "muddy", "old",
"red", "rough", "still", "small", "sparkling", "throbbing", "shy",
"wandering", "withered", "wild", "black", "young", "holy", "solitary",
"fragrant", "aged", "snowy", "proud", "floral", "restless", "divine",
"polished", "ancient", "purple", "lively", "nameless", "lucky", "odd", "tiny",
"free", "dry", "yellow", "orange", "gentle", "tight", "super", "royal", "broad",
"steep", "flat", "square", "round", "mute", "noisy", "hushy", "raspy", "soft",
"shrill", "rapid", "sweet", "curly", "calm", "jolly", "fancy", "plain", "shinny"
};
private String[] NOUNS = {
"waterfall", "river", "breeze", "moon", "rain", "wind", "sea", "morning",
"snow", "lake", "sunset", "pine", "shadow", "leaf", "dawn", "glitter",
"forest", "hill", "cloud", "meadow", "sun", "glade", "bird", "brook",
"butterfly", "bush", "dew", "dust", "field", "fire", "flower", "firefly",
"feather", "grass", "haze", "mountain", "night", "pond", "darkness",
"snowflake", "silence", "sound", "sky", "shape", "surf", "thunder",
"violet", "water", "wildflower", "wave", "water", "resonance", "sun",
"wood", "dream", "cherry", "tree", "fog", "frost", "voice", "paper",
"frog", "smoke", "star", "atom", "band", "bar", "base", "block", "boat",
"term", "credit", "art", "fashion", "truth", "disk", "math", "unit", "cell",
"scene", "heart", "recipe", "union", "limit", "bread", "toast", "bonus",
"lab", "mud", "mode", "poetry", "tooth", "hall", "king", "queen", "lion", "tiger",
"penguin", "kiwi", "cake", "mouse", "rice", "coke", "hola", "salad", "hat"
};
private final String delimiter;
private String tokenChars;
private final int tokenLength;
private final boolean tokenHex;
Haikunator(String delimiter, String tokenChars, int tokenLength, boolean tokenHex) {
this.delimiter = delimiter;
this.tokenChars = tokenChars;
this.tokenLength = tokenLength;
this.tokenHex = tokenHex;
}
/**
* Generate Heroku-like random names
* @return String
*/
public String haikunate() {
String adjective, noun, token = "";
if (tokenHex) tokenChars = "0123456789abcdef";
adjective = ADJECTIVES[rnd.nextInt(ADJECTIVES.length)];
noun = NOUNS[rnd.nextInt(NOUNS.length)];
for (int i = 0; i < tokenLength; i++) {
token += tokenChars.charAt(rnd.nextInt(tokenChars.length()));
}
List<String> list = new ArrayList<String>(Arrays.asList(adjective, noun, token));
list.removeAll(Arrays.asList("", null));
return join(list, delimiter);
}
private static String join(List<String> list, String delim) {
StringBuilder sb = new StringBuilder();
String loopDelim = "";
for(String s : list) {
sb.append(loopDelim);
sb.append(s);
loopDelim = delim;
}
return sb.toString();
}
}
class HaikunatorBuilder {
private String delimiter = "-", tokenChars = "0123456789";
private int tokenLength = 4;
private boolean tokenHex = false;
HaikunatorBuilder setDelimiter(String delimiter) {
this.delimiter = delimiter;
return this;
}
HaikunatorBuilder setTokenChars(String tokenChars) {
this.tokenChars = tokenChars;
return this;
}
HaikunatorBuilder setTokenLength(int tokenLength) {
this.tokenLength = tokenLength;
return this;
}
HaikunatorBuilder setTokenHex(boolean tokenHex) {
this.tokenHex = tokenHex;
return this;
}
Haikunator build() {
return new Haikunator(delimiter, tokenChars, tokenLength, tokenHex);
}
}
|
package com.xpn.xwiki.internal.render;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.xwiki.security.authorization.ContextualAuthorizationManager;
import org.xwiki.security.authorization.Right;
import com.xpn.xwiki.render.ScriptHttpSession;
import com.xpn.xwiki.render.ScriptXWikiServletRequest;
import com.xpn.xwiki.web.XWikiRequest;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
* Validate {@link ScriptXWikiServletRequest}.
*
* @version $Id$
*/
public class ScriptXWikiServletRequestTest
{
private final ContextualAuthorizationManager authorization = mock(ContextualAuthorizationManager.class);
private final XWikiRequest request = mock(XWikiRequest.class);
private final HttpSession session = mock(HttpSession.class);
private final ServletContext servletContext = mock(ServletContext.class);
private final Map<String, Object> sessionMap = new HashMap<>();
private ScriptXWikiServletRequest scriptRequest;
@BeforeEach
void beforeEach()
{
when(this.request.getSession()).thenReturn(this.session);
when(this.request.getSession(anyBoolean())).thenReturn(this.session);
when(this.request.getServletContext()).thenReturn(this.servletContext);
when(this.request.getHttpServletRequest()).thenReturn(this.request);
when(this.session.getServletContext()).thenReturn(this.servletContext);
doAnswer(new Answer<Void>()
{
@Override
public Void answer(InvocationOnMock invocation) throws Throwable
{
sessionMap.put(invocation.getArgument(0), invocation.getArgument(1));
return null;
}
}).when(this.session).setAttribute(anyString(), any());
doAnswer(new Answer<Object>()
{
@Override
public Object answer(InvocationOnMock invocation) throws Throwable
{
return sessionMap.get(invocation.getArgument(0));
}
}).when(this.session).getAttribute(anyString());
doAnswer(new Answer<Enumeration<String>>()
{
@Override
public Enumeration<String> answer(InvocationOnMock invocation) throws Throwable
{
return Collections.enumeration(sessionMap.keySet());
}
}).when(this.session).getAttributeNames();
this.scriptRequest = new ScriptXWikiServletRequest(this.request, this.authorization);
}
private void setProgramingRight(boolean allowed)
{
when(this.authorization.hasAccess(Right.PROGRAM)).thenReturn(allowed);
}
private <T> void assertEqualsSet(Collection<T> expect, Enumeration<T> actual)
{
assertEquals(new HashSet<>(expect), new HashSet<>(Collections.list(actual)));
}
// Tests
@Test
void getServletContext()
{
setProgramingRight(true);
assertSame(this.servletContext, this.scriptRequest.getServletContext());
setProgramingRight(false);
assertNull(this.scriptRequest.getServletContext());
}
@Test
void getHttpServletRequest()
{
setProgramingRight(true);
assertSame(this.request, this.scriptRequest.getHttpServletRequest());
setProgramingRight(false);
assertSame(this.scriptRequest, this.scriptRequest.getHttpServletRequest());
}
@Test
void sessionGetServletContext()
{
ScriptHttpSession scriptSession = (ScriptHttpSession) this.scriptRequest.getSession();
setProgramingRight(true);
assertSame(this.servletContext, scriptSession.getServletContext());
setProgramingRight(false);
assertNull(scriptSession.getServletContext());
}
@Test
void sessionInvalidate()
{
ScriptHttpSession scriptSession = (ScriptHttpSession) this.scriptRequest.getSession();
setProgramingRight(false);
scriptSession.invalidate();
verifyNoInteractions(this.session);
setProgramingRight(true);
scriptSession.invalidate();
verify(this.session).invalidate();
}
@Test
void sessionAttributes()
{
ScriptHttpSession scriptSession = (ScriptHttpSession) this.scriptRequest.getSession();
setProgramingRight(false);
assertNull(scriptSession.getAttribute("name"));
scriptSession.setAttribute("name", "value");
assertEquals("value", scriptSession.getAttribute("name"));
assertEquals("value", scriptSession.getSafeAttribute("name"));
scriptSession.setSafeAttribute("safename", "safevalue");
assertEquals("safevalue", scriptSession.getAttribute("safename"));
assertEquals("safevalue", scriptSession.getSafeAttribute("safename"));
scriptSession.removeAttribute("safename");
assertNull(scriptSession.getAttribute("safename"));
assertNull(scriptSession.getSafeAttribute("safename"));
setProgramingRight(true);
assertNull(scriptSession.getAttribute("name"));
assertEquals("value", scriptSession.getSafeAttribute("name"));
scriptSession.setAttribute("name", "unsafevalue");
assertEquals("unsafevalue", scriptSession.getAttribute("name"));
assertEquals("value", scriptSession.getSafeAttribute("name"));
assertEqualsSet(Arrays.asList("name", ScriptHttpSession.class.getName()), scriptSession.getAttributeNames());
setProgramingRight(false);
assertEquals("value", scriptSession.getAttribute("name"));
assertEquals("value", scriptSession.getSafeAttribute("name"));
assertEqualsSet(Arrays.asList("name"), scriptSession.getAttributeNames());
}
@Test
void getRequestURL()
{
StringBuffer buffer = new StringBuffer();
when(this.request.getRequestURL()).thenReturn(buffer);
assertSame(buffer, this.scriptRequest.getRequestURL());
}
}
|
package org.hibernate.validator.internal.engine;
import java.io.Serializable;
import java.lang.annotation.ElementType;
import java.util.Map;
import javax.validation.ConstraintViolation;
import javax.validation.Path;
import javax.validation.metadata.ConstraintDescriptor;
import org.hibernate.validator.engine.HibernateConstraintViolation;
import org.hibernate.validator.internal.util.logging.Log;
import org.hibernate.validator.internal.util.logging.LoggerFactory;
/**
* @author Emmanuel Bernard
* @author Hardy Ferentschik
*/
public class ConstraintViolationImpl<T> implements HibernateConstraintViolation<T>, Serializable {
private static final Log log = LoggerFactory.make();
private static final long serialVersionUID = -4970067626703103139L;
private final String interpolatedMessage;
private final T rootBean;
private final Object value;
private final Path propertyPath;
private final Object leafBeanInstance;
private final ConstraintDescriptor<?> constraintDescriptor;
private final String messageTemplate;
private final Map<String, Object> expressionVariables;
private final Class<T> rootBeanClass;
private final ElementType elementType;
private final Object[] executableParameters;
private final Object executableReturnValue;
private final Object dynamicPayload;
private final int hashCode;
public static <T> ConstraintViolation<T> forBeanValidation(String messageTemplate,
Map<String, Object> expressionVariables,
String interpolatedMessage,
Class<T> rootBeanClass,
T rootBean,
Object leafBeanInstance,
Object value,
Path propertyPath,
ConstraintDescriptor<?> constraintDescriptor,
ElementType elementType,
Object dynamicPayload) {
return new ConstraintViolationImpl<T>(
messageTemplate,
expressionVariables,
interpolatedMessage,
rootBeanClass,
rootBean,
leafBeanInstance,
value,
propertyPath,
constraintDescriptor,
elementType,
null,
null,
dynamicPayload
);
}
public static <T> ConstraintViolation<T> forParameterValidation(String messageTemplate,
Map<String, Object> expressionVariables,
String interpolatedMessage,
Class<T> rootBeanClass,
T rootBean,
Object leafBeanInstance,
Object value,
Path propertyPath,
ConstraintDescriptor<?> constraintDescriptor,
ElementType elementType,
Object[] executableParameters,
Object dynamicPayload) {
return new ConstraintViolationImpl<T>(
messageTemplate,
expressionVariables,
interpolatedMessage,
rootBeanClass,
rootBean,
leafBeanInstance,
value,
propertyPath,
constraintDescriptor,
elementType,
executableParameters,
null,
dynamicPayload
);
}
public static <T> ConstraintViolation<T> forReturnValueValidation(String messageTemplate,
Map<String, Object> expressionVariables,
String interpolatedMessage,
Class<T> rootBeanClass,
T rootBean,
Object leafBeanInstance,
Object value,
Path propertyPath,
ConstraintDescriptor<?> constraintDescriptor,
ElementType elementType,
Object executableReturnValue,
Object dynamicPayload) {
return new ConstraintViolationImpl<T>(
messageTemplate,
expressionVariables,
interpolatedMessage,
rootBeanClass,
rootBean,
leafBeanInstance,
value,
propertyPath,
constraintDescriptor,
elementType,
null,
executableReturnValue,
dynamicPayload
);
}
private ConstraintViolationImpl(String messageTemplate,
Map<String, Object> expressionVariables,
String interpolatedMessage,
Class<T> rootBeanClass,
T rootBean,
Object leafBeanInstance,
Object value,
Path propertyPath,
ConstraintDescriptor<?> constraintDescriptor,
ElementType elementType,
Object[] executableParameters,
Object executableReturnValue,
Object dynamicPayload) {
this.messageTemplate = messageTemplate;
this.expressionVariables = expressionVariables;
this.interpolatedMessage = interpolatedMessage;
this.rootBean = rootBean;
this.value = value;
this.propertyPath = propertyPath;
this.leafBeanInstance = leafBeanInstance;
this.constraintDescriptor = constraintDescriptor;
this.rootBeanClass = rootBeanClass;
this.elementType = elementType;
this.executableParameters = executableParameters;
this.executableReturnValue = executableReturnValue;
this.dynamicPayload = dynamicPayload;
// pre-calculate hash code, the class is immutable and hashCode is needed often
this.hashCode = createHashCode();
}
@Override
public final String getMessage() {
return interpolatedMessage;
}
@Override
public final String getMessageTemplate() {
return messageTemplate;
}
/**
*
* @return the expression variables added using {@link org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorContextImpl#addExpressionVariable(String, Object)}
*/
public Map<String, Object> getExpressionVariables() {
return expressionVariables;
}
@Override
public final T getRootBean() {
return rootBean;
}
@Override
public final Class<T> getRootBeanClass() {
return rootBeanClass;
}
@Override
public final Object getLeafBean() {
return leafBeanInstance;
}
@Override
public final Object getInvalidValue() {
return value;
}
@Override
public final Path getPropertyPath() {
return propertyPath;
}
@Override
public final ConstraintDescriptor<?> getConstraintDescriptor() {
return this.constraintDescriptor;
}
@Override
public <C> C unwrap(Class<C> type) {
// Keep backward compatibility
if ( type.isAssignableFrom( ConstraintViolation.class ) ) {
return type.cast( this );
}
if ( type.isAssignableFrom( HibernateConstraintViolation.class ) ) {
return type.cast( this );
}
throw log.getTypeNotSupportedForUnwrappingException( type );
}
@Override
public Object[] getExecutableParameters() {
return executableParameters;
}
@Override
public Object getExecutableReturnValue() {
return executableReturnValue;
}
@Override
public <C> C getDynamicPayload(Class<C> type) {
if ( dynamicPayload != null && type.isAssignableFrom( dynamicPayload.getClass() ) ) {
return type.cast( dynamicPayload );
}
else {
return null;
}
}
/**
* IMPORTANT - some behaviour of Validator depends on the correct implementation of this equals method! (HF)
*
* {@code expressionVariables} and {@code dynamicPayload} are not taken into account for equality. These
* variables solely enrich the actual Constraint Violation with additional information e.g how we actually
* got to this CV.
*
* @return true if the two ConstraintViolation's are considered equals; false otherwise
*/
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
ConstraintViolationImpl<?> that = (ConstraintViolationImpl<?>) o;
if ( interpolatedMessage != null ? !interpolatedMessage.equals( that.interpolatedMessage ) : that.interpolatedMessage != null ) {
return false;
}
if ( propertyPath != null ? !propertyPath.equals( that.propertyPath ) : that.propertyPath != null ) {
return false;
}
if ( rootBean != null ? !rootBean.equals( that.rootBean ) : that.rootBean != null ) {
return false;
}
if ( leafBeanInstance != null ? !leafBeanInstance.equals( that.leafBeanInstance ) : that.leafBeanInstance != null ) {
return false;
}
if ( constraintDescriptor != null ? !constraintDescriptor.equals( that.constraintDescriptor ) : that.constraintDescriptor != null ) {
return false;
}
if ( elementType != null ? !elementType.equals( that.elementType ) : that.elementType != null ) {
return false;
}
if ( messageTemplate != null ? !messageTemplate.equals( that.messageTemplate ) : that.messageTemplate != null ) {
return false;
}
if ( rootBeanClass != null ? !rootBeanClass.equals( that.rootBeanClass ) : that.rootBeanClass != null ) {
return false;
}
if ( value != null ? !value.equals( that.value ) : that.value != null ) {
return false;
}
return true;
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append( "ConstraintViolationImpl" );
sb.append( "{interpolatedMessage='" ).append( interpolatedMessage ).append( '\'' );
sb.append( ", propertyPath=" ).append( propertyPath );
sb.append( ", rootBeanClass=" ).append( rootBeanClass );
sb.append( ", messageTemplate='" ).append( messageTemplate ).append( '\'' );
sb.append( '}' );
return sb.toString();
}
/**
* @see #equals(Object) on which fields are taken into account
*/
private int createHashCode() {
int result = interpolatedMessage != null ? interpolatedMessage.hashCode() : 0;
result = 31 * result + ( propertyPath != null ? propertyPath.hashCode() : 0 );
result = 31 * result + ( rootBean != null ? rootBean.hashCode() : 0 );
result = 31 * result + ( leafBeanInstance != null ? leafBeanInstance.hashCode() : 0 );
result = 31 * result + ( value != null ? value.hashCode() : 0 );
result = 31 * result + ( constraintDescriptor != null ? constraintDescriptor.hashCode() : 0 );
result = 31 * result + ( messageTemplate != null ? messageTemplate.hashCode() : 0 );
result = 31 * result + ( rootBeanClass != null ? rootBeanClass.hashCode() : 0 );
result = 31 * result + ( elementType != null ? elementType.hashCode() : 0 );
return result;
}
}
|
package me.xuender.unidecode;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public final class Unidecode {
/**
* Array to cache already loaded maps.
*/
private static final String[][] cache = new String[256][];
/**
* Transliterate an Unicode object into an ASCII string.
*
* @param str
* Unicode String to transliterate.
* @return ASCII string.
*/
public static String decode(final String str) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int codepoint = str.codePointAt(i);
// Basic ASCII
if (codepoint < 0x80) {
sb.append(c);
continue;
}
// Characters in Private Use Area and above are ignored
if (codepoint > 0xeffff)
continue;
int section = codepoint >> 8; // Chop off the last two hex digits
int position = codepoint % 256; // Last two hex digits
String[] table = getCache(section);
if (table != null && table.length > position) {
sb.append(table[position]);
}
}
return sb.toString().trim();
}
private static String[] getCache(int section) {
String[] ret = cache[section];
if (ret == null) {
InputStream inStream = null;
try {
inStream = Unidecode.class.getResourceAsStream(String.format(
"/X%03x", section));
BufferedReader reader = new BufferedReader(
new InputStreamReader(inStream));
String line = null;
ret = new String[256];
int i = 0;
while ((line = reader.readLine()) != null) {
ret[i] = line;
i++;
}
cache[section] = ret;
} catch (Exception e) {
// No match: ignore this character and carry on.
cache[section] = new String[] {};
} finally {
if (inStream != null) {
try {
inStream.close();
} catch (IOException e) {
}
}
}
} else if (ret.length == 0) {
return null;
}
return ret;
}
}
|
package org.neo4j.cluster.protocol.election;
import static org.neo4j.helpers.collection.Iterables.filter;
import static org.neo4j.helpers.collection.Iterables.map;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.neo4j.cluster.InstanceId;
import org.neo4j.cluster.com.message.Message;
import org.neo4j.cluster.protocol.cluster.ClusterContext;
import org.neo4j.cluster.protocol.heartbeat.HeartbeatContext;
import org.neo4j.helpers.Function;
import org.neo4j.helpers.Predicate;
import org.neo4j.helpers.collection.Iterables;
import org.neo4j.kernel.impl.util.StringLogger;
/**
* Context used by {@link ElectionState}.
*/
public class ElectionContext
{
private final List<ElectionRole> roles = new ArrayList<ElectionRole>();
private final ClusterContext clusterContext;
private final HeartbeatContext heartbeatContext;
private final Map<String, Election> elections = new HashMap<String, Election>();
private ElectionCredentialsProvider electionCredentialsProvider;
public ElectionContext( Iterable<ElectionRole> roles, ClusterContext clusterContext,
HeartbeatContext heartbeatContext )
{
this.heartbeatContext = heartbeatContext;
Iterables.addAll( this.roles, roles );
this.clusterContext = clusterContext;
}
public void setElectionCredentialsProvider( ElectionCredentialsProvider electionCredentialsProvider )
{
this.electionCredentialsProvider = electionCredentialsProvider;
}
public void created()
{
for ( ElectionRole role : roles )
{
// Elect myself for all roles
clusterContext.elected( role.getName(), clusterContext.getMyId() );
}
}
public List<ElectionRole> getPossibleRoles()
{
return roles;
}
/*
* Removes all roles from the provided node. This is expected to be the first call when receiving a demote
* message for a node, since it is the way to ensure that election will happen for each role that node had
*/
public void nodeFailed( InstanceId node )
{
Iterable<String> rolesToDemote = getRoles( node );
for ( String role : rolesToDemote )
{
clusterContext.getConfiguration().removeElected( role );
}
}
public Iterable<String> getRoles( InstanceId server )
{
return clusterContext.getConfiguration().getRolesOf( server );
}
public ClusterContext getClusterContext()
{
return clusterContext;
}
public HeartbeatContext getHeartbeatContext()
{
return heartbeatContext;
}
public void unelect( String roleName )
{
clusterContext.getConfiguration().removeElected( roleName );
}
public boolean isElectionProcessInProgress( String role )
{
return elections.containsKey( role );
}
public void startDemotionProcess( String role, final InstanceId demoteNode )
{
elections.put( role, new Election( new WinnerStrategy()
{
@Override
public InstanceId pickWinner( Collection<Vote> voteList )
{
// Remove blank votes
List<Vote> filteredVoteList = Iterables.toList( Iterables.filter( new Predicate<Vote>()
{
@Override
public boolean accept( Vote item )
{
return !( item.getCredentials() instanceof NotElectableElectionCredentials );
}
}, voteList ) );
// Sort based on credentials
// The most suited candidate should come out on top
Collections.sort( filteredVoteList );
Collections.reverse( filteredVoteList );
for ( Vote vote : filteredVoteList )
{
// Don't elect as winner the node we are trying to demote
if ( !vote.getSuggestedNode().equals( demoteNode ) )
{
return vote.getSuggestedNode();
}
}
// No possible winner
return null;
}
} ) );
}
public void startElectionProcess( String role )
{
clusterContext.getLogger( getClass() ).info( "Doing elections for role " + role );
elections.put( role, new Election( new WinnerStrategy()
{
@Override
public InstanceId pickWinner( Collection<Vote> voteList )
{
// Remove blank votes
List<Vote> filteredVoteList = Iterables.toList( Iterables.filter( new Predicate<Vote>()
{
@Override
public boolean accept( Vote item )
{
return !( item.getCredentials() instanceof NotElectableElectionCredentials );
}
}, voteList ) );
// Sort based on credentials
// The most suited candidate should come out on top
Collections.sort( filteredVoteList );
Collections.reverse( filteredVoteList );
clusterContext.getLogger( getClass() ).debug( "Elections ended up with list " + filteredVoteList );
for ( Vote vote : filteredVoteList )
{
return vote.getSuggestedNode();
}
// No possible winner
return null;
}
} ) );
}
public void startPromotionProcess( String role, final InstanceId promoteNode )
{
elections.put( role, new Election( new WinnerStrategy()
{
@Override
public InstanceId pickWinner( Collection<Vote> voteList )
{
// Remove blank votes
List<Vote> filteredVoteList = Iterables.toList( Iterables.filter( new Predicate<Vote>()
{
@Override
public boolean accept( Vote item )
{
return !( item.getCredentials() instanceof NotElectableElectionCredentials);
}
}, voteList ) );
// Sort based on credentials
// The most suited candidate should come out on top
Collections.sort( filteredVoteList );
Collections.reverse( filteredVoteList );
for ( Vote vote : filteredVoteList )
{
// Don't elect as winner the node we are trying to demote
if ( !vote.getSuggestedNode().equals( promoteNode ) )
{
return vote.getSuggestedNode();
}
}
// No possible winner
return null;
}
} ) );
}
public void voted( String role, InstanceId suggestedNode, Comparable<Object> suggestionCredentials )
{
if ( isElectionProcessInProgress( role ) )
{
Map<InstanceId, Vote> votes = elections.get( role ).getVotes();
votes.put( suggestedNode, new Vote( suggestedNode, suggestionCredentials ) );
}
}
public InstanceId getElectionWinner( String role )
{
Election election = elections.get( role );
if ( election == null || election.getVotes().size() != getNeededVoteCount() )
{
return null;
}
elections.remove( role );
return election.pickWinner();
}
public Comparable<Object> getCredentialsForRole( String role )
{
return electionCredentialsProvider.getCredentials( role );
}
public int getVoteCount( String role )
{
Election election = elections.get( role );
if ( election != null )
{
Map<InstanceId, Vote> voteList = election.getVotes();
if ( voteList == null )
{
return 0;
}
return voteList.size();
}
else
{
return 0;
}
}
public int getNeededVoteCount()
{
return clusterContext.getConfiguration().getMembers().size() - heartbeatContext.getFailed().size();
}
public void cancelElection( String role )
{
elections.remove( role );
}
public Iterable<String> getRolesRequiringElection()
{
return filter( new Predicate<String>() // Only include roles that are not elected
{
@Override
public boolean accept( String role )
{
return clusterContext.getConfiguration().getElected( role ) == null;
}
}, map( new Function<ElectionRole, String>() // Convert ElectionRole to String
{
@Override
public String apply( ElectionRole role )
{
return role.getName();
}
}, roles ) );
}
public boolean electionOk()
{
return heartbeatContext.getFailed().size() <= clusterContext.getConfiguration().getMembers().size() /2;
}
public boolean isInCluster()
{
return getClusterContext().isInCluster();
}
public Iterable<InstanceId> getAlive()
{
return getHeartbeatContext().getAlive();
}
public InstanceId getMyId()
{
return getClusterContext().getMyId();
}
public boolean isElector()
{
// Only the first alive server should try elections. Everyone else waits
List<InstanceId> aliveInstances = Iterables.toList( getAlive() );
Collections.sort( aliveInstances );
return aliveInstances.indexOf( getMyId() ) == 0;
}
public Map<InstanceId, URI> getMembers()
{
return getClusterContext().getConfiguration().getMembers();
}
public boolean isFailed( InstanceId key )
{
return getHeartbeatContext().getFailed().contains( key );
}
public InstanceId getElected( String roleName )
{
return getClusterContext().getConfiguration().getElected( roleName );
}
public void setTimeout( String key, Message<ElectionMessage> timeout )
{
getClusterContext().timeouts.setTimeout( key, timeout );
}
public StringLogger getLogger()
{
return clusterContext.getLogger( ElectionState.class );
}
public boolean hasCurrentlyElectedVoted( String role, InstanceId currentElected )
{
return elections.containsKey( role ) && elections.get(role).getVotes().containsKey( currentElected );
}
private static class Vote
implements Comparable<Vote>
{
private final InstanceId suggestedNode;
private final Comparable<Object> voteCredentials;
private Vote( InstanceId suggestedNode, Comparable<Object> voteCredentials )
{
this.suggestedNode = suggestedNode;
this.voteCredentials = voteCredentials;
}
public InstanceId getSuggestedNode()
{
return suggestedNode;
}
@Override
public int compareTo( Vote o )
{
return this.voteCredentials.compareTo( o.voteCredentials );
}
@Override
public String toString()
{
return suggestedNode + ":" + voteCredentials;
}
public Comparable<Object> getCredentials()
{
return voteCredentials;
}
}
private static class Election
{
private final WinnerStrategy winnerStrategy;
// List<Vote> votes = new ArrayList<Vote>();
private final Map<InstanceId, Vote> votes = new HashMap<InstanceId, Vote>();
private Election( WinnerStrategy winnerStrategy )
{
this.winnerStrategy = winnerStrategy;
}
public Map<InstanceId, Vote> getVotes()
{
return votes;
}
public InstanceId pickWinner()
{
return winnerStrategy.pickWinner( votes.values() );
}
}
interface WinnerStrategy
{
InstanceId pickWinner( Collection<Vote> votes );
}
}
|
package net.pelleau.swagger;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import io.swagger.models.Swagger;
import io.swagger.parser.SwaggerParser;
public class SwagTester {
private Swagger swagger;
private Map<String, EntryPoint> entryPoints;
public SwagTester(String pathToJsonFile) {
swagger = new SwaggerParser().read(pathToJsonFile);
getEntryPoints();
}
private void getEntryPoints() {
entryPoints = new HashMap<>();
swagger.getPaths().forEach((name, path) -> {
EntryPoint ep = new EntryPointImpl(name, path);
entryPoints.put(name, ep);
});
}
public Map<String, EntryPoint> entryPoints() {
return entryPoints;
}
public EntryPoint entryPoint(String name) {
return entryPoints.get(name);
}
/**
* Test if the server is UP with a simple Ping.
*
* @param milliseconds
* - Time in milliseconds before timeout
* @return true if the server is UP
*/
public boolean serverUpTest(int milliseconds) {
String host = "";
boolean reachable = false;
try {
reachable = InetAddress.getByName(host).isReachable(milliseconds);
} catch (UnknownHostException e) {
return false;
} catch (IOException e) {
return false;
}
return reachable;
}
/**
* Test if the server is UP with a simple Ping.<br>
* Timeout of 5 seconds.
*
* @return true if the server is UP
*/
public boolean serverUpTest() {
return serverUpTest(5000);
}
}
|
package org.voltdb;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.util.EnumSet;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.voltcore.utils.VoltUnsafe;
import org.voltdb.VoltDB.Configuration;
import org.voltdb.VoltDB.SimulatedExitException;
import org.voltdb.catalog.Catalog;
import org.voltdb.compiler.VoltCompiler;
import org.voltdb.compiler.VoltProjectBuilder;
import org.voltdb.utils.CatalogUtil;
import org.voltdb.utils.InMemoryJarfile;
import org.voltdb.utils.VoltFile;
import com.google_voltpatches.common.base.Joiner;
import com.google_voltpatches.common.io.CharStreams;
import com.google_voltpatches.common.reflect.ClassPath;
import com.google_voltpatches.common.reflect.ClassPath.ClassInfo;
import org.voltdb_testprocs.fakeusecase.greetings.GetGreetingBase;
/** Tests starting the server with init + start without a schema,
* and 'init --schema --classes'.
* Starting after 'init --schema' is covered in "TestStartWithSchema" and (in Pro) "TestStartWithSchemaAndDurability".
*/
final public class TestInitStartAction {
static File rootDH;
static File cmdlogDH;
private static final String[] deploymentXML = {
"<?xml version=\"1.0\"?>",
"<deployment>",
" <cluster hostcount=\"1\"/>",
" <paths>",
" <voltdbroot path=\"_VOLTDBROOT_PATH_\"/>",
" <commandlog path=\"_COMMANDLOG_PATH_\"/>",
" </paths>",
" <httpd enabled=\"true\">",
" <jsonapi enabled=\"true\"/>",
" </httpd>",
" <commandlog enabled=\"false\"/>",
"</deployment>"
};
static final Pattern voltdbrootRE = Pattern.compile("_VOLTDBROOT_PATH_");
static final Pattern commandlogRE = Pattern.compile("_COMMANDLOG_PATH_");
static File legacyDeploymentFH;
@ClassRule
static public final TemporaryFolder tmp = new TemporaryFolder();
@BeforeClass
public static void setupClass() throws Exception {
rootDH = tmp.newFolder();
cmdlogDH = new File(tmp.newFolder(), "commandlog");
legacyDeploymentFH = new File(rootDH, "deployment.xml");
try (FileWriter fw = new FileWriter(legacyDeploymentFH)) {
Matcher mtc = voltdbrootRE.matcher(Joiner.on('\n').join(deploymentXML));
String expnd = mtc.replaceAll(new File(rootDH, "voltdbroot").getPath());
mtc = commandlogRE.matcher(expnd);
expnd = mtc.replaceAll(cmdlogDH.getPath());
fw.write(expnd);
}
System.setProperty("VOLT_JUSTATEST", "YESYESYES");
VoltDB.ignoreCrash = true;
}
AtomicReference<Throwable> serverException = new AtomicReference<>(null);
final Thread.UncaughtExceptionHandler handleUncaught = new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
serverException.compareAndSet(null, e);
}
};
/** Verifies that the VoltDB exit 'crash' was a simulated exit with the specified exit code.
* @param exitCode Expected exit code from VoltDB
*/
private void expectSimulatedExit(int exitCode){
assertNotNull(serverException.get());
if (!(serverException.get() instanceof VoltDB.SimulatedExitException)) {
System.err.println("got an unexpected exception");
serverException.get().printStackTrace(System.err);
if (VoltDB.wasCrashCalled) {
System.err.println("Crash message is:\n "+ VoltDB.crashMessage);
}
}
assertTrue(serverException.get() instanceof VoltDB.SimulatedExitException);
VoltDB.SimulatedExitException exitex = (VoltDB.SimulatedExitException)serverException.get();
assertEquals(exitCode, exitex.getStatus());
}
/** Clears recorded crash (or simulated exit) in preparation for another test.
*/
private void clearCrash(){
VoltDB.wasCrashCalled = false;
VoltDB.crashMessage = null;
serverException.set(null);
}
/** Tests starting an empty database with the NewCLI commands "init" and "start",
* plus a few error cases.
*/
@Test
public void testInitStartAction() throws Exception {
File deplFH = new VoltFile(new VoltFile(new VoltFile(rootDH, "voltdbroot"), "config"), "deployment.xml");
Configuration c1 = new Configuration(
new String[]{"initialize", "voltdbroot", rootDH.getPath(), "force", "deployment", legacyDeploymentFH.getPath()});
ServerThread server = new ServerThread(c1);
server.setUncaughtExceptionHandler(handleUncaught);
server.start();
server.join();
expectSimulatedExit(0);
assertTrue(deplFH.exists() && deplFH.isFile() && deplFH.canRead());
if (c1.m_isEnterprise) {
assertTrue(cmdlogDH.exists()
&& cmdlogDH.isDirectory()
&& cmdlogDH.canRead()
&& cmdlogDH.canWrite()
&& cmdlogDH.canExecute());
for (int i=0; i<10; ++i) {
new FileOutputStream(new File(cmdlogDH, String.format("dummy-%02d.log", i))).close();
}
assertEquals(10, cmdlogDH.list().length);
}
serverException.set(null);
// server thread sets m_forceVoltdbCreate to true by default
c1 = new Configuration(
new String[]{"initialize", "voltdbroot", rootDH.getPath(), "force", "deployment", legacyDeploymentFH.getPath()});
assertTrue(c1.m_forceVoltdbCreate);
server = new ServerThread(c1);
server.setUncaughtExceptionHandler(handleUncaught);
server.start();
server.join();
expectSimulatedExit(0);
assertTrue(deplFH.exists() && deplFH.isFile() && deplFH.canRead());
if (c1.m_isEnterprise) {
assertTrue(cmdlogDH.exists()
&& cmdlogDH.isDirectory()
&& cmdlogDH.canRead()
&& cmdlogDH.canWrite()
&& cmdlogDH.canExecute());
assertEquals(0, cmdlogDH.list().length);
}
try {
c1 = new Configuration(new String[]{"initialize", "voltdbroot", rootDH.getPath()});
fail("did not detect prexisting initialization");
} catch (VoltDB.SimulatedExitException e) {
assertEquals(-1, e.getStatus());
}
VoltDB.wasCrashCalled = false;
VoltDB.crashMessage = null;
serverException.set(null);
c1 = new Configuration(new String[]{"create", "deployment", legacyDeploymentFH.getPath(), "host", "localhost"});
server = new ServerThread(c1);
server.setUncaughtExceptionHandler(handleUncaught);
server.start();
server.join();
assertNotNull(serverException.get());
assertTrue(serverException.get() instanceof AssertionError);
assertTrue(VoltDB.wasCrashCalled);
assertTrue(VoltDB.crashMessage.contains("Cannot use legacy start action"));
if (!c1.m_isEnterprise) {
return;
}
clearCrash();
c1 = new Configuration(new String[]{"recover", "deployment", legacyDeploymentFH.getPath(), "host", "localhost"});
server = new ServerThread(c1);
server.setUncaughtExceptionHandler(handleUncaught);
server.start();
server.join();
assertNotNull(serverException.get());
assertTrue(serverException.get() instanceof AssertionError);
assertTrue(VoltDB.wasCrashCalled);
assertTrue(VoltDB.crashMessage.contains("Cannot use legacy start action"));
// this test which action should be considered legacy
EnumSet<StartAction> legacyOnes = EnumSet.complementOf(EnumSet.of(StartAction.INITIALIZE,StartAction.PROBE, StartAction.GET));
assertTrue(legacyOnes.stream().allMatch(StartAction::isLegacy));
}
/*
* "voltdb init --schema --procedures" tests:
* 1. Positive test with valid schema that requires no procedures
* 2a. Positive test with valid schema and procedures that are in CLASSPATH
* 2b. Negative test with valid files but not "init --force"
* 3. Negative test with a bad schema
* 4. Negative test with procedures missing
*
* Note that SimulatedExitException is thrown by the command line parser with no descriptive details.
* VoltDB.crashLocalVoltDB() throws an AssertionError with the message "Faux crash of VoltDB successful."
*/
/** Verifies that the staged catalog matches what VoltCompiler emits given the supplied schema.
* @param schema Schema used to generate the staged catalog
* @throws Exception upon test failure or error (unable to write temp file for example)
*/
private void validateStagedCatalog(String schema, InMemoryJarfile proceduresJar) throws Exception {
File schemaFile = null;
if (schema != null) {
// setup reference point for the supplied schema
schemaFile = VoltProjectBuilder.writeStringToTempFile(schema);
schemaFile.deleteOnExit();
}
File referenceFile = File.createTempFile("reference", ".jar");
referenceFile.deleteOnExit();
VoltCompiler compiler = new VoltCompiler(false);
compiler.setInitializeDDLWithFiltering(true);
boolean success;
if (schema == null) {
success = compiler.compileEmptyCatalog(referenceFile.getAbsolutePath());
} else {
success = compiler.compileFromDDL(referenceFile.getAbsolutePath(), schemaFile.getPath());
}
assertTrue(success);
InMemoryJarfile referenceCatalogJar = new InMemoryJarfile(referenceFile);
Catalog referenceCatalog = new Catalog();
referenceCatalog.execute(CatalogUtil.getSerializedCatalogStringFromJar(referenceCatalogJar));
// verify that the staged catalog is identical
File stagedJarFile = new VoltFile(RealVoltDB.getStagedCatalogPath(rootDH.getPath() + File.separator + "voltdbroot"));
assertTrue(stagedJarFile.isFile());
InMemoryJarfile stagedCatalogJar = new InMemoryJarfile(stagedJarFile);
Catalog stagedCatalog = new Catalog();
stagedCatalog.execute(CatalogUtil.getSerializedCatalogStringFromJar(stagedCatalogJar));
assertTrue(referenceCatalog.equals(stagedCatalog));
assertTrue(stagedCatalog.equals(referenceCatalog));
assertTrue(referenceFile.delete());
// If schema is not null we have a real file else we have a dummy reader.
if (schema != null) {
assertTrue(schemaFile.delete());
}
if (proceduresJar != null) {
// Validate that the list of files in the supplied jarfile are present in the staged catalog also.
InMemoryJarfile strippedReferenceJar = CatalogUtil.getCatalogJarWithoutDefaultArtifacts(proceduresJar);
InMemoryJarfile strippedTestJar = CatalogUtil.getCatalogJarWithoutDefaultArtifacts(stagedCatalogJar);
for (Entry<String, byte[]> entry : strippedReferenceJar.entrySet()) {
System.out.println("Checking " + entry.getKey());
byte[] testClass = strippedTestJar.get(entry.getKey());
assertNotNull(entry.getKey() + " was not found in staged catalog", testClass);
assertArrayEquals(entry.getValue(), testClass);
}
}
}
/** Test that a valid schema with no procedures can be used to stage a matching catalog.
* @throws Exception upon failure or error
*/
@Test
public void testInitWithSchemaValidNoProcedures() throws Exception {
final String schema =
"create table books (cash integer default 23 not null, title varchar(3) default 'foo', PRIMARY KEY(cash));\n" +
"-- here is a comment\n" +
"create procedure Foo as select * from books;\n" +
"-- here is another comment\n" +
"PARTITION TABLE -- hmmm\n" +
"-- VoltDB-specific mid statement comment\n" +
"books ON COLUMN cash; -- end of line comment\n" +
"-- comment comment comment\n" +
"CREATE STREAM mystream (\n" +
" -- a column:\n" +
" eventid BIGINT NOT NULL,\n" +
" data VARBINARY(64)\n" +
"); -- end of line comment\n" +
"-- the end.\n";
File schemaFile = VoltProjectBuilder.writeStringToTempFile(schema);
Configuration c1 = new Configuration(
new String[]{"initialize", "voltdbroot", rootDH.getPath(), "force", "schema", schemaFile.getPath()});
ServerThread server = new ServerThread(c1);
server.setUncaughtExceptionHandler(handleUncaught);
server.start();
server.join();
expectSimulatedExit(0);
validateStagedCatalog(schema, null);
assertTrue(schemaFile.delete());
}
/** Test that a valid schema with procedures can be used to stage a matching catalog,
* but running a second time without 'init --force' fails due to existing artifacts.
* @throws Exception upon failure or error
*/
@Test
public void testInitWithSchemaValidWithProcedures() throws Exception {
String schema =
"create table books" +
" (cash integer default 23 not null," +
" title varchar(3) default 'foo'," +
" PRIMARY KEY(cash));" +
"PARTITION TABLE books ON COLUMN cash;" +
"CREATE PROCEDURE partition on table books column cash FROM CLASS org.voltdb.compiler.procedures.AddBook;";
File schemaFile = VoltProjectBuilder.writeStringToTempFile(schema);
{
// valid use case
Configuration c1 = new Configuration(
new String[]{"initialize", "force", "voltdbroot", rootDH.getPath(), "schema", schemaFile.getPath()});
ServerThread server = new ServerThread(c1);
server.setUncaughtExceptionHandler(handleUncaught);
server.start();
server.join();
expectSimulatedExit(0);
validateStagedCatalog(schema, null);
clearCrash();
}
try {
// second attempt is not valid due to existing artifacts
new Configuration(
new String[]{"initialize", "voltdbroot", rootDH.getPath(), "schema", schemaFile.getPath()});
} catch (SimulatedExitException e){
assertEquals(e.getStatus(), -1);
}
assertTrue(schemaFile.delete());
}
/** Test that a valid schema with no procedures can be used to stage a matching catalog.
* @throws Exception upon failure or error
*/
@Test
public void testInitWithSchemaInvalidJunkSchema() throws Exception {
File schemaFile = Files.createTempDirectory("junk").toFile();
try {
new Configuration(
new String[]{"initialize", "voltdbroot", rootDH.getPath(), "force", "schema", schemaFile.getPath()});
fail("did not detect unusable schema file");
} catch (VoltDB.SimulatedExitException e) {
assertEquals(e.getStatus(), -1);
}
assertTrue(schemaFile.delete());
}
/** Test that init accepts classes without a schema.
* @throws Exception upon failure or error
*/
@Test
public void testInitWithNoSchema() throws Exception {
try {
new Configuration(
new String[]{"initialize", "voltdbroot", rootDH.getPath(), "force"});
} catch (VoltDB.SimulatedExitException e) {
fail("Should init without schema.");
}
}
/** Test that a valid schema with no procedures can be used to stage a matching catalog.
* @throws Exception upon failure or error
*/
@Test
public void testInitWithSchemaInvalidMissingClass() throws Exception {
String schema =
"CREATE TABLE unicorns" +
" (horn_size integer DEFAULT 12 NOT NULL," +
" name varchar(32) DEFAULT 'Pixie' NOT NULL," +
" PRIMARY KEY(name));" +
"PARTITION TABLE unicorns ON COLUMN name;" +
"CREATE PROCEDURE FROM CLASS org.voltdb.unicorns.ComputeSocialStanding;";
File schemaFile = VoltProjectBuilder.writeStringToTempFile(schema);
Configuration c1 = new Configuration(
new String[]{"initialize", "voltdbroot", rootDH.getPath(), "force", "schema", schemaFile.getPath()});
ServerThread server = new ServerThread(c1);
server.setUncaughtExceptionHandler(handleUncaught);
server.start();
server.join();
assertNotNull(serverException.get());
assertTrue(serverException.get().getMessage().equals("Faux crash of VoltDB successful."));
assertTrue(VoltDB.wasCrashCalled);
assertTrue(VoltDB.crashMessage.contains("Could not compile specified schema"));
assertTrue(schemaFile.delete());
}
/** Tests that when there are base classes and non-class files in the stored procedures,
* that these also exist in the staged catalog.
* @throws Exception upon failure or error
*/
@Test
public void testInitWithClassesAndArtifacts() throws Exception {
System.out.println("Loading the schema from testprocs");
File resource = new File("tests/testprocs/org/voltdb_testprocs/fakeusecase/greetings/ddl.sql");
InputStream schemaReader = new FileInputStream(resource);
assertNotNull("Could not find " + resource, schemaReader);
String schema = CharStreams.toString(new InputStreamReader(schemaReader));
System.out.println("Creating a .jar file using all of the classes associated with this test.");
InMemoryJarfile originalInMemoryJar = new InMemoryJarfile();
VoltCompiler compiler = new VoltCompiler(false, false);
// Start with JAVA 9, the appClassLoader no longer an instance of java.net.URLClassLoader
ClassPath classpath = ClassPath.from(new URLClassLoader(new URL[]{GetGreetingBase.class.getResource(".")}, GetGreetingBase.class.getClassLoader()));
String packageName = "org.voltdb_testprocs.fakeusecase.greetings";
int classesFound = 0;
if (VoltUnsafe.isJava8) {
for (ClassInfo myclass : classpath.getTopLevelClassesRecursive(packageName)) {
compiler.addClassToJar(originalInMemoryJar, myclass.load());
classesFound++;
}
} else {
for (ClassInfo myclass : classpath.getTopLevelClasses()) {
compiler.addClassToJar(originalInMemoryJar, Class.forName(packageName + "." + myclass.getName()));
classesFound++;
}
}
// check that classes were found and loaded. If another test modifies "fakeusecase.greetings" it should modify this assert also.
assertEquals(5, classesFound);
System.out.println("Writing " + classesFound + " classes to jar file");
File classesJarfile = File.createTempFile("TestInitStartWithClasses-procedures", ".jar");
classesJarfile.deleteOnExit();
originalInMemoryJar.writeToFile(classesJarfile);
Configuration c1 = new Configuration(
new String[]{"initialize", "voltdbroot", rootDH.getPath(), "force", "schema", resource.getPath(), "classes", classesJarfile.getPath()});
ServerThread server = new ServerThread(c1);
server.setUncaughtExceptionHandler(handleUncaught);
server.start();
server.join();
validateStagedCatalog(schema, originalInMemoryJar);
}
/** Tests that when there are base classes and non-class files in the stored procedures,
* that these also exist in the staged catalog.
* @throws Exception upon failure or error
*/
@Test
public void testInitWithClassesAndNoSchema() throws Exception {
System.out.println("Creating a .jar file using all of the classes associated with this test.");
InMemoryJarfile originalInMemoryJar = new InMemoryJarfile();
VoltCompiler compiler = new VoltCompiler(false, false);
String packageName = "org.voltdb_testprocs.fakeusecase.greetings";
ClassPath classpath = ClassPath.from(new URLClassLoader(new URL[]{GetGreetingBase.class.getResource(".")}, GetGreetingBase.class.getClassLoader()));
int classesFound = 0;
if (VoltUnsafe.isJava8) {
for (ClassInfo myclass : classpath.getTopLevelClassesRecursive(packageName)) {
compiler.addClassToJar(originalInMemoryJar, myclass.load());
classesFound++;
}
} else {
for (ClassInfo myclass : classpath.getTopLevelClasses()) {
compiler.addClassToJar(originalInMemoryJar, Class.forName(packageName + "." + myclass.getName()));
classesFound++;
}
}
// check that classes were found and loaded. If another test modifies "fakeusecase.greetings" it should modify this assert also.
assertEquals(5, classesFound);
System.out.println("Writing " + classesFound + " classes to jar file");
File classesJarfile = File.createTempFile("TestInitStartWithClassesNoSchema-procedures", ".jar");
classesJarfile.deleteOnExit();
originalInMemoryJar.writeToFile(classesJarfile);
Configuration c1 = new Configuration(
new String[]{"initialize", "voltdbroot", rootDH.getPath(), "force", "classes", classesJarfile.getPath()});
ServerThread server = new ServerThread(c1);
server.setUncaughtExceptionHandler(handleUncaught);
server.start();
server.join();
//Only validate jar
validateStagedCatalog(null, originalInMemoryJar);
}
@Test
public void testInitWithMultipleSchemaFiles() throws Exception {
String schema1 =
"CREATE TABLE unicorns" +
" (horn_size integer DEFAULT 12 NOT NULL," +
" name varchar(32) DEFAULT 'Pixie' NOT NULL," +
" PRIMARY KEY(name));" +
"PARTITION TABLE unicorns ON COLUMN name;";
File schemaFile1 = VoltProjectBuilder.writeStringToTempFile(schema1);
String schema2 = "CREATE TABLE unicorns2" + " (horn_size integer DEFAULT 12 NOT NULL,"
+ " name varchar(32) DEFAULT 'Pixie' NOT NULL," + " PRIMARY KEY(name));"
+ "PARTITION TABLE unicorns2 ON COLUMN name;";
File schemaFile2 = VoltProjectBuilder.writeStringToTempFile(schema2);
Configuration c1 = new Configuration(new String[] { "initialize", "voltdbroot", rootDH.getPath(), "force",
"schema", schemaFile1.getPath() + ',' + schemaFile2.getPath() });
ServerThread server = new ServerThread(c1);
server.setUncaughtExceptionHandler(handleUncaught);
server.start();
server.join();
expectSimulatedExit(0);
validateStagedCatalog(schema1 + schema2, null);
assertTrue(schemaFile1.delete());
assertTrue(schemaFile2.delete());
}
@Test
public void testInitWithMultipleJarFiles() throws Exception {
File resource = new File("tests/testprocs/org/voltdb_testprocs/fakeusecase/greetings/ddl.sql");
InputStream schemaReader = new FileInputStream(resource);
assertNotNull("Could not find " + resource, schemaReader);
String schema = CharStreams.toString(new InputStreamReader(schemaReader));
System.out.println("Creating a .jar file using all of the classes associated with this test.");
InMemoryJarfile inMemoryJar1 = new InMemoryJarfile();
InMemoryJarfile inMemoryJar2 = new InMemoryJarfile();
VoltCompiler compiler = new VoltCompiler(false, false);
String packageName = "org.voltdb_testprocs.fakeusecase.greetings";
ClassPath classpath = ClassPath.from(new URLClassLoader(new URL[]{GetGreetingBase.class.getResource(".")}, GetGreetingBase.class.getClassLoader()));
int classesFound = 0;
if (VoltUnsafe.isJava8) {
for (ClassInfo myclass : classpath.getTopLevelClassesRecursive(packageName)) {
if (myclass.getSimpleName().startsWith("Get")) {
compiler.addClassToJar(inMemoryJar1, myclass.load());
} else {
compiler.addClassToJar(inMemoryJar2, myclass.load());
}
classesFound++;
}
} else {
for (ClassInfo myclass : classpath.getTopLevelClasses()) {
if (myclass.getSimpleName().startsWith("Get")) {
compiler.addClassToJar(inMemoryJar1, Class.forName(packageName + "." + myclass.getName()));
} else {
compiler.addClassToJar(inMemoryJar2, Class.forName(packageName + "." + myclass.getName()));
}
classesFound++;
}
}
// check that classes were found and loaded. If another test modifies "fakeusecase.greetings" it should modify
// this assert also.
assertEquals(5, classesFound);
System.out.println("Writing " + classesFound + " classes to jar file");
File classesJarfile1 = File.createTempFile("testInitWIthMultipleJarFiles-procedures", ".jar");
classesJarfile1.deleteOnExit();
inMemoryJar1.writeToFile(classesJarfile1);
File classesJarfile2 = File.createTempFile("testInitWIthMultipleJarFiles-procedures", ".jar");
classesJarfile2.deleteOnExit();
inMemoryJar2.writeToFile(classesJarfile2);
Configuration c1 = new Configuration(new String[] { "initialize", "voltdbroot", rootDH.getPath(), "force",
"schema", resource.getPath(), "classes", classesJarfile1.getPath() + ',' + classesJarfile2.getPath() });
ServerThread server = new ServerThread(c1);
server.setUncaughtExceptionHandler(handleUncaught);
server.start();
server.join();
validateStagedCatalog(schema, inMemoryJar1);
validateStagedCatalog(schema, inMemoryJar2);
}
/* For 'voltdb start' test coverage see TestStartWithSchema and (in Pro) TestStartWithSchemaAndDurability.
*/
}
|
package nl.tudelft.jpacman.board;
import org.checkerframework.checker.initialization.qual.UnderInitialization;
/**
* A top-down view of a matrix of {@link Square}s.
*
* @author Jeroen Roosen
*/
public class Board {
/**
* The grid of squares with board[x][y] being the square at column x, row y.
*/
private final Square[][] board;
/**
* Creates a new board.
*
* @param grid
* The grid of squares with grid[x][y] being the square at column
* x, row y.
*/
Board(Square[][] grid) {
assert grid != null;
this.board = grid;
assert invariant() : "Initial grid cannot contain null squares";
}
/**
* Whatever happens, the squares on the board can't be null.
* @return false if any square on the board is null.
*
* This method uses Java 8's possibility to make the receiver ("this") explicit,
* so that it can be annotated for the Checker Framework to indicate that it
* is called from the constructor, i.e., that the object "this" is still in the making.
*/
protected final boolean invariant(@UnderInitialization(Board.class) Board this) {
for (Square[] row : board) {
for (Square square : row) {
if (square == null) {
return false;
}
}
}
return true;
}
/**
* Returns the number of columns.
*
* @return The width of this board.
*/
public int getWidth() {
return board.length;
}
/**
* Returns the number of rows.
*
* @return The height of this board.
*/
public int getHeight() {
return board[0].length;
}
/**
* Returns the square at the given <code>x,y</code> position.
*
* Precondition: The <code>(x, y)</code> coordinates are within the
* width and height of the board.
*
* @param x
* The <code>x</code> position (column) of the requested square.
* @param y
* The <code>y</code> position (row) of the requested square.
* @return The square at the given <code>x,y</code> position (never null).
*/
public Square squareAt(int x, int y) {
assert withinBorders(x, y);
Square result = board[x][y];
assert result != null : "Follows from invariant.";
return result;
}
/**
* Determines whether the given <code>x,y</code> position is on this board.
*
* @param x
* The <code>x</code> position (row) to test.
* @param y
* The <code>y</code> position (column) to test.
* @return <code>true</code> iff the position is on this board.
*/
public boolean withinBorders(int x, int y) {
return x >= 0 && x < getWidth() && y >= 0 && y < getHeight();
}
}
|
package org.jgroups.tests;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jgroups.*;
import org.jgroups.stack.IpAddress;
import org.jgroups.util.Util;
import java.util.*;
/**
* Test the multiplexer functionality provided by JChannelFactory
* @author Bela Ban
* @version $Id: MultiplexerTest.java,v 1.13 2006/08/21 00:48:05 bstansberry Exp $
*/
public class MultiplexerTest extends TestCase {
private Cache c1, c2, c1_repl, c2_repl;
private Channel ch1, ch2, ch1_repl, ch2_repl;
static final String CFG="stacks.xml";
static final String STACK_NAME="fc-fast-minimalthreads";
JChannelFactory factory, factory2;
public MultiplexerTest(String name) {
super(name);
}
public void setUp() throws Exception {
super.setUp();
factory=new JChannelFactory();
factory.setMultiplexerConfig(CFG);
factory2=new JChannelFactory();
factory2.setMultiplexerConfig(CFG);
}
protected void tearDown() throws Exception {
super.tearDown();
if(ch1_repl != null)
ch1_repl.close();
if(ch2_repl != null)
ch2_repl.close();
if(ch1 != null)
ch1.close();
if(ch2 != null)
ch2.close();
if(c1 != null) c1.clear();
if(c2 != null) c2.clear();
if(c1_repl != null) c1_repl.clear();
if(c2_repl != null) c2_repl.clear();
}
public void testReplicationWithOneChannel() throws Exception {
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
ch1.connect("bla");
c1=new Cache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
c1.put("name", "Bela");
Util.sleep(300); // we need to wait because replication is asynchronous here
assertEquals(1, c1.size());
assertEquals("Bela", c1.get("name"));
}
public void testReplicationWithTwoChannels() throws Exception {
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
ch1.connect("bla");
c1=new Cache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
ch1_repl=factory2.createMultiplexerChannel(STACK_NAME, "c1");
ch1_repl.connect("bla");
Util.sleep(500);
View v=ch1_repl.getView();
assertNotNull(v);
assertEquals(2, v.size());
c1_repl=new Cache(ch1_repl, "cache-1-repl");
assertEquals("cache has to be empty initially", 0, c1_repl.size());
c1.put("name", "Bela");
Util.sleep(1000);
System.out.println("c1: " + c1 + ", c1_repl: " + c1_repl);
assertEquals(1, c1.size());
assertEquals("Bela", c1.get("name"));
assertEquals(1, c1_repl.size());
assertEquals("Bela", c1_repl.get("name"));
c1.put("id", new Long(322649));
c1_repl.put("hobbies", "biking");
c1_repl.put("bike", "Centurion");
Util.sleep(500);
System.out.println("c1: " + c1 + ", c1_repl: " + c1_repl);
assertEquals(4, c1.size());
assertEquals(4, c1_repl.size());
assertEquals(new Long(322649), c1.get("id"));
assertEquals(new Long(322649), c1_repl.get("id"));
assertEquals("biking", c1.get("hobbies"));
assertEquals("biking", c1_repl.get("hobbies"));
assertEquals("Centurion", c1.get("bike"));
assertEquals("Centurion", c1_repl.get("bike"));
}
public void testReplicationWithReconnect() throws Exception {
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
ch1.connect("bla");
c1=new Cache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
c1.put("name", "Bela");
Util.sleep(300); // we need to wait because replication is asynchronous here
assertEquals(1, c1.size());
assertEquals("Bela", c1.get("name"));
ch1.disconnect();
ch1.connect("bla");
c2=new Cache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c2.size());
c2.put("name", "Bela");
Util.sleep(300); // we need to wait because replication is asynchronous here
assertEquals(1, c2.size());
assertEquals("Bela", c2.get("name"));
}
public void testStateTransfer() throws Exception {
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
ch1.connect("bla");
c1=new Cache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
ch1_repl=factory2.createMultiplexerChannel(STACK_NAME, "c1");
c1.put("name", "Bela");
c1.put("id", new Long(322649));
c1.put("hobbies", "biking");
c1.put("bike", "Centurion");
ch1_repl.connect("bla");
c1_repl=new Cache(ch1_repl, "cache-1-repl");
boolean rc=ch1_repl.getState(null, 5000);
System.out.println("state transfer: " + rc);
Util.sleep(500);
System.out.println("c1_repl: " + c1_repl);
assertEquals("initial state should have been transferred", 4, c1_repl.size());
assertEquals(new Long(322649), c1.get("id"));
assertEquals(new Long(322649), c1_repl.get("id"));
assertEquals("biking", c1.get("hobbies"));
assertEquals("biking", c1_repl.get("hobbies"));
assertEquals("Centurion", c1.get("bike"));
assertEquals("Centurion", c1_repl.get("bike"));
}
public void testStateTransferWithTwoApplications() throws Exception {
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
ch1.connect("bla");
c1=new Cache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
ch2=factory.createMultiplexerChannel(STACK_NAME, "c2");
ch2.connect("bla");
c2=new Cache(ch2, "cache-2");
assertEquals("cache has to be empty initially", 0, c2.size());
ch1_repl=factory2.createMultiplexerChannel(STACK_NAME, "c1");
ch2_repl=factory2.createMultiplexerChannel(STACK_NAME, "c2");
c1.put("name", "cache-1");
c2.put("name", "cache-2");
ch1_repl.connect("bla");
c1_repl=new Cache(ch1_repl, "cache-1-repl");
boolean rc=ch1_repl.getState(null, 5000);
System.out.println("state transfer: " + rc);
ch2_repl.connect("bla");
c2_repl=new Cache(ch2_repl, "cache-2-repl");
rc=ch2_repl.getState(null, 5000);
System.out.println("state transfer: " + rc);
Util.sleep(500);
System.out.println("Caches after state transfers:");
System.out.println("c1: " + c1);
System.out.println("c1_repl: " + c1_repl);
System.out.println("c2: " + c2);
System.out.println("c2_repl: " + c2_repl);
assertEquals(1, c1.size());
assertEquals(1, c1_repl.size());
assertEquals(1, c2.size());
assertEquals(1, c2_repl.size());
assertEquals("cache-1", c1.get("name"));
assertEquals("cache-1", c1_repl.get("name"));
assertEquals("cache-2", c2.get("name"));
assertEquals("cache-2", c2_repl.get("name"));
}
public void testStateTransferWithRegistration() throws Exception {
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
ch1.connect("bla");
c1=new Cache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
ch2=factory.createMultiplexerChannel(STACK_NAME, "c2");
ch2.connect("bla");
c2=new Cache(ch2, "cache-2");
assertEquals("cache has to be empty initially", 0, c2.size());
c1.put("name", "cache-1");
c2.put("name", "cache-2");
ch1_repl=factory2.createMultiplexerChannel(STACK_NAME, "c1", true, null); // register for state transfer
ch2_repl=factory2.createMultiplexerChannel(STACK_NAME, "c2", true, null); // register for state transfer
ch1_repl.connect("bla");
c1_repl=new Cache(ch1_repl, "cache-1-repl");
boolean rc=ch1_repl.getState(null, 5000); // this will *not* trigger the state transfer protocol
System.out.println("state transfer: " + rc);
ch2_repl.connect("bla");
c2_repl=new Cache(ch2_repl, "cache-2-repl");
rc=ch2_repl.getState(null, 5000); // only *this* will trigger the state transfer
System.out.println("state transfer: " + rc);
Util.sleep(500);
System.out.println("Caches after state transfers:");
System.out.println("c1: " + c1);
System.out.println("c1_repl: " + c1_repl);
System.out.println("c2: " + c2);
System.out.println("c2_repl: " + c2_repl);
assertEquals(1, c1.size());
assertEquals(1, c1_repl.size());
assertEquals(1, c2.size());
assertEquals(1, c2_repl.size());
assertEquals("cache-1", c1.get("name"));
assertEquals("cache-1", c1_repl.get("name"));
assertEquals("cache-2", c2.get("name"));
assertEquals("cache-2", c2_repl.get("name"));
c1.clear();
c1_repl.clear();
c2.clear();
c2_repl.clear();
}
public void testStateTransferWithReconnect() throws Exception {
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
ch1.connect("bla");
c1=new Cache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
ch1_repl=factory2.createMultiplexerChannel(STACK_NAME, "c1");
c1.put("name", "Bela");
c1.put("id", new Long(322649));
c1.put("hobbies", "biking");
c1.put("bike", "Centurion");
ch1_repl.connect("bla");
c1_repl=new Cache(ch1_repl, "cache-1-repl");
boolean rc=ch1_repl.getState(null, 5000);
System.out.println("state transfer: " + rc);
Util.sleep(500);
System.out.println("c1_repl: " + c1_repl);
assertEquals("initial state should have been transferred", 4, c1_repl.size());
assertEquals(new Long(322649), c1.get("id"));
assertEquals(new Long(322649), c1_repl.get("id"));
assertEquals("biking", c1.get("hobbies"));
assertEquals("biking", c1_repl.get("hobbies"));
assertEquals("Centurion", c1.get("bike"));
assertEquals("Centurion", c1_repl.get("bike"));
ch1_repl.disconnect();
c1_repl.clear();
ch1_repl.connect("bla");
// c2_repl=new Cache(ch1_repl, "cache-2-repl");
assertEquals("cache has to be empty initially", 0, c1_repl.size());
rc=ch1_repl.getState(null, 5000);
System.out.println("state transfer: " + rc);
Util.sleep(500);
System.out.println("c1_repl: " + c1_repl);
assertEquals("initial state should have been transferred", 4, c1_repl.size());
assertEquals(new Long(322649), c1.get("id"));
assertEquals(new Long(322649), c1_repl.get("id"));
assertEquals("biking", c1.get("hobbies"));
assertEquals("biking", c1_repl.get("hobbies"));
assertEquals("Centurion", c1.get("bike"));
assertEquals("Centurion", c1_repl.get("bike"));
// Now see what happens if we reconnect the first channel
// But first, add another MuxChannel on that JChannel
// just so it remains coordinator (test that it doesn't
// ask for state from itself)
ch2 = factory.createMultiplexerChannel(STACK_NAME, "c2");
ch1.disconnect();
c1.clear();
ch1.connect("bla");
assertEquals("cache has to be empty initially", 0, c1.size());
rc=ch1.getState(null, 5000);
System.out.println("state transfer: " + rc);
Util.sleep(500);
System.out.println("c1: " + c1);
assertEquals("initial state should have been transferred", 4, c1.size());
assertEquals(new Long(322649), c1.get("id"));
assertEquals(new Long(322649), c1_repl.get("id"));
assertEquals("biking", c1.get("hobbies"));
assertEquals("biking", c1_repl.get("hobbies"));
assertEquals("Centurion", c1.get("bike"));
assertEquals("Centurion", c1_repl.get("bike"));
}
public void testStateTransferFromSelfWithRegularChannel() throws Exception {
JChannel ch=new JChannel();
ch.connect("X");
try {
boolean rc=ch.getState(null, 2000);
assertFalse("getState() on singleton should return false", rc);
}
finally {
ch.close();
}
}
public void testStateTransferFromSelf() throws Exception {
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
ch1.connect("bla");
boolean rc=ch1.getState(null, 2000);
assertFalse("getState() on singleton should return false", rc);
ch2=factory.createMultiplexerChannel(STACK_NAME, "c2");
ch2.connect("foo");
rc=ch2.getState(null, 2000);
assertFalse("getState() on singleton should return false", rc);
}
public void testAdditionalData() throws Exception {
byte[] additional_data=new byte[]{'b', 'e', 'l', 'a'};
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
Map m=new HashMap(1);
m.put("additional_data", additional_data);
ch1.down(new Event(Event.CONFIG, m));
ch1.connect("bla");
IpAddress local_addr=(IpAddress)ch1.getLocalAddress();
assertNotNull(local_addr);
byte[] tmp=local_addr.getAdditionalData();
assertNotNull(tmp);
assertEquals(tmp, additional_data);
ch2=factory.createMultiplexerChannel(STACK_NAME, "c2");
ch2.connect("foo");
local_addr=(IpAddress)ch2.getLocalAddress();
assertNotNull(local_addr);
tmp=local_addr.getAdditionalData();
assertNotNull(tmp);
assertEquals(tmp, additional_data);
}
public void testAdditionalData2() throws Exception {
byte[] additional_data=new byte[]{'b', 'e', 'l', 'a'};
byte[] additional_data2=new byte[]{'m', 'i', 'c', 'h', 'i'};
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
ch1.connect("bla");
IpAddress local_addr=(IpAddress)ch1.getLocalAddress();
assertNotNull(local_addr);
byte[] tmp=local_addr.getAdditionalData();
assertNull(tmp);
ch2=factory.createMultiplexerChannel(STACK_NAME, "c2");
Map m=new HashMap(1);
m.put("additional_data", additional_data);
ch2.down(new Event(Event.CONFIG, m));
ch2.connect("foo");
local_addr=(IpAddress)ch2.getLocalAddress();
assertNotNull(local_addr);
tmp=local_addr.getAdditionalData();
assertNotNull(tmp);
assertEquals(tmp, additional_data);
local_addr=(IpAddress)ch1.getLocalAddress();
assertNotNull(local_addr);
tmp=local_addr.getAdditionalData();
assertNotNull(tmp);
assertEquals(tmp, additional_data);
m.clear();
m.put("additional_data", additional_data2);
ch2.down(new Event(Event.CONFIG, m));
local_addr=(IpAddress)ch2.getLocalAddress();
assertNotNull(local_addr);
tmp=local_addr.getAdditionalData();
assertNotNull(tmp);
assertEquals(tmp, additional_data2);
assertFalse(Arrays.equals(tmp, additional_data));
}
public void testGetSubstates() throws Exception {
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
ch1.connect("bla");
c1=new ExtendedCache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
ch2=factory.createMultiplexerChannel(STACK_NAME, "c2");
ch2.connect("bla");
c2=new ExtendedCache(ch2, "cache-2");
assertEquals("cache has to be empty initially", 0, c2.size());
for(int i=0; i < 10; i++) {
c1.put(new Integer(i), new Integer(i));
c2.put(new Integer(i), new Integer(i));
}
ch1_repl=factory2.createMultiplexerChannel(STACK_NAME, "c1");
ch2_repl=factory2.createMultiplexerChannel(STACK_NAME, "c2");
ch1_repl.connect("bla");
c1_repl=new ExtendedCache(ch1_repl, "cache-1-repl");
boolean rc=ch1_repl.getState(null, "odd", 5000);
System.out.println("state transfer: " + rc);
ch2_repl.connect("bla");
c2_repl=new ExtendedCache(ch2_repl, "cache-2-repl");
rc=ch2_repl.getState(null, "even", 5000);
System.out.println("state transfer: " + rc);
Util.sleep(500);
System.out.println("Caches after state transfers:");
System.out.println("c1: " + c1);
System.out.println("c2: " + c2);
System.out.println("c1_repl (removed odd substate): " + c1_repl);
System.out.println("c2_repl (removed even substate): " + c2_repl);
assertEquals(5, c1_repl.size());
assertEquals(5, c2_repl.size());
_testEvenNumbersPresent(c1_repl);
_testOddNumbersPresent(c2_repl);
}
private void _testEvenNumbersPresent(Cache c) {
Integer[] evens=new Integer[]{new Integer(0), new Integer(2), new Integer(4), new Integer(6), new Integer(8)};
_testNumbersPresent(c, evens);
}
private void _testOddNumbersPresent(Cache c) {
Integer[] odds=new Integer[]{new Integer(1), new Integer(3), new Integer(5), new Integer(7), new Integer(9)};
_testNumbersPresent(c, odds);
}
private void _testNumbersPresent(Cache c, Integer[] numbers) {
int len=numbers.length;
assertEquals(len, c.size());
for(int i=0; i < numbers.length; i++) {
Integer number=numbers[i];
assertEquals(number, c.get(number));
}
}
public void testGetSubstatesMultipleTimes() throws Exception {
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
ch1.connect("bla");
c1=new ExtendedCache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
ch2=factory.createMultiplexerChannel(STACK_NAME, "c2");
ch2.connect("bla");
c2=new ExtendedCache(ch2, "cache-2");
assertEquals("cache has to be empty initially", 0, c2.size());
for(int i=0; i < 10; i++) {
c1.put(new Integer(i), new Integer(i));
c2.put(new Integer(i), new Integer(i));
}
ch1_repl=factory2.createMultiplexerChannel(STACK_NAME, "c1");
ch2_repl=factory2.createMultiplexerChannel(STACK_NAME, "c2");
ch1_repl.connect("bla");
c1_repl=new ExtendedCache(ch1_repl, "cache-1-repl");
boolean rc=ch1_repl.getState(null, "odd", 5000);
System.out.println("state transfer: " + rc);
ch2_repl.connect("bla");
c2_repl=new ExtendedCache(ch2_repl, "cache-2-repl");
rc=ch2_repl.getState(null, "even", 5000);
System.out.println("state transfer: " + rc);
Util.sleep(500);
_testOddNumbersPresent(c2_repl);
System.out.println("Caches after state transfers:");
System.out.println("c1: " + c1);
System.out.println("c2: " + c2);
System.out.println("c1_repl (removed odd substate): " + c1_repl);
System.out.println("c2_repl (removed even substate): " + c2_repl);
assertEquals(5, c2_repl.size());
rc=ch2_repl.getState(null, "odd", 5000);
Util.sleep(500);
System.out.println("c2_repl (removed odd substate): " + c2_repl);
_testEvenNumbersPresent(c2_repl);
assertEquals(5, c2_repl.size());
rc=ch2_repl.getState(null, "even", 5000);
Util.sleep(500);
System.out.println("c2_repl (removed even substate): " + c2_repl);
_testOddNumbersPresent(c2_repl);
assertEquals(5, c2_repl.size());
rc=ch2_repl.getState(null, "odd", 5000);
Util.sleep(500);
System.out.println("c2_repl (removed odd substate): " + c2_repl);
_testEvenNumbersPresent(c2_repl);
}
public static Test suite() {
return new TestSuite(MultiplexerTest.class);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(MultiplexerTest.suite());
}
private static class Cache extends ExtendedReceiverAdapter {
final Map data=new HashMap();
Channel ch;
String name;
public Cache(Channel ch, String name) {
this.ch=ch;
this.name=name;
this.ch.setReceiver(this);
}
protected Object get(Object key) {
synchronized(data) {
return data.get(key);
}
}
protected void put(Object key, Object val) throws Exception {
Object[] buf=new Object[2];
buf[0]=key; buf[1]=val;
Message msg=new Message(null, null, buf);
ch.send(msg);
}
protected int size() {
synchronized(data) {
return data.size();
}
}
public void receive(Message msg) {
Object[] modification=(Object[])msg.getObject();
Object key=modification[0];
Object val=modification[1];
synchronized(data) {
data.put(key,val);
}
}
public byte[] getState() {
byte[] state=null;
synchronized(data) {
try {
state=Util.objectToByteBuffer(data);
}
catch(Exception e) {
e.printStackTrace();
return null;
}
}
return state;
}
public byte[] getState(String state_id) {
return getState();
}
public void setState(byte[] state) {
Map m;
try {
m=(Map)Util.objectFromByteBuffer(state);
synchronized(data) {
data.clear();
data.putAll(m);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
public void setState(String state_id, byte[] state) {
setState(state);
}
public void clear() {
data.clear();
}
public void viewAccepted(View new_view) {
log("view is " + new_view);
}
public String toString() {
return data.toString();
}
private void log(String msg) {
System.out.println("-- [" + name + "] " + msg);
}
}
static class ExtendedCache extends Cache {
public ExtendedCache(Channel ch, String name) {
super(ch, name);
}
public byte[] getState(String state_id) {
Map copy=new HashMap(data);
for(Iterator it=copy.keySet().iterator(); it.hasNext();) {
Integer key=(Integer)it.next();
if(state_id.equals("odd") && key.intValue() % 2 != 0)
it.remove();
else if(state_id.equals("even") && key.intValue() % 2 == 0)
it.remove();
}
try {
return Util.objectToByteBuffer(copy);
}
catch(Exception e) {
e.printStackTrace();
return null;
}
}
public void setState(String state_id, byte[] state) {
setState(state);
}
public String toString() {
synchronized(data) {
Set keys=new TreeSet(data.keySet());
StringBuffer sb=new StringBuffer();
for(Iterator it=keys.iterator(); it.hasNext();) {
Object o=it.next();
sb.append(o).append("=").append(data.get(o)).append(" ");
}
return sb.toString();
}
}
}
}
|
package org.arabellan.ui;
public class WidgetFactory {
public Label createLabel(String text) {
return Label.builder()
.text(text)
.shape(createShape(text))
.build();
}
private int[][] createShape(String text) {
// TODO: Build the shape from the text
return new int[][]{
{9, 9, 9, 0, 9, 9, 9, 0, 9, 9, 9, 0, 9, 9, 0, 0, 9, 9, 9, 0, 9, 9, 9},
{0, 9, 0, 0, 9, 0, 0, 0, 0, 9, 0, 0, 9, 0, 9, 0, 0, 9, 0, 0, 9, 0, 0},
{0, 9, 0, 0, 9, 0, 0, 0, 0, 9, 0, 0, 9, 0, 9, 0, 0, 9, 0, 0, 9, 0, 0},
{0, 9, 0, 0, 9, 9, 9, 0, 0, 9, 0, 0, 9, 9, 0, 0, 0, 9, 0, 0, 9, 9, 9},
{0, 9, 0, 0, 9, 0, 0, 0, 0, 9, 0, 0, 9, 0, 9, 0, 0, 9, 0, 0, 0, 0, 9},
{0, 9, 0, 0, 9, 0, 0, 0, 0, 9, 0, 0, 9, 0, 9, 0, 0, 9, 0, 0, 0, 0, 9},
{0, 9, 0, 0, 9, 9, 9, 0, 0, 9, 0, 0, 9, 0, 9, 0, 9, 9, 9, 0, 9, 9, 9}
};
}
}
|
package org.jgroups.tests;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jgroups.*;
import org.jgroups.mux.MuxChannel;
import org.jgroups.stack.IpAddress;
import org.jgroups.stack.ProtocolStack;
import org.jgroups.stack.Protocol;
import org.jgroups.util.Util;
import java.util.*;
import java.io.*;
import java.lang.management.ThreadMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
/**
* Test the multiplexer functionality provided by JChannelFactory
* @author Bela Ban
* @version $Id: MultiplexerTest.java,v 1.30 2006/10/27 06:59:38 belaban Exp $
*/
public class MultiplexerTest extends TestCase {
private Cache c1, c2, c1_repl, c2_repl;
private Channel ch1, ch2, ch1_repl, ch2_repl;
static String CFG="stacks.xml";
static String STACK_NAME="udp";
JChannelFactory factory, factory2;
int active_threads=0;
String thread_dump=null;
public MultiplexerTest(String name) {
super(name);
}
public void setUp() throws Exception {
super.setUp();
active_threads=Thread.activeCount();
thread_dump="active threads before (" + active_threads + "):\n" + Util.activeThreads();
CFG = System.getProperty("cfg",CFG);
STACK_NAME = System.getProperty("stack",STACK_NAME);
log("Using stack configuration file " + CFG + " and stack name " + STACK_NAME);
factory=new JChannelFactory();
factory.setMultiplexerConfig(CFG);
factory2=new JChannelFactory();
factory2.setMultiplexerConfig(CFG);
}
protected void tearDown() throws Exception {
super.tearDown();
if(ch1_repl != null)
ch1_repl.close();
if(ch2_repl != null)
ch2_repl.close();
if(ch1 != null)
ch1.close();
if(ch2 != null)
ch2.close();
if(ch1 != null) {
assertFalse(((MuxChannel)ch1).getChannel().isOpen());
assertFalse(((MuxChannel)ch1).getChannel().isConnected());
}
if(ch2 != null) {
assertFalse(((MuxChannel)ch2).getChannel().isOpen());
assertFalse(((MuxChannel)ch2).getChannel().isConnected());
}
if(ch1_repl != null) {
assertFalse(((MuxChannel)ch1_repl).getChannel().isOpen());
assertFalse(((MuxChannel)ch1_repl).getChannel().isConnected());
}
if(ch2_repl != null) {
assertFalse(((MuxChannel)ch2_repl).getChannel().isOpen());
assertFalse(((MuxChannel)ch2_repl).getChannel().isConnected());
}
if(c1 != null) c1.clear();
if(c2 != null) c2.clear();
if(c1_repl != null) c1_repl.clear();
if(c2_repl != null) c2_repl.clear();
ch1_repl=ch2_repl=ch1=ch2=null;
c1=c2=c1_repl=c2_repl=null;
Util.sleep(500); // remove this in 2.5 !
int current_active_threads=Thread.activeCount();
String msg="";
if(active_threads != current_active_threads) {
System.out.println(thread_dump);
System.out.println("active threads after (" + current_active_threads + "):\n" + Util.activeThreads());
msg="active threads:\n" + dumpThreads();
}
assertEquals(msg, active_threads, current_active_threads);
}
public void testReplicationWithOneChannel() throws Exception {
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
ch1.connect("bla");
c1=new Cache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
c1.put("name", "Bela");
Util.sleep(300); // we need to wait because replication is asynchronous here
assertEquals(1, c1.size());
assertEquals("Bela", c1.get("name"));
}
public void testLifecycle() throws Exception {
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
assertTrue(ch1.isOpen());
assertFalse(ch1.isConnected());
ch1.connect("bla");
assertTrue(ch1.isOpen());
assertTrue(ch1.isConnected());
ch2=factory.createMultiplexerChannel(STACK_NAME, "c2");
assertTrue(ch2.isOpen());
assertFalse(ch2.isConnected());
ch2.connect("bla");
assertTrue(ch2.isOpen());
assertTrue(ch2.isConnected());
ch2.disconnect();
assertTrue(ch2.isOpen());
assertFalse(ch2.isConnected());
ch2.connect("bla");
assertTrue(ch2.isOpen());
assertTrue(ch2.isConnected());
ch2.disconnect();
assertTrue(ch2.isOpen());
assertFalse(ch2.isConnected());
ch2.close();
assertFalse(ch2.isOpen());
assertFalse(ch2.isConnected());
ch2=factory.createMultiplexerChannel(STACK_NAME, "c2");
ch2.connect("bla");
assertTrue(ch2.isOpen());
assertTrue(ch2.isConnected());
ch2.close();
assertFalse(ch2.isOpen());
assertFalse(ch2.isConnected());
}
public void testDisconnect() throws Exception {
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
assertTrue(ch1.isOpen());
assertFalse(ch1.isConnected());
assertTrue(((MuxChannel)ch1).getChannel().isOpen());
assertFalse(((MuxChannel)ch1).getChannel().isConnected());
ch1.connect("bla");
assertTrue(ch1.isOpen());
assertTrue(ch1.isConnected());
assertTrue(((MuxChannel)ch1).getChannel().isOpen());
assertTrue(((MuxChannel)ch1).getChannel().isConnected());
ch2=factory.createMultiplexerChannel(STACK_NAME, "c2");
assertTrue(ch2.isOpen());
assertFalse(ch2.isConnected());
ch1.disconnect();
assertTrue(ch1.isOpen());
assertFalse(ch1.isConnected());
ch1.connect("bla");
assertTrue(ch1.isOpen());
assertTrue(ch1.isConnected());
ch1.close();
assertFalse(ch1.isOpen());
assertFalse(ch1.isConnected());
assertTrue(((MuxChannel)ch1).getChannel().isOpen());
assertTrue(((MuxChannel)ch1).getChannel().isConnected());
ch2.close();
assertFalse(ch2.isOpen());
assertFalse(ch2.isConnected());
}
public void testDisconnect2() throws Exception {
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
assertTrue(ch1.isOpen());
assertFalse(ch1.isConnected());
ch1.connect("bla");
assertTrue(ch1.isOpen());
assertTrue(ch1.isConnected());
ch2=factory.createMultiplexerChannel(STACK_NAME, "c2");
assertTrue(ch2.isOpen());
assertFalse(ch2.isConnected());
ch1.disconnect();
assertTrue(ch1.isOpen());
assertFalse(ch1.isConnected());
assertTrue(ch2.isOpen());
assertFalse(ch2.isConnected());
ch1.connect("bla");
assertTrue(ch1.isOpen());
assertTrue(ch1.isConnected());
assertTrue(ch2.isOpen());
assertFalse(ch2.isConnected());
}
public void testClose() throws Exception {
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
ch1.connect("bla");
ch2=factory.createMultiplexerChannel(STACK_NAME, "c2");
ch2.connect("bla");
ch1.close();
ch2.close();
}
public void testReplicationWithTwoChannels() throws Exception {
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
c1=new Cache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
ch1.connect("bla");
ch1_repl=factory2.createMultiplexerChannel(STACK_NAME, "c1");
c1_repl=new Cache(ch1_repl, "cache-1-repl");
assertEquals("cache has to be empty initially", 0, c1_repl.size());
ch1_repl.connect("bla");
View v=ch1_repl.getView();
assertNotNull(v);
assertEquals(2, v.size());
c1.put("name", "Bela");
if(ch1.flushSupported())
ch1.startFlush(5000, true);
else
Util.sleep(10000);
System.out.println("c1: " + c1 + ", c1_repl: " + c1_repl);
assertEquals(1, c1.size());
assertEquals("Bela", c1.get("name"));
assertEquals(1, c1_repl.size());
assertEquals("Bela", c1_repl.get("name"));
c1.put("id", new Long(322649));
c1_repl.put("hobbies", "biking");
c1_repl.put("bike", "Centurion");
Util.sleep(500);
System.out.println("c1: " + c1 + ", c1_repl: " + c1_repl);
assertEquals(4, c1.size());
assertEquals(4, c1_repl.size());
assertEquals(new Long(322649), c1.get("id"));
assertEquals(new Long(322649), c1_repl.get("id"));
assertEquals("biking", c1.get("hobbies"));
assertEquals("biking", c1_repl.get("hobbies"));
assertEquals("Centurion", c1.get("bike"));
assertEquals("Centurion", c1_repl.get("bike"));
}
public void testReplicationWithReconnect() throws Exception {
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
ch1.connect("bla");
c1=new Cache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
c1.put("name", "Bela");
Util.sleep(300); // we need to wait because replication is asynchronous here
assertEquals(1, c1.size());
assertEquals("Bela", c1.get("name"));
ch1.disconnect();
ch1.connect("bla");
c2=new Cache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c2.size());
c2.put("name", "Bela");
Util.sleep(300); // we need to wait because replication is asynchronous here
assertEquals(1, c2.size());
assertEquals("Bela", c2.get("name"));
}
public void testStateTransfer() throws Exception {
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
ch1.connect("bla");
c1=new Cache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
ch1_repl=factory2.createMultiplexerChannel(STACK_NAME, "c1");
c1.put("name", "Bela");
c1.put("id", new Long(322649));
c1.put("hobbies", "biking");
c1.put("bike", "Centurion");
ch1_repl.connect("bla");
c1_repl=new Cache(ch1_repl, "cache-1-repl");
boolean rc=ch1_repl.getState(null, 5000);
System.out.println("state transfer: " + rc);
Util.sleep(500);
System.out.println("c1_repl: " + c1_repl);
assertEquals("initial state should have been transferred", 4, c1_repl.size());
assertEquals(new Long(322649), c1.get("id"));
assertEquals(new Long(322649), c1_repl.get("id"));
assertEquals("biking", c1.get("hobbies"));
assertEquals("biking", c1_repl.get("hobbies"));
assertEquals("Centurion", c1.get("bike"));
assertEquals("Centurion", c1_repl.get("bike"));
}
public void testStateTransferWithTwoApplications() throws Exception {
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
ch1.connect("bla");
c1=new Cache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
ch2=factory.createMultiplexerChannel(STACK_NAME, "c2");
ch2.connect("bla");
c2=new Cache(ch2, "cache-2");
assertEquals("cache has to be empty initially", 0, c2.size());
ch1_repl=factory2.createMultiplexerChannel(STACK_NAME, "c1");
ch2_repl=factory2.createMultiplexerChannel(STACK_NAME, "c2");
c1.put("name", "cache-1");
c2.put("name", "cache-2");
ch1_repl.connect("bla");
c1_repl=new Cache(ch1_repl, "cache-1-repl");
boolean rc=ch1_repl.getState(null, 5000);
System.out.println("state transfer: " + rc);
ch2_repl.connect("bla");
c2_repl=new Cache(ch2_repl, "cache-2-repl");
rc=ch2_repl.getState(null, 5000);
System.out.println("state transfer: " + rc);
Util.sleep(500);
System.out.println("Caches after state transfers:");
System.out.println("c1: " + c1);
System.out.println("c1_repl: " + c1_repl);
System.out.println("c2: " + c2);
System.out.println("c2_repl: " + c2_repl);
assertEquals(1, c1.size());
assertEquals(1, c1_repl.size());
assertEquals(1, c2.size());
assertEquals(1, c2_repl.size());
assertEquals("cache-1", c1.get("name"));
assertEquals("cache-1", c1_repl.get("name"));
assertEquals("cache-2", c2.get("name"));
assertEquals("cache-2", c2_repl.get("name"));
}
public void testStateTransferWithRegistration() throws Exception {
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
ch1.connect("bla");
c1=new Cache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
ch2=factory.createMultiplexerChannel(STACK_NAME, "c2");
ch2.connect("bla");
c2=new Cache(ch2, "cache-2");
assertEquals("cache has to be empty initially", 0, c2.size());
c1.put("name", "cache-1");
c2.put("name", "cache-2");
ch1_repl=factory2.createMultiplexerChannel(STACK_NAME, "c1", true, null); // register for state transfer
ch2_repl=factory2.createMultiplexerChannel(STACK_NAME, "c2", true, null); // register for state transfer
ch1_repl.connect("bla");
c1_repl=new Cache(ch1_repl, "cache-1-repl");
boolean rc=ch1_repl.getState(null, 5000); // this will *not* trigger the state transfer protocol
System.out.println("state transfer: " + rc);
ch2_repl.connect("bla");
c2_repl=new Cache(ch2_repl, "cache-2-repl");
rc=ch2_repl.getState(null, 5000); // only *this* will trigger the state transfer
System.out.println("state transfer: " + rc);
Util.sleep(500);
System.out.println("Caches after state transfers:");
System.out.println("c1: " + c1);
System.out.println("c1_repl: " + c1_repl);
System.out.println("c2: " + c2);
System.out.println("c2_repl: " + c2_repl);
assertEquals(1, c1.size());
assertEquals(1, c1_repl.size());
assertEquals(1, c2.size());
assertEquals(1, c2_repl.size());
assertEquals("cache-1", c1.get("name"));
assertEquals("cache-1", c1_repl.get("name"));
assertEquals("cache-2", c2.get("name"));
assertEquals("cache-2", c2_repl.get("name"));
c1.clear();
c1_repl.clear();
c2.clear();
c2_repl.clear();
}
private void setCorrectPortRange(Channel ch) {
ProtocolStack stack=((MuxChannel)ch).getProtocolStack();
Protocol tcpping=stack.findProtocol("TCPPING");
if(tcpping == null)
return;
Properties props=tcpping.getProperties();
String port_range=props.getProperty("port_range");
if(port_range != null) {
System.out.println("port_range in TCPPING: " + port_range + ", setting it to 2");
port_range="2";
Properties p=new Properties();
// p.putAll(props);
p.setProperty("port_range", port_range);
tcpping.setProperties(p);
}
}
public void testStateTransferWithReconnect() throws Exception {
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
setCorrectPortRange(ch1);
assertTrue(ch1.isOpen());
assertFalse(ch1.isConnected());
ch1.connect("bla");
assertTrue(ch1.isOpen());
assertTrue(ch1.isConnected());
assertServiceAndClusterView(ch1, 1, 1);
c1=new Cache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
ch1_repl=factory2.createMultiplexerChannel(STACK_NAME, "c1");
setCorrectPortRange(ch1_repl);
assertTrue(ch1_repl.isOpen());
assertFalse(ch1_repl.isConnected());
c1.put("name", "Bela");
c1.put("id", new Long(322649));
c1.put("hobbies", "biking");
c1.put("bike", "Centurion");
ch1_repl.connect("bla");
assertTrue(ch1_repl.isOpen());
assertTrue(ch1_repl.isConnected());
assertServiceAndClusterView(ch1_repl, 2, 2);
Util.sleep(500);
assertServiceAndClusterView(ch1, 2, 2);
c1_repl=new Cache(ch1_repl, "cache-1-repl");
boolean rc=ch1_repl.getState(null, 5000);
System.out.println("state transfer: " + rc);
Util.sleep(500);
System.out.println("c1_repl: " + c1_repl);
assertEquals("initial state should have been transferred", 4, c1_repl.size());
assertEquals(new Long(322649), c1.get("id"));
assertEquals(new Long(322649), c1_repl.get("id"));
assertEquals("biking", c1.get("hobbies"));
assertEquals("biking", c1_repl.get("hobbies"));
assertEquals("Centurion", c1.get("bike"));
assertEquals("Centurion", c1_repl.get("bike"));
ch1_repl.disconnect();
assertTrue(ch1_repl.isOpen());
assertFalse(ch1_repl.isConnected());
Util.sleep(1000);
assertServiceAndClusterView(ch1, 1, 1);
c1_repl.clear();
ch1_repl.connect("bla");
assertTrue(ch1_repl.isOpen());
assertTrue(ch1_repl.isConnected());
assertServiceAndClusterView(ch1_repl, 2, 2);
Util.sleep(300);
assertServiceAndClusterView(ch1, 2, 2);
assertEquals("cache has to be empty initially", 0, c1_repl.size());
rc=ch1_repl.getState(null, 5000);
System.out.println("state transfer: " + rc);
Util.sleep(500);
System.out.println("c1_repl: " + c1_repl);
assertEquals("initial state should have been transferred", 4, c1_repl.size());
assertEquals(new Long(322649), c1.get("id"));
assertEquals(new Long(322649), c1_repl.get("id"));
assertEquals("biking", c1.get("hobbies"));
assertEquals("biking", c1_repl.get("hobbies"));
assertEquals("Centurion", c1.get("bike"));
assertEquals("Centurion", c1_repl.get("bike"));
// Now see what happens if we reconnect the first channel
// But first, add another MuxChannel on that JChannel
// just so it remains coordinator (test that it doesn't
// ask for state from itself)
ch2=factory.createMultiplexerChannel(STACK_NAME, "c2");
setCorrectPortRange(ch2);
assertTrue(ch2.isOpen());
assertFalse(ch2.isConnected());
assertServiceAndClusterView(ch1, 2, 2);
assertServiceAndClusterView(ch1_repl, 2, 2);
ch1.disconnect();
//sleep a bit and thus let asynch VIEW to propagate to other channel
Util.sleep(500);
assertTrue(ch1.isOpen());
assertFalse(ch1.isConnected());
assertServiceAndClusterView(ch1_repl, 1, 1);
assertTrue(ch2.isOpen());
assertFalse(ch2.isConnected());
c1.clear();
ch1.connect("bla");
assertTrue(ch1.isOpen());
assertTrue(ch1.isConnected());
assertServiceAndClusterView(ch1, 2, 2);
Util.sleep(500);
assertServiceAndClusterView(ch1_repl, 2, 2);
assertTrue(ch2.isOpen());
assertFalse(ch2.isConnected());
assertEquals("cache has to be empty initially", 0, c1.size());
rc=ch1.getState(null, 5000);
System.out.println("state transfer: " + rc);
Util.sleep(500);
System.out.println("c1: " + c1);
assertEquals("initial state should have been transferred", 4, c1.size());
assertEquals(new Long(322649), c1.get("id"));
assertEquals(new Long(322649), c1_repl.get("id"));
assertEquals("biking", c1.get("hobbies"));
assertEquals("biking", c1_repl.get("hobbies"));
assertEquals("Centurion", c1.get("bike"));
assertEquals("Centurion", c1_repl.get("bike"));
}
private void assertServiceAndClusterView(Channel ch, int num_service_view_mbrs, int num_cluster_view_mbrs) {
View service_view, cluster_view;
service_view=ch.getView();
cluster_view=((MuxChannel)ch).getClusterView();
String msg="cluster view=" + cluster_view + ", service view=" + service_view;
assertNotNull(service_view);
assertNotNull(cluster_view);
assertEquals(msg, num_service_view_mbrs, service_view.size());
assertEquals(msg, num_cluster_view_mbrs, cluster_view.size());
}
public void testStateTransferFromSelfWithRegularChannel() throws Exception {
JChannel ch=new JChannel();
ch.connect("X");
try {
boolean rc=ch.getState(null, 2000);
assertFalse("getState() on singleton should return false", rc);
}
finally {
ch.close();
}
}
public void testStateTransferFromSelf() throws Exception {
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
ch1.connect("bla");
boolean rc=ch1.getState(null, 2000);
assertFalse("getState() on singleton should return false", rc);
ch2=factory.createMultiplexerChannel(STACK_NAME, "c2");
ch2.connect("foo");
rc=ch2.getState(null, 2000);
assertFalse("getState() on singleton should return false", rc);
}
public void testAdditionalData() throws Exception {
byte[] additional_data=new byte[]{'b', 'e', 'l', 'a'};
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
Map m=new HashMap(1);
m.put("additional_data", additional_data);
ch1.down(new Event(Event.CONFIG, m));
ch1.connect("bla");
IpAddress local_addr=(IpAddress)ch1.getLocalAddress();
assertNotNull(local_addr);
byte[] tmp=local_addr.getAdditionalData();
assertNotNull(tmp);
assertEquals(tmp, additional_data);
ch2=factory.createMultiplexerChannel(STACK_NAME, "c2");
ch2.connect("foo");
local_addr=(IpAddress)ch2.getLocalAddress();
assertNotNull(local_addr);
tmp=local_addr.getAdditionalData();
assertNotNull(tmp);
assertEquals(tmp, additional_data);
}
public void testAdditionalData2() throws Exception {
byte[] additional_data=new byte[]{'b', 'e', 'l', 'a'};
byte[] additional_data2=new byte[]{'m', 'i', 'c', 'h', 'i'};
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
ch1.connect("bla");
IpAddress local_addr=(IpAddress)ch1.getLocalAddress();
assertNotNull(local_addr);
byte[] tmp=local_addr.getAdditionalData();
assertNull(tmp);
ch2=factory.createMultiplexerChannel(STACK_NAME, "c2");
Map m=new HashMap(1);
m.put("additional_data", additional_data);
ch2.down(new Event(Event.CONFIG, m));
ch2.connect("foo");
local_addr=(IpAddress)ch2.getLocalAddress();
assertNotNull(local_addr);
tmp=local_addr.getAdditionalData();
assertNotNull(tmp);
assertEquals(tmp, additional_data);
local_addr=(IpAddress)ch1.getLocalAddress();
assertNotNull(local_addr);
tmp=local_addr.getAdditionalData();
assertNotNull(tmp);
assertEquals(tmp, additional_data);
m.clear();
m.put("additional_data", additional_data2);
ch2.down(new Event(Event.CONFIG, m));
local_addr=(IpAddress)ch2.getLocalAddress();
assertNotNull(local_addr);
tmp=local_addr.getAdditionalData();
assertNotNull(tmp);
assertEquals(tmp, additional_data2);
assertFalse(Arrays.equals(tmp, additional_data));
}
public void testGetSubstates() throws Exception {
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
ch1.connect("bla");
c1=new ExtendedCache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
ch2=factory.createMultiplexerChannel(STACK_NAME, "c2");
ch2.connect("bla");
c2=new ExtendedCache(ch2, "cache-2");
assertEquals("cache has to be empty initially", 0, c2.size());
for(int i=0; i < 10; i++) {
c1.put(new Integer(i), new Integer(i));
c2.put(new Integer(i), new Integer(i));
}
ch1_repl=factory2.createMultiplexerChannel(STACK_NAME, "c1");
ch2_repl=factory2.createMultiplexerChannel(STACK_NAME, "c2");
ch1_repl.connect("bla");
c1_repl=new ExtendedCache(ch1_repl, "cache-1-repl");
boolean rc=ch1_repl.getState(null, "odd", 5000);
System.out.println("state transfer: " + rc);
ch2_repl.connect("bla");
c2_repl=new ExtendedCache(ch2_repl, "cache-2-repl");
rc=ch2_repl.getState(null, "even", 5000);
System.out.println("state transfer: " + rc);
Util.sleep(500);
System.out.println("Caches after state transfers:");
System.out.println("c1: " + c1);
System.out.println("c2: " + c2);
System.out.println("c1_repl (removed odd substate): " + c1_repl);
System.out.println("c2_repl (removed even substate): " + c2_repl);
assertEquals(5, c1_repl.size());
assertEquals(5, c2_repl.size());
_testEvenNumbersPresent(c1_repl);
_testOddNumbersPresent(c2_repl);
}
private void _testEvenNumbersPresent(Cache c) {
Integer[] evens=new Integer[]{new Integer(0), new Integer(2), new Integer(4), new Integer(6), new Integer(8)};
_testNumbersPresent(c, evens);
}
private void _testOddNumbersPresent(Cache c) {
Integer[] odds=new Integer[]{new Integer(1), new Integer(3), new Integer(5), new Integer(7), new Integer(9)};
_testNumbersPresent(c, odds);
}
private void _testNumbersPresent(Cache c, Integer[] numbers) {
int len=numbers.length;
assertEquals(len, c.size());
for(int i=0; i < numbers.length; i++) {
Integer number=numbers[i];
assertEquals(number, c.get(number));
}
}
public void testGetSubstatesMultipleTimes() throws Exception {
ch1=factory.createMultiplexerChannel(STACK_NAME, "c1");
ch1.connect("bla");
c1=new ExtendedCache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
ch2=factory.createMultiplexerChannel(STACK_NAME, "c2");
ch2.connect("bla");
c2=new ExtendedCache(ch2, "cache-2");
assertEquals("cache has to be empty initially", 0, c2.size());
for(int i=0; i < 10; i++) {
c1.put(new Integer(i), new Integer(i));
c2.put(new Integer(i), new Integer(i));
}
ch1_repl=factory2.createMultiplexerChannel(STACK_NAME, "c1");
ch2_repl=factory2.createMultiplexerChannel(STACK_NAME, "c2");
ch1_repl.connect("bla");
c1_repl=new ExtendedCache(ch1_repl, "cache-1-repl");
boolean rc=ch1_repl.getState(null, "odd", 5000);
System.out.println("state transfer: " + rc);
ch2_repl.connect("bla");
c2_repl=new ExtendedCache(ch2_repl, "cache-2-repl");
rc=ch2_repl.getState(null, "even", 5000);
System.out.println("state transfer: " + rc);
Util.sleep(500);
_testOddNumbersPresent(c2_repl);
System.out.println("Caches after state transfers:");
System.out.println("c1: " + c1);
System.out.println("c2: " + c2);
System.out.println("c1_repl (removed odd substate): " + c1_repl);
System.out.println("c2_repl (removed even substate): " + c2_repl);
assertEquals(5, c2_repl.size());
rc=ch2_repl.getState(null, "odd", 5000);
Util.sleep(500);
System.out.println("c2_repl (removed odd substate): " + c2_repl);
_testEvenNumbersPresent(c2_repl);
assertEquals(5, c2_repl.size());
rc=ch2_repl.getState(null, "even", 5000);
Util.sleep(500);
System.out.println("c2_repl (removed even substate): " + c2_repl);
_testOddNumbersPresent(c2_repl);
assertEquals(5, c2_repl.size());
rc=ch2_repl.getState(null, "odd", 5000);
Util.sleep(500);
System.out.println("c2_repl (removed odd substate): " + c2_repl);
_testEvenNumbersPresent(c2_repl);
}
/* CAUTION: JDK 5 specific code */
private String dumpThreads() {
StringBuffer sb=new StringBuffer();
ThreadMXBean bean=ManagementFactory.getThreadMXBean();
long[] ids=bean.getAllThreadIds();
ThreadInfo[] threads=bean.getThreadInfo(ids, 20);
for(int i=0; i < threads.length; i++) {
ThreadInfo info=threads[i];
if(info == null)
continue;
sb.append(info.getThreadName()).append(":\n");
StackTraceElement[] stack_trace=info.getStackTrace();
for(int j=0; j < stack_trace.length; j++) {
StackTraceElement el=stack_trace[j];
sb.append("at ").append(el.getClassName()).append(".").append(el.getMethodName());
sb.append("(").append(el.getFileName()).append(":").append(el.getLineNumber()).append(")");
sb.append("\n");
}
sb.append("\n\n");
}
return sb.toString();
}
public static Test suite() {
return new TestSuite(MultiplexerTest.class);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(MultiplexerTest.suite());
}
private static void log(String msg) {
System.out.println(Thread.currentThread() + " -- "+ msg);
}
private static class Cache extends ExtendedReceiverAdapter {
final Map data=new HashMap();
Channel ch;
String name;
public Cache(Channel ch, String name) {
this.ch=ch;
this.name=name;
this.ch.setReceiver(this);
}
protected Object get(Object key) {
synchronized(data) {
return data.get(key);
}
}
protected void put(Object key, Object val) throws Exception {
Object[] buf=new Object[2];
buf[0]=key; buf[1]=val;
Message msg=new Message(null, null, buf);
ch.send(msg);
}
protected int size() {
synchronized(data) {
return data.size();
}
}
public void receive(Message msg) {
Object[] modification=(Object[])msg.getObject();
Object key=modification[0];
Object val=modification[1];
synchronized(data) {
data.put(key,val);
}
}
public byte[] getState() {
byte[] state=null;
synchronized(data) {
try {
state=Util.objectToByteBuffer(data);
}
catch(Exception e) {
e.printStackTrace();
return null;
}
}
return state;
}
public byte[] getState(String state_id) {
return getState();
}
public void setState(byte[] state) {
Map m;
try {
m=(Map)Util.objectFromByteBuffer(state);
synchronized(data) {
data.clear();
data.putAll(m);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
public void setState(String state_id, byte[] state) {
setState(state);
}
public void getState(OutputStream ostream){
ObjectOutputStream oos = null;
try{
oos = new ObjectOutputStream(ostream);
synchronized(data){
oos.writeObject(data);
}
oos.flush();
}
catch (IOException e){}
finally{
try{
if(oos != null)
oos.close();
}
catch (IOException e){
System.err.println(e);
}
}
}
public void getState(String state_id, OutputStream ostream) {
getState(ostream);
}
public void setState(InputStream istream) {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(istream);
Map m = (Map)ois.readObject();
synchronized (data)
{
data.clear();
data.putAll(m);
}
} catch (Exception e) {}
finally{
try {
if(ois != null)
ois.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
public void setState(String state_id, InputStream istream) {
setState(istream);
}
public void clear() {
synchronized (data){
data.clear();
}
}
public void viewAccepted(View new_view) {
log("view is " + new_view);
}
public String toString() {
return data.toString();
}
private void log(String msg) {
System.out.println("-- [" + name + "] " + msg);
}
}
static class ExtendedCache extends Cache {
public ExtendedCache(Channel ch, String name) {
super(ch, name);
}
public byte[] getState(String state_id) {
Map copy=null;
synchronized (data){
copy=new HashMap(data);
}
for(Iterator it=copy.keySet().iterator(); it.hasNext();) {
Integer key=(Integer)it.next();
if(state_id.equals("odd") && key.intValue() % 2 != 0)
it.remove();
else if(state_id.equals("even") && key.intValue() % 2 == 0)
it.remove();
}
try {
return Util.objectToByteBuffer(copy);
}
catch(Exception e) {
e.printStackTrace();
return null;
}
}
public void getState(String state_id,OutputStream os) {
Map copy=null;
synchronized (data){
copy=new HashMap(data);
}
for(Iterator it=copy.keySet().iterator(); it.hasNext();) {
Integer key=(Integer)it.next();
if(state_id.equals("odd") && key.intValue() % 2 != 0)
it.remove();
else if(state_id.equals("even") && key.intValue() % 2 == 0)
it.remove();
}
ObjectOutputStream oos = null;
try {
oos=new ObjectOutputStream(os);
oos.writeObject(copy);
oos.flush();
}
catch (IOException e){}
finally{
try{
if(oos != null)
oos.close();
}
catch (IOException e){
System.err.println(e);
}
}
}
public void setState(String state_id, InputStream is){
setState(is);
}
public void setState(String state_id, byte[] state) {
setState(state);
}
public String toString() {
synchronized(data) {
Set keys=new TreeSet(data.keySet());
StringBuffer sb=new StringBuffer();
for(Iterator it=keys.iterator(); it.hasNext();) {
Object o=it.next();
sb.append(o).append("=").append(data.get(o)).append(" ");
}
return sb.toString();
}
}
}
}
|
package cgeo.geocaching.test;
import cgeo.geocaching.Settings;
import org.apache.commons.lang3.StringUtils;
import android.test.AndroidTestCase;
import android.util.Log;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* This test is meant for performance measurements of different whitespace replacement implementations.
* It does not test semantical correctness.
*
*/
public class WhitespaceTest extends AndroidTestCase {
private String data;
@Override
protected void setUp() throws Exception {
final StringBuffer buffer = new StringBuffer();
final InputStream is = this.getClass().getResourceAsStream("/cgeo/geocaching/test/mock/GC2CJPF.html");
final BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = br.readLine()) != null) {
buffer.append(line).append('\n');
}
data = buffer.toString();
br.close();
}
public static String replaceWhitespaceManually(final String data) {
final int length = data.length();
final char[] chars = new char[length];
data.getChars(0, length, chars, 0);
int resultSize = 0;
boolean lastWasWhitespace = false;
for (char c : chars) {
if (c == ' ' || c == '\n' || c == '\r' || c == '\t') {
if (!lastWasWhitespace) {
chars[resultSize++] = ' ';
}
lastWasWhitespace = true;
} else {
chars[resultSize++] = c;
lastWasWhitespace = false;
}
}
return String.valueOf(chars, 0, resultSize);
}
public static String replaceWhitespaceStringUtils(final String data) {
return StringUtils.join(StringUtils.split(data, " \n\r\t"), " ");
}
public void testManually() {
String result;
final long start = System.currentTimeMillis();
result = replaceWhitespaceManually(data);
final long end = System.currentTimeMillis();
assertEquals(111958, result.length());
Log.w(Settings.tag, (end - start) + " ms manually");
}
public void testStringUtils() {
String result;
final long start = System.currentTimeMillis();
result = replaceWhitespaceStringUtils(data);
final long end = System.currentTimeMillis();
assertEquals(111956, result.length());
Log.w(Settings.tag, (end - start) + " ms StringUtils");
}
}
|
package org.jruby.rack;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jruby.rack.servlet.ServletRackEnvironment;
import org.jruby.rack.servlet.ServletRackResponseEnvironment;
/**
*
* @author nicksieger
*/
@SuppressWarnings("serial")
public abstract class AbstractServlet extends HttpServlet {
@Override
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RackEnvironment env = new ServletRackEnvironment(request, response, getContext());
RackResponseEnvironment responseEnv = new ServletRackResponseEnvironment(response);
getDispatcher().process(env, responseEnv);
}
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
service((HttpServletRequest) request, (HttpServletResponse) response);
}
@Override
public void destroy() {
super.destroy();
getDispatcher().destroy();
}
protected abstract RackDispatcher getDispatcher();
protected abstract RackContext getContext();
}
|
package org.lantern;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicReference;
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.security.auth.login.CredentialException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.IQTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Type;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.lantern.event.ClosedBetaEvent;
import org.lantern.event.Events;
import org.lantern.event.GoogleTalkStateEvent;
import org.lantern.event.ResetEvent;
import org.lantern.event.UpdateEvent;
import org.lantern.event.UpdatePresenceEvent;
import org.lantern.kscope.KscopeAdHandler;
import org.lantern.kscope.LanternKscopeAdvertisement;
import org.lantern.state.Connectivity;
import org.lantern.state.Model;
import org.lantern.state.ModelIo;
import org.lantern.state.ModelUtils;
import org.lantern.state.Notification.MessageType;
import org.lantern.state.SyncPath;
import org.lantern.udtrelay.UdtRelayServerFiveTupleListener;
import org.lastbamboo.common.ice.MappedServerSocket;
import org.lastbamboo.common.ice.MappedTcpAnswererServer;
import org.lastbamboo.common.p2p.P2PConnectionEvent;
import org.lastbamboo.common.p2p.P2PConnectionListener;
import org.lastbamboo.common.p2p.P2PConstants;
import org.lastbamboo.common.portmapping.NatPmpService;
import org.lastbamboo.common.portmapping.UpnpService;
import org.lastbamboo.common.stun.client.StunServerRepository;
import org.littleshoot.commom.xmpp.XmppCredentials;
import org.littleshoot.commom.xmpp.XmppP2PClient;
import org.littleshoot.commom.xmpp.XmppUtils;
import org.littleshoot.p2p.P2PEndpoints;
import org.littleshoot.util.FiveTuple;
import org.littleshoot.util.SessionSocketListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Inject;
import com.google.inject.Singleton;
/**
* Handles logging in to the XMPP server and processing trusted users through
* the roster.
*/
@Singleton
public class DefaultXmppHandler implements XmppHandler {
private static final Logger LOG =
LoggerFactory.getLogger(DefaultXmppHandler.class);
private final AtomicReference<XmppP2PClient<FiveTuple>> client =
new AtomicReference<XmppP2PClient<FiveTuple>>();
static {
SmackConfiguration.setPacketReplyTimeout(30 * 1000);
}
private volatile long lastInfoMessageScheduled = 0L;
private final MessageListener typedListener = new MessageListener() {
@Override
public void processMessage(final Chat ch, final Message msg) {
// Note the Chat will always be null here. We try to avoid using
// actual Chat instances due to Smack's strange and inconsistent
// behavior with message listeners on chats.
final String from = msg.getFrom();
LOG.debug("Got chat participant: {} with message:\n {}", from,
msg.toXML());
if (msg.getType() == org.jivesoftware.smack.packet.Message.Type.error) {
LOG.warn("Received error message!! {}", msg.toXML());
return;
}
if (LanternUtils.isLanternHub(from)) {
processLanternHubMessage(msg);
}
final Integer type =
(Integer) msg.getProperty(P2PConstants.MESSAGE_TYPE);
if (type != null) {
LOG.debug("Processing typed message");
processTypedMessage(msg, type);
}
}
};
private String lastJson = "";
private String hubAddress;
private GoogleTalkState state;
private final NatPmpService natPmpService;
private final UpnpService upnpService;
private ClosedBetaEvent closedBetaEvent;
private final Object closedBetaLock = new Object();
private MappedServerSocket mappedServer;
//private final PeerProxyManager trustedPeerProxyManager;
private final Timer timer;
private final Stats stats;
private final LanternKeyStoreManager keyStoreManager;
private final LanternSocketsUtil socketsUtil;
private final LanternXmppUtil xmppUtil;
private final Model model;
private volatile boolean started;
private final ModelUtils modelUtils;
private final ModelIo modelIo;
private final org.lantern.Roster roster;
private final ProxyTracker proxyTracker;
private final KscopeAdHandler kscopeAdHandler;
/**
* HTTP proxy server other peers hit.
*/
private final SslHttpProxyServer peerProxyServer;
private TimerTask reconnectIfNoPong;
/**
* The XMPP message id that we are waiting for a pong on
*/
private String waitingForPong;
private long pingTimeout = 15 * 1000;
protected XMPPConnection previousConnection;
/**
* Creates a new XMPP handler.
*/
@Inject
public DefaultXmppHandler(final Model model,
//final PeerProxyManager trustedPeerProxyManager,
final Timer updateTimer, final Stats stats,
final LanternKeyStoreManager keyStoreManager,
final LanternSocketsUtil socketsUtil,
final LanternXmppUtil xmppUtil,
final ModelUtils modelUtils,
final ModelIo modelIo, final org.lantern.Roster roster,
final ProxyTracker proxyTracker,
final KscopeAdHandler kscopeAdHandler,
final SslHttpProxyServer peerProxyServer,
final NatPmpService natPmpService,
final UpnpService upnpService) {
this.model = model;
this.timer = updateTimer;
this.stats = stats;
this.keyStoreManager = keyStoreManager;
this.socketsUtil = socketsUtil;
this.xmppUtil = xmppUtil;
this.modelUtils = modelUtils;
this.modelIo = modelIo;
this.roster = roster;
this.proxyTracker = proxyTracker;
this.kscopeAdHandler = kscopeAdHandler;
this.peerProxyServer = peerProxyServer;
this.natPmpService = natPmpService;
this.upnpService = upnpService;
Events.register(this);
//setupJmx();
}
@Override
public MappedServerSocket getMappedServer() {
return mappedServer;
}
@Override
public void start() {
this.modelUtils.loadClientSecrets();
XmppUtils.setGlobalConfig(this.xmppUtil.xmppConfig());
XmppUtils.setGlobalProxyConfig(this.xmppUtil.xmppProxyConfig());
this.mappedServer = new MappedTcpAnswererServer(natPmpService,
upnpService, new InetSocketAddress(this.peerProxyServer.getPort()));
this.started = true;
}
@Override
public void stop() {
LOG.debug("Stopping XMPP handler...");
disconnect();
if (upnpService != null) {
upnpService.shutdown();
}
if (natPmpService != null) {
natPmpService.shutdown();
}
LOG.debug("Finished stoppeding XMPP handler...");
}
@Subscribe
public void onAuthStatus(final GoogleTalkStateEvent ase) {
this.state = ase.getState();
switch (state) {
case connected:
// We wait until we're logged in before creating our roster.
final XmppP2PClient<FiveTuple> cl = client.get();
if (cl == null) {
LOG.error("Null client for instance: "+hashCode());
return;
}
this.roster.onRoster(this);
break;
case notConnected:
this.roster.reset();
break;
case connecting:
break;
case LOGIN_FAILED:
this.roster.reset();
break;
}
}
@Subscribe
public void onConnectivityChanged(ConnectivityChangedEvent e) {
if (!e.isConnected()) {
// send a ping message to determine if we need to reconnect; failed
// STUN connectivity is not necessarily a death sentence for the
// XMPP connection.
// If the ping fails, then XmppP2PClient will retry that connection
// in a loop.
ping();
return;
}
LOG.info("connected to internet");
XmppP2PClient<FiveTuple> client = this.client.get();
if (client == null)
return; //this is probably at startup
final XMPPConnection conn = client.getXmppConnection();
if (e.isIpChanged()) {
//definitely need to reconnect here
reconnect();
} else {
if (conn == null || !conn.isConnected()) {
//definitely need to reconnect here
reconnect();
} else {
ping();
}
}
}
private void ping() {
//if we are already pinging, cancel the existing ping
//and retry
if (reconnectIfNoPong != null) {
reconnectIfNoPong.cancel();
}
XmppP2PClient<FiveTuple> client = this.client.get();
if (client == null) {
//no connection yet, so we'll just return; the connection
//will be established when we can
return;
}
XMPPConnection connection = client.getXmppConnection();
IQ ping = new IQ() {
@Override
public String getChildElementXML() {
return "<ping xmlns='urn:xmpp:ping'/>";
}
};
waitingForPong = ping.getPacketID();
//set up timer to reconnect if we don't hear a pong
reconnectIfNoPong = new Reconnector();
timer.schedule(reconnectIfNoPong, getPingTimeout());
//and send the ping
connection.sendPacket(ping);
}
/**
* How long we wait,
* @return
*/
public long getPingTimeout() {
return pingTimeout;
}
public void setPingTimeout(long pingTimeout) {
this.pingTimeout = pingTimeout;
}
//this will be cancelled if a pong is received
class Reconnector extends TimerTask {
@Override
public void run() {
reconnect();
}
}
@Override
public synchronized void connect() throws IOException, CredentialException,
NotInClosedBetaException {
if (!this.started) {
LOG.warn("Can't connect when not started!!");
throw new Error("Can't connect when not started!!");
}
if (!this.modelUtils.isConfigured()) {
if (this.model.getSettings().isUiEnabled()) {
LOG.debug("Not connecting when not configured and UI enabled");
return;
}
}
if (isLoggedIn()) {
LOG.warn("Already logged in!! Not connecting");
return;
}
LOG.debug("Connecting to XMPP servers...");
if (this.modelUtils.isOauthConfigured()) {
//if (this.model.getSettings().isUseGoogleOAuth2()) {
connectViaOAuth2();
} else {
//connectWithEmailAndPass();
throw new Error("Oauth not configured properly?");
}
}
private void connectViaOAuth2() throws IOException,
CredentialException, NotInClosedBetaException {
final XmppCredentials credentials =
this.modelUtils.newGoogleOauthCreds(getResource());
LOG.debug("Logging in with credentials: {}", credentials);
connect(credentials);
}
@Override
public void connect(final String email, final String pass)
throws IOException, CredentialException, NotInClosedBetaException {
//connect(new PasswordCredentials(email, pass, getResource()));
}
private String getResource() {
return LanternConstants.UNCENSORED_ID;
}
public void connect(final XmppCredentials credentials)
throws IOException, CredentialException, NotInClosedBetaException {
LOG.debug("Connecting to XMPP servers with user name and password...");
this.closedBetaEvent = null;
final InetSocketAddress plainTextProxyRelayAddress =
LanternUtils.isa("127.0.0.1",
LanternUtils.PLAINTEXT_LOCALHOST_PROXY_PORT);
if (this.client.get() == null) {
final SessionSocketListener sessionListener = new SessionSocketListener() {
@Override
public void reconnected() {
// We need to send a new presence message each time we
// reconnect to the XMPP server, as otherwise peers won't
// know we're available and we won't get data from the bot.
updatePresence();
}
@Override
public void onSocket(String arg0, Socket arg1) throws IOException {
}
};
this.client.set(P2PEndpoints.newXmppP2PHttpClient(
"shoot", natPmpService,
this.upnpService, this.mappedServer,
this.socketsUtil.newTlsSocketFactory(),
this.socketsUtil.newTlsServerSocketFactory(),
plainTextProxyRelayAddress, sessionListener, false,
new UdtRelayServerFiveTupleListener()));
LOG.debug("Set client for xmpp handler: "+hashCode());
this.client.get().addConnectionListener(new P2PConnectionListener() {
@Override
public void onConnectivityEvent(final P2PConnectionEvent event) {
LOG.debug("Got connectivity event: {}", event);
Events.asyncEventBus().post(event);
XMPPConnection connection = client.get().getXmppConnection();
if (connection == previousConnection) {
//only add packet listener once
return;
}
previousConnection = connection;
//listen to responses for XMPP pings, and if we get any,
//cancel pending reconnects
connection.addPacketListener(new PacketListener() {
@Override
public void processPacket(Packet packet) {
IQ iq = (IQ) packet;
if (iq.getPacketID().equals(waitingForPong)) {
LOG.debug("Got pong, cancelling pending reconnect");
reconnectIfNoPong.cancel();
}
}
}, new IQTypeFilter(org.jivesoftware.smack.packet.IQ.Type.RESULT));
}
});
} else {
LOG.debug("Using existing client for xmpp handler: "+hashCode());
}
// This is a global, backup listener added to the client. We might
// get notifications of messages twice in some cases, but that's
// better than the alternative of sometimes not being notified
// at all.
LOG.debug("Adding message listener...");
this.client.get().addMessageListener(typedListener);
Events.eventBus().post(
new GoogleTalkStateEvent("", GoogleTalkState.connecting));
try {
this.client.get().login(credentials);
modelUtils.syncConnectingStatus("Logged in to Google Talk...");
// Preemptively create our key.
this.keyStoreManager.getBase64Cert(getJid());
LOG.debug("Sending connected event");
Events.eventBus().post(
new GoogleTalkStateEvent(getJid(), GoogleTalkState.connected));
} catch (final IOException e) {
// Note that the XMPP library will internally attempt to connect
// to our backup proxy if it can.
handleConnectionFailure();
throw e;
} catch (final IllegalStateException e) {
handleConnectionFailure();
throw e;
} catch (final CredentialException e) {
handleConnectionFailure();
throw e;
}
// Note we don't consider ourselves connected in get mode until we
// actually get proxies to work with.
modelUtils.syncConnectingStatus("Gathering servers...");
final XMPPConnection connection = this.client.get().getXmppConnection();
final Collection<InetSocketAddress> googleStunServers =
XmppUtils.googleStunServers(connection);
StunServerRepository.setStunServers(googleStunServers);
this.model.getSettings().setStunServers(
new HashSet<String>(toStringServers(googleStunServers)));
// Make sure all connections between us and the server are stored
// OTR.
modelUtils.syncConnectingStatus("Activating Google Talk pseudo-OTR...");
LanternUtils.activateOtr(connection);
LOG.debug("Connection ID: {}", connection.getConnectionID());
modelUtils.syncConnectingStatus("Waiting for message from Lantern...");
// Here we handle allowing the server to subscribe to our presence.
connection.addPacketListener(new PacketListener() {
@Override
public void processPacket(final Packet pack) {
final Presence pres = (Presence) pack;
LOG.debug("Processing packet!! {}", pres.toXML());
final String from = pres.getFrom();
LOG.debug("Responding to presence from {} and to {}",
from, pack.getTo());
final Type type = pres.getType();
// Allow subscription requests from the lantern bot.
if (LanternUtils.isLanternHub(from)) {
if (type == Type.subscribe) {
final Presence packet =
new Presence(Presence.Type.subscribed);
packet.setTo(from);
packet.setFrom(pack.getTo());
connection.sendPacket(packet);
} else {
LOG.debug("Non-subscribe packet from hub? {}",
pres.toXML());
}
} else {
switch (type) {
case available:
return;
case error:
LOG.warn("Got error packet!! {}", pack.toXML());
return;
case subscribe:
LOG.debug("Adding subscription request from: {}", from);
// Did we originally invite them and they're
// subscribing back? Auto-allow if so.
if (roster.autoAcceptSubscription(from)) {
subscribed(from);
} else {
LOG.debug("We didn't invite them");
}
roster.addIncomingSubscriptionRequest(pres);
break;
case subscribed:
break;
case unavailable:
return;
case unsubscribe:
LOG.info("Removing subscription request from: {}",from);
roster.removeIncomingSubscriptionRequest(from);
return;
case unsubscribed:
break;
}
}
}
}, new PacketFilter() {
@Override
public boolean accept(final Packet packet) {
if(packet instanceof Presence) {
return true;
} else {
LOG.debug("Not a presence packet: {}", packet.toXML());
}
return false;
}
});
gTalkSharedStatus();
updatePresence();
waitForClosedBetaStatus(credentials.getUsername());
modelUtils.syncConnectingStatus("Lantern message received...");
}
private void handleConnectionFailure() {
Events.eventBus().post(
new GoogleTalkStateEvent("", GoogleTalkState.LOGIN_FAILED));
}
private void waitForClosedBetaStatus(final String email)
throws NotInClosedBetaException {
if (this.modelUtils.isInClosedBeta(email)) {
LOG.debug("Already in closed beta...");
return;
}
// The following is necessary because the call to login needs to either
// succeed or fail for the UI to work properly, but we don't know if
// a user is able to log in until we get an asynchronous XMPP message
// back from the server.
synchronized (this.closedBetaLock) {
if (this.closedBetaEvent == null) {
try {
this.closedBetaLock.wait(80 * 1000);
} catch (final InterruptedException e) {
LOG.info("Interrupted? Maybe on shutdown?", e);
}
}
}
if (this.closedBetaEvent != null) {
if(!this.closedBetaEvent.isInClosedBeta()) {
LOG.debug("Not in closed beta...");
notInClosedBeta("Not in closed beta");
} else {
LOG.debug("Server notified us we're in the closed beta!");
return;
}
} else {
LOG.warn("No closed beta event -- timed out!!");
notInClosedBeta("No closed beta event!!");
}
}
private void notInClosedBeta(final String msg)
throws NotInClosedBetaException {
LOG.debug("Not in closed beta!");
disconnect();
throw new NotInClosedBetaException(msg);
}
private Set<String> toStringServers(
final Collection<InetSocketAddress> googleStunServers) {
final Set<String> strings = new HashSet<String>();
for (final InetSocketAddress isa : googleStunServers) {
strings.add(isa.getHostName()+":"+isa.getPort());
}
return strings;
}
@Override
public void disconnect() {
LOG.debug("Disconnecting!!");
lastJson = "";
/*
LanternHub.eventBus().post(
new GoogleTalkStateEvent(GoogleTalkState.LOGGING_OUT));
*/
final XmppP2PClient<FiveTuple> cl = this.client.get();
if (cl != null) {
this.client.get().logout();
//this.client.set(null);
}
Events.eventBus().post(
new GoogleTalkStateEvent("", GoogleTalkState.notConnected));
proxyTracker.clearPeerProxySet();
this.closedBetaEvent = null;
// This is mostly logged for debugging thorny shutdown issues...
LOG.debug("Finished disconnecting XMPP...");
}
@SuppressWarnings("unchecked")
private void processLanternHubMessage(final Message msg) {
Connectivity connectivity = model.getConnectivity();
if (!connectivity.getLanternController()) {
connectivity.setLanternController(true);
Events.sync(SyncPath.CONNECTIVITY_LANTERN_CONTROLLER, true);
}
LOG.debug("Lantern controlling agent response");
this.hubAddress = msg.getFrom();
final String to = XmppUtils.jidToUser(msg.getTo());
LOG.debug("Set hub address to: {}", hubAddress);
final String body = msg.getBody();
LOG.debug("Hub message body: {}", body);
final Object obj = JSONValue.parse(body);
final JSONObject json = (JSONObject) obj;
final Boolean inClosedBeta =
(Boolean) json.get(LanternConstants.INVITED);
if (inClosedBeta != null) {
Events.asyncEventBus().post(new ClosedBetaEvent(to, inClosedBeta));
} else {
Events.asyncEventBus().post(new ClosedBetaEvent(to, false));
}
final Long invites =
(Long) json.get(LanternConstants.INVITES_KEY);
if (invites != null) {
LOG.info("Setting invites to: {}", invites);
final int oldInvites = this.model.getNinvites();
final int newInvites = invites.intValue();
if (oldInvites != newInvites) {
this.model.setNinvites(newInvites);
Events.syncNInvites(invites.intValue());
}
}
final Long delay =
(Long) json.get(LanternConstants.UPDATE_TIME);
LOG.debug("Server sent delay of: "+delay);
if (delay != null) {
final long now = System.currentTimeMillis();
final long elapsed = now - lastInfoMessageScheduled;
if (elapsed > 10000 && delay != 0L) {
lastInfoMessageScheduled = now;
timer.schedule(new TimerTask() {
@Override
public void run() {
updatePresence();
}
}, delay);
LOG.debug("Scheduled next info request in {} milliseconds",
delay);
} else {
LOG.debug("Ignoring duplicate info request scheduling- "+
"scheduled request {} milliseconds ago.", elapsed);
}
}
// This is really a JSONObject, but that itself is a map.
final JSONObject update =
(JSONObject) json.get(LanternConstants.UPDATE_KEY);
if (update != null) {
LOG.info("About to propagate update...");
final Map<String, Object> event =
new HashMap<String, Object>();
event.putAll(update);
Events.asyncEventBus().post(new UpdateEvent(event));
}
//list of invites that the server has processed
final List<Object> invited = (List<Object>) json.get(LanternConstants.INVITED_KEY);
if (invited != null) {
for (Object invite : invited) {
model.removePendingInvite((String)invite);
}
}
//list of invites that the server has given up on processing
//perhaps because you are out of invites.
final List<Object> failedInvites = (List<Object>) json.get(LanternConstants.FAILED_INVITES_KEY);
LOG.info("Failed invites: " + failedInvites);
if (failedInvites != null) {
for (Object inviteObj : failedInvites) {
JSONObject invite = (JSONObject) inviteObj;
String invitee = (String)invite.get(LanternConstants.INVITED_EMAIL);
if (!model.getPendingInvites().contains(invitee)) {
//we already notified about this one
continue;
}
String reason = (String)invite.get(LanternConstants.INVITE_FAILED_REASON);
LOG.info("Failed invite to " + invitee + " because " + reason);
model.removePendingInvite(invitee);
model.addNotification("Invite to " + invitee + " failed: " + reason, MessageType.error);
Events.sync(SyncPath.NOTIFICATIONS, model.getNotifications());
}
}
}
@Subscribe
public void onClosedBetaEvent(final ClosedBetaEvent cbe) {
LOG.debug("Got closed beta event!!");
this.closedBetaEvent = cbe;
if (this.closedBetaEvent.isInClosedBeta()) {
this.modelUtils.addToClosedBeta(cbe.getTo());
}
synchronized (this.closedBetaLock) {
// We have to make sure that this event is actually intended for
// the user we're currently logged in as!
final String to = this.closedBetaEvent.getTo();
LOG.debug("Analyzing closed beta event for: {}", to);
if (isLoggedIn()) {
final String user = LanternUtils.toEmail(
this.client.get().getXmppConnection());
if (user.equals(to)) {
LOG.debug("Users match!");
this.closedBetaLock.notifyAll();
} else {
LOG.debug("Users don't match {}, {}", user, to);
}
}
}
}
private void gTalkSharedStatus() {
// This is for Google Talk compatibility. Surprising, all we need to
// do is grab our Google Talk shared status, signifying support for
// their protocol, and then we don't interfere with GChat visibility.
final Packet status = XmppUtils.getSharedStatus(
this.client.get().getXmppConnection());
LOG.info("Status:\n{}", status.toXML());
}
private String askForEmail() {
try {
System.out.print("Please enter your gmail e-mail, as in johndoe@gmail.com: ");
return LanternUtils.readLineCLI();
} catch (final IOException e) {
final String msg = "IO error trying to read your email address!";
System.out.println(msg);
LOG.error(msg, e);
throw new IllegalStateException(msg, e);
}
}
private String askForPassword() {
try {
System.out.print("Please enter your gmail password: ");
return new String(LanternUtils.readPasswordCLI());
} catch (IOException e) {
final String msg = "IO error trying to read your email address!";
System.out.println(msg);
LOG.error(msg, e);
throw new IllegalStateException(msg, e);
}
}
/**
* Updates the user's presence. We also include any stats updates in this
* message. Note that periodic presence updates are also used on the server
* side to verify which clients are actually available.
*
* We in part send presence updates instead of typical chat messages to
* get around these messages showing up in the user's gchat window.
*/
private void updatePresence() {
if (!isLoggedIn()) {
LOG.info("Not updating presence when we're not connected");
return;
}
final XMPPConnection conn = this.client.get().getXmppConnection();
if (conn == null || !conn.isConnected()) {
return;
}
LOG.info("Sending presence available");
// OK, this is bizarre. For whatever reason, we **have** to send the
// following packet in order to get presence events from our peers.
// DO NOT REMOVE THIS MESSAGE!! See XMPP spec.
final Presence pres = new Presence(Presence.Type.available);
conn.sendPacket(pres);
final Presence forHub = new Presence(Presence.Type.available);
forHub.setTo(LanternClientConstants.LANTERN_JID);
forHub.setProperty("mode", model.getSettings().getMode().toString());
final String str = JsonUtils.jsonify(stats);
LOG.debug("Reporting data: {}", str);
if (!this.lastJson.equals(str)) {
this.lastJson = str;
forHub.setProperty("stats", str);
stats.resetCumulativeStats();
} else {
LOG.info("No new stats to report");
}
conn.sendPacket(forHub);
}
@Subscribe
public void onUpdatePresenceEvent(final UpdatePresenceEvent upe) {
// This was originally added to decouple the roster from this class.
final Presence pres = upe.getPresence();
addOrRemovePeer(pres, pres.getFrom());
}
@Override
public void addOrRemovePeer(final Presence p, final String from) {
LOG.info("Processing peer: {}", from);
final URI uri;
try {
uri = new URI(from);
} catch (final URISyntaxException e) {
LOG.error("Could not create URI from: {}", from);
return;
}
if (p.isAvailable()) {
LOG.info("Processing available peer");
// OK, we just request a certificate every time we get a present
// peer. If we get a response, this peer will be added to active
// peer URIs.
sendAndRequestCert(uri);
}
else {
LOG.info("Removing JID for peer '"+from);
this.proxyTracker.removePeer(uri);
}
}
private void processTypedMessage(final Message msg, final Integer type) {
final String from = msg.getFrom();
LOG.info("Processing typed message from {}", from);
switch (type) {
case (XmppMessageConstants.INFO_REQUEST_TYPE):
LOG.debug("Handling INFO request from {}", from);
processInfoData(msg);
sendInfoResponse(from);
break;
case (XmppMessageConstants.INFO_RESPONSE_TYPE):
LOG.debug("Handling INFO response from {}", from);
processInfoData(msg);
break;
case (LanternConstants.KSCOPE_ADVERTISEMENT):
LOG.debug("Handling KSCOPE ADVERTISEMENT");
final String payload =
(String) msg.getProperty(
LanternConstants.KSCOPE_ADVERTISEMENT_KEY);
if (StringUtils.isNotBlank(payload)) {
processKscopePayload(from, payload);
} else {
LOG.error("kscope ad with no payload? "+msg.toXML());
}
break;
default:
LOG.warn("Did not understand type: "+type);
break;
}
}
private void processKscopePayload(final String from, final String payload) {
LOG.debug("Processing payload: {}", payload);
final ObjectMapper mapper = new ObjectMapper();
try {
final LanternKscopeAdvertisement ad =
mapper.readValue(payload, LanternKscopeAdvertisement.class);
final URI uri = new URI(ad.getJid());
if (this.kscopeAdHandler.handleAd(uri, ad)) {
sendAndRequestCert(uri);
} else {
LOG.debug("Not requesting cert -- duplicate kscope ad?");
}
} catch (final JsonParseException e) {
LOG.warn("Could not parse JSON", e);
} catch (final JsonMappingException e) {
LOG.warn("Could not map JSON", e);
} catch (final IOException e) {
LOG.warn("IO error parsing JSON", e);
} catch (final URISyntaxException e) {
LOG.error("Syntax exception with URI?", e);
}
}
private void sendInfoResponse(final String from) {
final Message msg = new Message();
// The from becomes the to when we're responding.
msg.setTo(from);
msg.setProperty(P2PConstants.MESSAGE_TYPE,
XmppMessageConstants.INFO_RESPONSE_TYPE);
//msg.setProperty(P2PConstants.MAC, this.model.getNodeId());
msg.setProperty(P2PConstants.CERT,
this.keyStoreManager.getBase64Cert(getJid()));
this.client.get().getXmppConnection().sendPacket(msg);
}
private void processInfoData(final Message msg) {
LOG.debug("Processing INFO data from request or response.");
// This just makes sure it's a valid URI!!
final URI uri;
try {
uri = new URI(msg.getFrom());
} catch (final URISyntaxException e) {
LOG.error("Could not create URI from: {}", msg.getFrom());
return;
}
//final String mac = (String) msg.getProperty(P2PConstants.MAC);
final String base64Cert = (String) msg.getProperty(P2PConstants.CERT);
LOG.debug("Base 64 cert: {}", base64Cert);
if (StringUtils.isNotBlank(base64Cert)) {
LOG.debug("Got certificate:\n"+
new String(Base64.decodeBase64(base64Cert),
LanternConstants.UTF8));
// Add the peer if we're able to add the cert.
this.kscopeAdHandler.onBase64Cert(uri, base64Cert);
} else {
LOG.error("No cert for peer?");
}
}
@Override
public String getJid() {
// We may have already disconnected on shutdown, for example, so check
// for null.
if (this.client.get() != null &&
this.client.get().getXmppConnection() != null &&
this.client.get().getXmppConnection().getUser() != null) {
return this.client.get().getXmppConnection().getUser().trim();
}
return "";
}
private void sendAndRequestCert(final URI peer) {
LOG.debug("Requesting cert from {}", peer);
final Message msg = new Message();
msg.setProperty(P2PConstants.MESSAGE_TYPE,
XmppMessageConstants.INFO_REQUEST_TYPE);
msg.setTo(peer.toASCIIString());
// Set our certificate in the request as well -- we want to make
// extra sure these get through!
//msg.setProperty(P2PConstants.MAC, this.model.getNodeId());
msg.setProperty(P2PConstants.CERT,
this.keyStoreManager.getBase64Cert(getJid()));
if (isLoggedIn()) {
this.client.get().getXmppConnection().sendPacket(msg);
} else {
LOG.debug("No longer logged in? Not sending cert");
}
}
@Override
public XmppP2PClient<FiveTuple> getP2PClient() {
return client.get();
}
@Override
public boolean isLoggedIn() {
if (this.client.get() == null) {
return false;
}
final XMPPConnection conn = client.get().getXmppConnection();
if (conn == null) {
return false;
}
return conn.isAuthenticated();
}
@Override
public boolean sendInvite(final String email, boolean redo) {
LOG.info("Sending invite");
if (StringUtils.isBlank(this.hubAddress)) {
LOG.info("Blank hub address when sending invite?");
return true;
}
final Set<String> invited = roster.getInvited();
if ((!redo) && invited.contains(email)) {
LOG.info("Already invited");
return false;
}
final XMPPConnection conn = this.client.get().getXmppConnection();
final Roster rost = conn.getRoster();
final Presence pres = new Presence(Presence.Type.available);
pres.setTo(LanternClientConstants.LANTERN_JID);
// "emails" of the form xxx@public.talk.google.com aren't really
// e-mail addresses at all, so don't send 'em.
// In theory we might be able to use the Google Plus API to get
// actual e-mail addresses -- see:
if (LanternUtils.isNotJid(email)) {
pres.setProperty(LanternConstants.INVITED_EMAIL, email);
} else {
pres.setProperty(LanternConstants.INVITED_EMAIL, "");
}
pres.setProperty(LanternConstants.INVITER_REFRESH_TOKEN,
this.model.getSettings().getRefreshToken());
final RosterEntry entry = rost.getEntry(email);
if (entry != null) {
final String name = entry.getName();
if (StringUtils.isNotBlank(name)) {
pres.setProperty(LanternConstants.INVITEE_NAME, name);
}
}
invited.add(email);
final Runnable runner = new Runnable() {
@Override
public void run() {
conn.sendPacket(pres);
}
};
final Thread t = new Thread(runner, "Invite-Thread");
t.setDaemon(true);
t.start();
addToRoster(email);
return true;
}
/** Try to reconnect to the xmpp server */
private void reconnect() {
//this will trigger XmppP2PClient's internal reconnection logic
client.get().getXmppConnection().disconnect();
}
@Override
public void subscribe(final String jid) {
LOG.debug("Sending subscribe message to: {}", jid);
final Presence packet = new Presence(Presence.Type.subscribe);
packet.setTo(jid);
//final String json = JsonUtils.jsonify(this.model.getProfile());
//packet.setProperty(XmppMessageConstants.PROFILE, json);
final XMPPConnection conn = this.client.get().getXmppConnection();
conn.sendPacket(packet);
}
@Override
public void subscribed(final String jid) {
LOG.debug("Sending subscribed message to: {}", jid);
sendTypedPacket(jid, Presence.Type.subscribed);
roster.removeIncomingSubscriptionRequest(jid);
}
@Override
public void unsubscribe(final String jid) {
LOG.debug("Sending unsubscribe message to: {}", jid);
sendTypedPacket(jid, Presence.Type.unsubscribe);
}
@Override
public void unsubscribed(final String jid) {
LOG.debug("Sending unsubscribed message to: {}", jid);
sendTypedPacket(jid, Presence.Type.unsubscribed);
roster.removeIncomingSubscriptionRequest(jid);
}
private void sendTypedPacket(final String jid, final Type type) {
final Presence packet = new Presence(type);
packet.setTo(jid);
final XMPPConnection conn = this.client.get().getXmppConnection();
conn.sendPacket(packet);
}
@Override
public void addToRoster(final String email) {
// If the user is not already on our roster, we want to make sure to
// send them an invite. If the e-mail address specified does not
// correspond with a Jabber ID, then we're out of luck. If it does,
// then this will send the roster invite.
final XMPPConnection conn = this.client.get().getXmppConnection();
final Roster rost = conn.getRoster();
final RosterEntry entry = rost.getEntry(email);
if (entry == null) {
LOG.debug("Inviting user to join roster: {}", email);
try {
// Note this also sends a subscription request!!
rost.createEntry(email,
StringUtils.substringBefore(email, "@"), new String[]{});
} catch (final XMPPException e) {
LOG.error("Could not create entry?", e);
}
} else {
LOG.debug("User already on roster...");
}
}
@Override
public void removeFromRoster(final String email) {
final XMPPConnection conn = this.client.get().getXmppConnection();
final Roster rost = conn.getRoster();
final RosterEntry entry = rost.getEntry(email);
if (entry != null) {
LOG.debug("Removing user from roster: {}", email);
try {
rost.removeEntry(entry);
} catch (final XMPPException e) {
LOG.error("Could not create entry?", e);
}
}
}
private void setupJmx() {
final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
try {
final Class<? extends Object> clazz = getClass();
final String pack = clazz.getPackage().getName();
final String oName =
pack+":type="+clazz.getSimpleName()+"-"+clazz.getSimpleName();
LOG.debug("Registering MBean with name: {}", oName);
final ObjectName mxBeanName = new ObjectName(oName);
if(!mbs.isRegistered(mxBeanName)) {
mbs.registerMBean(this, mxBeanName);
}
} catch (final MalformedObjectNameException e) {
LOG.error("Could not set up JMX", e);
} catch (final InstanceAlreadyExistsException e) {
LOG.error("Could not set up JMX", e);
} catch (final MBeanRegistrationException e) {
LOG.error("Could not set up JMX", e);
} catch (final NotCompliantMBeanException e) {
LOG.error("Could not set up JMX", e);
}
}
@Subscribe
public void onReset(final ResetEvent event) {
disconnect();
}
@Override
public void sendPacket(final Packet packet) {
this.client.get().getXmppConnection().sendPacket(packet);
}
}
|
package org.jgrapht.alg;
import java.util.*;
import junit.framework.*;
import org.jgrapht.*;
/**
* @author Guillaume Boulmier
* @since July 5, 2007
*/
@SuppressWarnings("unchecked")
public class KShortestPathCostTest
extends TestCase
{
public void testKShortestPathCompleteGraph4()
{
int nbPaths = 5;
KShortestPathCompleteGraph4 graph = new KShortestPathCompleteGraph4();
KShortestPaths pathFinder = new KShortestPaths(graph, "vS", nbPaths);
List pathElements = pathFinder.getPaths("v3");
assertEquals(5, pathElements.size(), 0);
GraphPath pathElement = (GraphPath) pathElements.get(0);
assertEquals(2, pathElement.getWeight(), 0);
assertEquals(
Arrays.asList(new Object[] { graph.eS1, graph.e13 }),
pathElement.getEdgeList());
}
public void testKShortestPathCosts(Graph graph)
{
int maxSize = 20;
for (
Iterator sourceIterator = graph.vertexSet().iterator();
sourceIterator.hasNext();)
{
Object sourceVertex = sourceIterator.next();
for (
Iterator targetIterator = graph.vertexSet().iterator();
targetIterator.hasNext();)
{
Object targetVertex = targetIterator.next();
if (targetVertex != sourceVertex) {
KShortestPaths pathFinder =
new KShortestPaths(graph,
sourceVertex, maxSize);
List pathElements = pathFinder.getPaths(targetVertex);
GraphPath pathElement = (GraphPath) pathElements.get(0);
double lastCost = pathElement.getWeight();
for (int i = 0; i < pathElements.size(); i++) {
pathElement = (GraphPath) pathElements.get(i);
double cost = pathElement.getWeight();
assertTrue(lastCost <= cost);
lastCost = cost;
}
assertTrue(pathElements.size() <= maxSize);
}
}
}
}
public void testPicture1Graph()
{
Picture1Graph picture1Graph = new Picture1Graph();
int maxSize = 10;
KShortestPaths pathFinder =
new KShortestPaths(picture1Graph, "vS",
maxSize);
assertEquals(2, pathFinder.getPaths("v5").size());
List pathElements = pathFinder.getPaths("v5");
GraphPath pathElement = (GraphPath) pathElements.get(0);
assertEquals(
Arrays.asList(
new Object[] {
picture1Graph.eS1,
picture1Graph.e15
}),
pathElement.getEdgeList());
List vertices = Graphs.getPathVertexList(pathElement);
assertEquals(
Arrays.asList(
new Object[] {
"vS",
"v1",
"v5"
}),
vertices);
pathElement = (GraphPath) pathElements.get(1);
assertEquals(
Arrays.asList(
new Object[] {
picture1Graph.eS2,
picture1Graph.e25
}),
pathElement.getEdgeList());
vertices = Graphs.getPathVertexList(pathElement);
assertEquals(
Arrays.asList(
new Object[] {
"vS",
"v2",
"v5"
}),
vertices);
pathElements = pathFinder.getPaths("v7");
pathElement = (GraphPath) pathElements.get(0);
double lastCost = pathElement.getWeight();
for (int i = 0; i < pathElements.size(); i++) {
pathElement = (GraphPath) pathElements.get(i);
double cost = pathElement.getWeight();
assertTrue(lastCost <= cost);
lastCost = cost;
}
}
}
// End KShortestPathCostTest.java
|
package org.lightmare.jndi;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.spi.InitialContextFactory;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.ObjectUtils;
/**
* Utility class to initialize and set (
* {@link System#setProperty(String, String)}) the {@link InitialContextFactory}
* for simple JNDI extensions
*
* @author levan
*
*/
public class JndiManager {
// Value of InitialContextFactory implementation class
private static final Class<LightmareInitialContextFactory> FACTORY_CLASS = LightmareInitialContextFactory.class;
/**
* Caches JNDI system parameters for initializing {@link Context} instance
*
* @author levan
*
*/
protected static enum JNDIParameters {
// Name of InitialContextFactory implementation class
FACTORY_CLASS_NAME(Context.INITIAL_CONTEXT_FACTORY, FACTORY_CLASS
.getName()),
// Name of InitialContextFactory implementation class package
PACKAGE_PREFIXES(Context.URL_PKG_PREFIXES, FACTORY_CLASS.getPackage()
.getName()),
// Additional parameter to share JNDI cache
SHARED_PARAMETER("org.osjava.sj.jndi.shared", Boolean.TRUE.toString());
// Cache of JNDI configuration key value pairs
private static final Properties CONFIG = new Properties();
public String key;
public String value;
private JNDIParameters(String key, String value) {
this.key = key;
this.value = value;
}
/**
* Gets {@link Properties} of all key value pairs of this enumeration
*/
protected static Properties getConfig() {
if (CollectionUtils.notAvailable(CONFIG)) {
JNDIParameters[] parameters = JNDIParameters.values();
for (JNDIParameters parameter : parameters) {
CONFIG.put(parameter.key, parameter.value);
}
}
return CONFIG;
}
}
// Check variable if system property are set
private static boolean isContextFactory;
// Cached context variable
private static Context context;
private static final Lock LOCK = new ReentrantLock();
private void addSystemProperties(Properties configs) {
System.getProperties().putAll(configs);
}
private void setFactoryProperties(Properties properties) {
if (ObjectUtils.notTrue(isContextFactory)) {
addSystemProperties(properties);
isContextFactory = Boolean.TRUE;
}
}
private void createContext(Properties properties) throws IOException {
if (context == null) {
try {
context = new InitialContext(properties);
} catch (NamingException ex) {
throw new IOException(ex);
}
}
}
/**
* Creates and sets {@link InitialContext}
*
* @throws IOException
*/
private void setInitialCotext() throws IOException {
if (ObjectUtils.notTrue(isContextFactory) || context == null) {
Properties properties = JNDIParameters.getConfig();
setFactoryProperties(properties);
createContext(properties);
}
}
/**
* Getter for {@link Context} with check if it is initialized if not calls
* {@link JndiManager#setInitialCotext()} method
*
* @return {@link Context}
* @throws IOException
*/
public Context getContext() throws IOException {
if (context == null) {
LOCK.lock();
try {
setInitialCotext();
} finally {
LOCK.unlock();
}
}
return context;
}
/**
* Lookups data with passed name in {@link Context} and cast it in generic
* type
*
* @param name
* @return <code>T</code>
* @throws IOException
*/
public <T> T lookup(String name) throws IOException {
T value;
try {
Object data = getContext().lookup(name);
value = ObjectUtils.cast(data);
} catch (NamingException ex) {
throw new IOException(ex);
}
return value;
}
/**
* Rebinds passed {@link Object} to {@link Context} by appropriate name
*
* @param name
* @param data
* @throws IOException
*/
public void rebind(String name, Object data) throws IOException {
try {
getContext().rebind(name, data);
} catch (NamingException ex) {
throw new IOException(ex);
} catch (IOException ex) {
throw new IOException(ex);
}
}
/**
* Binds passed {@link Object} to {@link Context} by appropriate name
*
* @param name
* @param data
* @throws IOException
*/
public void bind(String name, Object data) throws IOException {
try {
getContext().bind(name, data);
} catch (NamingException ex) {
throw new IOException(ex);
} catch (IOException ex) {
throw new IOException(ex);
}
}
/**
* Unbinds passed name from {@link Context}
*
* @param name
* @throws IOException
*/
public void unbind(String name) throws IOException {
try {
getContext().unbind(name);
} catch (NamingException ex) {
throw new IOException(ex);
} catch (IOException ex) {
throw new IOException(ex);
}
}
}
|
package org.myrobotlab.service;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.io.FilenameUtils;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.framework.Status;
import org.myrobotlab.framework.interfaces.Attachable;
import org.myrobotlab.inmoov.LanguagePack;
import org.myrobotlab.inmoov.Utils;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.opencv.OpenCVData;
import org.myrobotlab.service.data.AudioData;
import org.myrobotlab.service.data.JoystickData;
import org.myrobotlab.service.interfaces.JoystickListener;
import org.myrobotlab.service.interfaces.ServoControl;
import org.myrobotlab.service.interfaces.SpeechRecognizer;
import org.myrobotlab.service.interfaces.SpeechSynthesis;
import org.myrobotlab.service.interfaces.TextListener;
import org.myrobotlab.service.interfaces.TextPublisher;
import org.slf4j.Logger;
public class InMoov2 extends Service implements TextListener, TextPublisher, JoystickListener {
public final static Logger log = LoggerFactory.getLogger(InMoov2.class);
// FIXME - why
static boolean RobotCanMoveRandom = true;
private static final long serialVersionUID = 1L;
static String speechRecognizer = "WebkitSpeechRecognition";
// FIXME - WTH ?
static String speechService = "MarySpeech";
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(InMoov2.class);
meta.addDescription("InMoov2 Service");
meta.addCategory("robot");
meta.sharePeer("mouthControl.mouth", "mouth", speechService, "shared Speech");
meta.addPeer("eye", "OpenCV", "eye");
// the two legacy controllers .. :(
meta.addPeer("left", "Arduino", "legacy controller");
meta.addPeer("right", "Arduino", "legacy controller");
meta.addPeer("brain", "ProgramAB", "brain");
meta.addPeer("head", "InMoov2Head", "head");
meta.addPeer("torso", "InMoov2Torso", "torso");
// meta.addPeer("eyelids", "InMoovEyelids", "eyelids");
meta.addPeer("leftArm", "InMoov2Arm", "left arm");
meta.addPeer("leftHand", "InMoov2Hand", "left hand");
meta.addPeer("rightArm", "InMoov2Arm", "right arm");
meta.addPeer("rightHand", "InMoov2Hand", "right hand");
meta.addPeer("mouthControl", "MouthControl", "MouthControl");
meta.addPeer("imageDisplay", "ImageDisplay", "image display service");
meta.addPeer("mouth", speechService, "InMoov speech service");
meta.addPeer("ear", speechRecognizer, "InMoov webkit speech recognition service");
meta.addPeer("headTracking", "Tracking", "Head tracking system");
meta.sharePeer("headTracking.opencv", "eye", "OpenCV", "shared head OpenCV");
// meta.sharePeer("headTracking.controller", "left", "Arduino", "shared head
// Arduino"); NO !!!!
meta.sharePeer("headTracking.x", "head.rothead", "Servo", "shared servo");
meta.sharePeer("headTracking.y", "head.neck", "Servo", "shared servo");
// Global - undecorated by self name
meta.addRootPeer("python", "Python", "shared Python service");
return meta;
}
public static void main(String[] args) {
try {
LoggingFactory.init(Level.INFO);
Runtime.main(new String[] { "--interactive", "--id", "inmoov" });
InMoov2 i01 = (InMoov2) Runtime.start("i01", "InMoov2");
WebGui webgui = (WebGui) Runtime.create("webgui", "WebGui");
webgui.autoStartBrowser(false);
webgui.startService();
i01.startBrain();
boolean done = true;
if (done) {
return;
}
i01.startAll("COM3","COM4");
Runtime.start("python", "Python");
// Runtime.start("log", "Log");
/*
* OpenCV cv = (OpenCV) Runtime.start("cv", "OpenCV");
* cv.setCameraIndex(2);
*/
// i01.startSimulator();
/*
* Arduino mega = (Arduino) Runtime.start("mega", "Arduino");
* mega.connect("/dev/ttyACM0");
*/
} catch (Exception e) {
log.error("main threw", e);
}
}
boolean autoStartBrowser = false;
transient ProgramAB brain;
Set<String> configs = null;
String currentConfigurationName = "default";
transient SpeechRecognizer ear;
// transient InMoovEyelids eyelids; they are in the head
transient OpenCV eye;
transient Tracking eyesTracking;
// waiting controable threaded gestures we warn user
boolean gestureAlreadyStarted = false;
// FIXME - what the hell is this for ?
Set<String> gestures = new TreeSet<String>();
transient InMoov2Head head;
transient Tracking headTracking;
transient ImageDisplay imageDisplay;
// TODO - refactor into a Simulator interface when more simulators are borgd
transient JMonkeyEngine jme;
String language;
transient LanguagePack languagePack = new LanguagePack();
LinkedHashMap<String, String> languages = new LinkedHashMap<>();
String lastGestureExecuted;
Long lastPirActivityTime;
transient InMoov2Arm leftArm;
transient InMoov2Hand leftHand;
int maxInactivityTimeSeconds = 120;
transient SpeechSynthesis mouth;
// FIXME - remove all direct references
// transient private HashMap<String, InMoov2Arm> arms = new HashMap<>();
// FIXME ugh - new MouthControl service that uses AudioFile output
transient public MouthControl mouthControl;
boolean mute = false;
boolean muted;
transient Pid pid;
transient Python python;
transient InMoov2Arm rightArm;
transient InMoov2Hand rightHand;
transient InMoov2Torso torso;
transient WebGui webgui;
public InMoov2(String n, String id) {
super(n, id);
// TODO : use locale it-IT,fi-FI
languages.put("en-US", "English - United States");
languages.put("fr-FR", "French - France");
languages.put("es-ES", "Spanish - Spain");
languages.put("de-DE", "German - Germany");
languages.put("nl-NL", "Dutch - Netherlands");
languages.put("ru-RU", "Russian");
languages.put("hi-IN", "Hindi - India");
languages.put("it-IT", "Italian - Italia");
languages.put("fi-FI", "Finnish - Finland");
languages.put("pt-PT", "Portuguese - Portugal");
language = getLanguage();
python = (Python) startPeer("python");
languagePack.load(language);
// get events of new services and shutdown
Runtime r = Runtime.getInstance();
subscribe(r.getName(), "shutdown");
listConfigFiles();
// FIXME - Framework should auto-magically auto-start peers AFTER
// construction - unless explicitly told not to
// peers to start on construction
imageDisplay = (ImageDisplay) startPeer("imageDisplay");
}
@Override /* local strong type - is to be avoided - use name string */
public void addTextListener(TextListener service) {
// CORRECT WAY ! - no direct reference - just use the name in a subscription
addListener("publishText", service.getName());
}
public void attachTextPublisher(String name) {
subscribe(name, "publishText");
}
public void beginCheckingOnInactivity() {
beginCheckingOnInactivity(maxInactivityTimeSeconds);
}
public void beginCheckingOnInactivity(int maxInactivityTimeSeconds) {
this.maxInactivityTimeSeconds = maxInactivityTimeSeconds;
// speakBlocking("power down after %s seconds inactivity is on",
// this.maxInactivityTimeSeconds);
log.info("power down after %s seconds inactivity is on", this.maxInactivityTimeSeconds);
addTask("checkInactivity", 5 * 1000, 0, "checkInactivity");
}
public long checkInactivity() {
// speakBlocking("checking");
long lastActivityTime = getLastActivityTime();
long now = System.currentTimeMillis();
long inactivitySeconds = (now - lastActivityTime) / 1000;
if (inactivitySeconds > maxInactivityTimeSeconds) {
// speakBlocking("%d seconds have passed without activity",
// inactivitySeconds);
powerDown();
} else {
// speakBlocking("%d seconds have passed without activity",
// inactivitySeconds);
info("checking checkInactivity - %d seconds have passed without activity", inactivitySeconds);
}
return lastActivityTime;
}
public void closeAllImages() {
imageDisplay.closeAll();
}
public void cycleGestures() {
// if not loaded load -
// FIXME - this needs alot of "help" :P
// WHY IS THIS DONE ?
if (gestures.size() == 0) {
loadGestures();
}
for (String gesture : gestures) {
try {
String methodName = gesture.substring(0, gesture.length() - 3);
speakBlocking(methodName);
log.info("executing gesture {}", methodName);
python.eval(methodName + "()");
// wait for finish - or timeout ?
} catch (Exception e) {
error(e);
}
}
}
public void disable() {
if (head != null) {
head.disable();
}
if (rightHand != null) {
rightHand.disable();
}
if (leftHand != null) {
leftHand.disable();
}
if (rightArm != null) {
rightArm.disable();
}
if (leftArm != null) {
leftArm.disable();
}
if (torso != null) {
torso.disable();
}
}
public void displayFullScreen(String src) {
try {
imageDisplay.displayFullScreen(src);
} catch (Exception e) {
error("could not display picture %s", src);
}
}
public void enable() {
if (head != null) {
head.enable();
}
if (rightHand != null) {
rightHand.enable();
}
if (leftHand != null) {
leftHand.enable();
}
if (rightArm != null) {
rightArm.enable();
}
if (leftArm != null) {
leftArm.enable();
}
if (torso != null) {
torso.enable();
}
}
/**
* This method will try to launch a python command with error handling
*/
public String execGesture(String gesture) {
lastGestureExecuted = gesture;
if (python == null) {
log.warn("execGesture : No jython engine...");
return null;
}
subscribe(python.getName(), "publishStatus", this.getName(), "onGestureStatus");
startedGesture(lastGestureExecuted);
return python.evalAndWait(gesture);
}
public void finishedGesture() {
finishedGesture("unknown");
}
public void finishedGesture(String nameOfGesture) {
if (gestureAlreadyStarted) {
waitTargetPos();
RobotCanMoveRandom = true;
gestureAlreadyStarted = false;
log.info("gesture : {} finished...", nameOfGesture);
}
}
public void fullSpeed() {
if (head != null) {
head.fullSpeed();
}
if (rightHand != null) {
rightHand.fullSpeed();
}
if (leftHand != null) {
leftHand.fullSpeed();
}
if (rightArm != null) {
rightArm.fullSpeed();
}
if (leftArm != null) {
leftArm.fullSpeed();
}
if (torso != null) {
torso.fullSpeed();
}
}
public InMoov2Arm getArm(String side) {
if ("left".equals(side)) {
return leftArm;
} else if ("right".equals(side)) {
return rightArm;
} else {
log.error("can not get arm {}", side);
}
return null;
}
public InMoov2Hand getHand(String side) {
if ("left".equals(side)) {
return leftHand;
} else if ("right".equals(side)) {
return rightHand;
} else {
log.error("can not get arm {}", side);
}
return null;
}
public InMoov2Head getHead() {
return head;
}
/**
* get current language
*/
public String getLanguage() {
if (this.language == null) {
// check if default locale supported by inmoov
if (languages.containsKey(Locale.getDefault().toLanguageTag())) {
this.language = Locale.getDefault().toLanguageTag();
} else {
this.language = "en-US";
}
}
// to be sure runtime == inmoov language
if (!Locale.getDefault().toLanguageTag().equals(this.language)) {
setLanguage(this.language);
}
return this.language;
}
/**
* finds most recent activity
*
* @return the timestamp of the last activity time.
*/
public long getLastActivityTime() {
long lastActivityTime = 0;
if (leftHand != null) {
lastActivityTime = Math.max(lastActivityTime, leftHand.getLastActivityTime());
}
if (leftArm != null) {
lastActivityTime = Math.max(lastActivityTime, leftArm.getLastActivityTime());
}
if (rightHand != null) {
lastActivityTime = Math.max(lastActivityTime, rightHand.getLastActivityTime());
}
if (rightArm != null) {
lastActivityTime = Math.max(lastActivityTime, rightArm.getLastActivityTime());
}
if (head != null) {
lastActivityTime = Math.max(lastActivityTime, head.getLastActivityTime());
}
if (torso != null) {
lastActivityTime = Math.max(lastActivityTime, torso.getLastActivityTime());
}
if (lastPirActivityTime != null) {
lastActivityTime = Math.max(lastActivityTime, lastPirActivityTime);
}
if (lastActivityTime == 0) {
error("invalid activity time - anything connected?");
lastActivityTime = System.currentTimeMillis();
}
return lastActivityTime;
}
public InMoov2Arm getLeftArm() {
return leftArm;
}
public InMoov2Hand getLeftHand() {
return leftHand;
}
public InMoov2Arm getRightArm() {
return rightArm;
}
public InMoov2Hand getRightHand() {
return rightHand;
}
public InMoov2Torso getTorso() {
return torso;
}
public void halfSpeed() {
if (head != null) {
head.setSpeed(25.0, 25.0, 25.0, 25.0, -1.0, 25.0);
}
if (rightHand != null) {
rightHand.setSpeed(30.0, 30.0, 30.0, 30.0, 30.0, 30.0);
}
if (leftHand != null) {
leftHand.setSpeed(30.0, 30.0, 30.0, 30.0, 30.0, 30.0);
}
if (rightArm != null) {
rightArm.setSpeed(25.0, 25.0, 25.0, 25.0);
}
if (leftArm != null) {
leftArm.setSpeed(25.0, 25.0, 25.0, 25.0);
}
if (torso != null) {
torso.setSpeed(20.0, 20.0, 20.0);
}
}
public boolean isMute() {
return muted;
}
public Set<String> listConfigFiles() {
configs = new HashSet<>();
// data list
String configDir = getResourceDir() + fs + "config";
File f = new File(configDir);
if (!f.exists()) {
f.mkdirs();
}
String[] files = f.list();
for (String config : files) {
configs.add(config);
}
// data list
configDir = getDataDir() + fs + "config";
f = new File(configDir);
if (!f.exists()) {
f.mkdirs();
}
files = f.list();
for (String config : files) {
configs.add(config);
}
return configs;
}
// FIXME - what is this for ???
public void loadGestures() {
loadGestures(getResourceDir() + fs + "gestures");
}
/**
* This blocking method will look at all of the .py files in a directory. One
* by one it will load the files into the python interpreter. A gesture python
* file should contain 1 method definition that is the same as the filename.
*
* @param directory
* - the directory that contains the gesture python files.
*/
public boolean loadGestures(String directory) {
speakBlocking("loading gestures"); // FIXME - make polyglot
// iterate over each of the python files in the directory
// and load them into the python interpreter.
String extension = "py";
Integer totalLoaded = 0;
Integer totalError = 0;
File dir = Utils.makeDirectory(directory);
if (dir.exists()) {
for (File f : dir.listFiles()) {
if (FilenameUtils.getExtension(f.getAbsolutePath()).equalsIgnoreCase(extension)) {
if (Utils.loadFile(f.getAbsolutePath()) == true) {
totalLoaded += 1;
String methodName = f.getName().substring(0, f.getName().length() - 3) + "()";
gestures.add(methodName);
} else {
error("could not load %s", f.getName());
totalError += 1;
}
} else {
log.info("{} is not a {} file", f.getAbsolutePath(), extension);
}
}
}
info("%s Gestures loaded, %s Gestures with error", totalLoaded, totalError);
broadcastState();
if (totalError > 0) {
speakAlert(languagePack.get("GESTURE_ERROR"));
return false;
}
return true;
}
public void moveArm(String which, double bicep, double rotate, double shoulder, double omoplate) {
InMoov2Arm arm = getArm(which);
arm.moveTo(bicep, rotate, shoulder, omoplate);
}
public void moveEyelids(double eyelidleftPos, double eyelidrightPos) {
if (head != null) {
head.moveEyelidsTo(eyelidleftPos, eyelidrightPos);
} else {
log.warn("moveEyelids - I have a null head");
}
}
public void moveEyes(double eyeX, double eyeY) {
if (head != null) {
head.moveTo(null, null, eyeX, eyeY, null, null);
} else {
log.warn("moveEyes - I have a null head");
}
}
public void moveHand(String which, double thumb, double index, double majeure, double ringFinger, double pinky) {
moveHand(which, thumb, index, majeure, ringFinger, pinky, null);
}
public void moveHand(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
InMoov2Hand hand = getHand(which);
hand.moveTo(thumb, index, majeure, ringFinger, pinky, wrist);
}
public void moveHead(double neck, double rothead) {
moveHead(neck, rothead, null);
}
public void moveHead(double neck, double rothead, double eyeX, double eyeY, double jaw) {
moveHead(neck, rothead, eyeX, eyeY, jaw, null);
}
public void moveHead(Double neck, Double rothead, Double rollNeck) {
moveHead(neck, rothead, null, null, null, rollNeck);
}
public void moveHead(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw, Double rollNeck) {
if (head != null) {
head.moveTo(neck, rothead, eyeX, eyeY, jaw, rollNeck);
} else {
log.error("I have a null head");
}
}
public void moveHeadBlocking(double neck, double rothead) {
moveHeadBlocking(neck, rothead, null);
}
public void moveHeadBlocking(double neck, double rothead, Double rollNeck) {
moveHeadBlocking(neck, rothead, null, null, null, rollNeck);
}
public void moveHeadBlocking(double neck, double rothead, Double eyeX, Double eyeY, Double jaw) {
moveHeadBlocking(neck, rothead, eyeX, eyeY, jaw, null);
}
public void moveHeadBlocking(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw, Double rollNeck) {
if (head != null) {
head.moveToBlocking(neck, rothead, eyeX, eyeY, jaw, rollNeck);
} else {
log.error("I have a null head");
}
}
public void moveTorso(double topStom, double midStom, double lowStom) {
if (torso != null) {
torso.moveTo(topStom, midStom, lowStom);
} else {
log.error("moveTorso - I have a null torso");
}
}
public void moveTorsoBlocking(double topStom, double midStom, double lowStom) {
if (torso != null) {
torso.moveToBlocking(topStom, midStom, lowStom);
} else {
log.error("moveTorsoBlocking - I have a null torso");
}
}
public void onGestureStatus(Status status) {
if (!status.equals(Status.success()) && !status.equals(Status.warn("Python process killed !"))) {
error("I cannot execute %s, please check logs", lastGestureExecuted);
}
finishedGesture(lastGestureExecuted);
unsubscribe(python.getName(), "publishStatus", this.getName(), "onGestureStatus");
}
@Override
public void onJoystickInput(JoystickData input) throws Exception {
// TODO Auto-generated method stub
}
public OpenCVData onOpenCVData(OpenCVData data) {
return data;
}
@Override
public void onText(String text) {
// FIXME - we should be able to "re"-publish text but text is coming from
// different sources
// some might be coming from the ear - some from the mouth ... - there has
// to be a distinction
log.info("onText - {}", text);
// invoke("publishText", text);
}
// TODO FIX/CHECK this, migrate from python land
public void powerDown() {
rest();
purgeTasks();
disable();
if (ear != null) {
ear.lockOutAllGrammarExcept("power up");
}
python.execMethod("power_down");
}
// TODO FIX/CHECK this, migrate from python land
public void powerUp() {
enable();
rest();
if (ear != null) {
ear.clearLock();
}
beginCheckingOnInactivity();
python.execMethod("power_up");
}
/**
* all published text from InMoov2 - including ProgramAB
*/
@Override
public String publishText(String text) {
return text;
}
// FIXME NO DIRECT REFERENCES - publishRest --> (onRest) --> rest
public void rest() {
log.info("InMoov2.rest()");
if (head != null) {
head.rest();
}
if (rightHand != null) {
rightHand.rest();
}
if (leftHand != null) {
leftHand.rest();
}
if (rightArm != null) {
rightArm.rest();
}
if (leftArm != null) {
leftArm.rest();
}
if (torso != null) {
torso.rest();
}
}
@Deprecated
public void setArmVelocity(String which, Double bicep, Double rotate, Double shoulder, Double omoplate) {
InMoov2Arm arm = getArm(which);
arm.setSpeed(bicep, rotate, shoulder, omoplate);
}
public void setHandSpeed(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky) {
setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, null);
}
public void setHandSpeed(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
InMoov2Hand hand = getHand(which);
hand.setSpeed(thumb, index, majeure, ringFinger, pinky, wrist);
}
@Deprecated
public void setHandVelocity(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky) {
setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, null);
}
@Deprecated
public void setHandVelocity(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, wrist);
}
public void setHeadSpeed(Double rothead, Double neck) {
setHeadSpeed(rothead, neck, null, null, null);
}
public void setHeadSpeed(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed) {
setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, null);
}
public void setHeadSpeed(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed, Double rollNeckSpeed) {
if (head != null) {
head.setSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, rollNeckSpeed);
} else {
log.warn("setHeadVelocity - I have no head");
}
}
@Deprecated
public void setHeadVelocity(Double rothead, Double neck) {
setHeadSpeed(rothead, neck, null, null, null, null);
}
@Deprecated
public void setHeadVelocity(Double rothead, Double neck, Double rollNeck) {
setHeadSpeed(rothead, neck, null, null, null, rollNeck);
}
@Deprecated
public void setHeadVelocity(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed) {
setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, null);
}
@Deprecated
public void setHeadVelocity(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed, Double rollNeckSpeed) {
setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, rollNeckSpeed);
}
/**
* TODO : use system locale set language for InMoov service used by chatbot +
* ear + mouth
*
* @param l
* - format : java Locale
*/
public boolean setLanguage(String l) {
if (languages.containsKey(l)) {
this.language = l;
info("Set language to %s", languages.get(l));
Runtime runtime = Runtime.getInstance();
runtime.setLocale(l);
languagePack.load(language);
broadcastState();
return true;
} else {
error("InMoov not yet support %s", l);
return false;
}
}
public void setMute(boolean mute) {
info("Set mute to %s", mute);
this.mute = mute;
if (mouth != null) {
if (mute) {
mouth.mute();
} else {
mouth.unmute();
}
}
}
@Deprecated
public void setTorsoSpeed(Double topStom, Double midStom, Double lowStom) {
if (torso != null) {
torso.setSpeed(topStom, midStom, lowStom);
} else {
log.warn("setTorsoSpeed - I have no torso");
}
}
public void setTorsoVelocity(Double topStom, Double midStom, Double lowStom) {
if (torso != null) {
torso.setVelocity(topStom, midStom, lowStom);
} else {
log.warn("setTorsoVelocity - I have no torso");
}
}
public List<AudioData> speak(String toSpeak) {
if (mouth == null) {
log.error("Speak is called, but my mouth is NULL...");
return null;
}
if (!mute) {
try {
return mouth.speak(toSpeak);
} catch (Exception e) {
Logging.logError(e);
}
}
return null;
}
public void speakAlert(String toSpeak) {
speakBlocking(languagePack.get("ALERT"));
speakBlocking(toSpeak);
}
/// end blah
// FIXME - publish text regardless if mouth exists ...
public void speakBlocking(String toSpeak) {
if (toSpeak == null) {
return;
}
// FIXME - publish onText when listening
invoke("publishText", toSpeak);
if (mouth == null) {
mouth = (SpeechSynthesis) startPeer("mouth");
}
if (mouth == null) {
log.error("speakBlocking is called, but my mouth is NULL...");
return;
}
if (!mute) {
try {
mouth.speakBlocking(toSpeak);
} catch (Exception e) {
log.error("speakBlocking threw", e);
}
}
}
public void startAll() throws Exception {
startAll(null, null);
}
public void startAll(String leftPort, String rightPort) throws Exception {
startMouth();
startBrain();
startHeadTracking();
// startEyesTracking();
// startOpenCV();
startEar();
startServos(leftPort, rightPort);
// startMouthControl(head.jaw, mouth);
speakBlocking("startup sequence completed");
}
public InMoov2Head startHead(String port) throws Exception {
return startHead(port, null, null, null, null, null, null, null);
}
public void startBrain() {
if (brain == null) {
brain = (ProgramAB) Runtime.start("brain", "ProgramAB");
speakBlocking(languagePack.get("CHATBOTACTIVATED"));
// GOOD EXAMPLE ! - no type, uses name - does a set of subscriptions !
attachTextPublisher(brain.getName());
// this.attach(brain); FIXME - attach as a TextPublisher - then re-publish
// FIXME - deal with language
// speakBlocking(languagePack.get("CHATBOTACTIVATED"));
brain.repetitionCount(10);
brain.setPath(getResourceDir() + fs + "chatBot");
brain.startSession("default", getLanguage());
// reset some parameters to default...
brain.setPredicate("topic", "default");
brain.setPredicate("questionfirstinit", "");
brain.setPredicate("tmpname", "");
brain.setPredicate("null", "");
// load last user session
if (!brain.getPredicate("name").isEmpty()) {
if (brain.getPredicate("lastUsername").isEmpty() || brain.getPredicate("lastUsername").equals("unknown")) {
brain.setPredicate("lastUsername", brain.getPredicate("name"));
}
}
brain.setPredicate("parameterHowDoYouDo", "");
try {
brain.savePredicates();
} catch (IOException e) {
log.error("saving predicates threw", e);
}
// start session based on last recognized person
if (!brain.getPredicate("default", "lastUsername").isEmpty() && !brain.getPredicate("default", "lastUsername").equals("unknown")) {
brain.startSession(brain.getPredicate("lastUsername"));
}
HtmlFilter htmlFilter = (HtmlFilter) Runtime.start("htmlFilter", "HtmlFilter");
brain.addTextListener(htmlFilter);
htmlFilter.addListener("publishText", getName(), "speak");
}
}
public void startEar() {
if (ear == null) {
ear = (SpeechRecognizer) startPeer("ear");
}
if (brain != null) {
brain.attach((Attachable) ear);
}
speakBlocking(languagePack.get("STARTINGEAR"));
}
public void startedGesture() {
startedGesture("unknown");
}
public void startedGesture(String nameOfGesture) {
if (gestureAlreadyStarted) {
warn("Warning 1 gesture already running, this can break spacetime and lot of things");
} else {
log.info("Starting gesture : {}", nameOfGesture);
gestureAlreadyStarted = true;
RobotCanMoveRandom = false;
}
}
// FIXME - universal (good) way of handling all exceptions - ie - reporting
// back to the user the problem in a short concise way but have
// expandable detail in appropriate places
public void startEye() throws Exception {
if (eye == null) {
speakBlocking(languagePack.get("STARTINGOPENCV"));
eye = (OpenCV) startPeer("eye", "OpenCV");
subscribeTo(eye.getName(), "publishOpenCVData");
}
}
public void startEyesTracking(ServoControl eyeX, ServoControl eyeY) throws Exception {
if (eye == null) {
startEye();
}
speakBlocking(languagePack.get("TRACKINGSTARTED"));
eyesTracking = (Tracking) this.startPeer("eyesTracking");
eyesTracking.connect(eye, head.eyeX, head.eyeY);
}
public InMoov2Head startHead() throws Exception {
return startHead(null, null, null, null, null, null, null, null);
}
// legacy inmoov head exposed pins
public InMoov2Head startHead(String port, String type, Integer headYPin, Integer headXPin, Integer eyeXPin, Integer eyeYPin, Integer jawPin, Integer rollNeckPin) {
// log.warn(InMoov.buildDNA(myKey, serviceClass))
// speakBlocking(languagePack.get("STARTINGHEAD") + " " + port);
// ??? SHOULD THERE BE REFERENCES AT ALL ??? ... probably not
if (head == null) {
speakBlocking(languagePack.get("STARTINGHEAD"));
head = (InMoov2Head) startPeer("head");
if (headYPin != null) {
head.setPins(headYPin, headXPin, eyeXPin, eyeYPin, jawPin, rollNeckPin);
}
// lame assumption - port is specified - it must be an Arduino :(
if (port != null) {
try {
speakBlocking(languagePack.get(port));
Arduino arduino = (Arduino) startPeer("left", "Arduino");
arduino.connect(port);
arduino.attach(head.neck);
arduino.attach(head.rothead);
arduino.attach(head.eyeX);
arduino.attach(head.eyeY);
arduino.attach(head.jaw);
arduino.attach(head.rollNeck);
} catch (Exception e) {
error(e);
}
}
} // if head null
if (mouthControl == null) {
speakBlocking(languagePack.get("STARTINGMOUTHCONTROL"));
mouthControl = (MouthControl) startPeer("mouthControl");
mouthControl.attach(head.jaw);
mouthControl.attach((Attachable) mouth);
mouthControl.setmouth(10, 50);// <-- FIXME - not the right place for
// config !!!
}
return head;
}
public void startHeadTracking() throws Exception {
if (eye == null) {
startEye();
}
if (head == null) {
startHead();
}
if (headTracking == null) {
speakBlocking(languagePack.get("TRACKINGSTARTED"));
headTracking = (Tracking) this.startPeer("headTracking");
headTracking.connect(this.eye, head.rothead, head.neck);
}
}
public InMoov2Arm startLeftArm() {
return startLeftArm(null);
}
public InMoov2Arm startLeftArm(String port) {
// log.warn(InMoov.buildDNA(myKey, serviceClass))
// speakBlocking(languagePack.get("STARTINGHEAD") + " " + port);
// ??? SHOULD THERE BE REFERENCES AT ALL ??? ... probably not
if (leftArm == null) {
speakBlocking(languagePack.get("STARTINGLEFTARM"));
leftArm = (InMoov2Arm) startPeer("leftArm");
}
if (port != null) {
try {
speakBlocking(port);
Arduino arduino = (Arduino) startPeer("left", "Arduino");
arduino.connect(port);
arduino.attach(leftArm.bicep);
arduino.attach(leftArm.omoplate);
arduino.attach(leftArm.rotate);
arduino.attach(leftArm.shoulder);
} catch (Exception e) {
error(e);
}
}
return leftArm;
}
public InMoov2Hand startLeftHand() {
return startLeftHand(null);
}
public InMoov2Hand startLeftHand(String port) {
if (leftHand == null) {
speakBlocking(languagePack.get("STARTINGLEFTHAND"));
leftHand = (InMoov2Hand) startPeer("leftHand");
}
if (port != null) {
try {
speakBlocking(port);
Arduino arduino = (Arduino) startPeer("left", "Arduino");
arduino.connect(port);
arduino.attach(leftHand.thumb);
arduino.attach(leftHand.index);
arduino.attach(leftHand.majeure);
arduino.attach(leftHand.ringFinger);
arduino.attach(leftHand.pinky);
arduino.attach(leftHand.wrist);
} catch (Exception e) {
error(e);
}
}
return leftHand;
}
public SpeechSynthesis startMouth() {
if (mouth == null) {
mouth = (SpeechSynthesis) startPeer("mouth");
if (mute) {
mouth.setMute(true);
}
}
// this.attach((Attachable) mouth);
// if (ear != null) ....
speakBlocking(languagePack.get("STARTINGMOUTH"));
speakBlocking(languagePack.get("WHATISTHISLANGUAGE"));
return mouth;
}
@Deprecated /* use start eye */
public void startOpenCV() throws Exception {
startEye();
}
public InMoov2Arm startRightArm() {
return startRightArm(null);
}
public InMoov2Arm startRightArm(String port) {
if (rightArm == null) {
speakBlocking(languagePack.get("STARTINGLEFTARM"));
rightArm = (InMoov2Arm) startPeer("rightArm");
}
if (port != null) {
try {
speakBlocking(port);
Arduino arduino = (Arduino)startPeer("right", "Arduino");
arduino.connect(port);
arduino.attach(rightArm.bicep);
arduino.attach(rightArm.omoplate);
arduino.attach(rightArm.rotate);
arduino.attach(rightArm.shoulder);
} catch (Exception e) {
error(e);
}
}
return rightArm;
}
public InMoov2Hand startRightHand() {
return rightHand;
}
public InMoov2Hand startRightHand(String port) {
if (rightHand == null) {
speakBlocking(languagePack.get("STARTINGRIGHTHAND"));
rightHand = (InMoov2Hand) startPeer("rightHand");
}
if (port != null) {
try {
speakBlocking(port);
Arduino arduino = (Arduino)startPeer("right", "Arduino");
arduino.connect(port);
arduino.attach(rightHand.thumb);
arduino.attach(rightHand.index);
arduino.attach(rightHand.majeure);
arduino.attach(rightHand.ringFinger);
arduino.attach(rightHand.pinky);
arduino.attach(rightHand.wrist);
} catch (Exception e) {
error(e);
}
}
return rightHand;
}
public void startServos(String leftPort, String rightPort) throws Exception {
startHead(leftPort);
startLeftArm(leftPort);
startLeftHand(leftPort);
startRightArm(rightPort);
startRightHand(rightPort);
startTorso(leftPort);
}
// FIXME .. externalize in a json file included in InMoov2
public void startSimulator() throws Exception {
if (jme == null) {
speakBlocking("starting simulator");
jme = (JMonkeyEngine) Runtime.start("simulator", "JMonkeyEngine");
}
// adding InMoov2 asset path to the jonkey simulator
String assetPath = getResourceDir() + fs + JMonkeyEngine.class.getSimpleName();
File check = new File(assetPath);
log.info("loading assets from {}", assetPath);
if (!check.exists()) {
log.warn("%s does not exist");
}
// disable the frustrating servo events ...
// Servo.eventsEnabledDefault(false);
jme.loadModels(assetPath);
jme.setRotation(getName() + ".head.jaw", "x");
jme.setRotation(getName() + ".head.neck", "x");
jme.setRotation(getName() + ".head.rothead", "y");
jme.setRotation(getName() + ".head.rollNeck", "z");
jme.setRotation(getName() + ".head.eyeY", "x");
jme.setRotation(getName() + ".head.eyeX", "y");
jme.setRotation(getName() + ".torso.topStom", "z");
jme.setRotation(getName() + ".torso.midStom", "y");
jme.setRotation(getName() + ".torso.lowStom", "x");
jme.setRotation(getName() + ".rightArm.bicep", "x");
jme.setRotation(getName() + ".leftArm.bicep", "x");
jme.setRotation(getName() + ".rightArm.shoulder", "x");
jme.setRotation(getName() + ".leftArm.shoulder", "x");
jme.setRotation(getName() + ".rightArm.rotate", "y");
jme.setRotation(getName() + ".leftArm.rotate", "y");
jme.setRotation(getName() + ".rightArm.omoplate", "z");
jme.setRotation(getName() + ".leftArm.omoplate", "z");
jme.setRotation(getName() + ".rightHand.wrist", "y");
jme.setRotation(getName() + ".leftHand.wrist", "y");
jme.setMapper(getName() + ".head.jaw", 0, 180, -5, 80);
jme.setMapper(getName() + ".head.neck", 0, 180, 20, -20);
jme.setMapper(getName() + ".head.rollNeck", 0, 180, 30, -30);
jme.setMapper(getName() + ".head.eyeY", 0, 180, 40, 140);
jme.setMapper(getName() + ".head.eyeX", 0, 180, -10, 70); // HERE there need
// to be
// two eyeX (left and
// right?)
jme.setMapper(getName() + ".rightArm.bicep", 0, 180, 0, -150);
jme.setMapper(getName() + ".leftArm.bicep", 0, 180, 0, -150);
jme.setMapper(getName() + ".rightArm.shoulder", 0, 180, 30, -150);
jme.setMapper(getName() + ".leftArm.shoulder", 0, 180, 30, -150);
jme.setMapper(getName() + ".rightArm.rotate", 0, 180, 80, -80);
jme.setMapper(getName() + ".leftArm.rotate", 0, 180, -80, 80);
jme.setMapper(getName() + ".rightArm.omoplate", 0, 180, 10, -180);
jme.setMapper(getName() + ".leftArm.omoplate", 0, 180, -10, 180);
jme.setMapper(getName() + ".rightHand.wrist", 0, 180, -20, 60);
jme.setMapper(getName() + ".leftHand.wrist", 0, 180, 20, -60);
jme.setMapper(getName() + ".torso.topStom", 0, 180, -30, 30);
jme.setMapper(getName() + ".torso.midStom", 0, 180, 50, 130);
jme.setMapper(getName() + ".torso.lowStom", 0, 180, -30, 30);
jme.attach(getName() + ".leftHand.thumb", getName() + ".leftHand.thumb1", getName() + ".leftHand.thumb2", getName() + ".leftHand.thumb3");
jme.setRotation(getName() + ".leftHand.thumb1", "y");
jme.setRotation(getName() + ".leftHand.thumb2", "x");
jme.setRotation(getName() + ".leftHand.thumb3", "x");
jme.attach(getName() + ".leftHand.index", getName() + ".leftHand.index", getName() + ".leftHand.index2", getName() + ".leftHand.index3");
jme.setRotation(getName() + ".leftHand.index", "x");
jme.setRotation(getName() + ".leftHand.index2", "x");
jme.setRotation(getName() + ".leftHand.index3", "x");
jme.attach(getName() + ".leftHand.majeure", getName() + ".leftHand.majeure", getName() + ".leftHand.majeure2", getName() + ".leftHand.majeure3");
jme.setRotation(getName() + ".leftHand.majeure", "x");
jme.setRotation(getName() + ".leftHand.majeure2", "x");
jme.setRotation(getName() + ".leftHand.majeure3", "x");
jme.attach(getName() + ".leftHand.ringFinger", getName() + ".leftHand.ringFinger", getName() + ".leftHand.ringFinger2", getName() + ".leftHand.ringFinger3");
jme.setRotation(getName() + ".leftHand.ringFinger", "x");
jme.setRotation(getName() + ".leftHand.ringFinger2", "x");
jme.setRotation(getName() + ".leftHand.ringFinger3", "x");
jme.attach(getName() + ".leftHand.pinky", getName() + ".leftHand.pinky", getName() + ".leftHand.pinky2", getName() + ".leftHand.pinky3");
jme.setRotation(getName() + ".leftHand.pinky", "x");
jme.setRotation(getName() + ".leftHand.pinky2", "x");
jme.setRotation(getName() + ".leftHand.pinky3", "x");
// left hand mapping complexities of the fingers
jme.setMapper(getName() + ".leftHand.index", 0, 180, -110, -179);
jme.setMapper(getName() + ".leftHand.index2", 0, 180, -110, -179);
jme.setMapper(getName() + ".leftHand.index3", 0, 180, -110, -179);
jme.setMapper(getName() + ".leftHand.majeure", 0, 180, -110, -179);
jme.setMapper(getName() + ".leftHand.majeure2", 0, 180, -110, -179);
jme.setMapper(getName() + ".leftHand.majeure3", 0, 180, -110, -179);
jme.setMapper(getName() + ".leftHand.ringFinger", 0, 180, -110, -179);
jme.setMapper(getName() + ".leftHand.ringFinger2", 0, 180, -110, -179);
jme.setMapper(getName() + ".leftHand.ringFinger3", 0, 180, -110, -179);
jme.setMapper(getName() + ".leftHand.pinky", 0, 180, -110, -179);
jme.setMapper(getName() + ".leftHand.pinky2", 0, 180, -110, -179);
jme.setMapper(getName() + ".leftHand.pinky3", 0, 180, -110, -179);
jme.setMapper(getName() + ".leftHand.thumb1", 0, 180, -30, -100);
jme.setMapper(getName() + ".leftHand.thumb2", 0, 180, 80, 20);
jme.setMapper(getName() + ".leftHand.thumb3", 0, 180, 80, 20);
// right hand
jme.attach(getName() + ".rightHand.thumb", getName() + ".rightHand.thumb1", getName() + ".rightHand.thumb2", getName() + ".rightHand.thumb3");
jme.setRotation(getName() + ".rightHand.thumb1", "y");
jme.setRotation(getName() + ".rightHand.thumb2", "x");
jme.setRotation(getName() + ".rightHand.thumb3", "x");
jme.attach(getName() + ".rightHand.index", getName() + ".rightHand.index", getName() + ".rightHand.index2", getName() + ".rightHand.index3");
jme.setRotation(getName() + ".rightHand.index", "x");
jme.setRotation(getName() + ".rightHand.index2", "x");
jme.setRotation(getName() + ".rightHand.index3", "x");
jme.attach(getName() + ".rightHand.majeure", getName() + ".rightHand.majeure", getName() + ".rightHand.majeure2", getName() + ".rightHand.majeure3");
jme.setRotation(getName() + ".rightHand.majeure", "x");
jme.setRotation(getName() + ".rightHand.majeure2", "x");
jme.setRotation(getName() + ".rightHand.majeure3", "x");
jme.attach(getName() + ".rightHand.ringFinger", getName() + ".rightHand.ringFinger", getName() + ".rightHand.ringFinger2", getName() + ".rightHand.ringFinger3");
jme.setRotation(getName() + ".rightHand.ringFinger", "x");
jme.setRotation(getName() + ".rightHand.ringFinger2", "x");
jme.setRotation(getName() + ".rightHand.ringFinger3", "x");
jme.attach(getName() + ".rightHand.pinky", getName() + ".rightHand.pinky", getName() + ".rightHand.pinky2", getName() + ".rightHand.pinky3");
jme.setRotation(getName() + ".rightHand.pinky", "x");
jme.setRotation(getName() + ".rightHand.pinky2", "x");
jme.setRotation(getName() + ".rightHand.pinky3", "x");
jme.setMapper(getName() + ".rightHand.index", 0, 180, 65, -10);
jme.setMapper(getName() + ".rightHand.index2", 0, 180, 70, -10);
jme.setMapper(getName() + ".rightHand.index3", 0, 180, 70, -10);
jme.setMapper(getName() + ".rightHand.majeure", 0, 180, 65, -10);
jme.setMapper(getName() + ".rightHand.majeure2", 0, 180, 70, -10);
jme.setMapper(getName() + ".rightHand.majeure3", 0, 180, 70, -10);
jme.setMapper(getName() + ".rightHand.ringFinger", 0, 180, 65, -10);
jme.setMapper(getName() + ".rightHand.ringFinger2", 0, 180, 70, -10);
jme.setMapper(getName() + ".rightHand.ringFinger3", 0, 180, 70, -10);
jme.setMapper(getName() + ".rightHand.pinky", 0, 180, 65, -10);
jme.setMapper(getName() + ".rightHand.pinky2", 0, 180, 70, -10);
jme.setMapper(getName() + ".rightHand.pinky3", 0, 180, 60, -10);
jme.setMapper(getName() + ".rightHand.thumb1", 0, 180, 30, 110);
jme.setMapper(getName() + ".rightHand.thumb2", 0, 180, -100, -150);
jme.setMapper(getName() + ".rightHand.thumb3", 0, 180, -100, -160);
// additional experimental mappings
/*
* simulator.attach(getName() + ".leftHand.pinky", getName() +
* ".leftHand.index2"); simulator.attach(getName() + ".leftHand.thumb",
* getName() + ".leftHand.index3"); simulator.setRotation(getName() +
* ".leftHand.index2", "x"); simulator.setRotation(getName() +
* ".leftHand.index3", "x"); simulator.setMapper(getName() +
* ".leftHand.index", 0, 180, -90, -270); simulator.setMapper(getName() +
* ".leftHand.index2", 0, 180, -90, -270); simulator.setMapper(getName() +
* ".leftHand.index3", 0, 180, -90, -270);
*/
}
public void startTorso(String port) {
if (torso == null) {
speakBlocking(languagePack.get("STARTINGTORSO"));
torso = (InMoov2Torso) startPeer("torso");
if (port != null) {
try {
speakBlocking(port);
Arduino left = (Arduino) startPeer("left");
left.connect(port);
left.attach(torso.lowStom);
left.attach(torso.midStom);
left.attach(torso.topStom);
} catch (Exception e) {
error(e);
}
}
}
}
public void stop() {
if (head != null) {
head.stop();
}
if (rightHand != null) {
rightHand.stop();
}
if (leftHand != null) {
leftHand.stop();
}
if (rightArm != null) {
rightArm.stop();
}
if (leftArm != null) {
leftArm.stop();
}
if (torso != null) {
torso.stop();
}
}
public void stopGesture() {
Python p = (Python) Runtime.getService("python");
p.stop();
}
public void waitTargetPos() {
head.waitTargetPos();
leftArm.waitTargetPos();
rightArm.waitTargetPos();
leftHand.waitTargetPos();
rightHand.waitTargetPos();
torso.waitTargetPos();
}
}
|
package pipe.actions.file;
import pipe.controllers.PipeApplicationController;
import pipe.gui.ApplicationSettings;
import pipe.views.PipeApplicationView;
import java.awt.event.ActionEvent;
public class CreateAction extends FileAction {
public CreateAction() {
super("New", "Create a new Petri net", "ctrl N");
}
@Override
public void actionPerformed(ActionEvent e) {
PipeApplicationController controller = ApplicationSettings.getApplicationController();
controller.createEmptyPetriNet();
}
}
|
package programminglife.utility;
import com.google.common.base.Charsets;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.net.URL;
import java.util.Optional;
/**
* A class which contains all the possible alerts we can give to the user.
*/
public final class Alerts {
private static final double ABOUT_MIN_WIDTH = 500;
private static final double INSTRUCTIONS_MIN_WIDTH = 800;
/**
* Constructor for the Alert.
*/
private Alerts() { }
/**
* Alert method used if the alert is an error.
* @param message String containing the message to be given to the user.
* @return Alert error.
*/
@NotNull
public static Alert error(String message) {
return new Alert(Alert.AlertType.ERROR, message, ButtonType.CLOSE);
}
/**
* Alert method used if the alert is a warning.
* @param message String containing the message to be given to the user.
* @return Alert warning.
*/
@NotNull
public static Alert warning(String message) {
return new Alert(Alert.AlertType.WARNING, message, ButtonType.CLOSE);
}
/**
* Alert method used if the user wants to quit.
*/
public static void quitAlert() {
Alert a = new Alert(Alert.AlertType.CONFIRMATION);
a.setTitle("Confirm Exit");
a.setHeaderText("Do you really want to exit?");
Optional<ButtonType> result = a.showAndWait();
if (result.isPresent()) {
if (result.get() == ButtonType.OK) {
Platform.exit();
System.exit(0);
}
if (result.get() == ButtonType.CANCEL) {
a.close();
}
}
}
/**
* Alert method used to show the infomation from the group.
*/
public static void infoAboutAlert() {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("About");
alert.setHeaderText(null);
alert.setResizable(true);
alert.getDialogPane().setMinWidth(ABOUT_MIN_WIDTH);
URL url = Alerts.class.getResource("/texts/About.txt");
try {
alert.setContentText(com.google.common.io.Resources.toString(url, Charsets.UTF_8));
alert.show();
} catch (IOException e) {
Alerts.error("Can't open the about file").show();
}
}
/**
* Alert method used to show the information from the instructions.
*/
public static void infoInstructionAlert() {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Instructions");
alert.setHeaderText(null);
alert.setResizable(true);
alert.getDialogPane().setMinWidth(INSTRUCTIONS_MIN_WIDTH);
URL url = Alerts.class.getResource("/texts/Instructions.txt");
try {
alert.setContentText(com.google.common.io.Resources.toString(url, Charsets.UTF_8));
alert.show();
} catch (IOException e) {
Alerts.error("Can't open the instructions file").show();
}
}
}
|
package sklearn_pandas;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Iterables;
import org.dmg.pmml.DataDictionary;
import org.dmg.pmml.DataField;
import org.dmg.pmml.DataType;
import org.dmg.pmml.DerivedField;
import org.dmg.pmml.Expression;
import org.dmg.pmml.FieldName;
import org.dmg.pmml.LocalTransformations;
import org.dmg.pmml.MiningField;
import org.dmg.pmml.Model;
import org.dmg.pmml.OpType;
import org.dmg.pmml.PMML;
import org.dmg.pmml.PMMLObject;
import org.dmg.pmml.Visitor;
import org.dmg.pmml.VisitorAction;
import org.jpmml.model.ReflectionUtil;
import org.jpmml.model.visitors.AbstractSimpleVisitor;
import org.jpmml.sklearn.CClassDict;
import sklearn.Transformer;
import sklearn.preprocessing.LabelEncoder;
public class DataFrameMapper extends CClassDict {
public DataFrameMapper(String module, String name){
super(module, name);
}
public void updatePMML(PMML pmml){
DataDictionary dataDictionary = pmml.getDataDictionary();
List<DataField> dataFields = dataDictionary.getDataFields();
Model model = Iterables.getOnlyElement(pmml.getModels());
LocalTransformations localTransformations = model.getLocalTransformations();
if(localTransformations == null){
localTransformations = new LocalTransformations();
model.setLocalTransformations(localTransformations);
}
List<Object[]> features = new ArrayList<>(getFeatures());
if(features.size() == 0 || features.size() != dataFields.size()){
throw new IllegalArgumentException();
}
// Move the target column from the last position to the first position
features.add(0, features.remove(features.size() - 1));
final
Map<FieldName, FieldName> renamedFields = new LinkedHashMap<>();
final
Map<FieldName, FieldName> transformedFields = new LinkedHashMap<>();
for(int i = 0; i < dataFields.size(); i++){
DataField dataField = dataFields.get(i);
Object[] feature = features.get(i);
if(feature[0] instanceof List){
feature[0] = Iterables.getOnlyElement((List<?>)feature[0]);
}
FieldName name = FieldName.create((String)feature[0]);
renamedFields.put(dataField.getName(), name);
if(i > 0){
Transformer transformer = (Transformer)feature[1];
if(transformer != null){
FieldName derivedName = FieldName.create("derived_" + name.getValue());
Expression expression = transformer.encode(name);
DerivedField derivedField = new DerivedField(dataField.getOpType(), dataField.getDataType())
.setName(derivedName)
.setExpression(expression);
localTransformations.addDerivedFields(derivedField);
// XXX
if(transformer instanceof LabelEncoder){
dataField.setOpType(OpType.CATEGORICAL)
.setDataType(DataType.STRING);
}
transformedFields.put(dataField.getName(), derivedName);
}
}
}
Visitor visitor = new AbstractSimpleVisitor(){
@Override
public VisitorAction visit(PMMLObject object){
List<Field> fields = ReflectionUtil.getAllInstanceFields(object);
for(Field field : fields){
Object value = ReflectionUtil.getFieldValue(field, object);
if(value instanceof FieldName){
FieldName name = (FieldName)value;
FieldName updatedName = name;
if(renamedFields.containsKey(name)){
updatedName = renamedFields.get(name);
} // End if
if(!(object instanceof DataField || object instanceof MiningField)){
if(transformedFields.containsKey(name)){
updatedName = transformedFields.get(name);
}
}
ReflectionUtil.setFieldValue(field, object, updatedName);
}
}
return VisitorAction.CONTINUE;
}
};
visitor.applyTo(pmml);
}
public List<Object[]> getFeatures(){
return (List)get("features");
}
}
|
package org.codehaus.groovy.ast;
import groovy.lang.CompilerConfig;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Represents the entire contents of a compilation step which consists of one
* or more {@link ModuleNode}instances
*
* @author <a href="mailto:james@coredevelopers.net">James Strachan </a>
* @version $Revision$
*/
public class CompileUnit {
private List modules = new ArrayList();
private Map classes = new HashMap();
private CompilerConfig config;
private ClassLoader classLoader;
private Map cachedClasses = new HashMap();
public static final Object NO_CLASS = new Object();
public CompileUnit(ClassLoader classLoader, CompilerConfig config) {
this.classLoader = classLoader;
this.config = config;
}
public List getModules() {
return modules;
}
public void addModule(ModuleNode node) {
modules.add(node);
node.setUnit(this);
addClasses(node.classes);
}
/**
* @return the ClassNode for the given qualified name or returns null if
* the name does not exist in the current compilation unit
* (ignoring the .class files on the classpath)
*/
public ClassNode getClass(String name) {
return (ClassNode) classes.get(name);
}
/**
* @return a list of all the classes in each module in the compilation unit
*/
public List getClasses() {
List answer = new ArrayList();
for (Iterator iter = modules.iterator(); iter.hasNext();) {
ModuleNode module = (ModuleNode) iter.next();
answer.addAll(module.getClasses());
}
return answer;
}
public CompilerConfig getConfig() {
return config;
}
public ClassLoader getClassLoader() {
return classLoader;
}
/**
* Loads a class on the compile classpath so that it can be introspected
*
* @param type
* @return @throws
* ClassNotFoundException
*/
public Class loadClass(String type) throws ClassNotFoundException {
Object obj = cachedClasses.get(type);
if ( obj == NO_CLASS ) {
throw new ClassNotFoundException(type);
}
if ( obj != null) {
return (Class)obj;
}
Class answer = null;
try {
answer = getClassLoader().loadClass(type);
} catch (ClassNotFoundException e) {
// fall through
}
// lets try the context class loader
try {
if ( answer == null ) {
answer = Thread.currentThread().getContextClassLoader().loadClass(type);
}
}
catch (ClassNotFoundException e1) {
// fall through
}
// lets try our class loader
try {
if ( answer == null ) {
answer = getClass().getClassLoader().loadClass(type);
}
}
catch (ClassNotFoundException e2) {
// fall through
}
try {
if (answer == null ) {
answer = Class.forName(type);
}
}
catch (ClassNotFoundException e2) {
// fall through
}
if ( answer == null ) {
cachedClasses.put(type,NO_CLASS);
throw new ClassNotFoundException(type);
} else {
cachedClasses.put(type,answer);
}
return answer;
}
/**
* Appends all of the fully qualified class names in this
* module into the given map
*/
void addClasses(List classList) {
for (Iterator iter = classList.iterator(); iter.hasNext();) {
addClass((ClassNode) iter.next());
}
}
void addClass(ClassNode node) {
String name = node.getName();
if (classes.containsKey(name)) {
throw new RuntimeException(
"Error: duplicate class declaration for name: " + name + " and class: " + node);
}
classes.put(name, node);
}
}
|
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
/**
* The main server program.
* @author Kevin
*
*/
public class Server {
public static final int INCREMENT = 1;
//payload tags in Slack POST
public static final String PAYLOAD_START = "token=";
public static final String CMD_TAG = "command=";
public static final String TEXT_TAG = "text=";
public static final String CHANNEL_NAME_TAG = "channel_name=";
public static final String CHANNEL_ID_TAG = "channel_id=";
public static final String USER_NAME_TAG = "user_name=";
public static final String USER_ID_TAG = "user_id=";
//custom commands.
public static final String TIP_CMD = "%2Ftip";
public static final String CHECK_CMD = "%2Fcheck";
public static final String REGISTER_CMD = "%2Fregister";
private static ServerSocket listenSock;
//loggers
private static volatile Logger log;
private static volatile Logger errorLog;
private static final String LOG_FILENAME = "log";
private static final String ERROR_LOG_FILENAME = "errorLog";
//threads
private static Thread acceptThread;
private static Thread maintanenceThread;
private static final int MAINTENANCE_TIME = 300000; //every 5 minutes, run maintenance thread.
private static boolean running = true; //server running or not
private static boolean silent = false; //silent mode prevents server from posting to slack
//private static Date startDate = new Date(System.currentTimeMillis());
private static Server instance;
public static Server getInstance(){
if (instance == null){
instance = new Server();
}
return instance;
}
private Server(){}
/**
* Starts the server, binds all resources. If an instance has already is or has been
* running, then nothing happens.
*/
public void startServer(){
//run only if the current thread is not created. Single instance
if (acceptThread == null){
println("Getting configuration settings...");
println("Retriving user database...");
println("Found " + UserDB.getUserCount() + " users in database.");
UserMapping.getCount(); //Initialize the mapping
//if there's no users in the database, warn user to add some
if (UserDB.getUserCount() == 0){
println("Warning! Server has no users registered in database.");
}
//create the system log
println("Creating system logs...");
log = new Logger(LOG_FILENAME);
errorLog = new Logger(ERROR_LOG_FILENAME);
println("Log started in file: " + log.getFileName());
println("Starting server on port " + Config.getPort() + "...");
System.out.println("\n=====================================================");
//create the listen socket
try {
listenSock = new ServerSocket(Config.getPort());
} catch (BindException e){
System.err.println(e.getMessage());
System.err.println("Cannot setup server! Quitting...");
System.exit(-1);
} catch (UnknownHostException e) {
e.printStackTrace();
System.err.println("Cannot setup server! Quitting...");
System.exit(-1);
} catch (IOException e) {
e.printStackTrace();
System.err.println("Cannot setup server! Quitting...");
System.exit(-1);
}
//create the handling thread and run it.
acceptThread = new Thread(new SocketAccepter());
acceptThread.start();
//startTime = new Date(System.currentTimeMillis()); //server actually starts running here.
maintanenceThread = new Thread(new MaintenanceThread());
maintanenceThread.start();
}
//move this thread into command line service
println("Server now running. Enter commands to maintain.");
commandLine();
}
/**
* Server commandline that runs commands to manage the
* server.
*/
private static void commandLine(){
Scanner in = new Scanner(System.in);
String nextInput;
while (running == true){
nextInput = in.nextLine();
String[] commandArgs = nextInput.split(" ", 2);
String command = commandArgs[0].trim();
String args = (commandArgs.length == 2)? commandArgs[1] : "";
if (command.equals("/stop")){
//stop server command
println("Saving all information and stopping server...");
saveAllFiles();
running = false;
}
else if(command.equals("/save")){
//save all current information immediately
println("Saving all logs and user information...");
saveAllFiles();
println("All files have been saved.");
}
else if(command.equals("/message")){
//sends a message onto slack given the channel and message respectively
String[] split = args.split(" ", 2);
//must be exactly two args.
if(split.length == 2){
println("Sending message...");
messageSlack(split[1], split[0]);
}
else{
println("To use /message, enter channel name then the message to send.");
}
}
else if (command.equals("/silent")){
//toggle silent mode
if (silent == false){
//turn silent on
silent = true;
printRecord("Slient mode is ON, no messages will be posted to Slack.");
}
else if (silent == true){
//turn silent of
silent = false;
printRecord("Slient mode is OFF, messages will be posted to Slack.");
}
}
else{
println("Invalid command.");
}
}
//shutdown server.
in.close();
System.exit(0);
}
/**
* Posts a message on slack on the specified channel
* @param message
* @param channel
*/
private static void messageSlack(String textPost, String channel){
//System.out.println(textPost);
if(silent == false){
String message;
//construct the JSON message
if (channel != null){
message = "payload={\"text\":\"`" + textPost + "`\", \"channel\":\"#" + channel + "\", \"username\": \"" + Config.getBotName() + "\"}";
}
else{
message = "payload={\"text\":\"`" + textPost + "`\", \"username\": \"" + Config.getBotName() + "\"}";
}
//System.out.println(message);
try {
CloseableHttpClient slackServer = HttpClients.createDefault();
HttpPost slackMessage = new HttpPost(Config.getSlackWebHook());
slackMessage.setHeader("User-Agent", "Slack Points Server");
slackMessage.setHeader("content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
slackMessage.setEntity(new StringEntity(message));
HttpResponse response = slackServer.execute(slackMessage);
//print reply from slack server if any.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
response.getEntity().writeTo(baos);
println("<Slack Server>: " + (new String(baos.toByteArray())));
slackServer.close();
} catch (UnknownHostException e){
printException(e);
} catch (IOException e) {
printException(e);
}
}
}
//The request handler
/**
* The request handler created when a new request is being made.
* @author Kevin
*
*/
private final class RequestHandler implements Runnable{
Socket client;
public RequestHandler(Socket client){
this.client = client;
}
@Override
public void run() {
try {
BufferedReader buff = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));
//find the command field of the POST request
//gather all lines
String complete = "";
String nextLine = buff.readLine();
while (nextLine != null){
complete = complete + nextLine;
nextLine = buff.readLine();
}
if (complete.indexOf("token=") >= 0){
//proper request.
String payload = complete.substring(complete.indexOf("token="));
//with complete request, find the command sent
String channelName = getTagArg(payload, CHANNEL_NAME_TAG);
//String channelID = getTagArg(payload, CHANNEL_ID_TAG);
String userID = getTagArg(payload, USER_ID_TAG);
String userName = getTagArg(payload, USER_NAME_TAG);
String command = getTagArg(payload, CMD_TAG);
String[] args = getTextArgs(payload); //arguements of the command
//print command out
String fullCommand = command;
for (int i =0; i < args.length; i++){
fullCommand = fullCommand + " " + args[i];
}
println("<SLACK_CMD> " + userName + " issued command: \t"+fullCommand );
if (command.equals(TIP_CMD)){
//increment command sent, increment points
//increment only if there is a user that exists.
if (args.length == 1){
String targetID = UserMapping.getID(args[0]);
if (targetID != null){
if (UserDB.hasUser(targetID)){
if (targetID.equals(userID) == false){
//not self, do tipping
UserDB.increment(targetID, INCREMENT);
log.writeLine(userName + " gave " + args[0] + " " + INCREMENT + Config.getCurrencyName());
messageSlack(userName + " gave " + args[0] + " " + INCREMENT + Config.getCurrencyName(), channelName);
}
else{
//error, cannot tip self.
messageSlack("You cannot tip yourself " + userName + "!", channelName);
}
}
}
else{
//no mapping found, return error
messageSlack("I do not recognize who " + args[0] + " is! Did that user get an account with the bank of Slack? Get that user to enter the command /register to sign up. If you already have an account, but changed your name recently please enter the command /register ASAP.", channelName);
}
}
}
else if (command.equals(CHECK_CMD)){
//check command sent, return current points.
if ((args.length == 1) && (args[0].equals("") == false)){
//get the id of the user
String targetID = UserMapping.getID(args[0]);
if(targetID != null){
if (UserDB.hasUser(targetID)){
//user exists, return their count.
User check = UserDB.getUser(targetID);
String humanName = UserMapping.getName(targetID);
messageSlack(humanName + " has " + check.getPts() + Config.getCurrencyName() + ".", channelName);
}
}
else{
//no such user exists, report back
messageSlack("No such user named " + userName + " exists. Have they registered yet?", channelName);
}
}
else if ((args.length == 1) && (args[0].equals("") == true)){
//get the id of the user
String targetID = UserMapping.getID(userName);
if(targetID != null){
if (UserDB.hasUser(targetID)){
//user exists, return their count.
User check = UserDB.getUser(targetID);
String humanName = UserMapping.getName(targetID);
messageSlack(humanName + " has " + check.getPts() + Config.getCurrencyName() + ".", channelName);
}
}
else{
//no such user exists, report back
messageSlack("I cannot find your record " + userName + ". Have you registered yet?", channelName);
}
}
}
else if (command.equals(REGISTER_CMD)){
//register command sent, update id of new user.
if (UserMapping.registerPair(userName, userID)){
UserMapping.saveAll();
log.writeLine("Added " + userName + " as new ID: " + userID);
//create new user in database
UserDB.registerUser(userID);
UserDB.saveAll();
messageSlack("Welcome "+ userName + "! You have " + UserDB.getUser(userID).getPts()
+ Config.getCurrencyName() + ". Earn more by getting tips from friends.", channelName);
}
else{
String oldName = UserMapping.getName(userID);
if (UserMapping.updateName(oldName, userName)){
//successful name update.
UserMapping.saveAll();
log.writeLine("Updated " + oldName + " -> " + userName);
messageSlack("Gotcha! I'll remember you as " + userName + " from now on.", channelName);
}
}
}
else{
//invalid command
messageSlack("Sorry I don't understand that command. :frown:", channelName);
}
}
} catch (IOException e) {
printException(e);
} catch(Exception e){
printException(e);
}
//always close the client
try {
client.close();
} catch (IOException e) {
printException(e);
}
}
}
/**
* Gets the command argument of the Slack slash command of the
* specified tag in the request.
* Returned string is pre-trimmed.
* @param postRequest The request to parse
* @param tag The tag to extract the value of
* @return Empty string if tag is not found, Value of the tag otherwise.
*/
private static String getTagArg(String payload, String tag){
int index = payload.indexOf(tag);
if (index >= 0){
String arg = payload.substring(index + tag.length(),payload.indexOf("&", index));
return arg.trim();
}
return "";
}
/**
* Gets all the arguments seperated by spaces (the '+' symbol).
* Returns a String array of each argument in the order they are found in.
*
* If there are no arguments, an empty array is returned.
* If the string does not contain the "
* @param payload
* @return
*/
private static String[] getTextArgs(String payload){
int index = payload.indexOf(TEXT_TAG);
if (index >=0){
String raw = payload.substring(index + TEXT_TAG.length());
return raw.split("\\+");
}
return (new String[0]);
}
/**
* The socket accepting thread that accepts all connections and attempts
* to service them.
* @author Kevin
*
*/
private final class SocketAccepter implements Runnable{
@Override
public void run() {
while( running == true ){
try {
Socket client = listenSock.accept();
//got a connection
println("Recieved connection from: " + client.getInetAddress().toString() + ":" + client.getPort());
//handle request in new thread
Thread clientHandler = new Thread(new RequestHandler(client));
clientHandler.start();
} catch (IOException e) {
printException(e);
}
}
try {
listenSock.close();
} catch (IOException e) {
printException(e);
}
}
}
private final class MaintenanceThread implements Runnable{
private static final long MILLIS_IN_DAY = 86400000;
private long currentDay;
public MaintenanceThread(){
this.currentDay = System.currentTimeMillis();
}
@Override
public void run() {
try {
Thread.sleep(MAINTENANCE_TIME);
//if new day, swap out logs
if ((System.currentTimeMillis() - currentDay) > MILLIS_IN_DAY){
Thread.sleep(1000);
log = new Logger(LOG_FILENAME);
errorLog = new Logger(ERROR_LOG_FILENAME);
}
saveAllFiles();
printRecord("--> Maintenance Thread saved all information");
} catch (InterruptedException e) {
printException(e);
}
}
}
/**
* Saves all critical files.
*/
private static void saveAllFiles(){
log.saveLog();
errorLog.saveLog();
UserDB.saveAll();
UserMapping.saveAll();
}
//Reporting methods and console print
private static SimpleDateFormat consoleDate = new SimpleDateFormat("HH:mm:ss");
private static String timeStamp(){
return "[" + (consoleDate.format(new Date(System.currentTimeMillis()))) + "]: ";
}
/**
* Prints out an exception when it occurs. Only the stack
* trace is printed to the error log. But an occurance is shown
* in both the console and the log.
*
* @param e
*/
public static void printException(Exception e){
String message = timeStamp() + "Exception occurred. " + UnknownHostException.class.getName() + ": " + e.getMessage();
printRecord(message + " --Please see error log for stack trace
//Convert stack trace into string and print to error log
StringWriter error = new StringWriter();
e.printStackTrace(new PrintWriter(error));
String stackTrace = error.toString();
errorLog.writeLine(message + "\n" + stackTrace);
messageSlack("Whoops! I ran into an exception. See my log.", null);
}
/**
* Prints a line in the server and in the log. Time stamped
*/
public static void printRecord(String message){
System.out.println(timeStamp() + message);
log.writeLine(message);
}
/**
* Prints a line in the server. Time stamped
*/
public static void println(String message){
System.out.println(timeStamp() + message);
}
/*
public static void main(String[] args){
Config.getInstance().getCount();
Server.messageSlack("Error! Insufficient Veto power. I belong to general-armstrong now.", "random");
}
*/
}
|
public class Sudoku {
public static void main (String[] args ) {
Board.SIZE = Integer.parseInt(args[0]);
Board board = new Board();
// board.setNumber(0, 0, 1);
// board.setConst(0, 0, true);
// board.setNumber(5, 0, 7);
// board.setConst(5, 0, true);
// board.setNumber(7, 0, 9);
// board.setConst(7, 0, true);
// board.setNumber(1, 1, 3);
// board.setConst(1, 1, true);
// board.setNumber(4, 1, 2);
// board.setConst(4, 1, true);
// board.setNumber(8, 1, 8);
// board.setConst(8, 1, true);
// board.setNumber(2, 2, 9);
// board.setConst(2, 2, true);
// board.setNumber(3, 2, 6);
// board.setConst(3, 2, true);
// board.setNumber(6, 2, 5);
// board.setConst(6, 2, true);
// board.setNumber(2, 3, 5);
// board.setConst(2, 3, true);
// board.setNumber(3, 3, 3);
// board.setConst(3, 3, true);
// board.setNumber(6, 3, 9);
// board.setConst(6, 3, true);
// board.setNumber(1, 4, 1);
// board.setConst(1, 4, true);
// board.setNumber(4, 4, 8);
// board.setConst(4, 4, true);
// board.setNumber(8, 4, 2);
// board.setConst(8, 4, true);
// board.setNumber(0, 5, 6);
// board.setConst(0, 5, true);
// board.setNumber(5, 5, 4);
// board.setConst(5, 5, true);
// board.setNumber(0, 6, 3);
// board.setConst(0, 6, true);
// board.setNumber(7, 6, 1);
// board.setConst(7, 6, true);
// board.setNumber(1, 7, 4);
// board.setConst(1, 7, true);
// board.setNumber(8, 7, 7);
// board.setConst(8, 7, true);
// board.setNumber(2, 8, 7);
// board.setConst(2, 8, true);
// board.setNumber(6, 8, 3);
// board.setConst(6, 8, true);
Solver solver = new Solver(board);
int compteur = 0;
while (!solver.nextStep()) {
compteur++;
// try {
// Thread.sleep(25);
// } catch (Exception e) {}
double pourcentage = (compteur / 23930039.0) * 100.0;
//System.out.println(" Etape numero : " + compteur );
if (compteur % 10000 == 0)
System.out.printf("\r%f %% effectues", pourcentage);
}
double pourcentage = (compteur / 23930039.0) * 100.0;
System.out.printf("\r%f %% effectues", pourcentage);
System.out.println();
Board b = solver.getBoard();
for (int i = 0; i < Board.SIZE; i++) {
if (i%((int)Math.sqrt(Board.SIZE))==0) {
afficherLigne(true);
} else {
afficherLigne(false);
}
for (int j = 0; j < Board.SIZE; j++) {
if(j%((int)Math.sqrt(Board.SIZE))==0) {
System.out.print("| ");
} else {
System.out.print(" ");
}
if (b.getNumber(j,i) == 0 ) {
System.out.print(" ");
}
else {
System.out.print(b.getNumber(j, i) + " ");
}
}
System.out.println("|");
}
afficherLigne(true);
}
public static void afficherLigne(boolean show) {
for ( int j = 0; j < Board.SIZE; j++) {
if (show) {
if ( j%((int)Math.sqrt(Board.SIZE))==0 ) {
System.out.print("+
} else {
System.out.print("
}
} else {
if ( j%((int)Math.sqrt(Board.SIZE))==0 ) {
System.out.print("| ");
} else {
System.out.print(" ");
}
}
}
if (show) {
System.out.println("+");
} else {
System.out.println("|");
}
}
}
|
/*package games.engine.gui;*/
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.net.*;
import javax.swing.JComponent.*;
import java.awt.geom.*;
import java.io.*;
class MainGUI extends JFrame implements ActionListener, MouseMotionListener, MouseListener, WindowListener {
JLabel image;
JTextArea msg;
JPanel panel;
JTextField input;
JScrollPane scrollPane;
int mouseX, mouseY;
JMenuBar menuBar;
JMenu menu;
JMenuItem menuItem;
JRadioButtonMenuItem rbMenuItem;
Image cardspic;
Image back;
Image backSW;
Image title;
Image pointer[] = new Image[4];
Image burntPic;
Graphics g;
BufferedImage offscreen;
ImageIcon imageI;
Image offscreen2;
Graphics g2;
Graphics2D g2d;
boolean player1 = false;
boolean player2 = false;
boolean myTurn = false;
Message message = null;
Dealer dealer = null;
Player player = null;
Score score;
String playersName = "unknown";
Hand hand;
Point pointplayer1[] = new Point[3];
Point pointplayer2[] = new Point[3];
Point pointplayer3[] = new Point[3];
Point pointplayer4[] = new Point[3];
Point centre1;
Dimension screenSize;
MainGUI() {
MediaTracker tracker = new MediaTracker(this);
Toolkit toolkit = Toolkit.getDefaultToolkit();
cardspic = toolkit.getImage(this.getClass().getResource("Images/cards.gif"));
back = toolkit.getImage(this.getClass().getResource("Images/back.gif"));
backSW = toolkit.getImage(this.getClass().getResource("Images/backSW.gif"));
title = toolkit.getImage(this.getClass().getResource("Images/Title.jpg"));
pointer[0] = toolkit.getImage(this.getClass().getResource("Images/pointer.gif"));
burntPic = toolkit.getImage(this.getClass().getResource("Images/burnt.jpg"));
tracker.addImage(cardspic, 1);
tracker.addImage(back, 1);
tracker.addImage(backSW, 1);
tracker.addImage(title, 1);
tracker.addImage(pointer[0], 1);
tracker.addImage(burntPic, 1);
try {
tracker.waitForAll();
} catch (InterruptedException e) {
msg.setText("Image load Error " + e);
}
pointer[3] = rotatePointer(pointer[0]);
pointer[2] = rotatePointer(pointer[3]);
pointer[1] = rotatePointer(pointer[2]);
offscreen = new BufferedImage(450, 550, BufferedImage.TYPE_3BYTE_BGR);
g = offscreen.getGraphics();
g.drawImage(title, -40, 120, this);
g.setColor(Color.white);
g.drawLine(0, 450, 450, 450);
screenSize = Toolkit.getDefaultToolkit().getScreenSize();
if(screenSize.width < 1024){
offscreen2 = new BufferedImage(338, 413, BufferedImage.TYPE_3BYTE_BGR);
g2 = offscreen2.getGraphics();
g2d = (Graphics2D) g2;
AffineTransform at = new AffineTransform();
at.scale(0.75, 0.75);
g2d.transform(at);
g2d.drawImage(offscreen, 0, 0, null);
imageI = new ImageIcon(offscreen2);
}else
imageI = new ImageIcon(offscreen);
image = new JLabel(imageI);
addMouseMotionListener(this);
addMouseListener(this);
requestFocus();
}
public static void main(String[] args) {
try {
MainGUI frame = new MainGUI();
frame.setTitle("Card Game");
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
} catch (Exception e) {
System.out.println("Game Error: " + e);
}
}
}
|
package com.RoboWars;
import java.util.Observable;
import java.util.Observer;
import org.openintents.sensorsimulator.hardware.SensorManagerSimulator;
import android.app.Activity;
import android.content.Context;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
public class RoboWars extends Activity implements SensorListener, Observer
{
/** The interval at which orientation updates should be pushed to the server */
public static final long ORIENTATION_INTERVAL_MS = 300;
/* Views invoked by the application. */
private TextView chat, users;
private EditText entry, server, port, user;
/** The time at which the reading of the orientation sensor was last updated */
private long lastOrientationUpdate;
private LobbyModel model; // General application model.
private TcpClient tcp; // TCP controller.
private String userlist; // Users currently in the lobby.
private SensorManager mSensorManager; // Manages the accelerometer and other sensors.
TextView mTextViewAcc; // Text view for accelerometer.
TextView mTextViewMag; // Text view for magnetic field.
TextView mTextViewOri; // Text view for orientation.
private static final int MAX_LINES = 12; // Max lines to show in the chat lobby.
/**
* Creates a tab view.
*/
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TabHost tabHost=(TabHost)findViewById(R.id.tabHost);
tabHost.setCurrentTab(0);
tabHost.setup();
/* First tab (Webcam interface; control the robot from here). */
TabSpec spec1=tabHost.newTabSpec("Main");
spec1.setIndicator("Main");
spec1.setContent(R.id.tab1);
/* Second tab (Lobby interface, contains chat and userlist). */
TabSpec spec2=tabHost.newTabSpec("Lobby");
spec2.setIndicator("Lobby");
spec2.setContent(R.id.tab2);
/* Third tab (Configuration, contains username and server information). */
TabSpec spec3=tabHost.newTabSpec("Config");
spec3.setIndicator("Config");
spec3.setContent(R.id.tab3);
/* Add the tabs to the tabHost. */
tabHost.addTab(spec1);
tabHost.addTab(spec2);
tabHost.addTab(spec3);
/* Instantiate the model and add the view as an observer. */
model = new LobbyModel();
model.addObserver(this);
model.setVersion(getString(R.string.version));
/* Reference to the application's widgets. */
chat = (TextView) findViewById(R.id.chat);
users = (TextView) findViewById(R.id.users);
entry = (EditText) findViewById(R.id.entry);
server = (EditText) findViewById(R.id.server);
port = (EditText) findViewById(R.id.port);
user = (EditText) findViewById(R.id.username);
/* The x,y,z coordinates of the orientation of the phone. */
mTextViewAcc = (TextView) findViewById(R.id.textAcc);
mTextViewMag = (TextView) findViewById(R.id.textMag);
mTextViewOri = (TextView) findViewById(R.id.textOri);
/* Setup the sensor manager. */
// Use these lines if using Android emulator.
//mSensorManager = SensorManagerSimulator.getSystemService(this, SENSOR_SERVICE);
//mSensorManager.connectSimulator();
// Use this line if using phone application.
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
/* Allow scrolling of the chat and user list. */
chat.setMovementMethod(new ScrollingMovementMethod());
users.setMovementMethod(new ScrollingMovementMethod());
lastOrientationUpdate = 0;
/* Initially blank user list. */
userlist = "";
}
/**
* Print a message in the chat lobby.
* @param msg
*/
public void printMessage(final String msg)
{
this.runOnUiThread(new Runnable(){
public void run(){
chat.append(msg + "\n");
if (chat.getLineCount() > MAX_LINES) chat.scrollBy(0, chat.getLineHeight());
}
});
}
/**
* Refreshes the lobby user list.
*/
public void updateUsers()
{
this.runOnUiThread(new Runnable(){
public void run(){
users.setText("");
users.append(userlist);
}
});
}
/**
* Method called whenever a button is pressed.
* Determines which button was pressed by getting the
* view's ID, then act accordingly.
*/
public void buttonClicked(View view)
{
switch (view.getId())
{
/* Connect (to TCP server) button. */
case (R.id.connect):
// Obtain login information.
String username = user.getText().toString();
String address = server.getText().toString();
int portNumber = Integer.parseInt(port.getText().toString());
// Disable the 'Connect' button.
view.setEnabled(false);
// Establish connection.
model.setMyUser(new User(username));
tcp = new TcpClient(model);
tcp.connect(address, portNumber);
break;
/* Send button. */
case (R.id.send):
// Get the text and set the entry field blank.
String message = entry.getText().toString();
entry.setText("");
// Send the message over TCP to the server.
tcp.sendMessage(message);
break;
default:
printMessage("Unknown button pressed.");
}
}
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, SensorManager.SENSOR_ORIENTATION);
}
@Override
protected void onStop() {
mSensorManager.unregisterListener(this);
super.onStop();
}
public void onAccuracyChanged(int sensor, int accuracy) { }
public void onSensorChanged(int sensor, float[] values) {
if(System.currentTimeMillis() - lastOrientationUpdate > ORIENTATION_INTERVAL_MS) {
switch(sensor) {
case SensorManager.SENSOR_ORIENTATION:
mTextViewOri.setText("Orientation: "
+ values[0] + ", "
+ values[1] + ", "
+ values[2]);
if(tcp != null) {
tcp.sendMessage("c:<"
+ values[0] + ","
+ values[1] + ","
+ values[2] + ">");
}
break;
default:
break;
}
lastOrientationUpdate = System.currentTimeMillis();
}
}
/**
* Updates based on changes to the model.
*/
public void update(Observable observable, Object data)
{
// Check for new chat message.
if (model.newChatMessage())
{
printMessage(model.getChatBuffer());
}
// Check for changes in the user list.
if (model.usersUpdated())
{
userlist = model.getUsers();
updateUsers();
}
}
}
|
package org.jgroups;
/**
* Globals used by JGroups packages.
*
* @author Bela Ban Mar 29, 2004
* @version $Id: Global.java,v 1.23 2007/08/21 08:56:26 belaban Exp $
*/
public class Global {
/** Allows for conditional compilation; e.g., if(log.isTraceEnabled()) if(log.isInfoEnabled()) log.info(...) would be removed from the code
(if recompiled) when this flag is set to false. Therefore, code that should be removed from the final
product should use if(log.isTraceEnabled()) rather than .
*/
public static final boolean debug=false;
public static final String THREAD_PREFIX=" (channel=";
public static final int BYTE_SIZE = Byte.SIZE / 8;
public static final int SHORT_SIZE = Short.SIZE / 8;
public static final int INT_SIZE = Integer.SIZE / 8;
public static final int LONG_SIZE = Long.SIZE / 8;
public static final Object NULL=new Object();
public static final String BIND_ADDR="jgroups.bind_addr";
public static final String BIND_ADDR_OLD="bind.address";
public static final String BIND_INTERFACE="jgroups.bind_interface";
public static final String IGNORE_BIND_ADDRESS_PROPERTY="jgroups.ignore.bind_addr";
public static final String IGNORE_BIND_ADDRESS_PROPERTY_OLD="ignore.bind.address";
public static final String MARSHALLING_COMPAT="jgroups.marshalling.compatible";
public static final String TCPPING_INITIAL_HOSTS="jgroups.tcpping.initial_hosts";
public static final String UDP_MCAST_ADDR="jgroups.udp.mcast_addr";
public static final String UDP_MCAST_PORT="jgroups.udp.mcast_port";
public static final String UDP_IP_TTL="jgroups.udp.ip_ttl";
public static final String MPING_MCAST_ADDR="jgroups.mping.mcast_addr";
public static final String MPING_MCAST_PORT="jgroups.mping.mcast_port";
public static final String MPING_IP_TTL="jgroups.mping.ip_ttl";
public static final String MAGIC_NUMBER_FILE="jgroups.conf.magic_number_file";
public static final String RESOLVE_DNS="jgroups.resolve_dns";
public static final String CHANNEL_LOCAL_ADDR_TIMEOUT="jgroups.channel.local_addr_timeout";
public static final String SCHEDULER_MAX_THREADS="jgroups.scheduler.max_threads";
public static final String TIMER_NUM_THREADS="jgroups.timer.num_threads";
public static final String MUX_ENABLED="jgroups.mux.enabled";
public static final String MUX_MIN_THREADS="jgroups.mux.min_threads";
public static final String MUX_MAX_THREADS="jgroups.mux.max_threads";
public static final String MUX_KEEPALIVE="jgroups.mux.keepalive_time";
public static final long THREADPOOL_SHUTDOWN_WAIT_TIME=3000;
public static final long THREAD_SHUTDOWN_WAIT_TIME=300;
public static boolean getPropertyAsBoolean(String property, boolean defaultValue) {
boolean result = defaultValue;
try{
String tmp = System.getProperty(property);
if(tmp != null)
result = Boolean.parseBoolean(tmp);
}catch(Throwable t){
}
return result;
}
public static long getPropertyAsLong(String property, long defaultValue) {
long result = defaultValue;
try{
String tmp = System.getProperty(property);
if(tmp != null)
result = Long.parseLong(tmp);
}catch(Throwable t){
}
return result;
}
public static int getPropertyAsInteger(String property, int defaultValue) {
int result = defaultValue;
try{
String tmp = System.getProperty(property);
if(tmp != null)
result = Integer.parseInt(tmp);
}catch(Throwable t){
}
return result;
}
}
|
package test.beast.beast2vs1;
import beast.core.Logger;
import beast.trace.Expectation;
import beast.trace.LogAnalyser;
import beast.util.Randomizer;
import beast.util.XMLParser;
import junit.framework.TestCase;
import java.util.List;
public abstract class TestFramework extends TestCase {
protected static long SEED = 128;
private String[] xmls;
protected abstract List<Expectation> giveExpectations(int index_XML) throws Exception;
protected void setUp(String[] xmls) throws Exception {
this.xmls = new String[xmls.length];
for (int i = 0; i < xmls.length; i++) {
this.xmls[i] = xmls[i];
}
}
// protected abstract void analyse() throws Exception;
protected void analyse(int index_XML) throws Exception {
// for (int i = 0; i < xmls.length; i++) {
// if (giveExpectations(i).size() > 0) {
Randomizer.setSeed(SEED);
Logger.FILE_MODE = Logger.FILE_OVERWRITE;
String sDir = System.getProperty("user.dir");
String sFileName = sDir + "/examples/beast2vs1/" + xmls[index_XML];
System.out.println("Processing " + sFileName);
XMLParser parser = new XMLParser();
beast.core.Runnable runable = parser.parseFile(sFileName);
runable.setStateFile("tmp.state", false);
// runable.setInputValue("preBurnin", 0);
// runable.setInputValue("chainLength", 1000);
runable.run();
String logFile = sDir + "/test." + SEED + ".log";
System.out.println("\nAnalysing log " + logFile);
LogAnalyser logAnalyser = new LogAnalyser(logFile, giveExpectations(index_XML)); // burnIn = 0.1 * maxState
for (Expectation expectation : logAnalyser.m_pExpectations.get()) {
TestCase.assertTrue(xmls[index_XML] + ": Expected " + expectation.traceName.get() + " delta mean: "
+ expectation.expValue.get() + " - " + expectation.getTraceStatistics().getMean()
+ " <= delta stdErr: 2*(" + expectation.getStdError() + " + "
+ expectation.getTraceStatistics().getStdErrorOfMean() + ")", expectation.isPassed());
TestCase.assertTrue(xmls[index_XML] + ": has very low effective sample sizes (ESS) "
+ expectation.getTraceStatistics().getESS(), expectation.isValid());
}
System.out.println("\nSucceed " + sFileName);
System.out.println("\n***************************************\n");
}
protected void addExpIntoList(List<Expectation> expList, String traceName, Double expValue, Double stdError) throws Exception {
Expectation exp = new Expectation(traceName, expValue, stdError);
expList.add(exp);
}
}
|
package BehaviorTests;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.nio.client.HttpAsyncClient;
import org.json.JSONObject;
import org.junit.Ignore;
import unirest.Unirest;
import org.junit.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.IntStream;
import static junit.framework.TestCase.assertNotSame;
import static junit.framework.TestCase.assertSame;
import static org.junit.Assert.assertEquals;
public class DefectTest extends BddTest {
@Test
public void hashOnLinksDoNotMessUpUri() {
Unirest.get(MockServer.GET + "?a=1&b=2#some_location")
.asObject(RequestCapture.class)
.getBody()
.assertParam("a", "1")
.assertParam("b", "2");
}
@Test
public void nullAndObjectValuesInMap() {
Map<String, Object> queryParams = new HashMap<>();
queryParams.put("foo", null);
queryParams.put("baz", "qux");
Unirest.get(MockServer.GET)
.queryString(queryParams)
.asObject(RequestCapture.class)
.getBody()
.assertParam("foo", "")
.assertParam("baz", "qux")
.assertQueryString("foo&baz=qux");
}
@Test
public void issue_41_IllegalThreadStateExceptionUnderHighLoad() throws IOException {
Unirest.get(MockServer.GET).asStringAsync();
HttpAsyncClient first = Unirest.config().getAsyncHttpClient();
IntStream.range(1, 50).forEach(i ->{
assertSame(first, Unirest.config().getAsyncHttpClient());
});
((CloseableHttpAsyncClient)Unirest.config().getAsyncHttpClient()).close();
Unirest.get(MockServer.GET).asStringAsync();
HttpAsyncClient second = Unirest.config().getAsyncHttpClient();
assertNotSame(first, second);
IntStream.range(1, 50).forEach(i ->{
assertSame(second, Unirest.config().getAsyncHttpClient());
});
}
@Test @Ignore
public void trySomeoneElsesGZip() throws Exception {
JSONObject body = Unirest.get("http://httpbin.org/gzip")
.asJsonAsync().get().getBody().getObject();
assertEquals(true, body.getBoolean("gzipped"));
assertEquals("gzip", body.getJSONObject("headers").getString("Accept-Encoding"));
}
}
|
import static org.junit.Assert.*;
import java.io.IOException;
import java.util.ArrayList;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import de.ids_mannheim.korap.query.serialize.QuerySerializer;
import de.ids_mannheim.korap.util.QueryException;
public class PoliqarpPlusTreeJSONTest {
String map;
String expected;
String metaExpected;
String metaMap;
String query;
ArrayList<JsonNode> operands;
QuerySerializer qs = new QuerySerializer();
ObjectMapper mapper = new ObjectMapper();
JsonNode res;
@Test
public void testContext() throws QueryException, JsonProcessingException, IOException {
query = "foo";
String contextString = "http://ids-mannheim.de/ns/KorAP/json-ld/v0.2/context.jsonld";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals(contextString, res.get("@context").asText());
}
@Test
public void testSingleTokens() throws QueryException, JsonProcessingException, IOException {
query = "[base=Mann]";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:token", res.at("/query/@type").asText());
assertEquals("Mann", res.at("/query/wrap/key").asText());
assertEquals("lemma", res.at("/query/wrap/layer").asText());
assertEquals("match:eq", res.at("/query/wrap/match").asText());
query = "[orth!=Frau]";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:token", res.at("/query/@type").asText());
assertEquals("Frau", res.at("/query/wrap/key").asText());
assertEquals("orth", res.at("/query/wrap/layer").asText());
assertEquals("match:ne", res.at("/query/wrap/match").asText());
query = "[p!=NN]";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:token", res.at("/query/@type").asText());
assertEquals("NN", res.at("/query/wrap/key").asText());
assertEquals("p", res.at("/query/wrap/layer").asText());
assertEquals("match:ne", res.at("/query/wrap/match").asText());
query = "[!p!=NN]";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:token", res.at("/query/@type").asText());
assertEquals("NN", res.at("/query/wrap/key").asText());
assertEquals("p", res.at("/query/wrap/layer").asText());
assertEquals("match:eq", res.at("/query/wrap/match").asText());
query = "[base=schland/x]";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:token", res.at("/query/@type").asText());
assertEquals(".*?schland.*?", res.at("/query/wrap/key").asText());
assertEquals("lemma", res.at("/query/wrap/layer").asText());
assertEquals("type:regex", res.at("/query/wrap/type").asText());
assertEquals("match:eq", res.at("/query/wrap/match").asText());
}
@Test
public void testValue() throws QueryException, JsonProcessingException, IOException {
query = "[mate/m=temp:pres]";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:token", res.at("/query/@type").asText());
assertEquals("korap:term", res.at("/query/wrap/@type").asText());
assertEquals("temp", res.at("/query/wrap/key").asText());
assertEquals("pres", res.at("/query/wrap/value").asText());
assertEquals("m", res.at("/query/wrap/layer").asText());
assertEquals("mate", res.at("/query/wrap/foundry").asText());
assertEquals("match:eq", res.at("/query/wrap/match").asText());
}
@Test
public void testRegex() throws QueryException, JsonProcessingException, IOException {
query = "[orth=\"M(a|ä)nn(er)?\"]";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:token", res.at("/query/@type").asText());
assertEquals("korap:term", res.at("/query/wrap/@type").asText());
assertEquals("M(a|ä)nn(er)?", res.at("/query/wrap/key").asText());
assertEquals("type:regex", res.at("/query/wrap/type").asText());
assertEquals("orth", res.at("/query/wrap/layer").asText());
assertEquals("match:eq", res.at("/query/wrap/match").asText());
query = "[orth=\"M(a|ä)nn(er)?\"/x]";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:token", res.at("/query/@type").asText());
assertEquals("korap:term", res.at("/query/wrap/@type").asText());
assertEquals(".*?M(a|ä)nn(er)?.*?", res.at("/query/wrap/key").asText());
assertEquals("type:regex", res.at("/query/wrap/type").asText());
assertEquals("orth", res.at("/query/wrap/layer").asText());
assertEquals("match:eq", res.at("/query/wrap/match").asText());
query = "\".*?Mann.*?\"";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:token", res.at("/query/@type").asText());
assertEquals("korap:term", res.at("/query/wrap/@type").asText());
assertEquals(".*?Mann.*?", res.at("/query/wrap/key").asText());
assertEquals("type:regex", res.at("/query/wrap/type").asText());
assertEquals("orth", res.at("/query/wrap/layer").asText());
assertEquals("match:eq", res.at("/query/wrap/match").asText());
query = "z.B./x";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:token", res.at("/query/@type").asText());
assertEquals("korap:term", res.at("/query/wrap/@type").asText());
assertEquals(".*?z\\.B\\..*?", res.at("/query/wrap/key").asText());
assertEquals("type:regex", res.at("/query/wrap/type").asText());
assertEquals("orth", res.at("/query/wrap/layer").asText());
assertEquals("match:eq", res.at("/query/wrap/match").asText());
}
@Test
public void testCaseSensitivityFlag() throws QueryException, JsonProcessingException, IOException {
query = "[orth=deutscher/i]";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:token", res.at("/query/@type").asText());
assertEquals("korap:term", res.at("/query/wrap/@type").asText());
assertEquals("deutscher", res.at("/query/wrap/key").asText());
assertEquals("true", res.at("/query/wrap/caseInsensitive").asText());
assertEquals("orth", res.at("/query/wrap/layer").asText());
assertEquals("match:eq", res.at("/query/wrap/match").asText());
query = "deutscher/i";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:token", res.at("/query/@type").asText());
assertEquals("korap:term", res.at("/query/wrap/@type").asText());
assertEquals("deutscher", res.at("/query/wrap/key").asText());
assertEquals("true", res.at("/query/wrap/caseInsensitive").asText());
assertEquals("orth", res.at("/query/wrap/layer").asText());
assertEquals("match:eq", res.at("/query/wrap/match").asText());
query = "deutscher/I";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:token", res.at("/query/@type").asText());
assertEquals("korap:term", res.at("/query/wrap/@type").asText());
assertEquals("deutscher", res.at("/query/wrap/key").asText());
assertEquals("false", res.at("/query/wrap/caseInsensitive").asText());
assertEquals("orth", res.at("/query/wrap/layer").asText());
assertEquals("match:eq", res.at("/query/wrap/match").asText());
query = "[orth=deutscher/i][orth=Bundestag]";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:group", res.at("/query/@type").asText());
assertEquals("operation:sequence", res.at("/query/operation").asText());
operands = Lists.newArrayList(res.at("/query/operands").elements());
assertEquals("korap:token", operands.get(0).at("/@type").asText());
assertEquals("deutscher", operands.get(0).at("/wrap/key").asText());
assertEquals("orth", operands.get(0).at("/wrap/layer").asText());
assertEquals("match:eq", operands.get(0).at("/wrap/match").asText());
assertEquals(true, operands.get(0).at("/wrap/caseInsensitive").asBoolean());
assertEquals("korap:token", operands.get(1).at("/@type").asText());
assertEquals("Bundestag", operands.get(1).at("/wrap/key").asText());
assertEquals("orth", operands.get(1).at("/wrap/layer").asText());
assertEquals("match:eq", operands.get(1).at("/wrap/match").asText());
assertEquals(true, operands.get(1).at("/wrap/caseInsensitive").isMissingNode());
query = "deutscher/i Bundestag";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:group", res.at("/query/@type").asText());
assertEquals("operation:sequence", res.at("/query/operation").asText());
operands = Lists.newArrayList(res.at("/query/operands").elements());
assertEquals("korap:token", operands.get(0).at("/@type").asText());
assertEquals("deutscher", operands.get(0).at("/wrap/key").asText());
assertEquals("orth", operands.get(0).at("/wrap/layer").asText());
assertEquals("match:eq", operands.get(0).at("/wrap/match").asText());
assertEquals(true, operands.get(0).at("/wrap/caseInsensitive").asBoolean());
assertEquals("korap:token", operands.get(1).at("/@type").asText());
assertEquals("Bundestag", operands.get(1).at("/wrap/key").asText());
assertEquals("orth", operands.get(1).at("/wrap/layer").asText());
assertEquals("match:eq", operands.get(1).at("/wrap/match").asText());
assertEquals(true, operands.get(1).at("/wrap/caseInsensitive").isMissingNode());
}
@Test
public void testSpans() throws QueryException, JsonProcessingException, IOException {
query = "<s>";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:span", res.at("/query/@type").asText());
assertEquals("s", res.at("/query/key").asText());
query = "<vp>";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:span", res.at("/query/@type").asText());
assertEquals("vp", res.at("/query/key").asText());
query = "<cnx/c=vp>";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:span", res.at("/query/@type").asText());
assertEquals("vp", res.at("/query/key").asText());
assertEquals("cnx", res.at("/query/foundry").asText());
assertEquals("c", res.at("/query/layer").asText());
query = "<cnx/c!=vp>";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:span", res.at("/query/@type").asText());
assertEquals("vp", res.at("/query/key").asText());
assertEquals("cnx", res.at("/query/foundry").asText());
assertEquals("c", res.at("/query/layer").asText());
assertEquals("match:ne", res.at("/query/match").asText());
query = "<cnx/c!=vp class!=header>";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:span", res.at("/query/@type").asText());
assertEquals("vp", res.at("/query/key").asText());
assertEquals("cnx", res.at("/query/foundry").asText());
assertEquals("c", res.at("/query/layer").asText());
assertEquals("match:ne", res.at("/query/match").asText());
assertEquals("class", res.at("/query/attr/key").asText());
assertEquals("header", res.at("/query/attr/value").asText());
assertEquals("match:ne", res.at("/query/attr/match").asText());
query = "<cnx/c!=vp !(class!=header)>";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:span", res.at("/query/@type").asText());
assertEquals("vp", res.at("/query/key").asText());
assertEquals("cnx", res.at("/query/foundry").asText());
assertEquals("c", res.at("/query/layer").asText());
assertEquals("match:ne", res.at("/query/match").asText());
assertEquals("class", res.at("/query/attr/key").asText());
assertEquals("header", res.at("/query/attr/value").asText());
assertEquals("match:eq", res.at("/query/attr/match").asText());
query = "<cnx/c!=vp !(class=header & id=7)>";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:span", res.at("/query/@type").asText());
assertEquals("vp", res.at("/query/key").asText());
assertEquals("cnx", res.at("/query/foundry").asText());
assertEquals("c", res.at("/query/layer").asText());
assertEquals("match:ne", res.at("/query/match").asText());
assertEquals("korap:termGroup", res.at("/query/attr/@type").asText());
assertEquals("relation:and", res.at("/query/attr/relation").asText());
operands = Lists.newArrayList( res.at("/query/attr/operands").elements());
assertEquals("korap:term", operands.get(0).at("/@type").asText());
assertEquals("class", operands.get(0).at("/key").asText());
assertEquals("header", operands.get(0).at("/value").asText());
assertEquals("match:ne", operands.get(0).at("/match").asText());
assertEquals("korap:term", operands.get(1).at("/@type").asText());
assertEquals("id", operands.get(1).at("/key").asText());
assertEquals(7, operands.get(1).at("/value").asInt());
assertEquals("match:ne", operands.get(1).at("/match").asText());
}
@Test
public void testDistances() throws QueryException, JsonProcessingException, IOException {
query = "[base=der][][base=Mann]";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:group", res.at("/query/@type").asText());
assertEquals("operation:sequence", res.at("/query/operation").asText());
assertEquals("true", res.at("/query/inOrder").asText());
assertEquals("korap:distance", res.at("/query/distances").elements().next().at("/@type").asText());
assertEquals("w", res.at("/query/distances").elements().next().at("/key").asText());
assertEquals("korap:boundary", res.at("/query/distances").elements().next().at("/boundary/@type").asText());
assertEquals(2, res.at("/query/distances").elements().next().at("/boundary/min").asInt());
assertEquals(2, res.at("/query/distances").elements().next().at("/boundary/max").asInt());
operands = Lists.newArrayList(res.at("/query/operands").elements());
assertEquals("korap:token", operands.get(0).at("/@type").asText());
assertEquals("der", operands.get(0).at("/wrap/key").asText());
assertEquals("lemma", operands.get(0).at("/wrap/layer").asText());
assertEquals("match:eq", operands.get(0).at("/wrap/match").asText());
assertEquals("korap:token", operands.get(1).at("/@type").asText());
assertEquals("Mann", operands.get(1).at("/wrap/key").asText());
assertEquals("lemma", operands.get(1).at("/wrap/layer").asText());
assertEquals("match:eq", operands.get(1).at("/wrap/match").asText());
query = "[base=der][][][base=Mann]";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:group", res.at("/query/@type").asText());
assertEquals("operation:sequence", res.at("/query/operation").asText());
assertEquals("true", res.at("/query/inOrder").asText());
assertEquals("korap:distance", res.at("/query/distances").elements().next().at("/@type").asText());
assertEquals("w", res.at("/query/distances").elements().next().at("/key").asText());
assertEquals("korap:boundary", res.at("/query/distances").elements().next().at("/boundary/@type").asText());
assertEquals(3, res.at("/query/distances").elements().next().at("/boundary/min").asInt());
assertEquals(3, res.at("/query/distances").elements().next().at("/boundary/max").asInt());
operands = Lists.newArrayList(res.at("/query/operands").elements());
assertEquals("korap:token", operands.get(0).at("/@type").asText());
assertEquals("der", operands.get(0).at("/wrap/key").asText());
assertEquals("lemma", operands.get(0).at("/wrap/layer").asText());
assertEquals("match:eq", operands.get(0).at("/wrap/match").asText());
assertEquals("korap:token", operands.get(1).at("/@type").asText());
assertEquals("Mann", operands.get(1).at("/wrap/key").asText());
assertEquals("lemma", operands.get(1).at("/wrap/layer").asText());
assertEquals("match:eq", operands.get(1).at("/wrap/match").asText());
query = "[base=der][][]?[base=Mann]";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:group", res.at("/query/@type").asText());
assertEquals("operation:sequence", res.at("/query/operation").asText());
assertEquals("true", res.at("/query/inOrder").asText());
assertEquals("korap:distance", res.at("/query/distances").elements().next().at("/@type").asText());
assertEquals("w", res.at("/query/distances").elements().next().at("/key").asText());
assertEquals("korap:boundary", res.at("/query/distances").elements().next().at("/boundary/@type").asText());
assertEquals(2, res.at("/query/distances").elements().next().at("/boundary/min").asInt());
assertEquals(3, res.at("/query/distances").elements().next().at("/boundary/max").asInt());
operands = Lists.newArrayList(res.at("/query/operands").elements());
assertEquals("korap:token", operands.get(0).at("/@type").asText());
assertEquals("der", operands.get(0).at("/wrap/key").asText());
assertEquals("lemma", operands.get(0).at("/wrap/layer").asText());
assertEquals("match:eq", operands.get(0).at("/wrap/match").asText());
assertEquals("korap:token", operands.get(1).at("/@type").asText());
assertEquals("Mann", operands.get(1).at("/wrap/key").asText());
assertEquals("lemma", operands.get(1).at("/wrap/layer").asText());
assertEquals("match:eq", operands.get(1).at("/wrap/match").asText());
query = "[base=der][]+[base=Mann]";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:group", res.at("/query/@type").asText());
assertEquals("operation:sequence", res.at("/query/operation").asText());
assertEquals("true", res.at("/query/inOrder").asText());
assertEquals("korap:distance", res.at("/query/distances").elements().next().at("/@type").asText());
assertEquals("w", res.at("/query/distances").elements().next().at("/key").asText());
assertEquals("korap:boundary", res.at("/query/distances").elements().next().at("/boundary/@type").asText());
assertEquals(2, res.at("/query/distances").elements().next().at("/boundary/min").asInt());
assertEquals(true, res.at("/query/distances").elements().next().at("/boundary/max").isMissingNode());
operands = Lists.newArrayList(res.at("/query/operands").elements());
assertEquals("korap:token", operands.get(0).at("/@type").asText());
assertEquals("der", operands.get(0).at("/wrap/key").asText());
assertEquals("lemma", operands.get(0).at("/wrap/layer").asText());
assertEquals("match:eq", operands.get(0).at("/wrap/match").asText());
assertEquals("korap:token", operands.get(1).at("/@type").asText());
assertEquals("Mann", operands.get(1).at("/wrap/key").asText());
assertEquals("lemma", operands.get(1).at("/wrap/layer").asText());
assertEquals("match:eq", operands.get(1).at("/wrap/match").asText());
query = "[base=der][]*[base=Mann]";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:group", res.at("/query/@type").asText());
assertEquals("operation:sequence", res.at("/query/operation").asText());
assertEquals("true", res.at("/query/inOrder").asText());
assertEquals("korap:distance", res.at("/query/distances").elements().next().at("/@type").asText());
assertEquals("w", res.at("/query/distances").elements().next().at("/key").asText());
assertEquals("korap:boundary", res.at("/query/distances").elements().next().at("/boundary/@type").asText());
assertEquals(1, res.at("/query/distances").elements().next().at("/boundary/min").asInt());
assertEquals(true, res.at("/query/distances").elements().next().at("/boundary/max").isMissingNode());
query = "[base=der][]{2,5}[base=Mann][]?[][base=Frau]";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:group", res.at("/query/@type").asText());
assertEquals("operation:sequence", res.at("/query/operation").asText());
assertEquals("true", res.at("/query/inOrder").asText());
assertEquals("korap:distance", res.at("/query/distances").elements().next().at("/@type").asText());
assertEquals("w", res.at("/query/distances").elements().next().at("/key").asText());
assertEquals("korap:boundary", res.at("/query/distances").elements().next().at("/boundary/@type").asText());
assertEquals(3, res.at("/query/distances").elements().next().at("/boundary/min").asInt());
assertEquals(6, res.at("/query/distances").elements().next().at("/boundary/max").asInt());
operands = Lists.newArrayList(res.at("/query/operands").elements());
assertEquals("korap:token", operands.get(0).at("/@type").asText());
assertEquals("der", operands.get(0).at("/wrap/key").asText());
assertEquals("lemma", operands.get(0).at("/wrap/layer").asText());
assertEquals("match:eq", operands.get(0).at("/wrap/match").asText());
assertEquals("korap:group", operands.get(1).at("/@type").asText());
assertEquals("operation:sequence", operands.get(1).at("/operation").asText());
assertEquals("korap:distance", operands.get(1).get("distances").elements().next().at("/@type").asText());
assertEquals("w", operands.get(1).get("distances").elements().next().at("/key").asText());
assertEquals("korap:boundary", operands.get(1).get("distances").elements().next().at("/boundary/@type").asText());
assertEquals(2, operands.get(1).get("distances").elements().next().at("/boundary/min").asInt());
assertEquals(3, operands.get(1).get("distances").elements().next().at("/boundary/max").asInt());
operands = Lists.newArrayList(operands.get(1).get("operands").elements());
assertEquals("Mann", operands.get(0).at("/wrap/key").asText());
assertEquals("lemma", operands.get(0).at("/wrap/layer").asText());
assertEquals("match:eq", operands.get(0).at("/wrap/match").asText());
assertEquals("Frau", operands.get(1).at("/wrap/key").asText());
assertEquals("lemma", operands.get(1).at("/wrap/layer").asText());
assertEquals("match:eq", operands.get(1).at("/wrap/match").asText());
query = "[base=geht][base=der][]*contains(<s>,<np>)";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:group", res.at("/query/@type").asText());
assertEquals("operation:sequence", res.at("/query/operation").asText());
assertEquals(true, res.at("/query/inOrder").isMissingNode());
assertEquals(true, res.at("/query/distances").isMissingNode());
operands = Lists.newArrayList(res.at("/query/operands").elements());
assertEquals("korap:token", operands.get(0).at("/@type").asText());
assertEquals("geht", operands.get(0).at("/wrap/key").asText());
assertEquals("lemma", operands.get(0).at("/wrap/layer").asText());
assertEquals("match:eq", operands.get(0).at("/wrap/match").asText());
assertEquals("korap:group", operands.get(1).at("/@type").asText());
assertEquals("operation:sequence", operands.get(1).at("/operation").asText());
assertEquals("korap:distance", operands.get(1).get("distances").elements().next().at("/@type").asText());
assertEquals("w", operands.get(1).get("distances").elements().next().at("/key").asText());
assertEquals("korap:boundary", operands.get(1).get("distances").elements().next().at("/boundary/@type").asText());
assertEquals(1, operands.get(1).get("distances").elements().next().at("/boundary/min").asInt());
assertEquals(true, operands.get(1).get("distances").elements().next().at("/boundary/max").isMissingNode());
operands = Lists.newArrayList(operands.get(1).get("operands").elements());
assertEquals("der", operands.get(0).at("/wrap/key").asText());
assertEquals("lemma", operands.get(0).at("/wrap/layer").asText());
assertEquals("match:eq", operands.get(0).at("/wrap/match").asText());
assertEquals("korap:group", operands.get(1).at("/@type").asText());
assertEquals("operation:position", operands.get(1).at("/operation").asText());
}
@Test
public void testDistancesWithClass() throws QueryException, JsonProcessingException, IOException {
query = "[base=der]{[]}[base=Mann]";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
assertEquals("korap:group", res.at("/query/@type").asText());
assertEquals("operation:sequence", res.at("/query/operation").asText());
assertEquals(true, res.at("/query/inOrder").isMissingNode());
assertEquals(true, res.at("/query/distances").isMissingNode());
operands = Lists.newArrayList(res.at("/query/operands").elements());
assertEquals("der", operands.get(0).at("/wrap/key").asText());
assertEquals("Mann", operands.get(2).at("/wrap/key").asText());
assertEquals("korap:group", operands.get(1).at("/@type").asText());
assertEquals("operation:class", operands.get(1).at("/operation").asText());
assertEquals(1, operands.get(1).at("/classOut").asInt());
operands = Lists.newArrayList(operands.get(1).at("/operands").elements());
assertEquals("korap:token", operands.get(0).at("/@type").asText());
assertEquals(true, operands.get(0).at("/wrap").isMissingNode());
query = "[base=der]{2:[]}[base=Mann]";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
operands = Lists.newArrayList(res.at("/query/operands").elements());
assertEquals("operation:class", operands.get(1).at("/operation").asText());
assertEquals(2, operands.get(1).at("/classOut").asInt());
query = "{1:[]}[base=der][base=Mann]";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
operands = Lists.newArrayList(res.at("/query/operands").elements());
assertEquals("operation:class", operands.get(0).at("/operation").asText());
assertEquals(1, operands.get(0).at("/classOut").asInt());
}
@Test
public void testLeadingTrailingEmptyTokens() throws QueryException, JsonProcessingException, IOException {
query = "[][base=Mann]";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
operands = Lists.newArrayList(res.at("/query/operands").elements());
assertEquals("korap:token", operands.get(0).at("/@type").asText());
assertEquals(true, operands.get(0).at("/key").isMissingNode());
query = "[][][base=Mann]";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
operands = Lists.newArrayList(res.at("/query/operands").elements());
assertEquals("korap:group", operands.get(0).at("/@type").asText());
assertEquals("operation:repetition",operands.get(0).at("/operation").asText());
assertEquals(2, operands.get(0).at("/boundary/min").asInt());
assertEquals(2, operands.get(0).at("/boundary/max").asInt());
operands = Lists.newArrayList(operands.get(0).at("/operands").elements());
assertEquals("korap:token", operands.get(0).at("/@type").asText());
assertEquals(true, operands.get(0).at("/key").isMissingNode());
query = "startswith(<s>, [][base=Mann])";
qs.setQuery(query, "poliqarpplus");
res = mapper.readTree(qs.toJSON());
operands = Lists.newArrayList(res.at("/query/operands"));
operands = Lists.newArrayList(operands.get(1).at("/operands"));
assertEquals("korap:token", operands.get(0).at("/@type").asText());
assertEquals(true, operands.get(0).at("/key").isMissingNode());
}
// @Test
// public void testCoordinatedFields() throws QueryException {
// // [base=Mann&(cas=N|cas=A)]
// String cof1 =
// "{@type=korap:token, wrap=" +
// "{@type=korap:termGroup, relation=relation:and, operands=[" +
// "{@type=korap:term, layer=lemma, key=Mann, match=match:eq}," +
// "{@type=korap:termGroup, relation=relation:or, operands=[" +
// "{@type=korap:term, layer=cas, key=N, match=match:eq}," +
// "{@type=korap:term, layer=cas, key=A, match=match:eq}" +
// ppt = new PoliqarpPlusTree("[base=Mann&(cas=N|cas=A)]");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(cof1.replaceAll(" ", ""), map.replaceAll(" ", ""));
// assertEquals(
// new PoliqarpPlusTree(" [ base=Mann & ( cas=N | cas=A)] ").getRequestMap().get("query").toString(),
// new PoliqarpPlusTree("[base=Mann &(cas=N|cas=A)]").getRequestMap().get("query").toString()
// // [base=Mann&cas=N&gen=m]
// String cof2 =
// "{@type=korap:token, wrap=" +
// "{@type=korap:termGroup, relation=relation:and, operands=[" +
// "{@type=korap:term, layer=lemma, key=Mann, match=match:eq}," +
// "{@type=korap:termGroup, relation=relation:and, operands=[" +
// "{@type=korap:term, layer=cas, key=N, match=match:eq}," +
// "{@type=korap:term, layer=gen, key=m, match=match:eq}" +
// ppt = new PoliqarpPlusTree("[base=Mann&cas=N&gen=m]");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(cof2.replaceAll(" ", ""), map.replaceAll(" ", ""));
// @Test
// public void testOccurrence() throws QueryException {
// // [base=foo]*
// String occ1 = "{@type=korap:group, operation=operation:repetition, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=foo, match=match:eq}}" +
// "], boundary={@type=korap:boundary, min=0}, min=0}";
// ppt = new PoliqarpPlusTree("[base=foo]*");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(occ1.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // [base=foo]*[base=bar]
// String occ2 =
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:group, operation=operation:repetition, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=foo, match=match:eq}}" +
// "], boundary={@type=korap:boundary, min=0}, min=0 }," +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=bar, match=match:eq}}" +
// ppt = new PoliqarpPlusTree("[base=foo]*[base=bar]");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(occ2.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // [base=bar][base=foo]*
// String occ3 =
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=bar, match=match:eq}}," +
// "{@type=korap:group, operation=operation:repetition, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=foo, match=match:eq}}" +
// "], boundary={@type=korap:boundary, min=0}, min=0 }" +
// ppt = new PoliqarpPlusTree("[base=bar][base=foo]*");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(occ3.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // ([base=bar][base=foo])*
// String occ4 =
// "{@type=korap:group, operation=operation:repetition, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=bar, match=match:eq}}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=foo, match=match:eq}}" +
// "], boundary={@type=korap:boundary, min=0}, min=0}" ;
// ppt = new PoliqarpPlusTree("([base=bar][base=foo])*");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(occ4.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // <s>([base=bar][base=foo])*
// String occ5 =
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:span, key=s}," +
// "{@type=korap:group, operation=operation:repetition, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=bar, match=match:eq}}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=foo, match=match:eq}}" +
// "], boundary={@type=korap:boundary, min=0}, min=0 }" +
// ppt = new PoliqarpPlusTree("<s>([base=bar][base=foo])*");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(occ5.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // <s><np>([base=bar][base=foo])*
// String occ6 =
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:span, key=s}," +
// "{@type=korap:span, key=np}," +
// "{@type=korap:group, operation=operation:repetition, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=bar, match=match:eq}}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=foo, match=match:eq}}" +
// "], boundary={@type=korap:boundary, min=0}, min=0 }" +
// ppt = new PoliqarpPlusTree("<s><np>([base=bar][base=foo])*");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(occ6.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // <s><np>([base=bar][base=foo])*[p=NN]
// // comment: embedded sequence shouldn't really be here, but does not really hurt, either. (?)
// // really hard to get this behaviour out of the PQPlus grammar...
// String occ7 =
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:span, key=s}," +
// "{@type=korap:span, key=np}," +
// "{@type=korap:group, operation=operation:repetition, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=bar, match=match:eq}}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=foo, match=match:eq}}" +
// "], boundary={@type=korap:boundary, min=0}, min=0 }," +
// "{@type=korap:token, wrap={@type=korap:term, layer=p, key=NN, match=match:eq}}" +
// ppt = new PoliqarpPlusTree("<s><np>([base=bar][base=foo])*[p=NN]");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(occ7.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // ([base=bar][base=foo])*[p=NN]
// String occ8 =
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:group, operation=operation:repetition, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=bar, match=match:eq}}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=foo, match=match:eq}}" +
// "], boundary={@type=korap:boundary, min=0}, min=0 }," +
// "{@type=korap:token, wrap={@type=korap:term, layer=p, key=NN, match=match:eq}}" +
// ppt = new PoliqarpPlusTree("([base=bar][base=foo])*[p=NN]");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(occ8.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // [base=foo]+
// String occ9 = "{@type=korap:group, operation=operation:repetition, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=foo, match=match:eq}}" +
// "], boundary={@type=korap:boundary, min=1}, min=1}";
// ppt = new PoliqarpPlusTree("[base=foo]+");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(occ9.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // [base=foo]?
// String occ10 = "{@type=korap:group, operation=operation:repetition, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=foo, match=match:eq}}" +
// "], boundary={@type=korap:boundary, min=0, max=1}, min=0, max=1}";
// ppt = new PoliqarpPlusTree("[base=foo]?");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(occ10.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // [base=foo]{2,5}
// String occ11 = "{@type=korap:group, operation=operation:repetition, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=foo, match=match:eq}}" +
// "], boundary={@type=korap:boundary, min=2, max=5}, min=2, max=5}";
// ppt = new PoliqarpPlusTree("[base=foo]{2,5}");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(occ11.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // [base=foo]{2}
// String occ12 = "{@type=korap:group, operation=operation:repetition, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=foo, match=match:eq}}" +
// "], boundary={@type=korap:boundary, min=2, max=2}, min=2, max=2}";
// ppt = new PoliqarpPlusTree("[base=foo]{2}");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(occ12.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // [base=foo]{2}
// String occ13 = "{@type=korap:group, operation=operation:repetition, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=foo, match=match:eq}}" +
// "], boundary={@type=korap:boundary, min=2}, min=2}";
// ppt = new PoliqarpPlusTree("[base=foo]{2,}");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(occ13.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // [base=foo]{2}
// String occ14 = "{@type=korap:group, operation=operation:repetition, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=foo, match=match:eq}}" +
// "], boundary={@type=korap:boundary, min=0, max=2}, min=0, max=2}";
// ppt = new PoliqarpPlusTree("[base=foo]{,2}");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(occ14.replaceAll(" ", ""), map.replaceAll(" ", ""));
// @Test
// public void testTokenSequence() throws QueryException {
// // [base=Mann][orth=Frau]
// String seq1 = "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Mann, match=match:eq}}, " +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Frau, match=match:eq}}" +
// assertTrue(equalsQueryContent(seq1, "[base=Mann][orth=Frau]"));
// // [base=Mann][orth=Frau][p=NN]
// String seq2 = "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Mann, match=match:eq}}, " +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Frau, match=match:eq}}, " +
// "{@type=korap:token, wrap={@type=korap:term, layer=p, key=NN, match=match:eq}}" +
// assertTrue(equalsQueryContent(seq2, "[base=Mann][orth=Frau][p=NN]"));
// @Test
// public void testDisjSegments() throws QueryException {
// // ([base=der]|[base=das])[base=Schild]
// String disj1 =
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:group, operation=operation:or, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=der, match=match:eq}}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=das, match=match:eq}}" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Schild, match=match:eq}}" +
// ppt = new PoliqarpPlusTree("([base=der]|[base=das])[base=Schild]");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(disj1.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // [base=Schild]([base=der]|[base=das])
// String disj2 =
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Schild, match=match:eq}}," +
// "{@type=korap:group, operation=operation:or, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=der, match=match:eq}}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=das, match=match:eq}}" +
// ppt = new PoliqarpPlusTree("[base=Schild]([base=der]|[base=das])");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(disj2.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // "([orth=der][base=katze])|([orth=eine][base=baum])"
// String disj3 =
// "{@type=korap:group, operation=operation:or, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=der, match=match:eq}}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=katze, match=match:eq}}" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=eine, match=match:eq}}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=baum, match=match:eq}}" +
// ppt = new PoliqarpPlusTree("([orth=der][base=katze])|([orth=eine][base=baum])");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(disj3.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // "[orth=der][base=katze]|[orth=eine][base=baum]"
// String disj4 =
// "{@type=korap:group, operation=operation:or, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=der, match=match:eq}}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=katze, match=match:eq}}" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=eine, match=match:eq}}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=baum, match=match:eq}}" +
// ppt = new PoliqarpPlusTree("[orth=der][base=katze]|[orth=eine][base=baum]");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(disj4.replaceAll(" ", ""), map.replaceAll(" ", ""));
// PoliqarpPlusTree ppt1 = new PoliqarpPlusTree("[orth=der][base=katze]|[orth=eine][base=baum]");
// PoliqarpPlusTree ppt2 = new PoliqarpPlusTree("([orth=der][base=katze])|([orth=eine][base=baum])");
// assertEquals(ppt1.getRequestMap().toString(), ppt2.getRequestMap().toString());
// // "[orth=der][base=katze]|[orth=der][base=hund]|[orth=der][base=baum]"
// String disj5 =
// "{@type=korap:group, operation=operation:or, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=der, match=match:eq}}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=katze, match=match:eq}}" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=der, match=match:eq}}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=hund, match=match:eq}}" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=der, match=match:eq}}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=baum, match=match:eq}}" +
// ppt = new PoliqarpPlusTree("[orth=der][base=katze]|[orth=der][base=hund]|[orth=der][base=baum]");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(disj5.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // [orth=der]([base=katze]|[base=hund]|[base=baum])
// String disj6 =
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=der, match=match:eq}}," +
// "{@type=korap:group, operation=operation:or, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=katze, match=match:eq}}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=hund, match=match:eq}}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=baum, match=match:eq}}" +
// ppt = new PoliqarpPlusTree("[orth=der]([base=katze]|[base=hund]|[base=baum])");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(disj6.replaceAll(" ", ""), map.replaceAll(" ", ""));
// @Test
// public void testTokenElemSequence() throws QueryException {
// // [base=Mann]<vp>
// String seq1 = "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Mann, match=match:eq}}, " +
// "{@type=korap:span, key=vp}" +
// assertTrue(equalsQueryContent(seq1, "[base=Mann]<vp>"));
// // <vp>[base=Mann]
// String seq2 = "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:span, key=vp}, "+
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Mann, match=match:eq}} " +
// assertTrue(equalsQueryContent(seq2, "<vp>[base=Mann]"));
// // <vp>[base=Mann]<pp>
// String seq3 = "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:span, key=vp}, "+
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Mann, match=match:eq}}, " +
// "{@type=korap:span, key=pp} "+
// assertTrue(equalsQueryContent(seq3, "<vp>[base=Mann]<pp>"));
// @Test
// public void testElemSequence() throws QueryException {
// // <np><vp>
// String seq1 = "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:span, key=np}," +
// "{@type=korap:span, key=vp}" +
// assertTrue(equalsQueryContent(seq1, "<np><vp>"));
// // <np><vp><pp>
// String seq2 = "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:span, key=np}," +
// "{@type=korap:span, key=vp}," +
// "{@type=korap:span, key=pp}" +
// assertTrue(equalsQueryContent(seq2, "<np><vp><pp>"));
// @Test
// public void testClasses() throws QueryException {
// String query;
// // {[base=Mann]}
// String cls1 = "{@type=korap:group, operation=operation:class, class=0, classOut=0, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Mann, match=match:eq}}" +
// ppt = new PoliqarpPlusTree("{[base=Mann]}");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(cls1.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // {[base=Mann][orth=Frau]}
// query = "{[base=Mann][orth=Frau]}";
// String cls2 = "{@type=korap:group, operation=operation:class, class=0, classOut=0, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Mann, match=match:eq}}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Frau, match=match:eq}}" +
// ppt = new PoliqarpPlusTree(query);
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(cls2.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // [p=NN]{[base=Mann][orth=Frau]}
// String cls3 = "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=p, key=NN, match=match:eq}}," +
// "{@type=korap:group, operation=operation:class, class=0, classOut=0, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Mann, match=match:eq}}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Frau, match=match:eq}}" +
// ppt = new PoliqarpPlusTree("[p=NN]{[base=Mann][orth=Frau]}");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(cls3.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // {[base=Mann][orth=Frau]}[p=NN]
// String cls4 = "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:group, operation=operation:class, class=0, classOut=0, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Mann, match=match:eq}}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Frau, match=match:eq}}" +
// "{@type=korap:token, wrap={@type=korap:term, layer=p, key=NN, match=match:eq}}" +
// ppt = new PoliqarpPlusTree("{[base=Mann][orth=Frau]}[p=NN]");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(cls4.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // {2:{1:[tt/p=ADJA]}[mate/p=NN]}"
// String cls5 = "{@type=korap:group, operation=operation:class, class=2, classOut=2, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:group, operation=operation:class, class=1, classOut=1, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, foundry=tt, layer=p, key=ADJA, match=match:eq}}" +
// "{@type=korap:token, wrap={@type=korap:term, foundry=mate, layer=p, key=NN, match=match:eq}}" +
// ppt = new PoliqarpPlusTree("{2: {1:[tt/p=ADJA]}[mate/p=NN]}");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(cls5.replaceAll(" ", ""), map.replaceAll(" ", ""));
// @Test
// public void testPositions() throws QueryException {
// // contains(<s>,<np>)
// String pos1 = "{@type=korap:group, operation=operation:position, frames=[frames:contains], operands=[" +
// "{@type=korap:span, key=s}," +
// "{@type=korap:span, key=np}" +
// "], frame=frame:contains}";
// assertTrue(equalsQueryContent(pos1, "contains(<s>,<np>)"));
// // contains(<s>,[base=Mann])
// String pos2 = "{@type=korap:group, operation=operation:position, frames=[frames:contains], operands=[" +
// "{@type=korap:span, key=s}," +
// "{@type=korap:token, wrap= {@type=korap:term, layer=lemma, key=Mann, match=match:eq}}" +
// "], frame=frame:contains}";
// assertTrue(equalsQueryContent(pos2, "contains(<s>,[base=Mann])"));
// // contains(<s>,[orth=der][orth=Mann])
// String pos3 = "{@type=korap:group, operation=operation:position, frames=[frames:contains], operands=[" +
// "{@type=korap:span, key=s}," +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=der, match=match:eq}}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Mann, match=match:eq}}" +
// "], frame=frame:contains}";
// ppt = new PoliqarpPlusTree("contains(<s>,[orth=der][orth=Mann])");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(pos3.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // [base=Auto]contains(<s>,[base=Mann])
// String pos4 =
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Auto, match=match:eq}}," +
// "{@type=korap:group, operation=operation:position, frames=[frames:contains], operands=[" +
// "{@type=korap:span, key=s}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Mann, match=match:eq}}" +
// "], frame=frame:contains}" +
// ppt = new PoliqarpPlusTree("[base=Auto]contains(<s>,[base=Mann])");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(pos4.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // contains(<s>,[pos=N]*)
// String pos5 =
// "{@type=korap:group, operation=operation:position, frames=[frames:contains], operands=[" +
// "{@type=korap:span, key=s}," +
// "{@type=korap:group, operation=operation:repetition, " +
// "operands=[{@type=korap:token, wrap={@type=korap:term, layer=pos, key=N, match=match:eq}}" +
// "], boundary={@type=korap:boundary, min=0}, min=0" +
// "], frame=frame:contains}";
// ppt = new PoliqarpPlusTree("contains(<s>,[pos=N]*)");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(pos5.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // [base=Auto]contains(<s>,[pos=N]*)
// String pos6 =
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Auto, match=match:eq}}," +
// "{@type=korap:group, operation=operation:position, frames=[frames:contains], operands=[" +
// "{@type=korap:span, key=s}," +
// "{@type=korap:group, operation=operation:repetition, " +
// "operands=[{@type=korap:token, wrap={@type=korap:term, layer=pos, key=N, match=match:eq}}" +
// "], boundary={@type=korap:boundary, min=0}, min=0" +
// "], frame=frame:contains}" +
// ppt = new PoliqarpPlusTree("[base=Auto]contains(<s>,[pos=N]*)");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(pos6.replaceAll(" ", ""), map.replaceAll(" ", ""));
// @Test
// public void testNestedPositions() throws QueryException {
// // contains(<s>,startswith(<np>,[orth=Der]))
// String npos1 =
// "{@type=korap:group, operation=operation:position, frames=[frames:contains], operands=[" +
// "{@type=korap:span, key=s}," +
// "{@type=korap:group, operation=operation:position, frames=[frames:startswith], operands=[" +
// "{@type=korap:span, key=np}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Der, match=match:eq}}" +
// "], frame=frame:startswith}" +
// "], frame=frame:contains}";
// ppt = new PoliqarpPlusTree("contains(<s>, startswith(<np>,[orth=Der]))");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(npos1.replaceAll(" ", ""), map.replaceAll(" ", ""));
// @Test
// public void testFocusSplit() throws QueryException {
// // focus([orth=Der]{[orth=Mann]})
// String shr1 =
// "{@type=korap:reference, operation=operation:focus, classRef=[0], operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Der, match=match:eq}}," +
// "{@type=korap:group, operation=operation:class, class=0, classOut=0, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Mann, match=match:eq}}" +
// ppt = new PoliqarpPlusTree("focus([orth=Der]{[orth=Mann]})");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(shr1.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // focus([orth=Der]{[orth=Mann][orth=geht]})
// String shr2 =
// "{@type=korap:reference, operation=operation:focus, classRef=[0], operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Der, match=match:eq}}," +
// "{@type=korap:group, operation=operation:class, class=0, classOut=0, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Mann, match=match:eq}}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=geht, match=match:eq}}" +
// ppt = new PoliqarpPlusTree("focus([orth=Der]{[orth=Mann][orth=geht]})");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(shr2.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // focus(1:[orth=Der]{1:[orth=Mann][orth=geht]})
// String shr3 =
// "{@type=korap:reference, operation=operation:focus, classRef=[1], operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Der, match=match:eq}}," +
// "{@type=korap:group, operation=operation:class, class=1, classOut=1, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Mann, match=match:eq}}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=geht, match=match:eq}}" +
// ppt = new PoliqarpPlusTree("focus(1:[orth=Der]{1:[orth=Mann][orth=geht]})");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(shr3.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // focus(1:startswith(<s>,{1:<np>}))
// String shr4 =
// "{@type=korap:reference, operation=operation:focus, classRef=[1], operands=[" +
// "{@type=korap:group, operation=operation:position, frames=[frames:startswith], operands=[" +
// "{@type=korap:span, key=s}," +
// "{@type=korap:group, operation=operation:class, class=1, classOut=1, operands=[" +
// "{@type=korap:span, key=np}" +
// "], frame=frame:startswith}" +
// ppt = new PoliqarpPlusTree("focus(1:startswith(<s>,{1:<np>}))");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(shr4.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // focus(3: startswith(<s>, {3:[base=der]{1:[mate/p=ADJA]{2:[tt/p=NN]}}}))
// String shr5 =
// "{@type=korap:reference, operation=operation:focus, classRef=[3], operands=[" +
// "{@type=korap:group, operation=operation:position, frames=[frames:startswith], operands=[" +
// "{@type=korap:span, key=s}," +
// "{@type=korap:group, operation=operation:class, class=3, classOut=3, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=der, match=match:eq}}," +
// "{@type=korap:group, operation=operation:class, class=1, classOut=1, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, foundry=mate, layer=p, key=ADJA, match=match:eq}}," +
// "{@type=korap:group, operation=operation:class, class=2, classOut=2, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, foundry=tt, layer=p, key=NN, match=match:eq}}" +
// "], frame=frame:startswith}" +
// ppt = new PoliqarpPlusTree("focus(3:startswith(<s>,{3:[base=der]{1:[mate/p=ADJA]{2:[tt/p=NN]}}})) ");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(shr5.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // split(3: startswith(<s>, {3:[base=der]{1:[mate/p=ADJA]{2:[tt/p=NN]}}}))
// String shr6 =
// "{@type=korap:reference, operation=operation:split, classRef=[3], operands=[" +
// "{@type=korap:group, operation=operation:position, frames=[frames:startswith], operands=[" +
// "{@type=korap:span, key=s}," +
// "{@type=korap:group, operation=operation:class, class=3, classOut=3, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=der, match=match:eq}}," +
// "{@type=korap:group, operation=operation:class, class=1, classOut=1, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, foundry=mate, layer=p, key=ADJA, match=match:eq}}," +
// "{@type=korap:group, operation=operation:class, class=2, classOut=2, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, foundry=tt, layer=p, key=NN, match=match:eq}}" +
// "], frame=frame:startswith}" +
// ppt = new PoliqarpPlusTree("split(3:startswith(<s>,{3:[base=der]{1:[mate/p=ADJA]{2:[tt/p=NN]}}})) ");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(shr6.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // split(2|3: startswith(<s>, {3:[base=der]{1:[mate/p=ADJA]{2:[tt/p=NN]}}}))
// String shr7 =
// "{@type=korap:reference, operation=operation:split, classRef=[2, 3], classRefOp=classRefOp:intersection, operands=[" +
// "{@type=korap:group, operation=operation:position, frames=[frames:startswith], operands=[" +
// "{@type=korap:span, key=s}," +
// "{@type=korap:group, operation=operation:class, class=3, classOut=3, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=der, match=match:eq}}," +
// "{@type=korap:group, operation=operation:class, class=1, classOut=1, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, foundry=mate, layer=p, key=ADJA, match=match:eq}}," +
// "{@type=korap:group, operation=operation:class, class=2, classOut=2, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, foundry=tt, layer=p, key=NN, match=match:eq}}" +
// "], frame=frame:startswith}" +
// ppt = new PoliqarpPlusTree("split(2|3:startswith(<s>,{3:[base=der]{1:[mate/p=ADJA]{2:[tt/p=NN]}}})) ");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(shr7.replaceAll(" ", ""), map.replaceAll(" ", ""));
// String shr8 =
// "{@type=korap:reference, operation=operation:focus, classRef=[1], operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:group, operation=operation:class, class=0, classOut=0, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=der, match=match:eq}}" +
// "{@type=korap:group, operation=operation:class, class=1, classOut=1, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=pos, key=ADJA, match=match:eq}}" +
// ppt = new PoliqarpPlusTree("focus(1:{[base=der]}{1:[pos=ADJA]})");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(shr8.replaceAll(" ", ""), map.replaceAll(" ", ""));
// @Test
// public void testSubspan() throws QueryException {
// query = "submatch(1,:<s>)";
// expected =
// "{@type=korap:reference, operation=operation:focus, operands=[" +
// "{@type=korap:span, key=s}" +
// "], spanRef=[1]" +
// ppt = new PoliqarpPlusTree(query);
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", ""));
// query = "submatch(1,4:<s>)";
// expected =
// "{@type=korap:reference, operation=operation:focus, operands=[" +
// "{@type=korap:span, key=s}" +
// "], spanRef=[1,4]" +
// ppt = new PoliqarpPlusTree(query);
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", ""));
// query = "submatch(1,4:contains(<s>,[base=Haus]))";
// expected =
// "{@type=korap:reference, operation=operation:focus, operands=[" +
// "{@type=korap:group, operation=operation:position, frames=[frames:contains], operands=[" +
// "{@type=korap:span, key=s}," +
// "{@type=korap:token, wrap= {@type=korap:term, layer=lemma, key=Haus, match=match:eq}}" +
// "], frame=frame:contains}" +
// "], spanRef=[1,4]" +
// ppt = new PoliqarpPlusTree(query);
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", ""));
// @Test
// public void testRelations() throws QueryException {
// query = "relatesTo(<s>,<np>)";
// expected =
// "{@type=korap:group, operation=operation:relation, operands=[" +
// "{@type=korap:span, key=s}," +
// "{@type=korap:span, key=np}" +
// "], relation={@type=korap:relation}" +
// ppt = new PoliqarpPlusTree(query);
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", ""));
// query = "relatesTo([base=Baum],<np>)";
// expected =
// "{@type=korap:group, operation=operation:relation, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Baum, match=match:eq}}," +
// "{@type=korap:span, key=np}" +
// "], relation={@type=korap:relation}" +
// ppt = new PoliqarpPlusTree(query);
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", ""));
// query = "dominates(<np>,[base=Baum])";
// expected =
// "{@type=korap:group, operation=operation:relation, operands=[" +
// "{@type=korap:span, key=np}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Baum, match=match:eq}}" +
// "], relation={@type=korap:relation, layer=c}" +
// ppt = new PoliqarpPlusTree(query);
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", ""));
// query = "dominates(cnx/c:<np>,[base=Baum])";
// expected =
// "{@type=korap:group, operation=operation:relation, operands=[" +
// "{@type=korap:span, key=np}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Baum, match=match:eq}}" +
// "], relation={@type=korap:relation, layer=c, foundry=cnx}" +
// ppt = new PoliqarpPlusTree(query);
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", ""));
// query = "dominates(cnx/c*:<np>,[base=Baum])";
// expected =
// "{@type=korap:group, operation=operation:relation, operands=[" +
// "{@type=korap:span, key=np}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Baum, match=match:eq}}" +
// "], relation={@type=korap:relation, layer=c, foundry=cnx, boundary={@type=korap:boundary, min=0}}" +
// ppt = new PoliqarpPlusTree(query);
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", ""));
// query = "dominates(cnx/c{1,5}:<np>,[base=Baum])";
// expected =
// "{@type=korap:group, operation=operation:relation, operands=[" +
// "{@type=korap:span, key=np}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Baum, match=match:eq}}" +
// "], relation={@type=korap:relation, layer=c, foundry=cnx, boundary={@type=korap:boundary, min=1, max=5}}" +
// ppt = new PoliqarpPlusTree(query);
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", ""));
// query = "relatesTo(mate/d=HEAD:<np>,[base=Baum])";
// expected =
// "{@type=korap:group, operation=operation:relation, operands=[" +
// "{@type=korap:span, key=np}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=Baum, match=match:eq}}" +
// "], relation={@type=korap:relation, foundry=mate, layer=d, key=HEAD}" +
// ppt = new PoliqarpPlusTree(query);
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", ""));
// @Test
// public void testFoundries() throws QueryException {
// // [tt/base=Mann]
// String layer1 = "{@type=korap:token, wrap={@type=korap:term, foundry=tt, layer=lemma, key=Mann, match=match:eq}}";
// ppt = new PoliqarpPlusTree("[tt/base=Mann]");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(layer1.replaceAll(" ", ""), map.replaceAll(" ", ""));
// @Test
// public void testAlign() throws QueryException {
// // [orth=der]^[orth=Mann]
// query = "[orth=der]^[orth=Mann]";
// expected =
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=der, match=match:eq}}," +
// "{@type=korap:group, operation=operation:class, class=1025, classOut=1025, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Mann, match=match:eq}}" +
// metaExpected =
// "{alignment=1025}";
// ppt = new PoliqarpPlusTree(query);
// map = ppt.getRequestMap().get("query").toString();
// metaMap = ppt.getRequestMap().get("meta").toString();
// assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", ""));
// assertEquals(metaExpected.replaceAll(" ", ""), metaMap.replaceAll(" ", ""));
// String expected =
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=der, match=match:eq}}," +
// "{@type=korap:group, operation=operation:class, class=1025, classOut=1025, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Mann, match=match:eq}}" +
// metaExpected =
// "{alignment=1025}";
// ppt = new PoliqarpPlusTree(query);
// map = ppt.getRequestMap().get("query").toString();
// metaMap = ppt.getRequestMap().get("meta").toString();
// assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", ""));
// assertEquals(metaExpected.replaceAll(" ", ""), metaMap.replaceAll(" ", ""));
// query = "([base=a]^[base=b])|[base=c]";
// expected =
// "{@type=korap:group, operation=operation:or, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=a, match=match:eq}}," +
// "{@type=korap:group, operation=operation:class, class=1025, classOut=1025, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=b, match=match:eq}}" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=c, match=match:eq}}" +
// metaExpected =
// "{alignment=1025}";
// ppt = new PoliqarpPlusTree(query);
// map = ppt.getRequestMap().get("query").toString();
// metaMap = ppt.getRequestMap().get("meta").toString();
// assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", ""));
// assertEquals(metaExpected.replaceAll(" ", ""), metaMap.replaceAll(" ", ""));
// query = "([base=a]^[base=b][base=c])|[base=d]";
// expected =
// "{@type=korap:group, operation=operation:or, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=a, match=match:eq}}," +
// "{@type=korap:group, operation=operation:class, class=1025, classOut=1025, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=b, match=match:eq}}," +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=c, match=match:eq}}" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=d, match=match:eq}}" +
// metaExpected =
// "{alignment=1025}";
// ppt = new PoliqarpPlusTree(query);
// map = ppt.getRequestMap().get("query").toString();
// metaMap = ppt.getRequestMap().get("meta").toString();
// assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", ""));
// assertEquals(metaExpected.replaceAll(" ", ""), metaMap.replaceAll(" ", ""));
// query = "([base=a]^[base=b]^[base=c])|[base=d]";
// expected =
// "{@type=korap:group, operation=operation:or, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=a, match=match:eq}}," +
// "{@type=korap:group, operation=operation:class, class=1025, classOut=1025, operands=[" +
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=b, match=match:eq}}," +
// "{@type=korap:group, operation=operation:class, class=1026, classOut=1026, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=c, match=match:eq}}" +
// "{@type=korap:token, wrap={@type=korap:term, layer=lemma, key=d, match=match:eq}}" +
// metaExpected =
// "{alignment=[1025,1026]}";
// ppt = new PoliqarpPlusTree(query);
// map = ppt.getRequestMap().get("query").toString();
// metaMap = ppt.getRequestMap().get("meta").toString();
// assertEquals(expected.replaceAll(" ", ""), map.replaceAll(" ", ""));
// assertEquals(metaExpected.replaceAll(" ", ""), metaMap.replaceAll(" ", ""));
// @Test
// public void testSimpleQueries() throws QueryException {
// // Baum
// String simple1 =
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Baum, match=match:eq}}";
// ppt = new PoliqarpPlusTree("Baum");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(simple1.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // Baum/i
// String simple1b =
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Baum, match=match:eq, caseInsensitive=true}}";
// ppt = new PoliqarpPlusTree("Baum/i");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(simple1b.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // Der Baum
// String simple2 =
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Der, match=match:eq}}, " +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Baum, match=match:eq}}" +
// ppt = new PoliqarpPlusTree("Der Baum");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(simple2.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // Der Baum/i
// String simple2b =
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Der, match=match:eq}}, " +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Baum, match=match:eq, caseInsensitive=true}}" +
// ppt = new PoliqarpPlusTree("Der Baum/i");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(simple2b.replaceAll(" ", ""), map.replaceAll(" ", ""));
// String simple3 =
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Der, match=match:eq}}, " +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Baum, match=match:eq}}" +
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(simple3.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // Baum | Stein
// String simple4 =
// "{@type=korap:group, operation=operation:or, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Baum, match=match:eq}}, " +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Stein, match=match:eq}}" +
// ppt = new PoliqarpPlusTree("Baum | Stein");
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(simple4.replaceAll(" ", ""), map.replaceAll(" ", ""));
// // Baum | Stein Haus
// String query = "(Baum | Stein) Haus";
// String simple5 =
// "{@type=korap:group, operation=operation:sequence, operands=[" +
// "{@type=korap:group, operation=operation:or, operands=[" +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Baum, match=match:eq}}, " +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Stein, match=match:eq}}" +
// "{@type=korap:token, wrap={@type=korap:term, layer=orth, key=Haus, match=match:eq}} " +
// ppt = new PoliqarpPlusTree(query);
// map = ppt.getRequestMap().get("query").toString();
// assertEquals(simple5.replaceAll(" ", ""), map.replaceAll(" ", ""));
}
|
package guitests;
import static org.junit.Assert.assertTrue;
import static t16b4.yats.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import org.junit.Test;
import guitests.guihandles.PersonCardHandle;
import t16b4.yats.commons.core.Messages;
import t16b4.yats.logic.commands.EditCommand;
import t16b4.yats.model.item.Description;
import t16b4.yats.model.item.Timing;
import t16b4.yats.model.item.Title;
import t16b4.yats.model.item.Deadline;
import t16b4.yats.model.tag.Tag;
import t16b4.yats.testutil.PersonBuilder;
import t16b4.yats.testutil.TestPerson;
// TODO: reduce GUI tests by transferring some tests to be covered by lower level tests.
public class EditCommandTest extends AddressBookGuiTest {
// The list of persons in the person list panel is expected to match this list.
// This list is updated with every successful call to assertEditSuccess().
TestPerson[] expectedPersonsList = td.getTypicalPersons();
@Test
public void edit_allFieldsSpecified_success() throws Exception {
String detailsToEdit = "Bobby p/91234567 e/bobby@gmail.com a/Block 123, Bobby Street 3 t/husband";
int addressBookIndex = 1;
TestPerson editedPerson = new PersonBuilder().withName("Bobby").withPhone("91234567")
.withEmail("bobby@gmail.com").withAddress("Block 123, Bobby Street 3").withTags("husband").build();
assertEditSuccess(addressBookIndex, addressBookIndex, detailsToEdit, editedPerson);
}
@Test
public void edit_notAllFieldsSpecified_success() throws Exception {
String detailsToEdit = "t/sweetie t/bestie";
int addressBookIndex = 2;
TestPerson personToEdit = expectedPersonsList[addressBookIndex - 1];
TestPerson editedPerson = new PersonBuilder(personToEdit).withTags("sweetie", "bestie").build();
assertEditSuccess(addressBookIndex, addressBookIndex, detailsToEdit, editedPerson);
}
@Test
public void edit_clearTags_success() throws Exception {
String detailsToEdit = "t/";
int addressBookIndex = 2;
TestPerson personToEdit = expectedPersonsList[addressBookIndex - 1];
TestPerson editedPerson = new PersonBuilder(personToEdit).withTags().build();
assertEditSuccess(addressBookIndex, addressBookIndex, detailsToEdit, editedPerson);
}
@Test
public void edit_findThenEdit_success() throws Exception {
commandBox.runCommand("find Elle");
String detailsToEdit = "Belle";
int filteredPersonListIndex = 1;
int addressBookIndex = 5;
TestPerson personToEdit = expectedPersonsList[addressBookIndex - 1];
TestPerson editedPerson = new PersonBuilder(personToEdit).withName("Belle").build();
assertEditSuccess(filteredPersonListIndex, addressBookIndex, detailsToEdit, editedPerson);
}
@Test
public void edit_missingPersonIndex_failure() {
commandBox.runCommand("edit Bobby");
assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE));
}
@Test
public void edit_invalidPersonIndex_failure() {
commandBox.runCommand("edit 8 Bobby");
assertResultMessage(Messages.MESSAGE_INVALID_PERSON_DISPLAYED_INDEX);
}
@Test
public void edit_noFieldsSpecified_failure() {
commandBox.runCommand("edit 1");
assertResultMessage(EditCommand.MESSAGE_NOT_EDITED);
}
@Test
public void edit_invalidValues_failure() {
commandBox.runCommand("edit 1 *&");
assertResultMessage(Title.MESSAGE_NAME_CONSTRAINTS);
commandBox.runCommand("edit 1 p/abcd");
assertResultMessage(Deadline.MESSAGE_PHONE_CONSTRAINTS);
commandBox.runCommand("edit 1 e/yahoo!!!");
assertResultMessage(Timing.MESSAGE_EMAIL_CONSTRAINTS);
commandBox.runCommand("edit 1 a/");
// assertResultMessage(Description.MESSAGE_ADDRESS_CONSTRAINTS);
/**
* Checks whether the edited person has the correct updated details.
*
* @param filteredPersonListIndex index of person to edit in filtered list
* @param addressBookIndex index of person to edit in the address book.
* Must refer to the same person as {@code filteredPersonListIndex}
* @param detailsToEdit details to edit the person with as input to the edit command
* @param editedPerson the expected person after editing the person's details
*/
private void assertEditSuccess(int filteredPersonListIndex, int addressBookIndex,
String detailsToEdit, TestPerson editedPerson) {
commandBox.runCommand("edit " + filteredPersonListIndex + " " + detailsToEdit);
// confirm the new card contains the right data
PersonCardHandle editedCard = personListPanel.navigateToPerson(editedPerson.getTitle().fullName);
assertMatching(editedPerson, editedCard);
// confirm the list now contains all previous persons plus the person with updated details
expectedPersonsList[addressBookIndex - 1] = editedPerson;
assertTrue(personListPanel.isListMatching(expectedPersonsList));
assertResultMessage(String.format(EditCommand.MESSAGE_EDIT_PERSON_SUCCESS, editedPerson));
}
}
|
package guitests;
import static org.junit.Assert.assertTrue;
import static seedu.task.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import org.junit.Test;
import guitests.guihandles.PersonCardHandle;
import seedu.task.commons.core.Messages;
import seedu.task.logic.commands.EditCommand;
import seedu.task.model.tag.Tag;
import seedu.task.model.task.Name;
import seedu.task.testutil.TaskBuilder;
import seedu.task.testutil.TestTask;
// TODO: reduce GUI tests by transferring some tests to be covered by lower level tests.
public class EditCommandTest extends TaskListGuiTest {
// The list of tasks in the task list panel is expected to match this list.
// This list is updated with every successful call to assertEditSuccess().
TestTask[] expectedTaskList = td.getTypicalPersons();
@Test
public void edit_allFieldsSpecified_success() throws Exception {
String detailsToEdit = "Bobby t/husband";
int taskListIndex = 1;
TestTask editedTask = new TaskBuilder().withName("Bobby").withTags("husband").build();
assertEditSuccess(taskListIndex, taskListIndex, detailsToEdit, editedTask);
}
@Test
public void edit_notAllFieldsSpecified_success() throws Exception {
String detailsToEdit = "t/sweetie t/bestie";
int taskListIndex = 2;
TestTask taskToEdit = expectedTaskList[taskListIndex - 1];
TestTask editedTask = new TaskBuilder(taskToEdit).withTags("sweetie", "bestie").build();
assertEditSuccess(taskListIndex, taskListIndex, detailsToEdit, editedTask);
}
@Test
public void edit_clearTags_success() throws Exception {
String detailsToEdit = "t/";
int taskListIndex = 2;
TestTask taskToEdit = expectedTaskList[taskListIndex - 1];
TestTask editedTask = new TaskBuilder(taskToEdit).withTags().build();
assertEditSuccess(taskListIndex, taskListIndex, detailsToEdit, editedTask);
}
@Test
public void edit_findThenEdit_success() throws Exception {
commandBox.runCommand("find Elle");
String detailsToEdit = "Belle";
int filteredTaskListIndex = 1;
int taskListIndex = 5;
TestTask taskToEdit = expectedTaskList[taskListIndex - 1];
TestTask editedTask = new TaskBuilder(taskToEdit).withName("Belle").build();
assertEditSuccess(filteredTaskListIndex, taskListIndex, detailsToEdit, editedTask);
}
@Test
public void edit_missingTaskIndex_failure() {
commandBox.runCommand("edit Bobby");
assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE));
}
@Test
public void edit_invalidTaskIndex_failure() {
commandBox.runCommand("edit 8 Bobby");
assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
}
@Test
public void edit_noFieldsSpecified_failure() {
commandBox.runCommand("edit 1");
assertResultMessage(EditCommand.MESSAGE_NOT_EDITED);
}
@Test
public void edit_invalidValues_failure() {
commandBox.runCommand("edit 1 *&");
assertResultMessage(Name.MESSAGE_DESCRIPTION_CONSTRAINTS);
/**
* Checks whether the edited tasks has the correct updated details.
*
* @param filteredTaskListIndex index of task to edit in filtered list
* @param taskListIndex index of task to edit in the task list.
* Must refer to the same task as {@code filteredPersonListIndex}
* @param detailsToEdit details to edit the task with as input to the edit command
* @param editedTask the expected task after editing the task's details
*/
private void assertEditSuccess(int filteredTaskListIndex, int taskListIndex,
String detailsToEdit, TestTask editedTask) {
commandBox.runCommand("edit " + filteredTaskListIndex + " " + detailsToEdit);
// confirm the new card contains the right data
PersonCardHandle editedCard = personListPanel.navigateToPerson(editedTask.getName().fullName);
assertMatching(editedTask, editedCard);
// confirm the list now contains all previous persons plus the person with updated details
expectedTaskList[taskListIndex - 1] = editedTask;
assertTrue(personListPanel.isListMatching(expectedTaskList));
assertResultMessage(String.format(EditCommand.MESSAGE_EDIT_TASK_SUCCESS, editedTask));
}
}
|
//@@author A0142073R
package guitests;
import org.junit.Test;
import seedu.taskell.commons.core.Messages;
import seedu.taskell.commons.exceptions.IllegalValueException;
import seedu.taskell.model.task.Description;
import seedu.taskell.model.task.TaskDate;
import seedu.taskell.model.task.TaskPriority;
import seedu.taskell.model.task.TaskTime;
import seedu.taskell.testutil.TestTask;
import seedu.taskell.testutil.TestUtil;
import static org.junit.Assert.assertTrue;
import static seedu.taskell.logic.commands.EditCommand.MESSAGE_EDIT_TASK_SUCCESS;
import static seedu.taskell.logic.commands.EditCommand.MESSAGE_USAGE;
import static seedu.taskell.logic.commands.EditCommand.COMMAND_WORD;
public class EditCommandTest extends TaskManagerGuiTest {
public static final String INVALID_PRIORITY = "4";
public static final String INVALID_END_TIME = "12am";
public static final String INVALID_START_TIME = "1159pm";
public static final String INVALID_TIME = "1400";
public static final String VALID_DATE = "30-10-2100";
public static final String VALID_START_DATE = "1-12-2100";
public static final String VALID_END_DATE = "10-12-2100";
public static final String INVALID_DATE = "30Nov";
@Test
public void edit_desc_exceptionThrown() throws IllegalValueException {
TestTask[] currentList = td.getTypicalTasks();
int targetIndex = 1;
// edit the description of first task in the list
TestTask oldTask = currentList[targetIndex - 1];
TestTask newTask = new TestTask(new Description("make tea"), oldTask.getTaskType(), oldTask.getTaskPriority(),
oldTask.getStartTime(), oldTask.getEndTime(), oldTask.getStartDate(), oldTask.getEndDate(),
oldTask.getRecurringType(), oldTask.getTaskStatus(), oldTask.getTags());
commandBox.runCommand("edit " + targetIndex + " desc: make tea");
currentList[0] = newTask;
assertEditSuccess(targetIndex, currentList, oldTask, newTask);
// edit the description of last task in the list
targetIndex = currentList.length;
oldTask = currentList[targetIndex - 1];
newTask = new TestTask(new Description("finish software demo"), oldTask.getTaskType(),
oldTask.getTaskPriority(), oldTask.getStartTime(), oldTask.getEndTime(), oldTask.getStartDate(),
oldTask.getEndDate(), oldTask.getRecurringType(), oldTask.getTaskStatus(), oldTask.getTags());
commandBox.runCommand(COMMAND_WORD + " " + targetIndex + " desc: finish software demo");
assertEditSuccess(targetIndex, currentList, oldTask, newTask);
// invalid index
commandBox.runCommand(COMMAND_WORD + " " + currentList.length + 1 + " desc: go shopping");
assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
// invalid command
commandBox.runCommand(COMMAND_WORD);
assertResultMessage("Invalid command format! \n" + MESSAGE_USAGE);
commandBox.runCommand(COMMAND_WORD + " " + COMMAND_WORD);
assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
commandBox.runCommand(
COMMAND_WORD + " " + targetIndex + " desc: finish homework " + " st: 8am " + " desc: submit homework");
assertResultMessage("Invalid command format! \n" + MESSAGE_USAGE);
}
@Test
public void edit_priority_exceptionThrown() throws IllegalValueException {
TestTask[] currentList = td.getTypicalTasks();
int targetIndex = 1;
// edit the priority of first task in the list
targetIndex = 1;
TestTask oldTask = currentList[targetIndex - 1];
TestTask newTask = new TestTask(oldTask.getDescription(), oldTask.getTaskType(),
new TaskPriority(TaskPriority.DEFAULT_PRIORITY), oldTask.getStartTime(), oldTask.getEndTime(),
oldTask.getStartDate(), oldTask.getEndDate(), oldTask.getRecurringType(), oldTask.getTaskStatus(),
oldTask.getTags());
commandBox.runCommand("edit " + targetIndex + " p: " + TaskPriority.DEFAULT_PRIORITY);
currentList[0] = newTask;
assertEditSuccess(targetIndex, currentList, oldTask, newTask);
// edit the priority of last task in the list
targetIndex = currentList.length;
oldTask = currentList[targetIndex - 1];
newTask = new TestTask(oldTask.getDescription(), oldTask.getTaskType(),
new TaskPriority(TaskPriority.HIGH_PRIORITY), oldTask.getStartTime(), oldTask.getEndTime(),
oldTask.getStartDate(), oldTask.getEndDate(), oldTask.getRecurringType(), oldTask.getTaskStatus(),
oldTask.getTags());
commandBox.runCommand("edit " + targetIndex + " p: " + TaskPriority.HIGH_PRIORITY);
assertEditSuccess(targetIndex, currentList, oldTask, newTask);
// invalid index
commandBox.runCommand(COMMAND_WORD + " " + currentList.length + 1 + " p: " + TaskPriority.DEFAULT_PRIORITY);
assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
// invalid command
commandBox.runCommand(COMMAND_WORD + " " + targetIndex + " p:");
assertResultMessage("Invalid command format! \n" + MESSAGE_USAGE);
commandBox.runCommand(COMMAND_WORD + " " + targetIndex + " p: " + TaskPriority.DEFAULT_PRIORITY + " "+ TaskPriority.HIGH_PRIORITY);
assertResultMessage("Invalid command format! \n" + MESSAGE_USAGE);
commandBox.runCommand(COMMAND_WORD + " " + targetIndex + " p: " + INVALID_PRIORITY);
assertResultMessage("Invalid command format! \n" + TaskPriority.MESSAGE_TASK_PRIORITY_CONSTRAINTS);
commandBox.runCommand(COMMAND_WORD + " " + targetIndex + " p: " + TaskPriority.DEFAULT_PRIORITY + " st: 8am"
+ " p: " + TaskPriority.HIGH_PRIORITY);
assertResultMessage("Invalid command format! \n" + MESSAGE_USAGE);
}
@Test
public void edit_startTime_exceptionThrown() throws IllegalValueException {
TestTask[] currentList = td.getTypicalTasks();
int targetIndex = 1;
// edit the start time of first task in the list
targetIndex = 1;
TestTask oldTask = currentList[targetIndex - 1];
TestTask newTask = new TestTask(oldTask.getDescription(), oldTask.getTaskType(), oldTask.getTaskPriority(),
new TaskTime(TaskTime.MIDNIGHT), oldTask.getEndTime(), oldTask.getStartDate(), oldTask.getEndDate(),
oldTask.getRecurringType(), oldTask.getTaskStatus(), oldTask.getTags());
commandBox.runCommand("edit " + targetIndex + " st: " + TaskTime.MIDNIGHT);
currentList[0] = newTask;
assertEditSuccess(targetIndex, currentList, oldTask, newTask);
// edit the start time of last task in the list
targetIndex = currentList.length;
oldTask = currentList[targetIndex - 1];
newTask = new TestTask(oldTask.getDescription(), oldTask.getTaskType(), oldTask.getTaskPriority(),
new TaskTime(TaskTime.DEFAULT_START_TIME), oldTask.getEndTime(), oldTask.getStartDate(),
oldTask.getEndDate(), oldTask.getRecurringType(), oldTask.getTaskStatus(), oldTask.getTags());
commandBox.runCommand("edit " + targetIndex + " st: " + TaskTime.DEFAULT_START_TIME);
assertEditSuccess(targetIndex, currentList, oldTask, newTask);
// invalid index
commandBox.runCommand(COMMAND_WORD + " " + currentList.length + 1 + " st: " + TaskTime.DEFAULT_START_TIME);
assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
// invalid command
commandBox.runCommand(COMMAND_WORD + " " + targetIndex + " st:");
assertResultMessage("Invalid command format! \n" + MESSAGE_USAGE);
commandBox.runCommand(COMMAND_WORD + " " + targetIndex + " st: " + TaskTime.DEFAULT_START_TIME + " " + TaskTime.DEFAULT_END_TIME);
assertResultMessage("Invalid command format! \n" + MESSAGE_USAGE);
commandBox.runCommand(COMMAND_WORD + " " + targetIndex + " st: " + INVALID_TIME);
assertResultMessage("Invalid command format! \n" + TaskTime.MESSAGE_TASK_TIME_CONSTRAINTS);
commandBox.runCommand(COMMAND_WORD + " " + targetIndex + " st: " + TaskTime.DEFAULT_START_TIME + " p: "
+ TaskPriority.DEFAULT_PRIORITY + " st: " + TaskTime.DEFAULT_START_TIME);
assertResultMessage("Invalid command format! \n" + MESSAGE_USAGE);
}
@Test
public void edit_endTime_exceptionThrown() throws IllegalValueException {
TestTask[] currentList = td.getTypicalTasks();
int targetIndex = 1;
// edit the end time of first task in the list
targetIndex = 1;
TestTask oldTask = currentList[targetIndex - 1];
TestTask newTask = new TestTask(oldTask.getDescription(), oldTask.getTaskType(), oldTask.getTaskPriority(),
oldTask.getStartTime(), new TaskTime(TaskTime.DEFAULT_END_TIME), oldTask.getStartDate(),
oldTask.getEndDate(), oldTask.getRecurringType(), oldTask.getTaskStatus(), oldTask.getTags());
commandBox.runCommand("edit " + targetIndex + " et: " + TaskTime.DEFAULT_END_TIME);
currentList[0] = newTask;
assertEditSuccess(targetIndex, currentList, oldTask, newTask);
// edit the end time of last task in the list
targetIndex = currentList.length;
oldTask = currentList[targetIndex - 1];
newTask = new TestTask(oldTask.getDescription(), oldTask.getTaskType(), oldTask.getTaskPriority(),
oldTask.getStartTime(), new TaskTime(TaskTime.DEFAULT_END_TIME), oldTask.getStartDate(),
oldTask.getEndDate(), oldTask.getRecurringType(), oldTask.getTaskStatus(), oldTask.getTags());
commandBox.runCommand("edit " + targetIndex + " et: " + TaskTime.DEFAULT_END_TIME);
assertEditSuccess(targetIndex, currentList, oldTask, newTask);
// invalid index
commandBox.runCommand(COMMAND_WORD + " " + currentList.length + 1 + " et: 3pm");
assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
// invalid command
commandBox.runCommand(COMMAND_WORD + " " + targetIndex + " et:");
assertResultMessage("Invalid command format! \n" + MESSAGE_USAGE);
commandBox.runCommand(COMMAND_WORD + " " + targetIndex + " et: " + TaskTime.DEFAULT_END_TIME + " " + TaskTime.DEFAULT_START_TIME);
assertResultMessage("Invalid command format! \n" + MESSAGE_USAGE);
commandBox.runCommand(COMMAND_WORD + " " + targetIndex + " et: " + INVALID_TIME);
assertResultMessage("Invalid command format! \n" + TaskTime.MESSAGE_TASK_TIME_CONSTRAINTS);
commandBox.runCommand(COMMAND_WORD + " " + targetIndex + " et: " + TaskTime.DEFAULT_START_TIME + " p: "
+ TaskPriority.DEFAULT_PRIORITY + " et: " + TaskTime.DEFAULT_START_TIME);
assertResultMessage("Invalid command format! \n" + MESSAGE_USAGE);
}
@Test
public void edit_endDate_exceptionThrown() throws IllegalValueException {
TestTask[] currentList = td.getTypicalTasks();
int targetIndex = 1;
// edit the end date of first task in the list
targetIndex = 1;
TestTask oldTask = currentList[targetIndex - 1];
TestTask newTask = new TestTask(oldTask.getDescription(), oldTask.getTaskType(), oldTask.getTaskPriority(),
oldTask.getStartTime(), oldTask.getEndTime(), oldTask.getStartDate(), new TaskDate(VALID_END_DATE),
oldTask.getRecurringType(), oldTask.getTaskStatus(), oldTask.getTags());
commandBox.runCommand("edit " + targetIndex + " ed: " + VALID_END_DATE);
currentList[0] = newTask;
assertEditSuccess(targetIndex, currentList, oldTask, newTask);
// invalid index
commandBox.runCommand(COMMAND_WORD + " " + currentList.length + 1 + " ed: " + VALID_END_DATE);
assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
// invalid command
commandBox.runCommand(COMMAND_WORD + " " + targetIndex + " ed:");
assertResultMessage("Invalid command format! \n" + MESSAGE_USAGE);
commandBox.runCommand(COMMAND_WORD + " " + targetIndex + " ed: " + VALID_END_DATE + " " + VALID_END_DATE);
assertResultMessage("Invalid command format! \n" + MESSAGE_USAGE);
commandBox.runCommand(COMMAND_WORD + " " + targetIndex + " ed: " + INVALID_DATE);
assertResultMessage("Invalid command format! \n" + TaskDate.MESSAGE_TASK_DATE_CONSTRAINTS);
commandBox.runCommand(COMMAND_WORD + " " + targetIndex + " ed: " + VALID_END_DATE + " st: "
+ TaskTime.DEFAULT_START_TIME + " ed: " + VALID_END_DATE);
assertResultMessage("Invalid command format! \n" + MESSAGE_USAGE);
}
@Test
public void edit_startDate_exceptionThrown() throws IllegalValueException {
TestTask[] currentList = td.getTypicalTasks();
int targetIndex = 1;
// edit the start date of first task in the list
targetIndex = 1;
TestTask oldTask = currentList[targetIndex - 1];
TestTask newTask = new TestTask(oldTask.getDescription(), oldTask.getTaskType(), oldTask.getTaskPriority(),
oldTask.getStartTime(), oldTask.getEndTime(), new TaskDate(VALID_DATE), oldTask.getEndDate(),
oldTask.getRecurringType(), oldTask.getTaskStatus(), oldTask.getTags());
commandBox.runCommand("edit " + targetIndex + " sd: " + VALID_DATE);
currentList[0] = newTask;
assertEditSuccess(targetIndex, currentList, oldTask, newTask);
// edit the start date of last task in the list
targetIndex = currentList.length;
oldTask = currentList[targetIndex - 1];
newTask = new TestTask(oldTask.getDescription(), oldTask.getTaskType(), oldTask.getTaskPriority(),
oldTask.getStartTime(), oldTask.getEndTime(), new TaskDate(VALID_DATE), oldTask.getEndDate(),
oldTask.getRecurringType(), oldTask.getTaskStatus(), oldTask.getTags());
commandBox.runCommand("edit " + targetIndex + " sd: " + VALID_DATE);
assertEditSuccess(targetIndex, currentList, oldTask, newTask);
// invalid index
commandBox.runCommand(COMMAND_WORD + " " + currentList.length + 1 + " sd: " + VALID_DATE);
assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
// invalid command
commandBox.runCommand(COMMAND_WORD + " " + targetIndex + " sd:");
assertResultMessage("Invalid command format! \n" + MESSAGE_USAGE);
commandBox.runCommand(COMMAND_WORD + " " + targetIndex + " sd: " + VALID_START_DATE + " " + VALID_END_DATE);
assertResultMessage("Invalid command format! \n" + MESSAGE_USAGE);
commandBox.runCommand(COMMAND_WORD + " " + targetIndex + " sd: " + INVALID_DATE);
assertResultMessage("Invalid command format! \n" + TaskDate.MESSAGE_TASK_DATE_CONSTRAINTS);
commandBox.runCommand(COMMAND_WORD + " " + targetIndex + " sd: " + VALID_DATE + " st: "
+ TaskTime.DEFAULT_START_TIME + " sd: " + VALID_DATE);
assertResultMessage("Invalid command format! \n" + MESSAGE_USAGE);
}
@Test
public void edit_fewPart_exceptionThrown() throws IllegalValueException {
TestTask[] currentList = td.getTypicalTasks();
int targetIndex = 1;
// edit the description, start time and priority of first task in the
// list
TestTask oldTask = currentList[targetIndex - 1];
TestTask newTask = new TestTask(new Description("send emails"), oldTask.getTaskType(),
new TaskPriority(TaskPriority.DEFAULT_PRIORITY), new TaskTime("12am"), oldTask.getEndTime(),
oldTask.getStartDate(), oldTask.getEndDate(), oldTask.getRecurringType(), oldTask.getTaskStatus(),
oldTask.getTags());
commandBox.runCommand("edit " + targetIndex + " desc: send emails st: " + TaskTime.DEFAULT_START_TIME + " p: "
+ TaskPriority.DEFAULT_PRIORITY);
currentList[0] = newTask;
assertEditSuccess(targetIndex, currentList, oldTask, newTask);
// edit start time and end time of first task in the
// list
oldTask = currentList[targetIndex - 1];
newTask = new TestTask(oldTask.getDescription(), oldTask.getTaskType(), oldTask.getTaskPriority(),
new TaskTime(TaskTime.DEFAULT_START_TIME), new TaskTime(TaskTime.DEFAULT_END_TIME),
oldTask.getStartDate(), oldTask.getEndDate(), oldTask.getRecurringType(), oldTask.getTaskStatus(),
oldTask.getTags());
commandBox.runCommand(
"edit " + targetIndex + " st: " + TaskTime.DEFAULT_START_TIME + " et: " + TaskTime.DEFAULT_END_TIME);
currentList[0] = newTask;
assertEditSuccess(targetIndex, currentList, oldTask, newTask);
// edit start date and end date of first task in the
// list
oldTask = currentList[targetIndex - 1];
newTask = new TestTask(oldTask.getDescription(), oldTask.getTaskType(), oldTask.getTaskPriority(),
oldTask.getStartTime(), oldTask.getEndTime(), new TaskDate(VALID_START_DATE),
new TaskDate(VALID_END_DATE), oldTask.getRecurringType(), oldTask.getTaskStatus(), oldTask.getTags());
commandBox.runCommand("edit " + targetIndex + " sd: " + VALID_START_DATE + " ed: " + VALID_END_DATE);
currentList[0] = newTask;
assertEditSuccess(targetIndex, currentList, oldTask, newTask);
// invalid command
commandBox.runCommand("edit " + targetIndex + " st: st: st: ");
currentList[0] = newTask;
assertResultMessage("Invalid command format! \n" + TaskTime.MESSAGE_TASK_TIME_CONSTRAINTS);
commandBox.runCommand("edit " + targetIndex + " st: " + TaskTime.DEFAULT_START_TIME + " st: "
+ TaskTime.DEFAULT_START_TIME + " st: " + TaskTime.DEFAULT_START_TIME);
currentList[0] = newTask;
assertResultMessage("Invalid command format! \n" + MESSAGE_USAGE);
commandBox.runCommand(COMMAND_WORD + " " + targetIndex + " sd: " + VALID_DATE + " st: "
+ TaskTime.DEFAULT_START_TIME + " sd: " + VALID_DATE);
assertResultMessage("Invalid command format! \n" + MESSAGE_USAGE);
}
private void assertEditSuccess(int targetIndexOneIndexed, final TestTask[] currentList, TestTask oldTask,
TestTask newTask) throws IllegalValueException {
TestTask[] current = TestUtil.replaceTaskFromList(currentList, newTask, targetIndexOneIndexed - 1);
// confirm the list now contains all previous tasks except the edited
// task
assertTrue(taskListPanel.isListMatching(current));
// confirm the result message is correct
assertResultMessage(String.format(MESSAGE_EDIT_TASK_SUCCESS, oldTask, newTask));
}
}
// @@author
|
package guitests;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import seedu.taskboss.commons.core.Messages;
import seedu.taskboss.logic.commands.RedoCommand;
import seedu.taskboss.testutil.TestTask;
import seedu.taskboss.testutil.TestUtil;
//@@author A0138961W
public class RedoCommandTest extends TaskBossGuiTest {
@Test
public void redo() {
//without any last command
commandBox.runCommand("redo");
assertResultMessage(RedoCommand.MESSAGE_WITHOUT_PREVIOUS_OPERATION);
//redo one undo command
TestTask[] currentList = td.getTypicalTasks();
TestTask taskToAdd = td.taskI;
commandBox.runCommand(taskToAdd.getAddCommand());
commandBox.runCommand("undo");
TestTask[] expectedList = TestUtil.addTasksToList(currentList, taskToAdd);
assertUndoCommandSuccess(false, expectedList);
//redo operation fails when apply delete operation after undo operation
commandBox.runCommand("undo");
commandBox.runCommand("delete 1");
commandBox.runCommand("redo");
assertResultMessage(RedoCommand.MESSAGE_WITHOUT_PREVIOUS_OPERATION);
//invalid command
commandBox.runCommand("redo2");
assertResultMessage(Messages.MESSAGE_UNKNOWN_COMMAND);
}
@Test
public void redoShortCommand() {
//without any last command
commandBox.runCommand("redo");
assertResultMessage(RedoCommand.MESSAGE_WITHOUT_PREVIOUS_OPERATION);
//redo one undo command
TestTask[] currentList = td.getTypicalTasks();
TestTask taskToAdd = td.taskI;
commandBox.runCommand(taskToAdd.getAddCommand());
commandBox.runCommand("undo");
TestTask[] expectedList = TestUtil.addTasksToList(currentList, taskToAdd);
assertUndoCommandSuccess(true, expectedList);
//redo operation fails when apply delete operation after undo operation
commandBox.runCommand("u");
commandBox.runCommand("delete 1");
commandBox.runCommand("r");
assertResultMessage(RedoCommand.MESSAGE_WITHOUT_PREVIOUS_OPERATION);
//invalid command
commandBox.runCommand("r2");
assertResultMessage(Messages.MESSAGE_UNKNOWN_COMMAND);
}
private void assertUndoCommandSuccess(boolean isShortCommand, TestTask[] expectedList) {
if (isShortCommand) {
commandBox.runCommand("r");
} else {
commandBox.runCommand("redo");
}
assertTrue(taskListPanel.isListMatching(expectedList));
assertResultMessage(RedoCommand.MESSAGE_SUCCESS);
}
}
|
package com.exedio.cope;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import bak.pcj.map.IntKeyOpenHashMap;
public final class EnumAttribute<E extends Enum<E>> extends FunctionAttribute<E>
{
private final List<E> values;
private final IntKeyOpenHashMap numbersToValues;
private final EnumMap<E, Integer> valuesToNumbers;
private EnumAttribute(final boolean isfinal, final boolean optional, final boolean unique, final Class<E> valueClass, final E defaultConstant)
{
super(isfinal, optional, unique, valueClass, defaultConstant);
checkValueClass(Enum.class);
final ArrayList<E> values = new ArrayList<E>();
final IntKeyOpenHashMap numbersToValues = new IntKeyOpenHashMap();
final EnumMap<E, Integer> valuesToNumbers = new EnumMap<E, Integer>(valueClass);
final E[] enumConstants = valueClass.getEnumConstants();
if(enumConstants==null)
throw new RuntimeException("must have at least one enum value: " + valueClass);
for(int j = 0; j<enumConstants.length; j++)
{
final E enumConstant = enumConstants[j];
final int number = (enumConstant.ordinal() + 1) * 10;
values.add(enumConstant);
if(numbersToValues.put(number, enumConstant)!=null)
throw new RuntimeException("duplicate number " + number + " for enum attribute on " + valueClass);
if(valuesToNumbers.put(enumConstant, number)!=null)
throw new RuntimeException("duplicate value " + enumConstant + " for enum attribute on " + valueClass);
}
values.trimToSize();
numbersToValues.trimToSize();
this.values = Collections.unmodifiableList(values);
this.numbersToValues = numbersToValues;
this.valuesToNumbers = valuesToNumbers;
checkDefaultValue();
}
public EnumAttribute(final Option option, final Class<E> valueClass)
{
this(option.isFinal, option.optional, option.unique, valueClass, null);
}
public FunctionAttribute<E> copyFunctionAttribute()
{
return new EnumAttribute<E>(isfinal, optional, implicitUniqueConstraint!=null, valueClass, defaultConstant);
}
public EnumAttribute<E> defaultTo(final E defaultConstant)
{
return new EnumAttribute<E>(isfinal, optional, implicitUniqueConstraint!=null, valueClass, defaultConstant);
}
public List<E> getValues()
{
assert values!=null;
return values;
}
private E getValue(final int number)
{
final E result = cast(numbersToValues.get(number)); // TODO remove cast when pcj.IntKeyOpenHashMap supports generics
assert result!=null : toString() + number;
return result;
}
private Integer getNumber(final E value)
{
final Integer result = valuesToNumbers.get(value);
assert result!=null : toString() + value;
return result;
}
/**
* @see Enum#valueOf(Class, String)
*/
public E getValue(final String code)
{
//System.out.println("EnumerationValue#getValue("+code+") from "+codesToValues);
return Enum.valueOf(valueClass, code);
}
Column createColumn(final Table table, final String name, final boolean optional)
{
final int[] allowedValues = new int[values.size()];
int in = 0;
for(E value : values)
allowedValues[in++] = getNumber(value).intValue();
return new IntegerColumn(table, name, optional, allowedValues);
}
E get(final Row row)
{
final Object cell = row.get(getColumn());
return
cell==null ?
null :
getValue(((Integer)cell).intValue());
}
void set(final Row row, final E surface)
{
row.put(getColumn(), surface==null ? null : getNumber(surface));
}
}
|
package guitests;
//@@author A0125221Y
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import guitests.guihandles.TaskCardHandle;
import seedu.mypotato.commons.exceptions.IllegalValueException;
import seedu.mypotato.logic.commands.EditCommand;
import seedu.mypotato.logic.commands.UndoCommand;
import seedu.mypotato.testutil.TaskBuilder;
import seedu.mypotato.testutil.TestTask;
import seedu.mypotato.testutil.TestUtil;
public class UndoCommandTest extends AddressBookGuiTest {
@Test
public void undoAddSuccess() {
TestTask[] currentList = td.getTypicalTasks();
//Begin by adding one task
TestTask taskToAdd = td.hoon;
commandBox.runCommand(taskToAdd.getAddCommand());
assertListSize(currentList.length + 1);
//Next undo the previous add command
commandBox.runCommand("undo");
assertListSize(currentList.length);
assertTrue(taskListPanel.isListMatching(currentList));
}
@Test
public void undoDeleteSuccess() {
TestTask[] currentList = td.getTypicalTasks();
//Now test deletion of one single task
commandBox.runCommand("delete 1");
assertListSize(currentList.length - 1);
currentList = TestUtil.removeTaskFromList(currentList, 1);
//Try to undo the previous delete command
commandBox.runCommand("undo");
currentList = TestUtil.addTasksToListAtIndex(currentList, 0, td.alice);
assertListSize(currentList.length);
assertTrue(taskListPanel.isListMatching(currentList));
}
@Test
public void undoClearSuccess() {
TestTask[] allTaskList = td.getTypicalTasks();
//clear all tasks
commandBox.runCommand("clear");
assertListSize(0);
//undo
commandBox.runCommand("undo");
assertTrue(taskListPanel.isListMatching(allTaskList));
}
@Test
public void undoEditSuccess() throws IllegalValueException {
TestTask[] oldTaskList = td.getTypicalTasks();
//edit start time of a task
String detailsToEdit = "start/9 Nov 2010 12pm";
int addressBookIndex = 2;
TestTask taskToEdit = oldTaskList[addressBookIndex - 1];
TestTask editedTask = new TaskBuilder(taskToEdit).withStartDateTime("9 Nov 2010 12pm").build();
assertEditSuccess(addressBookIndex, addressBookIndex, detailsToEdit, editedTask);
//undo
commandBox.runCommand("undo");
assertTrue(taskListPanel.isListMatching(oldTaskList));
//edit tags of a task
String newTags = "#friend #lol";
TestTask taskToBeEdit = oldTaskList[addressBookIndex - 1];
TestTask nextEditedTask = new TaskBuilder(taskToBeEdit).withTags("friend", "lol").build();
assertEditSuccess(addressBookIndex, addressBookIndex, newTags, nextEditedTask);
//undo
commandBox.runCommand("undo");
assertTrue(taskListPanel.isListMatching(oldTaskList));
//remove tags of a task
String detailsToEdit2 = "
TestTask taskToEdit2 = oldTaskList[addressBookIndex - 1];
TestTask editedTask2 = new TaskBuilder(taskToEdit2).withTags().build();
assertEditSuccess(addressBookIndex, addressBookIndex, detailsToEdit2, editedTask2);
//undo
commandBox.runCommand("undo");
assertTrue(taskListPanel.isListMatching(oldTaskList));
//edit deadline of task
String detailsToEdit3 = "end/10 Dec 10pm";
TestTask taskToEdit3 = oldTaskList[addressBookIndex - 1];
TestTask editedTask3 = new TaskBuilder(taskToEdit3).withEndDateTime("10 Dec 10pm").build();
assertEditSuccess(addressBookIndex, addressBookIndex, detailsToEdit3, editedTask3);
//undo
commandBox.runCommand("undo");
assertTrue(taskListPanel.isListMatching(oldTaskList));
}
@Test
public void undoMultipleSuccess() throws IllegalValueException {
TestTask[] allTaskList = td.getTypicalTasks();
TestTask[] oldTaskList = td.getTypicalTasks();
//edit a task
String detailsToEdit = "start/9 Nov 2010 12pm";
int addressBookIndex = 2;
TestTask taskToEdit = oldTaskList[addressBookIndex - 1];
TestTask editedTask = new TaskBuilder(taskToEdit).withStartDateTime("9 Nov 2010 12pm").build();
assertEditSuccess(addressBookIndex, addressBookIndex, detailsToEdit, editedTask);
//clear all tasks
commandBox.runCommand("clear");
assertListSize(0);
//undo clear
commandBox.runCommand("undo");
assertTrue(taskListPanel.isListMatching(allTaskList));
//undo edit
commandBox.runCommand("undo");
assertTrue(taskListPanel.isListMatching(oldTaskList));
}
@Test
public void undoCommandFail() {
// Undo without any previous commands
commandBox.runCommand("undo");
assertResultMessage(UndoCommand.MESSAGE_FAIL);
// Undo those commands that are not undoable
commandBox.runCommand("list all");
commandBox.runCommand("undo");
assertResultMessage(UndoCommand.MESSAGE_FAIL);
// Undo again after you had undo all the previous commands
commandBox.runCommand("delete 1");
commandBox.runCommand("delete 2");
commandBox.runCommand("clear");
commandBox.runCommand("undo");
commandBox.runCommand("undo");
commandBox.runCommand("undo");
commandBox.runCommand("undo");
assertResultMessage(UndoCommand.MESSAGE_FAIL);
}
private void assertEditSuccess(int filteredTaskListIndex, int addressBookIndex,
String detailsToEdit, TestTask editedTask) {
TestTask[] oldTaskList = td.getTypicalTasks();
commandBox.runCommand("edit " + filteredTaskListIndex + " " + detailsToEdit);
// confirm the new card contains the right data
TaskCardHandle editedCard = taskListPanel.navigateToTask(editedTask.getTitle().fullTitle);
assertMatching(editedTask, editedCard);
// confirm the list now contains all previous tasks plus the task with updated details
oldTaskList[addressBookIndex - 1] = editedTask;
assertTrue(taskListPanel.isListMatching(oldTaskList));
assertResultMessage(String.format(EditCommand.MESSAGE_EDIT_TASK_SUCCESS, editedTask));
}
}
|
package org.takes.tk;
import java.io.IOException;
import java.net.URI;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.takes.Request;
import org.takes.Response;
import org.takes.Take;
import org.takes.http.FtRemote;
import org.takes.rq.RqFake;
import org.takes.rq.RqHref;
import org.takes.rq.RqMethod;
import org.takes.rs.RsPrint;
import org.takes.rs.RsText;
/**
* Test case for {@link TkProxy}.
* @author Dragan Bozanovic (bozanovicdr@gmail.com)
* @author sebing
* @version $Id$
* @since 0.25
* @checkstyle ClassDataAbstractionCouplingCheck (500 lines)
*/
public final class TkProxyTest {
/**
* TkProxy Testcase for testing the creation of the object with method POST.
* @throws Exception If some problem inside.
*/
@Test
public void justWorksPost()throws Exception {
this.justWorks(RqMethod.POST);
}
/**
*TkProxy Testcase for testing the creation of the object with method GET.
* @throws Exception If some problem inside.
*/
@Test
public void justWorksGet()throws Exception {
this.justWorks(RqMethod.GET);
}
/**
* TkProxy Testcase for testing the act method with GET.
* @throws Exception If some problem inside.
*/
@Test
public void correctlyMapsPathStringGet() throws Exception {
this.correctlyMapsPathString(RqMethod.GET);
}
/**
*TkProxy Testcase for testing the act method with POST.
* @throws Exception If some problem inside.
*/
@Test
public void correctlyMapsPathStringPost() throws Exception {
this.correctlyMapsPathString(RqMethod.POST);
}
/**
* A private method to do test with multiple httpMethods.
* @param httpmethod HTTP methods (GET, POST, etc),
* @throws Exception If some problem inside.
*/
private void justWorks(final String httpmethod) throws Exception {
new FtRemote(new TkFixed("hello, world!")).exec(
new FtRemote.Script() {
@Override
public void exec(final URI home) throws IOException {
MatcherAssert.assertThat(
new RsPrint(
new TkProxy(home).act(new RqFake(httpmethod))
).print(),
Matchers.containsString("hello")
);
}
}
);
}
/**
* A private method to call the TkProxy. act with httpMethod.
*
* @param httpmethod HTTP methods (GET, POST, etc),
* @throws Exception If some problem inside.
*/
private void correctlyMapsPathString(final String httpmethod)
throws Exception {
final Take take = new Take() {
@Override
public Response act(final Request req) throws IOException {
return new RsText(new RqHref.Base(req).href().toString());
}
};
new FtRemote(take).exec(
new FtRemote.Script() {
@Override
public void exec(final URI home) throws IOException {
MatcherAssert.assertThat(
new RsPrint(
new TkProxy(home).act(
new RqFake(httpmethod, "/a/b/c")
)
).printBody(),
Matchers.equalTo(
String.format(
"http://%s:%d/a/b/c",
home.getHost(), home.getPort()
)
)
);
}
}
);
}
}
|
package org.takes.tk;
import java.io.IOException;
import java.net.URI;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.takes.Request;
import org.takes.Response;
import org.takes.Take;
import org.takes.http.FtRemote;
import org.takes.rq.RqFake;
import org.takes.rq.RqHref;
import org.takes.rq.RqMethod;
import org.takes.rs.RsPrint;
import org.takes.rs.RsText;
/**
* Test case for {@link TkProxy}.
* @author Dragan Bozanovic (bozanovicdr@gmail.com)
* @version $Id$
* @since 0.25
* @checkstyle ClassDataAbstractionCouplingCheck (500 lines)
*/
public final class TkProxyTest {
/**
* TkProxy can just works on POST.
* @throws Exception If some problem inside.
*/
@Test
public void justWorksOnPost()throws Exception {
this.justWorks(RqMethod.POST);
}
/**
*TkProxy can just works on GET.
* @throws Exception If some problem inside.
*/
@Test
public void justWorksOnGet()throws Exception {
this.justWorks(RqMethod.GET);
}
/**
* TkProxy can correctly maps path string on GET.
* @throws Exception If some problem inside.
*/
@Test
public void correctlyMapsPathStringOnGet() throws Exception {
this.correctlyMapsPathString(RqMethod.GET);
}
/**
*TkProxy can correctly maps path string on POST.
* @throws Exception If some problem inside.
*/
@Test
public void correctlyMapsPathStringOnPost() throws Exception {
this.correctlyMapsPathString(RqMethod.POST);
}
/**
* A private method to do test with multiple httpMethods.
* @param method HTTP methods (GET, POST, etc),
* @throws Exception If some problem inside.
*/
private void justWorks(final String method) throws Exception {
new FtRemote(new TkFixed("hello, world!")).exec(
new FtRemote.Script() {
@Override
public void exec(final URI home) throws IOException {
MatcherAssert.assertThat(
new RsPrint(
new TkProxy(home).act(new RqFake(method))
).print(),
Matchers.containsString("hello")
);
}
}
);
}
/**
* A private method to call the TkProxy. act with httpMethod.
*
* @param method HTTP methods (GET, POST, etc),
* @throws Exception If some problem inside.
*/
private void correctlyMapsPathString(final String method)
throws Exception {
final Take take = new Take() {
@Override
public Response act(final Request req) throws IOException {
return new RsText(new RqHref.Base(req).href().toString());
}
};
new FtRemote(take).exec(
new FtRemote.Script() {
@Override
public void exec(final URI home) throws IOException {
MatcherAssert.assertThat(
new RsPrint(
new TkProxy(home).act(
new RqFake(method, "/a/b/c")
)
).printBody(),
Matchers.equalTo(
String.format(
"http://%s:%d/a/b/c",
home.getHost(), home.getPort()
)
)
);
}
}
);
}
}
|
package org.jsimpledb;
import org.jsimpledb.annotation.JField;
import org.jsimpledb.annotation.JSimpleClass;
import org.jsimpledb.annotation.OnChange;
import org.jsimpledb.change.SimpleFieldChange;
import org.testng.annotations.Test;
public class GenericsFunTest extends TestSupport {
@Test
public void testGenerics1() throws Exception {
final JSimpleDB jdb = BasicTest.getJSimpleDB(Widget.class);
final JTransaction jtx = jdb.createTransaction(true, ValidationMode.MANUAL);
JTransaction.setCurrent(jtx);
try {
jtx.queryIndex(AbstractData.class, "name", String.class);
} finally {
JTransaction.setCurrent(null);
}
}
@Test
public void testGenerics2() throws Exception {
final JSimpleDB jdb = BasicTest.getJSimpleDB(AccountEvent.class, Account.class);
final JTransaction jtx = jdb.createTransaction(true, ValidationMode.MANUAL);
JTransaction.setCurrent(jtx);
try {
jtx.queryIndex(AbstractData.class, "name", String.class);
jtx.queryIndex(Account.class, "name", String.class);
jtx.queryIndex(AccountEvent.class, "account", Account.class);
} finally {
JTransaction.setCurrent(null);
}
}
@Test
public void testGenerics3() throws Exception {
final JSimpleDB jdb = BasicTest.getJSimpleDB(Class2.class, Class3.class);
final JTransaction jtx = jdb.createTransaction(true, ValidationMode.MANUAL);
JTransaction.setCurrent(jtx);
try {
final Class2 c2 = jtx.create(Class2.class);
final Class3 c3 = jtx.create(Class3.class);
c2.setFriend(c3);
c3.setFriend(c2);
} finally {
JTransaction.setCurrent(null);
}
}
@Test
public void testGenerics4() throws Exception {
final JSimpleDB jdb = BasicTest.getJSimpleDB(Class2.class, Class3.class);
final JTransaction jtx = jdb.createTransaction(true, ValidationMode.MANUAL);
JTransaction.setCurrent(jtx);
try {
final Class2 c2 = jtx.create(Class2.class);
try {
c2.setWrong(c2);
assert false;
} catch (IllegalArgumentException e) {
// expected
}
} finally {
JTransaction.setCurrent(null);
}
}
// Model Classes
public abstract static class AbstractData<T extends AbstractData<T>> implements JObject {
@JField(storageId = 201, indexed = true)
public abstract String getName();
public abstract void setName(String name);
@OnChange("name")
public void nameChanged(SimpleFieldChange<? extends AbstractData<?>, String> change) {
}
}
public abstract static class AbstractAccountData<T extends AbstractAccountData<T>> extends AbstractData<T> {
@JField(storageId = 101)
public abstract Account getAccount();
public abstract void setAccount(Account name);
}
@JSimpleClass(storageId = 200)
public abstract static class Account extends AbstractData<Account> {
}
@JSimpleClass(storageId = 300)
public abstract static class AccountEvent extends AbstractAccountData<AccountEvent> {
@JField(storageId = 301)
public abstract int getEventId();
public abstract void setEventId(int eventId);
}
@JSimpleClass(storageId = 400)
public abstract static class Widget extends AbstractData<Widget> {
}
// Model Classes
public abstract static class Class1<T> implements JObject {
public abstract T getFriend();
public abstract void setFriend(T friend);
@SuppressWarnings("unchecked")
public void setWrong(Object obj) {
this.setFriend((T)obj);
}
}
@JSimpleClass
public abstract static class Class2 extends Class1<Class3> {
}
@JSimpleClass
public abstract static class Class3 extends Class1<Class2> {
}
}
|
package uk.org.ownage.dmdirc.logger;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import uk.org.ownage.dmdirc.Config;
import uk.org.ownage.dmdirc.ui.FatalErrorDialog;
import uk.org.ownage.dmdirc.ui.MainFrame;
/**
* Logger class for an applications, provides logging, error logging and debug
* logging
*/
public class Logger {
/**
* Logging Printwriter
*/
private static PrintWriter logWriter = null;
/**
* Debug Printwriter
*/
private static PrintWriter debugWriter = null;
/**
* Error Printwriter
*/
private static PrintWriter errorWriter = null;
/**
* dialog used to report errors to the ui
*/
private static JDialog dialog;
/**
* JOptionPane used as part of some dialogs
*/
private static JOptionPane optionPane;
/**
* Date formatter, used for logging and displaying messages
*/
private static SimpleDateFormat formatter;
/**
* Prevents creation a new instance of Logger
*/
private Logger() {
}
/**
* Record an error message for the application, notifying the user if appropriate
* @param level error level
* @param message Error message/cause
*/
public static void error(ErrorLevel level, String message) {
if (logWriter == null || debugWriter == null || errorWriter == null) {
createWriters();
}
switch (level) {
case FATAL:
errorWriter.println(formatter.format(new Date())+": ERROR: "+level+" :"+message);
dialog = new FatalErrorDialog(MainFrame.getMainFrame(), true, new String[]{message});
dialog.pack();
dialog.setLocationRelativeTo(MainFrame.getMainFrame());
dialog.setVisible(true);
break;
default:
errorWriter.println(formatter.format(new Date())+": ERROR: "+level+" :"+message);
System.err.println(formatter.format(new Date())+": ERROR: "+level+" :"+message);
break;
}
}
/**
* Record an error message for the application at the error error level,
* notifying the user if appropriate
* @param message Error message/cause
*/
public static void error(String message) {
error(ErrorLevel.ERROR, message);
}
/**
* Record an error message for the application, notifying the user if
* appropriate
* @param level error level
* @param exception Cause of error
*/
public static void error(ErrorLevel level, Exception exception) {
String[] message;
int i;
if (logWriter == null || debugWriter == null || errorWriter == null) {
createWriters();
}
StackTraceElement[] stackTrace = exception.getStackTrace();
switch (level) {
case FATAL:
errorWriter.println(formatter.format(new Date())+
": ERROR: "+level+" :"+exception);
message = new String[stackTrace.length+1];
message[0] = exception.toString();
i = 1;
for (StackTraceElement traceElement: stackTrace) {
message[i] = traceElement.toString();
logWriter.println("\t\t\t\t"+traceElement);
i++;
}
dialog = new FatalErrorDialog(MainFrame.getMainFrame(),
true, message);
dialog.pack();
dialog.setLocationRelativeTo(MainFrame.getMainFrame());
dialog.setVisible(true);
break;
default:
System.err.println(formatter.format(new Date())+
": ERROR: "+level+" :"+exception);
errorWriter.println(formatter.format(new Date())+
": ERROR: "+level+" :"+exception);
message = new String[stackTrace.length+1];
message[0] = exception.toString();
i = 1;
for (StackTraceElement traceElement: stackTrace) {
message[i] = traceElement.toString();
System.err.println("\t\t"+traceElement);
i++;
}
break;
}
}
/**
* Record an error message for the application at the error error level,
* notifying the user if appropriate
* @param exception Cause of error
*/
public static void error(Exception exception) {
error(ErrorLevel.ERROR, exception);
}
/**
* Record an debug message for the application, notifying the user if
* appropriate
* @param level debug level
* @param message Debug message
*/
public static void debug(DebugLevel level, String message) {
if (!Config.hasOption("logging","debugLogging")
&& !Config.getOption("logging", "debugLogging").equals("true")) {
return;
}
if (logWriter == null || debugWriter == null || errorWriter == null) {
createWriters();
}
switch(level) {
default:
if (Config.hasOption("logging","debugLoggingSysOut")
&& Config.getOption("logging", "debugLoggingSysOut")
.equals("true")) {
System.out.println(formatter.format(new Date())+
": DEBUG: "+level+" :"+message);
}
debugWriter.println(formatter.format(new Date())+
": DEBUG: "+level+" :"+message);
break;
}
}
/**
* Record an debug message for the application at the normal debug level,
* notifying the user if appropriate
* @param message Debug message
*/
public static void debug(String message) {
debug(DebugLevel.NORMAL, message);
}
/**
* Record a log message for the application
* @param level log level
* @param message Log message
*/
public static void log(LogLevel level, String message) {
if (!Config.hasOption("logging","programLogging")
&& !Config.getOption("logging", "programLogging").equals("true")) {
return;
}
if (logWriter == null || debugWriter == null || errorWriter == null) {
createWriters();
}
switch(level) {
default:
logWriter.println(formatter.format(new Date())+
": LOG: "+level+" :"+message);
break;
}
}
/**
* Initialises the the loggers writers (debug, error, log) and date formatter
*/
private static void createWriters() {
try {
if (logWriter == null) {
logWriter = new PrintWriter(new BufferedWriter(
new FileWriter(Config.getConfigDir()+"log.log")));
}
if (debugWriter == null) {
debugWriter = new PrintWriter(new BufferedWriter(
new FileWriter(Config.getConfigDir()+"debug.log")));
}
if (errorWriter == null) {
errorWriter = new PrintWriter(new BufferedWriter(
new FileWriter(Config.getConfigDir()+"error.log")));
}
} catch (IOException ex) {
Logger.error(ErrorLevel.WARNING, ex);
}
if (Config.hasOption("logging", "dateFormat")) {
formatter = new SimpleDateFormat(
Config.getOption("logging", "dateFormat"));
} else {
formatter = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
}
}
}
|
package com.cloud.vm.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.ejb.Local;
import org.apache.log4j.Logger;
import com.cloud.api.ApiDBUtils;
import com.cloud.api.response.NicResponse;
import com.cloud.api.response.SecurityGroupResponse;
import com.cloud.api.response.UserVmResponse;
import com.cloud.user.Account;
import com.cloud.uservm.UserVm;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.Attribute;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.GenericSearchBuilder;
import com.cloud.utils.db.JoinBuilder;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Func;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.NicVO;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachine.State;
@Local(value={UserVmDao.class})
public class UserVmDaoImpl extends GenericDaoBase<UserVmVO, Long> implements UserVmDao {
public static final Logger s_logger = Logger.getLogger(UserVmDaoImpl.class);
protected final SearchBuilder<UserVmVO> AccountPodSearch;
protected final SearchBuilder<UserVmVO> AccountDataCenterSearch;
protected final SearchBuilder<UserVmVO> AccountSearch;
protected final SearchBuilder<UserVmVO> HostSearch;
protected final SearchBuilder<UserVmVO> LastHostSearch;
protected final SearchBuilder<UserVmVO> HostUpSearch;
protected final SearchBuilder<UserVmVO> HostRunningSearch;
protected final SearchBuilder<UserVmVO> StateChangeSearch;
protected final SearchBuilder<UserVmVO> AccountHostSearch;
protected final SearchBuilder<UserVmVO> DestroySearch;
protected SearchBuilder<UserVmVO> AccountDataCenterVirtualSearch;
protected GenericSearchBuilder<UserVmVO, Long> CountByAccountPod;
protected GenericSearchBuilder<UserVmVO, Long> CountByAccount;
protected GenericSearchBuilder<UserVmVO, Long> PodsHavingVmsForAccount;
protected SearchBuilder<UserVmVO> UserVmSearch;
protected final Attribute _updateTimeAttr;
private static final String LIST_PODS_HAVING_VMS_FOR_ACCOUNT = "SELECT pod_id FROM cloud.vm_instance WHERE data_center_id = ? AND account_id = ? AND pod_id IS NOT NULL AND state = 'Running' OR state = 'Stopped' " +
"GROUP BY pod_id HAVING count(id) > 0 ORDER BY count(id) DESC";
private static final String VM_DETAILS = "select account.account_name, account.type, domain.name, instance_group.id, instance_group.name," +
"data_center.id, data_center.name, data_center.is_security_group_enabled, host.id, host.name, " +
"vm_template.id, vm_template.name, vm_template.display_text, iso.id, iso.name, " +
"vm_template.enable_password, service_offering.id, disk_offering.name, storage_pool.id, storage_pool.pool_type, " +
"service_offering.cpu, service_offering.speed, service_offering.ram_size, volumes.id, volumes.device_id, volumes.volume_type, security_group.id, security_group.name, " +
"security_group.description, nics.id, nics.ip4_address, nics.gateway, nics.network_id, nics.netmask, nics.mac_address, nics.broadcast_uri, nics.isolation_uri, " +
"networks.traffic_type, networks.guest_type, networks.is_default from vm_instance " +
"left join account on vm_instance.account_id=account.id " +
"left join domain on vm_instance.domain_id=domain.id " +
"left join instance_group_vm_map on vm_instance.id=instance_group_vm_map.instance_id " +
"left join instance_group on instance_group_vm_map.group_id=instance_group.id " +
"left join data_center on vm_instance.data_center_id=data_center.id " +
"left join host on vm_instance.host_id=host.id " +
"left join vm_template on vm_instance.vm_template_id=vm_template.id " +
"left join vm_template iso on iso.id=? " +
"left join service_offering on vm_instance.service_offering_id=service_offering.id " +
"left join disk_offering on vm_instance.service_offering_id=disk_offering.id " +
"left join volumes on vm_instance.id=volumes.instance_id " +
"left join storage_pool on volumes.pool_id=storage_pool.id " +
"left join security_group_vm_map on vm_instance.id=security_group_vm_map.instance_id " +
"left join security_group on security_group_vm_map.security_group_id=security_group.id " +
"left join nics on vm_instance.id=nics.instance_id " +
"left join networks on nics.network_id=networks.id " +
"where vm_instance.id=?";
protected final UserVmDetailsDaoImpl _detailsDao = ComponentLocator.inject(UserVmDetailsDaoImpl.class);
protected UserVmDaoImpl() {
AccountSearch = createSearchBuilder();
AccountSearch.and("account", AccountSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
AccountSearch.done();
HostSearch = createSearchBuilder();
HostSearch.and("host", HostSearch.entity().getHostId(), SearchCriteria.Op.EQ);
HostSearch.done();
LastHostSearch = createSearchBuilder();
LastHostSearch.and("lastHost", LastHostSearch.entity().getLastHostId(), SearchCriteria.Op.EQ);
LastHostSearch.and("state", LastHostSearch.entity().getState(), SearchCriteria.Op.EQ);
LastHostSearch.done();
HostUpSearch = createSearchBuilder();
HostUpSearch.and("host", HostUpSearch.entity().getHostId(), SearchCriteria.Op.EQ);
HostUpSearch.and("states", HostUpSearch.entity().getState(), SearchCriteria.Op.NIN);
HostUpSearch.done();
HostRunningSearch = createSearchBuilder();
HostRunningSearch.and("host", HostRunningSearch.entity().getHostId(), SearchCriteria.Op.EQ);
HostRunningSearch.and("state", HostRunningSearch.entity().getState(), SearchCriteria.Op.EQ);
HostRunningSearch.done();
AccountPodSearch = createSearchBuilder();
AccountPodSearch.and("account", AccountPodSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
AccountPodSearch.and("pod", AccountPodSearch.entity().getPodIdToDeployIn(), SearchCriteria.Op.EQ);
AccountPodSearch.done();
AccountDataCenterSearch = createSearchBuilder();
AccountDataCenterSearch.and("account", AccountDataCenterSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
AccountDataCenterSearch.and("dc", AccountDataCenterSearch.entity().getDataCenterIdToDeployIn(), SearchCriteria.Op.EQ);
AccountDataCenterSearch.done();
StateChangeSearch = createSearchBuilder();
StateChangeSearch.and("id", StateChangeSearch.entity().getId(), SearchCriteria.Op.EQ);
StateChangeSearch.and("states", StateChangeSearch.entity().getState(), SearchCriteria.Op.EQ);
StateChangeSearch.and("host", StateChangeSearch.entity().getHostId(), SearchCriteria.Op.EQ);
StateChangeSearch.and("update", StateChangeSearch.entity().getUpdated(), SearchCriteria.Op.EQ);
StateChangeSearch.done();
DestroySearch = createSearchBuilder();
DestroySearch.and("state", DestroySearch.entity().getState(), SearchCriteria.Op.IN);
DestroySearch.and("updateTime", DestroySearch.entity().getUpdateTime(), SearchCriteria.Op.LT);
DestroySearch.done();
AccountHostSearch = createSearchBuilder();
AccountHostSearch.and("accountId", AccountHostSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
AccountHostSearch.and("hostId", AccountHostSearch.entity().getHostId(), SearchCriteria.Op.EQ);
AccountHostSearch.done();
CountByAccountPod = createSearchBuilder(Long.class);
CountByAccountPod.select(null, Func.COUNT, null);
CountByAccountPod.and("account", CountByAccountPod.entity().getAccountId(), SearchCriteria.Op.EQ);
CountByAccountPod.and("pod", CountByAccountPod.entity().getPodIdToDeployIn(), SearchCriteria.Op.EQ);
CountByAccountPod.done();
CountByAccount = createSearchBuilder(Long.class);
CountByAccount.select(null, Func.COUNT, null);
CountByAccount.and("account", CountByAccount.entity().getAccountId(), SearchCriteria.Op.EQ);
CountByAccount.and("type", CountByAccount.entity().getType(), SearchCriteria.Op.EQ);
CountByAccount.and("state", CountByAccount.entity().getState(), SearchCriteria.Op.NIN);
CountByAccount.done();
_updateTimeAttr = _allAttributes.get("updateTime");
assert _updateTimeAttr != null : "Couldn't get this updateTime attribute";
}
@Override
public List<UserVmVO> listByAccountAndPod(long accountId, long podId) {
SearchCriteria<UserVmVO> sc = AccountPodSearch.create();
sc.setParameters("account", accountId);
sc.setParameters("pod", podId);
return listIncludingRemovedBy(sc);
}
@Override
public List<UserVmVO> listByAccountAndDataCenter(long accountId, long dcId) {
SearchCriteria<UserVmVO> sc = AccountDataCenterSearch.create();
sc.setParameters("account", accountId);
sc.setParameters("dc", dcId);
return listIncludingRemovedBy(sc);
}
@Override
public void updateVM(long id, String displayName, boolean enable, Long osTypeId, String userData) {
UserVmVO vo = createForUpdate();
vo.setDisplayName(displayName);
vo.setHaEnabled(enable);
vo.setGuestOSId(osTypeId);
vo.setUserData(userData);
update(id, vo);
}
@Override
public List<UserVmVO> findDestroyedVms(Date date) {
SearchCriteria<UserVmVO> sc = DestroySearch.create();
sc.setParameters("state", State.Destroyed, State.Expunging, State.Error);
sc.setParameters("updateTime", date);
return listBy(sc);
}
@Override
public List<UserVmVO> listByAccountId(long id) {
SearchCriteria<UserVmVO> sc = AccountSearch.create();
sc.setParameters("account", id);
return listBy(sc);
}
@Override
public List<UserVmVO> listByHostId(Long id) {
SearchCriteria<UserVmVO> sc = HostSearch.create();
sc.setParameters("host", id);
return listBy(sc);
}
@Override
public List<UserVmVO> listUpByHostId(Long hostId) {
SearchCriteria<UserVmVO> sc = HostUpSearch.create();
sc.setParameters("host", hostId);
sc.setParameters("states", new Object[] {State.Destroyed, State.Stopped, State.Expunging});
return listBy(sc);
}
@Override
public List<UserVmVO> listRunningByHostId(long hostId) {
SearchCriteria<UserVmVO> sc = HostRunningSearch.create();
sc.setParameters("host", hostId);
sc.setParameters("state", State.Running);
return listBy(sc);
}
@Override
public List<UserVmVO> listVirtualNetworkInstancesByAcctAndZone(long accountId, long dcId, long networkId) {
if (AccountDataCenterVirtualSearch == null) {
NicDao _nicDao = ComponentLocator.getLocator("management-server").getDao(NicDao.class);
SearchBuilder<NicVO> nicSearch = _nicDao.createSearchBuilder();
nicSearch.and("networkId", nicSearch.entity().getNetworkId(), SearchCriteria.Op.EQ);
nicSearch.and("ip4Address", nicSearch.entity().getIp4Address(), SearchCriteria.Op.NNULL);
AccountDataCenterVirtualSearch = createSearchBuilder();
AccountDataCenterVirtualSearch.and("account", AccountDataCenterVirtualSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
AccountDataCenterVirtualSearch.and("dc", AccountDataCenterVirtualSearch.entity().getDataCenterIdToDeployIn(), SearchCriteria.Op.EQ);
AccountDataCenterVirtualSearch.join("nicSearch", nicSearch, AccountDataCenterVirtualSearch.entity().getId(), nicSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER);
AccountDataCenterVirtualSearch.done();
}
SearchCriteria<UserVmVO> sc = AccountDataCenterVirtualSearch.create();
sc.setParameters("account", accountId);
sc.setParameters("dc", dcId);
sc.setJoinParameters("nicSearch", "networkId", networkId);
return listBy(sc);
}
@Override
public List<UserVmVO> listByNetworkIdAndStates(long networkId, State... states) {
if (UserVmSearch == null) {
NicDao _nicDao = ComponentLocator.getLocator("management-server").getDao(NicDao.class);
SearchBuilder<NicVO> nicSearch = _nicDao.createSearchBuilder();
nicSearch.and("networkId", nicSearch.entity().getNetworkId(), SearchCriteria.Op.EQ);
nicSearch.and("ip4Address", nicSearch.entity().getIp4Address(), SearchCriteria.Op.NNULL);
UserVmSearch = createSearchBuilder();
UserVmSearch.and("states", UserVmSearch.entity().getState(), SearchCriteria.Op.IN);
UserVmSearch.join("nicSearch", nicSearch, UserVmSearch.entity().getId(), nicSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER);
UserVmSearch.done();
}
SearchCriteria<UserVmVO> sc = UserVmSearch.create();
if (states != null && states.length != 0) {
sc.setParameters("states", (Object[]) states);
}
sc.setJoinParameters("nicSearch", "networkId", networkId);
return listBy(sc);
}
@Override
public List<UserVmVO> listByLastHostId(Long hostId) {
SearchCriteria<UserVmVO> sc = LastHostSearch.create();
sc.setParameters("lastHost", hostId);
sc.setParameters("state", State.Stopped);
return listBy(sc);
}
@Override
public List<UserVmVO> listByAccountIdAndHostId(long accountId, long hostId) {
SearchCriteria<UserVmVO> sc = AccountHostSearch.create();
sc.setParameters("hostId", hostId);
sc.setParameters("accountId", accountId);
return listBy(sc);
}
@Override
public void loadDetails(UserVmVO vm) {
Map<String, String> details = _detailsDao.findDetails(vm.getId());
vm.setDetails(details);
}
@Override
public void saveDetails(UserVmVO vm) {
Map<String, String> details = vm.getDetails();
if (details == null) {
return;
}
_detailsDao.persist(vm.getId(), details);
}
@Override
public List<Long> listPodIdsHavingVmsforAccount(long zoneId, long accountId){
Transaction txn = Transaction.currentTxn();
PreparedStatement pstmt = null;
List<Long> result = new ArrayList<Long>();
try {
String sql = LIST_PODS_HAVING_VMS_FOR_ACCOUNT;
pstmt = txn.prepareAutoCloseStatement(sql);
pstmt.setLong(1, zoneId);
pstmt.setLong(2, accountId);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
result.add(rs.getLong(1));
}
return result;
} catch (SQLException e) {
throw new CloudRuntimeException("DB Exception on: " + LIST_PODS_HAVING_VMS_FOR_ACCOUNT, e);
} catch (Throwable e) {
throw new CloudRuntimeException("Caught: " + LIST_PODS_HAVING_VMS_FOR_ACCOUNT, e);
}
}
@Override
public UserVmResponse listVmDetails(UserVm userVm, boolean show_host){
Transaction txn = Transaction.currentTxn();
PreparedStatement pstmt = null;
try {
String sql = VM_DETAILS;
pstmt = txn.prepareAutoCloseStatement(sql);
pstmt.setLong(1, userVm.getIsoId() == null ? -1 : userVm.getIsoId());
pstmt.setLong(2, userVm.getId());
ResultSet rs = pstmt.executeQuery();
boolean is_data_center_security_group_enabled=false;
Set<SecurityGroupResponse> securityGroupResponse = new HashSet<SecurityGroupResponse>();
Set<NicResponse> nicResponses = new HashSet<NicResponse>();
UserVmResponse userVmResponse = null;
while (rs.next()) {
if (userVmResponse==null){
userVmResponse=new UserVmResponse();
userVmResponse.setId(userVm.getId());
userVmResponse.setName(userVm.getDisplayName());
userVmResponse.setCreated(userVm.getCreated());
userVmResponse.setGuestOsId(userVm.getGuestOSId());
userVmResponse.setHaEnable(userVm.isHaEnabled());
if (userVm.getState() != null) {
userVmResponse.setState(userVm.getState().toString());
}
if (userVm.getDisplayName() != null) {
userVmResponse.setDisplayName(userVm.getDisplayName());
} else {
userVmResponse.setDisplayName(userVm.getHostName());
}
//account.account_name, account.type, domain.name, instance_group.id, instance_group.name,"
userVmResponse.setAccountName(rs.getString("account.account_name"));
userVmResponse.setDomainId(userVm.getDomainId());
userVmResponse.setDomainName(rs.getString("domain.name"));
long grp_id = rs.getLong("instance_group.id");
if (grp_id > 0){
userVmResponse.setGroupId(grp_id);
userVmResponse.setGroup(rs.getString("instance_group.name"));
}
//"data_center.id, data_center.name, host.id, host.name, vm_template.id, vm_template.name, vm_template.display_text, vm_template.enable_password,
userVmResponse.setZoneId(rs.getLong("data_center.id"));
userVmResponse.setZoneName(rs.getString("data_center.name"));
if (show_host){
userVmResponse.setHostId(rs.getLong("host.id"));
userVmResponse.setHostName(rs.getString("host.name"));
}
if (userVm.getHypervisorType() != null) {
userVmResponse.setHypervisor(userVm.getHypervisorType().toString());
}
long template_id = rs.getLong("vm_template.id");
if (template_id > 0){
userVmResponse.setTemplateId(template_id);
userVmResponse.setTemplateName(rs.getString("vm_template.name"));
userVmResponse.setTemplateDisplayText(rs.getString("vm_template.display_text"));
userVmResponse.setPasswordEnabled(rs.getBoolean("vm_template.enable_password"));
}
else {
userVmResponse.setTemplateId(-1L);
userVmResponse.setTemplateName("ISO Boot");
userVmResponse.setTemplateDisplayText("ISO Boot");
userVmResponse.setPasswordEnabled(false);
}
long iso_id = rs.getLong("iso.id");
if (iso_id > 0){
userVmResponse.setIsoId(iso_id);
userVmResponse.setIsoName(rs.getString("iso.name"));
}
if (userVm.getPassword() != null) {
userVmResponse.setPassword(userVm.getPassword());
}
//service_offering.id, disk_offering.name, "
//"service_offering.cpu, service_offering.speed, service_offering.ram_size,
userVmResponse.setServiceOfferingId(rs.getLong("service_offering.id"));
userVmResponse.setServiceOfferingName(rs.getString("disk_offering.name"));
userVmResponse.setCpuNumber(rs.getInt("service_offering.cpu"));
userVmResponse.setCpuSpeed(rs.getInt("service_offering.speed"));
userVmResponse.setMemory(rs.getInt("service_offering.ram_size"));
// volumes.device_id, volumes.volume_type,
long vol_id = rs.getLong("volumes.id");
if (vol_id > 0){
userVmResponse.setRootDeviceId(rs.getLong("volumes.device_id"));
userVmResponse.setRootDeviceType(rs.getString("volumes.volume_type"));
// storage pool
long pool_id = rs.getLong("storage_pool.id");
if (pool_id > 0){
userVmResponse.setRootDeviceType(rs.getString("storage_pool.pool_type"));
}
else {
userVmResponse.setRootDeviceType("Not created");
}
}
is_data_center_security_group_enabled = rs.getBoolean("data_center.is_security_group_enabled");
}
//security_group.id, security_group.name, security_group.description, , data_center.is_security_group_enabled
if (is_data_center_security_group_enabled){
SecurityGroupResponse resp = new SecurityGroupResponse();
resp.setId(rs.getLong("security_group.id"));
resp.setName(rs.getString("security_group.name"));
resp.setDescription(rs.getString("security_group.description"));
resp.setObjectName("securitygroup");
securityGroupResponse.add(resp);
}
//nics.id, nics.ip4_address, nics.gateway, nics.network_id, nics.netmask, nics. mac_address, nics.broadcast_uri, nics.isolation_uri, " +
//"networks.traffic_type, networks.guest_type, networks.is_default from vm_instance, "
long nic_id = rs.getLong("nics.id");
if (nic_id > 0){
NicResponse nicResponse = new NicResponse();
nicResponse.setId(nic_id);
nicResponse.setIpaddress(rs.getString("nics.ip4_address"));
nicResponse.setGateway(rs.getString("nics.gateway"));
nicResponse.setNetmask(rs.getString("nics.netmask"));
nicResponse.setNetworkid(rs.getLong("nics.network_id"));
nicResponse.setMacAddress(rs.getString("nics.mac_address"));
int account_type = rs.getInt("account.type");
if (account_type == Account.ACCOUNT_TYPE_ADMIN) {
nicResponse.setBroadcastUri(rs.getString("nics.broadcast_uri"));
nicResponse.setIsolationUri(rs.getString("nics.isolation_uri"));
}
nicResponse.setTrafficType(rs.getString("networks.traffic_type"));
nicResponse.setType(rs.getString("networks.guest_type"));
nicResponse.setIsDefault(rs.getBoolean("networks.is_default"));
nicResponse.setObjectName("nic");
nicResponses.add(nicResponse);
}
}
userVmResponse.setSecurityGroupList(new ArrayList(securityGroupResponse));
userVmResponse.setNics(new ArrayList(nicResponses));
return userVmResponse;
} catch (SQLException e) {
throw new CloudRuntimeException("DB Exception on: " + VM_DETAILS, e);
} catch (Throwable e) {
throw new CloudRuntimeException("Caught: " + VM_DETAILS, e);
}
}
@Override
public Long countAllocatedVMsForAccount(long accountId) {
SearchCriteria<Long> sc = CountByAccount.create();
sc.setParameters("account", accountId);
sc.setParameters("type", VirtualMachine.Type.User);
sc.setParameters("state", new Object[] {State.Destroyed, State.Error, State.Expunging});
return customSearch(sc, null).get(0);
}
}
|
package image;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.DefaultHandler;
import utils.Math2;
import utils.SAXUtils;
/**
* An input equirectangular map based on an SVG file
*
* @author jkunimune
*/
public class SVGMap implements Iterable<SVGMap.Path> {
public static final double[] NULL_TRANSFORM = {1, 1, 0, 0};
private static final double MAX_EDGE_FACTOR = 20; // cut lines that are more than this much longer than their neighbors
private static final double MAX_EDGE_LENGTH = 1/20.; // cut lines that are more than this far across the map
private List<Path> paths; //the set of closed curves in this image
private List<String> format; //the stuff that goes between the curve descriptions, probably important for something.
private double vbMinX, vbMinY, vbWidth, vbHeight; //the SVG viewBox
private double svgWidth, svgHeight; //the actual SVG dimensions
private int length; //the total number of path commands, for optimization purposes
private static final Map<String, String> ATTRIBUTE_PLACEHOLDERS;
static {
Map<String, String> map = new HashMap<String, String>();
map.put("width", "hmxMLwhWHeqMA8Ba");
map.put("height", "VlMBunXsmQUtmCw4");
map.put("viewBox", "UrFo1q9niPDkKSNC"); //attributes of the SVG object to change
ATTRIBUTE_PLACEHOLDERS = Collections.unmodifiableMap(map);
}
public SVGMap(File file) throws IOException, SAXException, ParserConfigurationException {
paths = new LinkedList<Path>();
format = new LinkedList<String>();
final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
final DefaultHandler handler = new DefaultHandler() {
private Deque<double[]> transformStack =
new ArrayDeque<double[]>(Collections.singleton(NULL_TRANSFORM));
private String currentFormatString = "";
@Override
public InputSource resolveEntity(String publicId, String systemId) {
return new InputSource(new StringReader("")); //ignore all external references - we don't need to validate
}
@Override
public void startElement(
String uri, String localName, String qName, Attributes attributes) throws SAXException {
currentFormatString += "<"+qName;
if (attributes.getIndex("transform") >= 0)
attributes = parseTransform(attributes);
else
parseTransform();
if (qName.equals("svg")) {
attributes = parseViewBox(attributes);
}
else if (qName.equals("path")) {
try {
attributes = parsePath(attributes);
} catch (Exception e) {
throw new SAXException(e.getLocalizedMessage(), null);
}
}
else if (attributes.getIndex("x") >= 0 && attributes.getIndex("y") >= 0) {
attributes = parsePoint(attributes, false);
}
else if (attributes.getIndex("cx") >= 0 && attributes.getIndex("cy") >= 0) {
attributes = parsePoint(attributes, true);
}
for (int i = 0; i < attributes.getLength(); i ++)
currentFormatString +=
" "+attributes.getQName(i)+"=\""+attributes.getValue(i)+"\"";
currentFormatString += ">";
}
@Override
public void endElement(String uri, String localName, String qName) {
currentFormatString += "</"+qName+">";
transformStack.pop();
}
@Override
public void characters(char[] ch, int start, int length) {
for (int i = 0; i < length; i ++) {
char c = ch[start+i];
// if (c >= 128 || c == '\'' || c == '"' || c == '<' || c == '>' || c == '&') // some characters must be escaped here
// currentFormatString += "&#" + (int)c + ";";
// else
currentFormatString += c;
}
}
@Override
public void endDocument() {
format.add(currentFormatString);
}
private Attributes parseViewBox(Attributes attrs) {
if (attrs.getValue("width") != null)
svgWidth = Double.parseDouble(attrs.getValue("width"));
else
svgWidth = 360.;
if (attrs.getValue("height") != null)
svgHeight = Double.parseDouble(attrs.getValue("height"));
else
svgHeight = 180.;
if (attrs.getValue("viewBox") != null) {
String[] values = attrs.getValue("viewBox").split("\\s", 4);
vbMinX = Double.parseDouble(values[0]);
vbMinY = Double.parseDouble(values[1]);
vbWidth = Double.parseDouble(values[2]);
vbHeight = Double.parseDouble(values[3]);
}
else {
vbWidth = svgWidth;
vbHeight = svgHeight;
vbMinX = 0;
vbMinY = 0;
}
AttributesImpl modAttrs = new AttributesImpl(attrs); //now insert the placeholders for the format string
for (String qName: ATTRIBUTE_PLACEHOLDERS.keySet()) {
if (modAttrs.getIndex(qName) >= 0)
modAttrs.setValue(modAttrs.getIndex(qName), ATTRIBUTE_PLACEHOLDERS.get(qName));
else
modAttrs.addAttribute("", "", qName, "", ATTRIBUTE_PLACEHOLDERS.get(qName));
}
return modAttrs;
}
private void parseTransform() {
transformStack.push(transformStack.peek());
}
private Attributes parseTransform(Attributes attrs) {
String transString = attrs.getValue("transform");
double xScale = 1, yScale = 1, xTrans = 0, yTrans = 0;
int i;
while ((i = transString.indexOf('(')) >= 0) {
int j = transString.indexOf(')');
String type = transString.substring(0, i).trim();
String argString = transString.substring(i+1, j);
String[] args = argString.split("[,\\s]+");
if (type.equals("matrix")) {
xScale = Double.parseDouble(args[0]);
yScale = Double.parseDouble(args[3]);
xTrans = Double.parseDouble(args[4]);
yTrans = Double.parseDouble(args[5]);
}
else if (type.equals("translate")) {
if (args.length == 1) {
xTrans = yTrans = Double.parseDouble(args[0]);
}
else {
xTrans = Double.parseDouble(args[0]);
yTrans = Double.parseDouble(args[1]);
}
}
else if (type.equals("scale")) {
if (args.length == 1) {
xScale = yScale = Double.parseDouble(args[0]);
}
else {
xScale = Double.parseDouble(args[0]);
yScale = Double.parseDouble(args[1]);
}
} //I'm not worrying about shear and rotation because I don't want to
transString = transString.substring(j+1);
}
transformStack.push(new double[] {xScale, yScale, xTrans, yTrans});
return SAXUtils.removeAttribute(attrs, "transform");
}
private Attributes parsePath(Attributes attrs) throws Exception {
currentFormatString += " d=\"";
format.add(currentFormatString);
paths.add(new Path(attrs.getValue("d"), transformStack.peek(),
vbMinX, vbMinY, vbWidth, vbHeight));
currentFormatString = "\"";
length += paths.get(paths.size()-1).size();
return SAXUtils.removeAttribute(attrs, "d");
}
private Attributes parsePoint(Attributes attrs, boolean center) {
format.add(currentFormatString); //points are represented as single-point paths
double[] transform = transformStack.peek();
double[] coords = new double[2];
coords[0] = Double.parseDouble(attrs.getValue(center ? "cx" : "x")); //get the coordinates from the attributes
coords[1] = Double.parseDouble(attrs.getValue(center ? "cy" : "y"));
coords[0] = transform[0]*coords[0] + transform[2]; //apply any necessary transformation
coords[1] = transform[1]*coords[1] + transform[3];
coords[0] = Math2.linInterp(coords[0], vbMinX, vbMinX+vbWidth, -Math.PI, Math.PI);
coords[1] = Math2.linInterp(coords[1], vbMinY+vbHeight, vbMinY, -Math.PI/2, Math.PI/2);
paths.add(new Path(new Command(center ? 'O' : 'P', coords)));
currentFormatString = "";
length += 1;
if (center)
return SAXUtils.removeAttribute(attrs, "cx", "cy");
else
return SAXUtils.removeAttribute(attrs, "x", "y");
}
};
parser.parse(new BufferedInputStream(new FileInputStream(file)), handler);
}
private SVGMap(List<Path> paths, List<String> format, double vbMinX, double vbMinY,
double vbWidth, double vbHeight, double svgWidth, double svgHeight, int size) {
this.paths = paths;
this.format = format;
this.vbMinX = vbMinX;
this.vbMinY = vbMinY;
this.vbWidth = vbWidth;
this.vbHeight = vbHeight;
this.svgWidth = svgWidth;
this.svgHeight = svgHeight;
this.length = size;
}
public int length() {
return this.length;
}
public int numCurves() {
return paths.size();
}
@Override
public Iterator<Path> iterator() {
return paths.iterator();
}
/**
* @return the result of replacing all instances of target in the format strings
*/
public SVGMap replace(CharSequence target, CharSequence replacement) {
List<String> newFormat = new LinkedList<String>();
for (String f: this.format)
newFormat.add(f.replace(target, replacement));
return new SVGMap(
paths, newFormat, vbMinX, vbMinY, vbWidth, vbHeight, svgWidth, svgHeight, length);
}
public void save(List<Path> paths, File file, double inMinX, double inMaxY, double inWidth,
double inHeight) throws IOException {
BufferedWriter out = new BufferedWriter(new FileWriter(file));
final Iterator<String> formatIterator = format.iterator();
final Iterator<Path> curveIterator = paths.iterator();
out.write(SAXUtils.encode(replacePlaceholders(formatIterator.next(), inWidth/inHeight)));
while (curveIterator.hasNext()) {
out.write(closePaths(
breakWraps(curveIterator.next(), Math.max(inWidth, inHeight))
).toString(
inMinX, inMaxY, vbMinX, vbMinY,
Math.max(vbWidth, vbHeight)/Math.max(inWidth, inHeight)));
out.write(SAXUtils.encode(formatIterator.next()));
}
out.close();
}
private String replacePlaceholders(String str, double desiredAspectRatio) { //change the width, height, and viewBox attributes to match the new aspect ratio
double outVBWidth, outVBHeight, outSVGWidth, outSVGHeight;
if (desiredAspectRatio > 1) {
outVBWidth = Math.max(this.vbWidth, this.vbHeight);
outVBHeight = outVBWidth/desiredAspectRatio;
outSVGWidth = Math.max(this.svgWidth, this.svgHeight);
outSVGHeight = outSVGWidth/desiredAspectRatio;
}
else {
outVBHeight = Math.max(this.vbWidth, this.vbHeight);
outVBWidth = outVBHeight*desiredAspectRatio;
outSVGHeight = Math.max(this.svgWidth, this.svgHeight);
outSVGWidth = outSVGHeight*desiredAspectRatio;
}
String viewBoxString = formatDouble(vbMinX) + " " + formatDouble(vbMinY) + " "
+ formatDouble(outVBWidth) + " " + formatDouble(outVBHeight);
str = str.replace(ATTRIBUTE_PLACEHOLDERS.get("viewBox"), viewBoxString);
str = str.replace(ATTRIBUTE_PLACEHOLDERS.get("width"), formatDouble(outSVGWidth));
str = str.replace(ATTRIBUTE_PLACEHOLDERS.get("height"), formatDouble(outSVGHeight));
return str;
}
private Path breakWraps(Path continuous, double inSize) { //break excessively long commands, as they are likely wrapping over a discontinuity
if (continuous.size() <= 2) return continuous;
Path broken = new Path();
final double lengthThreshold = inSize*MAX_EDGE_LENGTH;
double[] lens = {Double.NaN, Double.NaN, Double.NaN}; //the revolving array of command lengths
for (int i = 0; i < continuous.size(); i ++) {
if (i < continuous.size()-1 && continuous.get(i+1).type != 'M')
lens[2] = Math.hypot( //compute this next length
continuous.get(i+1).args[0] - continuous.get(i).args[0],
continuous.get(i+1).args[1] - continuous.get(i).args[1]);
else
lens[2] = Double.NaN;
char type = continuous.get(i).type;
if (lens[1] >= lengthThreshold && // check it against an absolute threshold
(Double.isNaN(lens[0]) || lens[1] > 20*lens[0]) && //and compare it to the last two lengths
(Double.isNaN(lens[2]) || lens[1] > 20*lens[2])) //if both sides are far longer or nonexistent
type = 'M'; //break this line
broken.add(new Command(type, continuous.get(i).args.clone()));
lens[0] = lens[1];
lens[1] = lens[2];
}
return broken;
}
private Path closePaths(Path open) { //replace plain loops with 'Z's and combine connected parts
if (open.size() <= 1) return open;
List<Path> parts = new ArrayList<Path>();
Path currentPart = null;
for (Command cmd: open) { //start by breaking the Path into parts,
if (cmd.type == 'M') { //separated by movetos
if (currentPart != null)
parts.add(currentPart);
currentPart = new Path();
}
currentPart.add(cmd);
}
parts.add(currentPart);
Path closed = new Path();
for (int i = 0; i < parts.size(); i ++) { //now look through those parts
Path partI = parts.get(i);
if (partI.size() > 1
&& Arrays.equals(partI.get(0).args, partI.get(partI.size()-1).args)) { //if it is self-enclosing
partI.set(partI.size()-1, new Command('Z', new double[0])); //give it a closepath and send it on its way
}
else { //if it is open
for (int j = i+1; j < parts.size(); j ++) { //look to see if there is anything that completes it
Path partJ = parts.get(j);
if (Arrays.equals(partI.get(0).args, partJ.get(partJ.size()-1).args)) { //if so,
partI.remove(0); //remove the useless moveto
partJ.addAll(partI); //combine them
partI = partJ;
parts.remove(j); //don't look at J anymone; it has been absorbed.
break;
}
}
}
closed.addAll(partI); //now turn in whatever you've got
}
return closed;
}
private static boolean isNonELetter(char c) {
return (c >= 'A' && c <= 'Z' && c != 'E') || (c >= 'a' && c <= 'z' && c != 'e');
}
private static String formatDouble(double d) { //format numbers just the way I want them
String str = String.format("%04d", (int)Math.round(d*1000));
str = str.substring(0, str.length()-3) + "." + str.substring(str.length()-3);
return str.replaceFirst("\\.?0*$", "");
}
/**
* An svg path String, stored in a modifiable form
* @author jkunimune
*/
public static class Path extends ArrayList<Command> {
private static final long serialVersionUID = 8635895911857570332L;
public Path() {
super();
}
public Path(Command... commands) {
this();
this.addAll(Arrays.asList(commands));
}
public Path(String d, double vbWidth, double vbHeight) throws Exception {
this(d, new double[] {1,1,0,0}, 0, 0, vbWidth, vbHeight);
}
public Path(String d, double[] transform,
double vbMinX, double vbMinY, double vbWidth, double vbHeight) throws Exception { //I don't know if this is bad coding practice, but I don't really want to find a way to gracefully catch all possible errors into some more specific Exception class
super();
int i = 0;
double[] lastMove = {0, 0}; //for closepaths
double[] last = {0, 0}; //for relative coordinates
while (i < d.length()) {
char type = d.charAt(i);
String argString = "";
while (i+1 < d.length() && !isNonELetter(d.charAt(i+1))) {
i ++;
argString += d.charAt(i);
}
argString = argString.replaceAll("([0-9\\.])-", "$1,-"); //this is necessary because some Adobe products leave out delimiters between negative numbers
i ++;
String[] argStrings;
if (argString.trim().isEmpty()) argStrings = new String[0];
else argStrings = argString.trim().split("[\\s,]+");
final double[] args;
if (type == 'a' || type == 'A') {
type += (type == 'a') ? 'l' : 'L'; //change this to a line; I don't want to deal with arcs
argStrings = new String[] {argStrings[3], argStrings[4]};
}
if (type == 'h' || type == 'H' || type == 'v' || type == 'V') { //convert these to 'L'
final int direcIdx = (type%32 == 8) ? 0 : 1;
args = new double[] {last[0], last[1]};
if (type <= 'Z') args[direcIdx] = Double.parseDouble(argStrings[0]); //uppercase (absolute)
else args[direcIdx] += Double.parseDouble(argStrings[0]); //lowercase (relative)
last[direcIdx] = args[direcIdx];
type = 'L';
}
else if (type == 'z' || type == 'Z') { //change this to 'L', too
args = new double[] {lastMove[0], lastMove[1]};
type = 'L';
}
else {
args = new double[argStrings.length];
for (int j = 0; j < args.length; j ++) {
args[j] = Double.parseDouble(argStrings[j]); //parse the coordinate
if (type >= 'a')
args[j] += last[j%2]; //account for relative commands
last[j%2] = args[j];
}
if (type >= 'a') //make all letters uppercase
type -= 32;
}
if (type == 'M') { //make note, so we can interpret closepaths properly
lastMove[0] = args[args.length-2];
lastMove[1] = args[args.length-1];
}
for (int j = 0; j < args.length; j ++) {
if (!Double.isFinite(args[j]))
throw new IllegalArgumentException("uhh... "+type+argString);
if (j%2 == 0) {
args[j] = args[j]*transform[0] + transform[2]; //apply the transformation
args[j] = Math2.linInterp(args[j], vbMinX, vbMinX+vbWidth,
-Math.PI, Math.PI); //scale to radians
}
else {
args[j] = args[j]*transform[1] + transform[3];
args[j] = Math2.linInterp(args[j], vbMinY+vbHeight, vbMinY, //keep in mind that these are paired longitude-latitude
-Math.PI/2, Math.PI/2); //not latitude-longitude, as they are elsewhere
}
}
this.add(new Command(type, args));
}
}
public String toString(
double inMinX, double inMaxY, double outMinX, double outMinY, double outScale) {
String s = "";
for (Command c: this)
s += c.toString(inMinX, inMaxY, outMinX, outMinY, outScale)+" ";
return s;
}
}
/**
* An SVG command, like line or bezier curve or whatever
* @author jkunimune
*/
public static class Command {
final public char type; //M, L, C, etc. This will never be lowercase
final public double[] args; //the absolute coordinates that go with it
public Command(char type, double[] args) {
this.type = type;
this.args = args;
}
public Command(Command command) {
this(command.type, command.args.clone());
}
public String toString() {
return this.toString(-1, -1, 0, 0, 1);
}
public String toString(
double inMinX, double inMaxY, double outMinX, double outMinY, double outScale) {
if (type == 'O') //'O' and 'P' are special; specific points
return " cx=\""+formatDouble(outMinX + (args[0]-inMinX)*outScale)+
"\" cy=\""+formatDouble(outMinY + (inMaxY-args[1])*outScale)+"\"";
else if (type == 'P')
return " x=\""+formatDouble(outMinX + (args[0]-inMinX)*outScale)+
"\" y=\""+formatDouble(outMinY + (inMaxY-args[1])*outScale)+"\"";
String s = Character.toString(type);
for (int i = 0; i < args.length; i ++) {
if (i%2 == 0)
s += formatDouble(outMinX + (args[i]-inMinX)*outScale)+",";
else
s += formatDouble(outMinY + (inMaxY-args[i])*outScale)+",";
}
return s.substring(0, Math.max(1, s.length()-1));
}
}
}
|
// Utiilities for LAN
package lan;
import java.net.Socket;
public class LANUtils
{
public static boolean hostIsActive(String host, int port)
{
try
{
Socket s //= new Socket();
s.setSoTimeout(400);
//set address host port
//connect
s.close();
return true;
}
catch (Exception e)
{
return false;
}
}
}
|
package org.postgresql.jdbc2;
// IMPORTANT NOTE: This file implements the JDBC 2 version of the driver.
// If you make any modifications to this file, you must make sure that the
// changes are also made (if relevent) to the related JDBC 1 class in the
// org.postgresql.jdbc1 package.
import java.io.*;
import java.math.*;
import java.sql.*;
import java.text.*;
import java.util.*;
import org.postgresql.largeobject.*;
import org.postgresql.util.*;
/**
* A SQL Statement is pre-compiled and stored in a PreparedStatement object.
* This object can then be used to efficiently execute this statement multiple
* times.
*
* <p><B>Note:</B> The setXXX methods for setting IN parameter values must
* specify types that are compatible with the defined SQL type of the input
* parameter. For instance, if the IN parameter has SQL type Integer, then
* setInt should be used.
*
* <p>If arbitrary parameter type conversions are required, then the setObject
* method should be used with a target SQL type.
*
* @see ResultSet
* @see java.sql.PreparedStatement
*/
public class PreparedStatement extends Statement implements java.sql.PreparedStatement
{
String sql;
String[] templateStrings;
String[] inStrings;
Connection connection;
// Some performance caches
private StringBuffer sbuf = new StringBuffer();
// We use ThreadLocal for SimpleDateFormat's because they are not that
// thread safe, so each calling thread has its own object.
private static ThreadLocal tl_df = new ThreadLocal(); // setDate() SimpleDateFormat
private static ThreadLocal tl_tsdf = new ThreadLocal(); // setTimestamp() SimpleDateFormat
/**
* Constructor for the PreparedStatement class.
* Split the SQL statement into segments - separated by the arguments.
* When we rebuild the thing with the arguments, we can substitute the
* args and join the whole thing together.
*
* @param conn the instanatiating connection
* @param sql the SQL statement with ? for IN markers
* @exception SQLException if something bad occurs
*/
public PreparedStatement(Connection connection, String sql) throws SQLException
{
super(connection);
Vector v = new Vector();
boolean inQuotes = false;
int lastParmEnd = 0, i;
this.sql = sql;
this.connection = connection;
// might just as well create it here, so we don't take the hit later
SimpleDateFormat df = new SimpleDateFormat("''yyyy-MM-dd''");
tl_df.set(df);
df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
tl_tsdf.set(df);
for (i = 0; i < sql.length(); ++i)
{
int c = sql.charAt(i);
if (c == '\'')
inQuotes = !inQuotes;
if (c == '?' && !inQuotes)
{
v.addElement(sql.substring (lastParmEnd, i));
lastParmEnd = i + 1;
}
}
v.addElement(sql.substring (lastParmEnd, sql.length()));
templateStrings = new String[v.size()];
inStrings = new String[v.size() - 1];
clearParameters();
for (i = 0 ; i < templateStrings.length; ++i)
templateStrings[i] = (String)v.elementAt(i);
}
/**
* New in 7.1 - overides Statement.close() to dispose of a few local objects
*/
public void close() throws SQLException
{
// free the ThreadLocal caches
tl_df.set(null);
tl_tsdf.set(null);
super.close();
}
/**
* A Prepared SQL query is executed and its ResultSet is returned
*
* @return a ResultSet that contains the data produced by the
* query - never null
* @exception SQLException if a database access error occurs
*/
public java.sql.ResultSet executeQuery() throws SQLException
{
return super.executeQuery(compileQuery()); // in Statement class
}
/**
* Execute a SQL INSERT, UPDATE or DELETE statement. In addition,
* SQL statements that return nothing such as SQL DDL statements can
* be executed.
*
* @return either the row count for INSERT, UPDATE or DELETE; or
* 0 for SQL statements that return nothing.
* @exception SQLException if a database access error occurs
*/
public int executeUpdate() throws SQLException
{
return super.executeUpdate(compileQuery()); // in Statement class
}
/**
* Helper - this compiles the SQL query from the various parameters
* This is identical to toString() except it throws an exception if a
* parameter is unused.
*/
private synchronized String compileQuery() throws SQLException
{
sbuf.setLength(0);
int i;
for (i = 0 ; i < inStrings.length ; ++i)
{
if (inStrings[i] == null)
throw new PSQLException("postgresql.prep.param",new Integer(i + 1));
sbuf.append (templateStrings[i]).append (inStrings[i]);
}
sbuf.append(templateStrings[inStrings.length]);
return sbuf.toString();
}
/**
* Set a parameter to SQL NULL
*
* <p><B>Note:</B> You must specify the parameters SQL type (although
* PostgreSQL ignores it)
*
* @param parameterIndex the first parameter is 1, etc...
* @param sqlType the SQL type code defined in java.sql.Types
* @exception SQLException if a database access error occurs
*/
public void setNull(int parameterIndex, int sqlType) throws SQLException
{
set(parameterIndex, "null");
}
/**
* Set a parameter to a Java boolean value. The driver converts this
* to a SQL BIT value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setBoolean(int parameterIndex, boolean x) throws SQLException
{
set(parameterIndex, x ? "'t'" : "'f'");
}
/**
* Set a parameter to a Java byte value. The driver converts this to
* a SQL TINYINT value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setByte(int parameterIndex, byte x) throws SQLException
{
set(parameterIndex, Integer.toString(x));
}
/**
* Set a parameter to a Java short value. The driver converts this
* to a SQL SMALLINT value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setShort(int parameterIndex, short x) throws SQLException
{
set(parameterIndex, Integer.toString(x));
}
/**
* Set a parameter to a Java int value. The driver converts this to
* a SQL INTEGER value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setInt(int parameterIndex, int x) throws SQLException
{
set(parameterIndex, Integer.toString(x));
}
/**
* Set a parameter to a Java long value. The driver converts this to
* a SQL BIGINT value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setLong(int parameterIndex, long x) throws SQLException
{
set(parameterIndex, Long.toString(x));
}
/**
* Set a parameter to a Java float value. The driver converts this
* to a SQL FLOAT value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setFloat(int parameterIndex, float x) throws SQLException
{
set(parameterIndex, Float.toString(x));
}
/**
* Set a parameter to a Java double value. The driver converts this
* to a SQL DOUBLE value when it sends it to the database
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setDouble(int parameterIndex, double x) throws SQLException
{
set(parameterIndex, Double.toString(x));
}
/**
* Set a parameter to a java.lang.BigDecimal value. The driver
* converts this to a SQL NUMERIC value when it sends it to the
* database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException
{
set(parameterIndex, x.toString());
}
/**
* Set a parameter to a Java String value. The driver converts this
* to a SQL VARCHAR or LONGVARCHAR value (depending on the arguments
* size relative to the driver's limits on VARCHARs) when it sends it
* to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setString(int parameterIndex, String x) throws SQLException
{
// if the passed string is null, then set this column to null
if(x==null)
set(parameterIndex,"null");
else {
// use the shared buffer object. Should never clash but this makes
// us thread safe!
synchronized(sbuf) {
sbuf.setLength(0);
int i;
sbuf.append('\'');
for (i = 0 ; i < x.length() ; ++i)
{
char c = x.charAt(i);
if (c == '\\' || c == '\'')
sbuf.append((char)'\\');
sbuf.append(c);
}
sbuf.append('\'');
set(parameterIndex, sbuf.toString());
}
}
}
/**
* Set a parameter to a Java array of bytes. The driver converts this
* to a SQL VARBINARY or LONGVARBINARY (depending on the argument's
* size relative to the driver's limits on VARBINARYs) when it sends
* it to the database.
*
* <p>Implementation note:
* <br>With org.postgresql, this creates a large object, and stores the
* objects oid in this column.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setBytes(int parameterIndex, byte x[]) throws SQLException
{
LargeObjectManager lom = connection.getLargeObjectAPI();
int oid = lom.create();
LargeObject lob = lom.open(oid);
lob.write(x);
lob.close();
setInt(parameterIndex,oid);
}
/**
* Set a parameter to a java.sql.Date value. The driver converts this
* to a SQL DATE value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setDate(int parameterIndex, java.sql.Date x) throws SQLException
{
SimpleDateFormat df = (SimpleDateFormat) tl_df.get();
set(parameterIndex, df.format(x));
// The above is how the date should be handled.
// However, in JDK's prior to 1.1.6 (confirmed with the
// Linux jdk1.1.3 and the Win95 JRE1.1.5), SimpleDateFormat seems
// to format a date to the previous day. So the fix is to add a day
// before formatting.
// PS: 86400000 is one day
//set(parameterIndex, df.format(new java.util.Date(x.getTime()+86400000)));
}
/**
* Set a parameter to a java.sql.Time value. The driver converts
* this to a SQL TIME value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...));
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setTime(int parameterIndex, Time x) throws SQLException
{
set(parameterIndex, "'" + x.toString() + "'");
}
/**
* Set a parameter to a java.sql.Timestamp value. The driver converts
* this to a SQL TIMESTAMP value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException
{
SimpleDateFormat df = (SimpleDateFormat) tl_tsdf.get();
df.setTimeZone(TimeZone.getTimeZone("GMT"));
// Use the shared StringBuffer
synchronized(sbuf) {
sbuf.setLength(0);
sbuf.append("'").append(df.format(x)).append('.').append(x.getNanos()/10000000).append("+00'");
set(parameterIndex, sbuf.toString());
}
// The above works, but so does the following. I'm leaving the above in, but this seems
// to be identical. Pays to read the docs ;-)
//set(parameterIndex,"'"+x.toString()+"'");
}
/**
* When a very large ASCII value is input to a LONGVARCHAR parameter,
* it may be more practical to send it via a java.io.InputStream.
* JDBC will read the data from the stream as needed, until it reaches
* end-of-file. The JDBC driver will do any necessary conversion from
* ASCII to the database char format.
*
* <P><B>Note:</B> This stream object can either be a standard Java
* stream object or your own subclass that implements the standard
* interface.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @param length the number of bytes in the stream
* @exception SQLException if a database access error occurs
*/
public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException
{
setBinaryStream(parameterIndex, x, length);
}
/**
* When a very large Unicode value is input to a LONGVARCHAR parameter,
* it may be more practical to send it via a java.io.InputStream.
* JDBC will read the data from the stream as needed, until it reaches
* end-of-file. The JDBC driver will do any necessary conversion from
* UNICODE to the database char format.
*
* ** DEPRECIATED IN JDBC 2 **
*
* <P><B>Note:</B> This stream object can either be a standard Java
* stream object or your own subclass that implements the standard
* interface.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
* @deprecated
*/
public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException
{
setBinaryStream(parameterIndex, x, length);
}
/**
* When a very large binary value is input to a LONGVARBINARY parameter,
* it may be more practical to send it via a java.io.InputStream.
* JDBC will read the data from the stream as needed, until it reaches
* end-of-file.
*
* <P><B>Note:</B> This stream object can either be a standard Java
* stream object or your own subclass that implements the standard
* interface.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException
{
LargeObjectManager lom = connection.getLargeObjectAPI();
int oid = lom.create();
LargeObject lob = lom.open(oid);
OutputStream los = lob.getOutputStream();
try {
// could be buffered, but then the OutputStream returned by LargeObject
// is buffered internally anyhow, so there would be no performance
// boost gained, if anything it would be worse!
int c=x.read();
int p=0;
while(c>-1 && p<length) {
los.write(c);
c=x.read();
p++;
}
los.close();
} catch(IOException se) {
throw new PSQLException("postgresql.prep.is",se);
}
// lob is closed by the stream so don't call lob.close()
setInt(parameterIndex,oid);
}
/**
* In general, parameter values remain in force for repeated used of a
* Statement. Setting a parameter value automatically clears its
* previous value. However, in coms cases, it is useful to immediately
* release the resources used by the current parameter values; this
* can be done by calling clearParameters
*
* @exception SQLException if a database access error occurs
*/
public void clearParameters() throws SQLException
{
int i;
for (i = 0 ; i < inStrings.length ; i++)
inStrings[i] = null;
}
/**
* Set the value of a parameter using an object; use the java.lang
* equivalent objects for integral values.
*
* <P>The given Java object will be converted to the targetSqlType before
* being sent to the database.
*
* <P>note that this method may be used to pass database-specific
* abstract data types. This is done by using a Driver-specific
* Java type and using a targetSqlType of java.sql.Types.OTHER
*
* @param parameterIndex the first parameter is 1...
* @param x the object containing the input parameter value
* @param targetSqlType The SQL type to be send to the database
* @param scale For java.sql.Types.DECIMAL or java.sql.Types.NUMERIC
* types this is the number of digits after the decimal. For
* all other types this value will be ignored.
* @exception SQLException if a database access error occurs
*/
public void setObject(int parameterIndex, Object x, int targetSqlType, int scale) throws SQLException
{
if (x == null){
setNull(parameterIndex,Types.OTHER);
return;
}
switch (targetSqlType)
{
case Types.TINYINT:
case Types.SMALLINT:
case Types.INTEGER:
case Types.BIGINT:
case Types.REAL:
case Types.FLOAT:
case Types.DOUBLE:
case Types.DECIMAL:
case Types.NUMERIC:
if (x instanceof Boolean)
set(parameterIndex, ((Boolean)x).booleanValue() ? "1" : "0");
else
set(parameterIndex, x.toString());
break;
case Types.CHAR:
case Types.VARCHAR:
case Types.LONGVARCHAR:
setString(parameterIndex, x.toString());
break;
case Types.DATE:
setDate(parameterIndex, (java.sql.Date)x);
break;
case Types.TIME:
setTime(parameterIndex, (Time)x);
break;
case Types.TIMESTAMP:
setTimestamp(parameterIndex, (Timestamp)x);
break;
case Types.BIT:
if (x instanceof Boolean) {
set(parameterIndex, ((Boolean)x).booleanValue() ? "TRUE" : "FALSE");
} else {
throw new PSQLException("postgresql.prep.type");
}
break;
case Types.BINARY:
case Types.VARBINARY:
setObject(parameterIndex,x);
break;
case Types.OTHER:
setString(parameterIndex, ((PGobject)x).getValue());
break;
default:
throw new PSQLException("postgresql.prep.type");
}
}
public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException
{
setObject(parameterIndex, x, targetSqlType, 0);
}
/**
* This stores an Object into a parameter.
* <p>New for 6.4, if the object is not recognised, but it is
* Serializable, then the object is serialised using the
* org.postgresql.util.Serialize class.
*/
public void setObject(int parameterIndex, Object x) throws SQLException
{
if (x == null){
setNull(parameterIndex,Types.OTHER);
return;
}
if (x instanceof String)
setString(parameterIndex, (String)x);
else if (x instanceof BigDecimal)
setBigDecimal(parameterIndex, (BigDecimal)x);
else if (x instanceof Short)
setShort(parameterIndex, ((Short)x).shortValue());
else if (x instanceof Integer)
setInt(parameterIndex, ((Integer)x).intValue());
else if (x instanceof Long)
setLong(parameterIndex, ((Long)x).longValue());
else if (x instanceof Float)
setFloat(parameterIndex, ((Float)x).floatValue());
else if (x instanceof Double)
setDouble(parameterIndex, ((Double)x).doubleValue());
else if (x instanceof byte[])
setBytes(parameterIndex, (byte[])x);
else if (x instanceof java.sql.Date)
setDate(parameterIndex, (java.sql.Date)x);
else if (x instanceof Time)
setTime(parameterIndex, (Time)x);
else if (x instanceof Timestamp)
setTimestamp(parameterIndex, (Timestamp)x);
else if (x instanceof Boolean)
setBoolean(parameterIndex, ((Boolean)x).booleanValue());
else if (x instanceof PGobject)
setString(parameterIndex, ((PGobject)x).getValue());
else
setLong(parameterIndex, connection.putObject(x));
}
/**
* Some prepared statements return multiple results; the execute method
* handles these complex statements as well as the simpler form of
* statements handled by executeQuery and executeUpdate
*
* @return true if the next result is a ResultSet; false if it is an
* update count or there are no more results
* @exception SQLException if a database access error occurs
*/
public boolean execute() throws SQLException
{
return super.execute(compileQuery()); // in Statement class
}
/**
* Returns the SQL statement with the current template values
* substituted.
* NB: This is identical to compileQuery() except instead of throwing
* SQLException if a parameter is null, it places ? instead.
*/
public String toString() {
synchronized(sbuf) {
sbuf.setLength(0);
int i;
for (i = 0 ; i < inStrings.length ; ++i)
{
if (inStrings[i] == null)
sbuf.append( '?' );
else
sbuf.append (templateStrings[i]);
sbuf.append (inStrings[i]);
}
sbuf.append(templateStrings[inStrings.length]);
return sbuf.toString();
}
}
// END OF PUBLIC INTERFACE
/**
* There are a lot of setXXX classes which all basically do
* the same thing. We need a method which actually does the
* set for us.
*
* @param paramIndex the index into the inString
* @param s a string to be stored
* @exception SQLException if something goes wrong
*/
private void set(int paramIndex, String s) throws SQLException
{
if (paramIndex < 1 || paramIndex > inStrings.length)
throw new PSQLException("postgresql.prep.range");
inStrings[paramIndex - 1] = s;
}
// ** JDBC 2 Extensions **
/**
* This parses the query and adds it to the current batch
*/
public void addBatch() throws SQLException
{
super.addBatch(compileQuery());
}
/**
* Not sure what this one does, so I'm saying this returns the MetaData for
* the last ResultSet returned!
*/
public java.sql.ResultSetMetaData getMetaData() throws SQLException
{
java.sql.ResultSet rs = getResultSet();
if(rs!=null)
return rs.getMetaData();
// Does anyone really know what this method does?
return null;
}
public void setArray(int i,Array x) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Sets a Blob - basically its similar to setBinaryStream()
*/
public void setBlob(int i,Blob x) throws SQLException
{
setBinaryStream(i,x.getBinaryStream(),(int)x.length());
}
/**
* This is similar to setBinaryStream except it uses a Reader instead of
* InputStream.
*/
public void setCharacterStream(int i,java.io.Reader x,int length) throws SQLException
{
LargeObjectManager lom = connection.getLargeObjectAPI();
int oid = lom.create();
LargeObject lob = lom.open(oid);
OutputStream los = lob.getOutputStream();
try {
// could be buffered, but then the OutputStream returned by LargeObject
// is buffered internally anyhow, so there would be no performance
// boost gained, if anything it would be worse!
int c=x.read();
int p=0;
while(c>-1 && p<length) {
los.write(c);
c=x.read();
p++;
}
los.close();
} catch(IOException se) {
throw new PSQLException("postgresql.prep.is",se);
}
// lob is closed by the stream so don't call lob.close()
setInt(i,oid);
}
/**
* New in 7.1
*/
public void setClob(int i,Clob x) throws SQLException
{
setBinaryStream(i,x.getAsciiStream(),(int)x.length());
}
/**
* At least this works as in PostgreSQL null represents anything null ;-)
*
* New in 7,1
*/
public void setNull(int i,int t,String s) throws SQLException
{
setNull(i,t);
}
public void setRef(int i,Ref x) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* New in 7,1
*/
public void setDate(int i,java.sql.Date d,java.util.Calendar cal) throws SQLException
{
if(cal==null)
setDate(i,d);
else {
cal.setTime(d);
setDate(i,new java.sql.Date(cal.getTime().getTime()));
}
}
/**
* New in 7,1
*/
public void setTime(int i,Time t,java.util.Calendar cal) throws SQLException
{
if(cal==null)
setTime(i,t);
else {
cal.setTime(t);
setTime(i,new java.sql.Time(cal.getTime().getTime()));
}
}
/**
* New in 7,1
*/
public void setTimestamp(int i,Timestamp t,java.util.Calendar cal) throws SQLException
{
if(cal==null)
setTimestamp(i,t);
else {
cal.setTime(t);
setTimestamp(i,new java.sql.Timestamp(cal.getTime().getTime()));
}
}
}
|
package org.commcare.utils;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.webkit.MimeTypeMap;
import org.commcare.core.network.AuthenticationInterceptor;
import org.commcare.network.CommcareRequestGenerator;
import org.commcare.network.EncryptedFileBody;
import org.commcare.tasks.DataSubmissionListener;
import org.commcare.util.LogTypes;
import org.javarosa.core.io.StreamsUtil;
import org.javarosa.core.io.StreamsUtil.InputIOException;
import org.javarosa.core.model.User;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.xml.ElementParser;
import org.javarosa.xml.util.InvalidStructureException;
import org.javarosa.xml.util.UnfullfilledRequirementsException;
import org.json.JSONException;
import org.json.JSONObject;
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Response;
import static org.commcare.network.HttpUtils.parseUserVisibleError;
public class FormUploadUtil {
private static final String TAG = FormUploadUtil.class.getSimpleName();
/**
* 15 MB size limit
*/
public static final long MAX_BYTES = (15 * 1048576) - 1024;
private static final String[] SUPPORTED_FILE_EXTS =
{".xml", ".jpg", "jpeg", ".3gpp", ".3gp", ".3ga", ".3g2", ".mp3",
".wav", ".amr", ".mp4", ".3gp2", ".mpg4", ".mpeg4",
".m4v", ".mpg", ".mpeg", ".qcp", ".ogg"};
public static Cipher getDecryptCipher(SecretKeySpec key) {
Cipher cipher;
try {
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher;
//TODO: Something smart here;
} catch (NoSuchAlgorithmException |
NoSuchPaddingException | InvalidKeyException e) {
e.printStackTrace();
}
return null;
}
/**
* Send unencrypted data to the server without user facing progress
* reporting.
*
* @param submissionNumber For progress reporting
* @param folder All supported files in this folder will be
* attached to the submission
* @param url Submission server url
* @param user Used to build the http post
* @return Submission status code
* @throws FileNotFoundException Is raised if xml file isn't found on the
* file-system
*/
public static FormUploadResult sendInstance(int submissionNumber, File folder,
String url, User user)
throws FileNotFoundException {
return sendInstance(submissionNumber, folder, null, url, null, user);
}
/**
* Send data to the server, encrypting xml files and reporting progress
* along the way.
*
* @param submissionNumber For progress reporting
* @param folder All supported files in this folder will be
* attached to the submission
* @param key For encrypting xml files
* @param url Submission server url
* @param listener Used to report progress to the calling task
* @param user Used to build the http post
* @return Submission status code
* @throws FileNotFoundException Is raised if xml file isn't found on the
* file-system
*/
public static FormUploadResult sendInstance(int submissionNumber, File folder,
SecretKeySpec key, String url,
AsyncTask listener, User user)
throws FileNotFoundException {
boolean hasListener = false;
DataSubmissionListener myListener = null;
if (listener instanceof DataSubmissionListener) {
hasListener = true;
myListener = (DataSubmissionListener)listener;
}
File[] files = folder.listFiles();
if (files == null) {
// make sure external storage is available to begin with.
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
// If so, just bail as if the user had logged out.
throw new SessionUnavailableException("External Storage Removed");
} else {
throw new FileNotFoundException("No directory found at: " +
folder.getAbsoluteFile());
}
}
// If we're listening, figure out how much (roughly) we have to send
long bytes = estimateUploadBytes(files);
if (hasListener) {
myListener.startSubmission(submissionNumber, bytes);
}
if (files.length == 0) {
Log.e(TAG, "no files to upload");
listener.cancel(true);
throw new FileNotFoundException("Folder at path " + folder.getAbsolutePath() + " had no files.");
}
List<MultipartBody.Part> parts = new ArrayList<>();
if (!buildMultipartEntity(parts, key, files)) {
return FormUploadResult.RECORD_FAILURE;
}
CommcareRequestGenerator generator = new CommcareRequestGenerator(user);
return submitEntity(parts, url, generator);
}
/**
* Submit multipart entity with plenty of logging
*
* @return submission status of multipart entity post
*/
private static FormUploadResult submitEntity(List<MultipartBody.Part> parts, String url,
CommcareRequestGenerator generator) {
Response<ResponseBody> response;
try {
response = generator.postMultipart(url, parts);
} catch (InputIOException ioe) {
// This implies that there was a problem with the _source_ of the
// transmission, not the processing or receiving end.
Logger.log(LogTypes.TYPE_ERROR_STORAGE,
"Internal error reading form record during submission: " +
ioe.getWrapped().getMessage());
return FormUploadResult.RECORD_FAILURE;
} catch (UnknownHostException e) {
e.printStackTrace();
Logger.log(LogTypes.TYPE_WARNING_NETWORK,
"Client network issues during submission: " + e.getMessage());
return FormUploadResult.TRANSPORT_FAILURE;
} catch (AuthenticationInterceptor.PlainTextPasswordException e) {
e.printStackTrace();
Logger.log(LogTypes.TYPE_ERROR_CONFIG_STRUCTURE,
"Encountered PlainTextPasswordException while submission: Sending password over HTTP");
return FormUploadResult.AUTH_OVER_HTTP;
} catch (IOException | IllegalStateException e) {
Logger.exception("Error reading form during submission: " + e.getMessage(), e);
return FormUploadResult.TRANSPORT_FAILURE;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
if (response.body() != null) {
InputStream responseStream = response.body().byteStream();
StreamsUtil.writeFromInputToOutputNew(responseStream, bos);
}
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
String responseString = new String(bos.toByteArray());
int responseCode = response.code();
logResponse(responseCode, responseString);
if (responseCode >= 200 && responseCode < 300) {
return FormUploadResult.FULL_SUCCESS;
} else if (responseCode == 401) {
return FormUploadResult.AUTH_FAILURE;
} else if (responseCode == 406) {
return processActionableFaiure(response);
} else if (responseCode == 422) {
return handleProcessingFailure(response.errorBody().byteStream());
} else if (responseCode == 503) {
return FormUploadResult.RATE_LIMITED;
} else {
return FormUploadResult.FAILURE;
}
}
private static FormUploadResult processActionableFaiure(Response<ResponseBody> response) {
String message = parseUserVisibleError(response);
FormUploadResult result = FormUploadResult.ACTIONABLE_FAILURE;
result.setErrorMessage(message);
return result;
}
private static FormUploadResult handleProcessingFailure(InputStream responseStream) {
FormUploadResult result = FormUploadResult.PROCESSING_FAILURE;
try {
result.setErrorMessage(parseProcessingFailureResponse(responseStream));
} catch (IOException | InvalidStructureException | XmlPullParserException |
UnfullfilledRequirementsException e) {
// If we can't parse out the failure reason then we won't quarantine this form, because
// we won't have any clear info about what happened
result = FormUploadResult.FAILURE;
Logger.exception("Form processing failed", e);
e.printStackTrace();
}
return result;
}
private static void logResponse(int responseCode, String responseString) {
String responseCodeMessage = "Response code to form submission attempt was: " + responseCode;
Log.e(TAG, responseCodeMessage);
Log.d(TAG, responseString);
if (!(responseCode >= 200 && responseCode < 300)) {
Logger.log(LogTypes.TYPE_WARNING_NETWORK, responseCodeMessage);
Logger.log(LogTypes.TYPE_FORM_SUBMISSION, responseCodeMessage);
if (!responseString.startsWith("<html>")) {
// Only log this if it's going to be useful
Logger.log(LogTypes.TYPE_FORM_SUBMISSION,
"Response string to failed form submission attempt was: " + responseString);
}
}
}
/**
* Validate the content body of the XML submission file.
*
* TODO: this should really be the responsibility of the form record, not
* of the submission process, persay.
*
* NOTE: this is a shallow validation (everything should be more or else
* constant time). Throws an exception if the file is gone because that's
* a common issue that gets caught to check if storage got removed
*
* @param f xml file to check
* @return false if the file is empty; otherwise true
* @throws FileNotFoundException file in question isn't found on the
* file-system
*/
private static boolean validateSubmissionFile(File f)
throws FileNotFoundException {
if (!f.exists()) {
throw new FileNotFoundException("Submission file: " +
f.getAbsolutePath());
}
// Gotta check f exists here since f.length returns 0 if the file isn't
// there for some reason.
if (f.length() == 0 && f.exists()) {
Logger.log(LogTypes.TYPE_ERROR_STORAGE,
"Submission body has no content at: " + f.getAbsolutePath());
return false;
}
return true;
}
/**
* @return The aggregated size in bytes the files of supported extension
* type.
*/
private static long estimateUploadBytes(File[] files) {
long bytes = 0;
for (File file : files) {
// Make sure we'll be sending it
if (!isSupportedMultimediaFile(file.getName())) {
continue;
}
bytes += file.length();
Log.d(TAG, "Added file: " + file.getName() +
". Bytes to send: " + bytes);
}
return bytes;
}
/**
* Add files of supported type to the multipart entity, encrypting xml
* files.
*
* @param parts Add files to this
* @param key Used to encrypt xml files
* @param files The files to be added to the entity,
* @return false if invalid xml files are found; otherwise true.
* @throws FileNotFoundException Is raised when an xml doesn't exist on the
* file-system
*/
private static boolean buildMultipartEntity(List<MultipartBody.Part> parts,
SecretKeySpec key,
File[] files)
throws FileNotFoundException {
int numAttachmentsInInstanceFolder = 0;
int numAttachmentsSuccessfullyAdded = 0;
for (File f : files) {
if (f.getName().endsWith(".xml")) {
if (key != null) {
if (!validateSubmissionFile(f)) {
return false;
}
parts.add(createEncryptedFilePart("xml_submission_file", f, "text/xml", key));
} else {
parts.add(createFilePart("xml_submission_file", f, "text/xml"));
}
} else {
String contentType = getFileContentType(f);
if (contentType != null) {
numAttachmentsInInstanceFolder++;
numAttachmentsSuccessfullyAdded += addPartToEntity(parts, f, contentType);
} else if (isSupportedMultimediaFile(f.getName())) {
numAttachmentsInInstanceFolder++;
numAttachmentsSuccessfullyAdded += addPartToEntity(parts, f, "application/octet-stream");
} else {
Logger.log(LogTypes.TYPE_FORM_SUBMISSION,
"Could not add unsupported file type to submission entity: " + f.getName());
}
}
}
Logger.log(LogTypes.TYPE_FORM_SUBMISSION, "Attempted to add "
+ numAttachmentsInInstanceFolder + " attachments to submission entity");
Logger.log(LogTypes.TYPE_FORM_SUBMISSION, "Successfully added "
+ numAttachmentsSuccessfullyAdded + " attachments to submission entity");
return true;
}
private static int addPartToEntity(List<MultipartBody.Part> parts, File f, String contentType) {
if (f.length() <= MAX_BYTES) {
parts.add(createFilePart(f.getName(), f, contentType));
return 1;
} else {
Logger.log(LogTypes.TYPE_FORM_SUBMISSION,
"Failed to add attachment to submission entity (too large): " + f.getName());
return 0;
}
}
private static String getFileContentType(File f) {
if (f.getName().endsWith(".xml")) {
return "text/xml";
} else if (f.getName().endsWith(".jpg")) {
return "image/jpeg";
} else if (f.getName().endsWith(".3gpp")) {
return "audio/3gpp";
} else if (f.getName().endsWith(".3gp")) {
return "video/3gpp";
}
return null;
}
private static MultipartBody.Part createFilePart(String partName, File file, String contentType) {
// create RequestBody instance from file
RequestBody requestFile = RequestBody.create(
MediaType.parse(contentType),
file);
// MultipartBody.Part is used to send also the actual file name
return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}
public static MultipartBody.Part createEncryptedFilePart(String partName, File file, String contentType, SecretKeySpec key) {
// create RequestBody instance from file
RequestBody requestFile = new EncryptedFileBody(
MediaType.parse(contentType),
file,
FormUploadUtil.getDecryptCipher(key));
// MultipartBody.Part is used to send also the actual file name
return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}
/**
* @return Is the filename's extension in the hard-coded list of supported
* files or have a media mimetype?
*/
public static boolean isSupportedMultimediaFile(String filename) {
for (String ext : SUPPORTED_FILE_EXTS) {
if (filename.endsWith(ext)) {
return true;
}
}
return isAudioVisualMimeType(filename);
}
/**
* Use the file's extension to determine if it has an audio,
* video, or image mimetype.
*
* @return true if the file has an audio, image, or video mimetype
*/
private static boolean isAudioVisualMimeType(String filename) {
MimeTypeMap mtm = MimeTypeMap.getSingleton();
String[] filenameSegments = filename.split("\\.");
if (filenameSegments.length > 1) {
// use the file extension to determine the mimetype
String ext = filenameSegments[filenameSegments.length - 1];
String mimeType = mtm.getMimeTypeFromExtension(ext);
return (mimeType != null) &&
(mimeType.startsWith("audio") ||
mimeType.startsWith("image") ||
mimeType.startsWith("video"));
}
return false;
}
public static String parseProcessingFailureResponse(InputStream responseStream)
throws IOException, InvalidStructureException, UnfullfilledRequirementsException,
XmlPullParserException {
KXmlParser baseParser = ElementParser.instantiateParser(responseStream);
ElementParser<String> responseParser = new ElementParser<String>(baseParser) {
@Override
public String parse() throws InvalidStructureException, IOException,
XmlPullParserException, UnfullfilledRequirementsException {
checkNode("OpenRosaResponse");
nextTag("message");
String natureOfResponse = parser.getAttributeValue(null, "nature");
if ("processing_failure".equals(natureOfResponse)) {
return parser.nextText();
} else {
throw new UnfullfilledRequirementsException(
"<message> for 422 response did not contain expected content");
}
}
};
return responseParser.parse();
}
}
|
package cz.cvut.fel.integracniportal.controller;
import cz.cvut.fel.integracniportal.exceptions.UserRoleNotFoundException;
import cz.cvut.fel.integracniportal.model.UserDetails;
import cz.cvut.fel.integracniportal.resource.UserDetailsResource;
import cz.cvut.fel.integracniportal.service.UserDetailsService;
import cz.cvut.fel.integracniportal.validator.UserDetailsResourceValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping("/rest")
public class UserController {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private UserDetailsResourceValidator userDetailsResourceValidator;
@InitBinder()
public void initBinderUserDetailsResource(WebDataBinder binder) {
binder.setValidator(userDetailsResourceValidator);
}
@RequestMapping(value = "/v0.1/users", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_ADMIN')")
@ResponseBody
public List<UserDetailsResource> getAllUsers() {
List<UserDetails> userDetailsList = userDetailsService.getAllUsers();
List<UserDetailsResource> result = new ArrayList<UserDetailsResource>(userDetailsList.size());
for (UserDetails userDetails: userDetailsList) {
result.add(userDetailsToResource(userDetails));
}
return result;
}
@RequestMapping(value = "/v0.1/users", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<String> createUser(@Validated @RequestBody UserDetailsResource userDetailsResource, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return new ResponseEntity<String>(bindingResult.getAllErrors().toString(), HttpStatus.BAD_REQUEST);
}
try {
UserDetails userDetails = userDetailsService.createUser(userDetailsResource);
return new ResponseEntity<String>("/rest/v0.1/user/"+userDetails.getUserId(), HttpStatus.OK);
} catch (UserRoleNotFoundException e) {
return new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
}
@RequestMapping(value = "/v0.1/user/{userid}", method = RequestMethod.GET)
@ResponseBody
public UserDetailsResource getUser(@PathVariable("userid") long userId) {
UserDetails userDetails = userDetailsService.getUserById(userId);
return userDetailsToResource(userDetails);
}
private UserDetailsResource userDetailsToResource(UserDetails userDetails) {
UserDetailsResource userDetailsResource = new UserDetailsResource();
userDetailsResource.setUserId(userDetails.getUserId());
userDetailsResource.setUsername(userDetails.getUsername());
return userDetailsResource;
}
}
|
package de.domisum.lib.auxilium.contracts.source.io;
import de.domisum.lib.auxilium.contracts.source.io.ioaction.IoAction;
import de.domisum.lib.auxilium.util.java.annotations.API;
import org.apache.commons.lang3.Validate;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.function.Consumer;
public class IoOptional<T>
{
private final T value;
private final IOException exception;
// INIT
public IoOptional(T value, IOException exception)
{
this.value = value;
this.exception = exception;
if((value == null) && (exception == null))
throw new IllegalArgumentException("value and exception can't both be null");
if((value != null) && (exception != null))
throw new IllegalArgumentException("value can't be provided while exception is provided as well");
}
@API
public static <T> IoOptional<T> of(T value)
{
Validate.notNull(value);
return new IoOptional<>(value, null);
}
@API
public static <T> IoOptional<T> ofException(IOException exception)
{
Validate.notNull(exception);
return new IoOptional<>(null, exception);
}
@API
public static <T> IoOptional<T> ofAction(IoAction<T> ioAction)
{
try
{
return of(ioAction.execute());
}
catch(IOException e)
{
return ofException(e);
}
}
// GETTERS
public boolean isPresent()
{
return value != null;
}
public boolean isEmpty()
{
return value == null;
}
public T get()
{
if(!isPresent())
throw new NoSuchElementException("no value present");
return value;
}
public IOException getException()
{
if(exception == null)
throw new NoSuchElementException("no exception present");
return exception;
}
@API
public T getOrThrow() throws IOException
{
if(isPresent())
return value;
throw exception;
}
@API
public T getOrThrowWrapped(String message) throws IOException
{
try
{
return getOrThrow();
}
catch(IOException e)
{
throw new IOException(message, e);
}
}
@API
public T getOrThrowUnchecked()
{
if(isPresent())
return value;
throw new UncheckedIOException(exception);
}
// USAGE
@API
public void ifPresent(Consumer<T> consumer)
{
if(isPresent())
consumer.accept(value);
}
// CONVERSION
@API
public Optional<T> toOptional()
{
return Optional.ofNullable(value);
}
}
|
package de.fraunhofer.iosb.ilt.sta.service;
import de.fraunhofer.iosb.ilt.sta.ServiceFailureException;
import de.fraunhofer.iosb.ilt.sta.dao.DatastreamDao;
import de.fraunhofer.iosb.ilt.sta.dao.FeatureOfInterestDao;
import de.fraunhofer.iosb.ilt.sta.dao.HistoricalLocationDao;
import de.fraunhofer.iosb.ilt.sta.dao.LocationDao;
import de.fraunhofer.iosb.ilt.sta.dao.MultiDatastreamDao;
import de.fraunhofer.iosb.ilt.sta.dao.ObservationDao;
import de.fraunhofer.iosb.ilt.sta.dao.ObservedPropertyDao;
import de.fraunhofer.iosb.ilt.sta.dao.SensorDao;
import de.fraunhofer.iosb.ilt.sta.dao.ThingDao;
import de.fraunhofer.iosb.ilt.sta.model.Entity;
import de.fraunhofer.iosb.ilt.sta.model.EntityType;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
/**
* A SensorThingsService represents the service endpoint of a server.
*
* @author Nils Sommer, Hylke van der Schaaf
*/
public class SensorThingsService {
private final URI endpoint;
private RequestConfig config = null;
private CloseableHttpClient client;
private TokenManager tokenManager;
/**
* Constructor.
*
* @param endpoint the base URI of the SensorThings service
* @throws java.net.URISyntaxException when building the final url fails.
*/
public SensorThingsService(URL endpoint) throws URISyntaxException {
this(endpoint, null);
}
/**
* Constructor.
*
* @param endpoint the base URI of the SensorThings service
* @param config the config for the jersey client
* @throws java.net.URISyntaxException when building the final url fails.
*/
public SensorThingsService(URL endpoint, RequestConfig config) throws URISyntaxException {
this.endpoint = new URI(endpoint.toString() + "/").normalize();
this.config = config;
this.client = HttpClients.createSystem();
}
public URI getEndpoint() {
return this.endpoint;
}
/**
* The local path to the entity or collection. e.g.:
* <ul>
* <li>Things</li>
* <li>Things(2)/Datastreams</li>
* <li>Datastreams(5)/Thing</li>
* </ul>
*
* @param parent The entity holding the relation, can be null.
* @param relation The relation or collection to get.
* @return The path to the entity collection.
*/
public String getPath(Entity<?> parent, EntityType relation) {
if (parent == null) {
return relation.getName();
}
if (!parent.getType().hasRelationTo(relation)) {
throw new IllegalArgumentException("Entity of type " + parent.getType() + " has no relation of type " + relation + ".");
}
return String.format("%s(%d)/%s", EntityType.listForClass(parent.getClass()).getName(), parent.getId(), relation.getName());
}
/**
* The full path to the entity or collection.
*
* @param parent The entity holding the relation, can be null.
* @param relation The relation or collection to get.
* @return the full path to the entity or collection.
*/
public URI getFullPath(Entity<?> parent, EntityType relation) {
return getEndpoint().resolve(getPath(parent, relation));
}
/**
* Execute the given request, adding a token header if needed.
*
* @param request The request to execute.
* @return the response.
* @throws IOException in case of problems.
*/
public CloseableHttpResponse execute(HttpUriRequest request) throws IOException {
if (tokenManager != null) {
tokenManager.addAuthHeader(request);
}
return client.execute(request);
}
public RequestConfig getConfig() {
return config;
}
/**
* @return a new Datastream Dao.
*/
public DatastreamDao datastreams() {
return new DatastreamDao(this);
}
/**
* @return a new MultiDatastream Dao.
*/
public MultiDatastreamDao multiDatastreams() {
return new MultiDatastreamDao(this);
}
/**
* @return a new FeatureOfInterest Dao.
*/
public FeatureOfInterestDao featuresOfInterest() {
return new FeatureOfInterestDao(this);
}
/**
* @return a new HistoricalLocation Dao.
*/
public HistoricalLocationDao historicalLocations() {
return new HistoricalLocationDao(this);
}
/**
* @return a new Location Dao.
*/
public LocationDao locations() {
return new LocationDao(this);
}
/**
* @return a new Observation Dao.
*/
public ObservationDao observations() {
return new ObservationDao(this);
}
/**
* @return a new PbservedProperty Dao.
*/
public ObservedPropertyDao observedProperties() {
return new ObservedPropertyDao(this);
}
/**
* @return a new Sensor Dao.
*/
public SensorDao sensors() {
return new SensorDao(this);
}
/**
* @return a new Thing Dao.
*/
public ThingDao things() {
return new ThingDao(this);
}
/**
* Create the given entity in this service. Executes a POST to the
* Collection of the entity type. The entity will be updated with the ID of
* the entity in the Service and it will be linked to the Service.
*
* @param <T> The type of entity to create. Inferred from the entity.
* @param entity The entity to create in the service.
* @throws ServiceFailureException in case the server rejects the POST.
*/
public <T extends Entity<T>> void create(T entity) throws ServiceFailureException {
entity.getDao(this).create(entity);
}
/**
* Patches the entity in the Service.
*
* @param <T> The type of entity to update. Inferred from the entity.
* @param entity The entity to update in the service.
* @throws ServiceFailureException in case the server rejects the PATCH.
*/
public <T extends Entity<T>> void update(T entity) throws ServiceFailureException {
entity.getDao(this).update(entity);
}
/**
* Deletes the given entity from the service.
*
* @param <T> The type of entity to delete. Inferred from the entity.
* @param entity The entity to delete in the service.
* @throws ServiceFailureException in case the server rejects the DELETE.
*/
public <T extends Entity<T>> void delete(T entity) throws ServiceFailureException {
entity.getDao(this).delete(entity);
}
/**
* Sets the TokenManager. Before each request is sent to the Service, the
* TokenManager has the opportunity to modify the request and add any
* headers required for Authentication and Authorisation.
*
* @param tokenManager The TokenManager to use, can be null.
* @return This SensorThingsService.
*/
public SensorThingsService setTokenManager(TokenManager tokenManager) {
if (tokenManager != null && tokenManager.getHttpClient() == null) {
tokenManager.setHttpClient(client);
}
this.tokenManager = tokenManager;
return this;
}
/**
* @return The current TokenManager.
*/
public TokenManager getTokenManager() {
return tokenManager;
}
}
|
package io.scalecube.gateway.benchmarks;
import io.rsocket.Payload;
import io.scalecube.benchmarks.BenchmarkSettings;
import io.scalecube.benchmarks.BenchmarkState;
import io.scalecube.gateway.clientsdk.Client;
import io.scalecube.gateway.clientsdk.ClientMessage;
import io.scalecube.gateway.clientsdk.ClientSettings;
import io.scalecube.gateway.clientsdk.codec.ClientMessageCodec;
import io.scalecube.gateway.clientsdk.codec.RSocketPayloadCodec;
import io.scalecube.gateway.clientsdk.rsocket.RSocketClientTransport;
import io.scalecube.services.codec.DataCodec;
import io.scalecube.services.codec.HeadersCodec;
import reactor.core.publisher.Mono;
import reactor.ipc.netty.resources.LoopResources;
public abstract class AbstractBenchmarkState<T extends AbstractBenchmarkState<T>>
extends BenchmarkState<T> {
private LoopResources loopResources;
public AbstractBenchmarkState(BenchmarkSettings settings) {
super(settings);
}
@Override
protected void beforeAll() throws Exception {
super.beforeAll();
loopResources = LoopResources.create("worker", 1, true);
}
@Override
protected void afterAll() throws Exception {
super.afterAll();
if (loopResources != null) {
loopResources.disposeLater().block();
}
}
public abstract Mono<Client> createClient();
protected final Mono<Client> createClient(ClientSettings settings) {
HeadersCodec headersCodec = HeadersCodec.getInstance(settings.contentType());
DataCodec dataCodec = DataCodec.getInstance(settings.contentType());
ClientMessageCodec<Payload> messageCodec = new RSocketPayloadCodec(headersCodec, dataCodec);
RSocketClientTransport transport =
new RSocketClientTransport(settings, messageCodec, loopResources);
Client client = new Client(transport, messageCodec);
ClientMessage request = ClientMessage.builder().qualifier("/benchmarks/one").build();
return client.requestResponse(request).then(Mono.just(client));
}
}
|
package jp.gr.java_conf.afterthesunrise.commons.object;
import static java.math.BigDecimal.ONE;
import static java.math.RoundingMode.DOWN;
import static java.util.concurrent.TimeUnit.MINUTES;
import java.math.BigDecimal;
import org.apache.commons.lang.StringUtils;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
/**
* @author takanori.takase
*/
public final class Numbers {
private Numbers() {
throw new IllegalAccessError("Utility class shouldn't be instantiated.");
}
private static final int MAX = 1000;
private static final long DURATION = 1L;
private static final LoadingCache<String, BigDecimal> CACHE;
private static final BigDecimal NULL = new BigDecimal("0.0");
static {
CacheLoader<String, BigDecimal> loader = new CacheLoader<String, BigDecimal>() {
@Override
public BigDecimal load(String key) throws Exception {
try {
return new BigDecimal(key);
} catch (Exception e) {
return NULL;
}
}
};
CACHE = CacheBuilder.newBuilder().expireAfterAccess(DURATION, MINUTES)
.maximumSize(MAX).build(loader);
}
public static final BigDecimal convert(String value) {
return convert(value, null);
}
public static final BigDecimal convert(String value, BigDecimal defaultValue) {
if (StringUtils.isBlank(value)) {
return defaultValue;
}
BigDecimal cached = CACHE.getUnchecked(value.intern());
return cached != NULL ? cached : defaultValue;
}
public static BigDecimal round(BigDecimal value) {
return round(value, ONE, null);
}
public static BigDecimal round(BigDecimal value, BigDecimal unit) {
return round(value, unit, null);
}
public static BigDecimal round(BigDecimal value, BigDecimal unit,
BigDecimal defaultValue) {
if (value == null || unit == null || unit.signum() == 0) {
return defaultValue;
}
BigDecimal quotient = value.divide(unit, 0, DOWN);
return unit.multiply(quotient);
}
}
|
package mil.nga.giat.geopackage.projection;
import mil.nga.giat.geopackage.BoundingBox;
import mil.nga.giat.wkb.geom.Point;
import org.osgeo.proj4j.CoordinateTransform;
import org.osgeo.proj4j.CoordinateTransformFactory;
import org.osgeo.proj4j.ProjCoordinate;
/**
* Projection transform wrapper
*
* @author osbornb
*/
public class ProjectionTransform {
/**
* Coordinate transform factory
*/
private static CoordinateTransformFactory ctFactory = new CoordinateTransformFactory();
/**
* From Projection
*/
private final Projection fromProjection;
/**
* To Projection
*/
private final Projection toProjection;
/**
* Coordinate transform
*/
private final CoordinateTransform transform;
/**
* Constructor
*
* @param fromProjection
* @param toProjection
*/
ProjectionTransform(Projection fromProjection, Projection toProjection) {
this.fromProjection = fromProjection;
this.toProjection = toProjection;
this.transform = ctFactory.createTransform(fromProjection.getCrs(),
toProjection.getCrs());
}
/**
* Transform the projected coordinate
*
* @param from
* @return
*/
public ProjCoordinate transform(ProjCoordinate from) {
ProjCoordinate to = new ProjCoordinate();
transform.transform(from, to);
return to;
}
/**
* Transform the projected point
*
* @param from
* @return
*/
public Point transform(Point from) {
ProjCoordinate fromCoord;
if (from.hasZ()) {
fromCoord = new ProjCoordinate(from.getX(), from.getY(),
from.getZ() != null ? from.getZ() : Double.NaN);
} else {
fromCoord = new ProjCoordinate(from.getX(), from.getY());
}
ProjCoordinate toCoord = transform(fromCoord);
Point to = new Point(from.hasZ(), from.hasM(), toCoord.x, toCoord.y);
if (from.hasZ()) {
to.setZ(toCoord.z);
}
if (from.hasM()) {
to.setM(from.getM());
}
return to;
}
/**
* Transform the bounding box
*
* @param boundingBox
* @return
*/
public BoundingBox transform(BoundingBox boundingBox) {
ProjCoordinate lowerLeft = new ProjCoordinate(
boundingBox.getMinLongitude(), boundingBox.getMinLatitude());
ProjCoordinate lowerRight = new ProjCoordinate(
boundingBox.getMaxLongitude(), boundingBox.getMinLatitude());
ProjCoordinate upperRight = new ProjCoordinate(
boundingBox.getMaxLongitude(), boundingBox.getMaxLatitude());
ProjCoordinate upperLeft = new ProjCoordinate(
boundingBox.getMinLongitude(), boundingBox.getMaxLatitude());
ProjCoordinate projectedLowerLeft = transform(lowerLeft);
ProjCoordinate projectedLowerRight = transform(lowerRight);
ProjCoordinate projectedUpperRight = transform(upperRight);
ProjCoordinate projectedUpperLeft = transform(upperLeft);
double minX = Math.min(projectedLowerLeft.x, projectedUpperLeft.x);
double maxX = Math.max(projectedLowerRight.x, projectedUpperRight.x);
double minY = Math.min(projectedLowerLeft.y, projectedLowerRight.y);
double maxY = Math.max(projectedUpperLeft.y, projectedUpperRight.y);
BoundingBox projectedBoundingBox = new BoundingBox(minX, maxX, minY,
maxY);
return projectedBoundingBox;
}
/**
* Transform a x and y location
*
* @param x
* @return
*/
public double[] transform(double x, double y) {
ProjCoordinate fromCoord = new ProjCoordinate(x, y);
ProjCoordinate toCoord = transform(fromCoord);
return new double[] { toCoord.x, toCoord.y };
}
/**
* Get the from projection in the transform
*
* @return
*/
public Projection getFromProjection() {
return fromProjection;
}
/**
* Get the to projection in the transform
*
* @return
*/
public Projection getToProjection() {
return toProjection;
}
/**
* Get the transform
*
* @return
*/
public CoordinateTransform getTransform() {
return transform;
}
}
|
package net.davidvoid.thor.lightning.data.access;
import java.util.ArrayList;
import java.util.List;
import net.davidvoid.thor.lightning.data.source.MongoDataSource;
import net.davidvoid.thor.lightning.entity.Entity;
import net.davidvoid.thor.lightning.exception.ResourceNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
public abstract class AbstractStore {
@Autowired
private MongoDataSource data_source = null;
@Autowired
private Counter counter = null;
final public void add(Entity entity) {
assert (!entity.has_valid_id());
generateId(entity);
DBObject object = toDBObject(entity);
getCollection().insert(object);
}
final public void delete(Entity entity) {
assert (entity.has_valid_id());
DBObject query = getModifyQuery(entity);
getCollection().remove(query);
}
final public void update(Entity entity) {
assert (entity.has_valid_id());
DBObject query = getModifyQuery(entity);
DBObject update = toDBObject(entity);
getCollection().update(query, update, false, true);
}
final protected List<Entity> get(DBObject query) {
DBCursor cursor = getCollection().find(query);
ArrayList<Entity> list = new ArrayList<Entity>();
while (cursor.hasNext()) {
Entity entity = toEntity(cursor.next());
list.add(entity);
}
return list;
}
final protected Entity getOne(DBObject query) {
DBObject object = getCollection().findOne(query);
if (object == null)
throw new ResourceNotFoundException("resource not found in db");
return toEntity(object);
}
final protected long generateNextId(String name) {
return counter.getNextId(name);
}
final protected DBCollection getCollection(String col_name) {
return data_source.getDatabase().getCollection(col_name);
}
protected abstract DBObject toDBObject(Entity entity);
protected abstract Entity toEntity(DBObject object);
protected abstract DBCollection getCollection();
protected abstract void generateId(Entity entity);
protected abstract DBObject getModifyQuery(Entity entity);
}
|
package nl.tudelft.jpacman.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.CLASS)
public @interface ParameterizedAssignment {
}
|
package nom.bdezonia.zorbage.type.real.float128;
import java.math.BigDecimal;
import java.math.BigInteger;
import nom.bdezonia.zorbage.algebra.Allocatable;
import nom.bdezonia.zorbage.algebra.Duplicatable;
import nom.bdezonia.zorbage.algebra.G;
import nom.bdezonia.zorbage.algebra.GetAsBigDecimal;
import nom.bdezonia.zorbage.algebra.GetAsBigDecimalArray;
import nom.bdezonia.zorbage.algebra.GetReal;
import nom.bdezonia.zorbage.algebra.Gettable;
import nom.bdezonia.zorbage.algebra.HighPrecRepresentation;
import nom.bdezonia.zorbage.algebra.NumberMember;
import nom.bdezonia.zorbage.algebra.SetFromBigDecimal;
import nom.bdezonia.zorbage.algebra.SetFromBigInteger;
import nom.bdezonia.zorbage.algebra.SetFromDouble;
import nom.bdezonia.zorbage.algebra.SetFromLong;
import nom.bdezonia.zorbage.algebra.SetReal;
import nom.bdezonia.zorbage.algebra.Settable;
import nom.bdezonia.zorbage.misc.BigDecimalUtils;
import nom.bdezonia.zorbage.misc.Hasher;
import nom.bdezonia.zorbage.sampling.IntegerIndex;
import nom.bdezonia.zorbage.storage.coder.ByteCoder;
import nom.bdezonia.zorbage.type.real.highprec.HighPrecisionMember;
import nom.bdezonia.zorbage.type.universal.OctonionRepresentation;
import nom.bdezonia.zorbage.type.universal.PrimitiveConversion;
import nom.bdezonia.zorbage.type.universal.PrimitiveRepresentation;
import nom.bdezonia.zorbage.type.universal.TensorOctonionRepresentation;
import nom.bdezonia.zorbage.type.universal.TensorStringRepresentation;
import nom.bdezonia.zorbage.type.universal.UniversalRepresentation;
/**
*
* @author Barry DeZonia
*
*/
public final class Float128Member
implements
NumberMember<Float128Member>,
ByteCoder,
Allocatable<Float128Member>, Duplicatable<Float128Member>,
Settable<Float128Member>, Gettable<Float128Member>,
UniversalRepresentation, PrimitiveConversion,
HighPrecRepresentation, SetReal<Float128Member>, GetReal<Float128Member>,
SetFromBigDecimal, SetFromBigInteger, SetFromDouble, SetFromLong,
GetAsBigDecimal, GetAsBigDecimalArray
{
BigDecimal num;
byte classification;
static final BigDecimal TWO = BigDecimal.valueOf(2);
static final BigDecimal MAX_NORMAL = TWO.pow(16383).multiply(TWO.subtract(TWO.pow(-112, Float128Algebra.CONTEXT)));
static final BigDecimal MIN_NORMAL = MAX_NORMAL.negate();
static final BigDecimal MAX_SUBNORMAL = TWO.pow(-16382, Float128Algebra.CONTEXT).multiply(BigDecimal.ONE.subtract(TWO.pow(-112, Float128Algebra.CONTEXT)));
static final BigDecimal MIN_SUBNORMAL = TWO.pow(-16382, Float128Algebra.CONTEXT).multiply(TWO.pow(-112, Float128Algebra.CONTEXT));
static final BigInteger FULL_RANGE = new BigInteger("10000000000000000000000000000",16);
static final BigDecimal FULL_RANGE_BD = new BigDecimal(FULL_RANGE);
static final BigInteger FULL_FRACTION = new BigInteger("ffffffffffffffffffffffffffff", 16);
static final byte NORMAL = 0;
static final byte POSZERO = 1;
static final byte NEGZERO = -1;
static final byte POSINF = 2;
static final byte NEGINF = -2;
static final byte NAN = 3;
public Float128Member() {
primitiveInit();
}
// Prefer this ctor over the BigDecimal based one since it can propagate
// nan, inf, etc.
public Float128Member(Float128Member other) {
set(other);
}
// Prefer the previous ctor over this one since this cannot represent
// nan, inf, etc.
public Float128Member(BigDecimal v) {
setV(v);
}
public Float128Member(String str) {
TensorStringRepresentation rep = new TensorStringRepresentation(str);
OctonionRepresentation val = rep.firstValue();
setV(val.r());
}
public Float128Member(BigInteger v) {
this(new BigDecimal(v));
}
public Float128Member(long v) {
this(BigDecimal.valueOf(v));
}
public Float128Member(double v) {
this(BigDecimal.valueOf(v));
}
@Override
public long dimension(int d) {
return 0;
}
@Override
public int numDimensions() {
return 0;
}
@Override
public void setR(Float128Member val) {
set(val);
}
@Override
public void getR(Float128Member val) {
get(val);
}
public BigDecimal v() {
if (classification == POSINF || classification == NEGINF || classification == NAN)
throw new java.lang.NumberFormatException("nan/posinf/neginf cannot be converted to big decimal");
return num;
}
public void setV(BigDecimal v) {
if (v == null)
throw new IllegalArgumentException("this class does not allow null values");
if (v.signum() == 0) {
setPosZero();
}
else {
setNormal(v);
clamp();
}
}
@Override
public BigDecimal getAsBigDecimal() {
return v();
}
@Override
public void setFromLong(long... vals) {
setV(BigDecimal.valueOf(vals[0]));
}
@Override
public void setFromDouble(double... vals) {
setV(BigDecimal.valueOf(vals[0]));
}
@Override
public void setFromBigInteger(BigInteger... vals) {
setV(new BigDecimal(vals[0]));
}
@Override
public void setFromBigDecimal(BigDecimal... vals) {
setV(vals[0]);
}
@Override
public void toHighPrec(HighPrecisionMember output) {
if (classification == POSINF || classification == NEGINF || classification == NAN)
throw new java.lang.NumberFormatException("nan/posinf/neginf cannot encode as a high precision decimal");
// can use num with classifications NORMAL, POSZERO, and NEGZERO because they are all accurate
output.setV(num);
}
@Override
public void fromHighPrec(HighPrecisionMember input) {
setV(input.v());
}
@Override
public PrimitiveRepresentation preferredRepresentation() {
return PrimitiveRepresentation.BIGDECIMAL;
}
@Override
public int componentCount() {
return 1;
}
@Override
public void primComponentSetByte(IntegerIndex index, int component, byte v) {
setV(BigDecimal.valueOf(v));
}
@Override
public void primComponentSetShort(IntegerIndex index, int component, short v) {
setV(BigDecimal.valueOf(v));
}
@Override
public void primComponentSetInt(IntegerIndex index, int component, int v) {
setV(BigDecimal.valueOf(v));
}
@Override
public void primComponentSetLong(IntegerIndex index, int component, long v) {
setV(BigDecimal.valueOf(v));
}
@Override
public void primComponentSetFloat(IntegerIndex index, int component, float v) {
setV(BigDecimal.valueOf(v));
}
@Override
public void primComponentSetDouble(IntegerIndex index, int component, double v) {
setV(BigDecimal.valueOf(v));
}
@Override
public void primComponentSetBigInteger(IntegerIndex index, int component, BigInteger v) {
setV(new BigDecimal(v));
}
@Override
public void primComponentSetBigDecimal(IntegerIndex index, int component, BigDecimal v) {
setV(v);
}
@Override
public void primComponentSetByteSafe(IntegerIndex index, int component, byte v) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
if (v != 0)
throw new IllegalArgumentException(
"cannot set nonzero value outside extents");
}
else {
setV(BigDecimal.valueOf(v));
}
}
@Override
public void primComponentSetShortSafe(IntegerIndex index, int component, short v) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
if (v != 0)
throw new IllegalArgumentException(
"cannot set nonzero value outside extents");
}
else {
setV(BigDecimal.valueOf(v));
}
}
@Override
public void primComponentSetIntSafe(IntegerIndex index, int component, int v) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
if (v != 0)
throw new IllegalArgumentException(
"cannot set nonzero value outside extents");
}
else {
setV(BigDecimal.valueOf(v));
}
}
@Override
public void primComponentSetLongSafe(IntegerIndex index, int component, long v) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
if (v != 0)
throw new IllegalArgumentException(
"cannot set nonzero value outside extents");
}
else {
setV(BigDecimal.valueOf(v));
}
}
@Override
public void primComponentSetFloatSafe(IntegerIndex index, int component, float v) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
if (v != 0)
throw new IllegalArgumentException(
"cannot set nonzero value outside extents");
}
else {
setV(BigDecimal.valueOf(v));
}
}
@Override
public void primComponentSetDoubleSafe(IntegerIndex index, int component, double v) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
if (v != 0)
throw new IllegalArgumentException(
"cannot set nonzero value outside extents");
}
else {
setV(BigDecimal.valueOf(v));
}
}
@Override
public void primComponentSetBigIntegerSafe(IntegerIndex index, int component, BigInteger v) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
if (v.signum() != 0)
throw new IllegalArgumentException(
"cannot set nonzero value outside extents");
}
else {
setV(new BigDecimal(v));
}
}
@Override
public void primComponentSetBigDecimalSafe(IntegerIndex index, int component, BigDecimal v) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
if (v.signum() != 0)
throw new IllegalArgumentException(
"cannot set nonzero value outside extents");
}
else {
setV(v);
}
}
@Override
public byte primComponentGetAsByte(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
if (component == 0) return v().byteValue();
return 0;
}
@Override
public short primComponentGetAsShort(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
if (component == 0) return v().shortValue();
return 0;
}
@Override
public int primComponentGetAsInt(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
if (component == 0) return v().intValue();
return 0;
}
@Override
public long primComponentGetAsLong(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
if (component == 0) return v().longValue();
return 0;
}
@Override
public float primComponentGetAsFloat(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
if (component == 0) return v().floatValue();
return 0;
}
@Override
public double primComponentGetAsDouble(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
if (component == 0) return v().doubleValue();
return 0;
}
@Override
public BigInteger primComponentGetAsBigInteger(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
if (component == 0) return v().toBigInteger();
return BigInteger.ZERO;
}
@Override
public BigDecimal primComponentGetAsBigDecimal(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
if (component == 0) return v();
return BigDecimal.ZERO;
}
@Override
public byte primComponentGetAsByteSafe(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
return 0;
}
else {
return v().byteValue();
}
}
@Override
public short primComponentGetAsShortSafe(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
return 0;
}
else {
return v().shortValue();
}
}
@Override
public int primComponentGetAsIntSafe(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
return 0;
}
else {
return v().intValue();
}
}
@Override
public long primComponentGetAsLongSafe(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
return 0;
}
else {
return v().longValue();
}
}
@Override
public float primComponentGetAsFloatSafe(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
return 0;
}
else {
return v().floatValue();
}
}
@Override
public double primComponentGetAsDoubleSafe(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
return 0;
}
else {
return v().doubleValue();
}
}
@Override
public BigInteger primComponentGetAsBigIntegerSafe(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
return BigInteger.ZERO;
}
else {
return v().toBigInteger();
}
}
@Override
public BigDecimal primComponentGetAsBigDecimalSafe(IntegerIndex index, int component) {
if (component < 0)
throw new IllegalArgumentException(
"negative component index error");
boolean oob = component > 0;
if (!oob) {
for (int i = 0; i < numDimensions(); i++) {
if (index.get(i) != 0) {
oob = true;
break;
}
}
}
if (oob) {
return BigDecimal.ZERO;
}
else {
return v();
}
}
@Override
public void primitiveInit() {
setPosZero();
}
@Override
public void toRep(TensorOctonionRepresentation rep) {
rep.setValue(new OctonionRepresentation(v()));
}
@Override
public void fromRep(TensorOctonionRepresentation rep) {
setV(rep.getValue().r());
}
@Override
public void get(Float128Member other) {
other.num = this.num;
other.classification = this.classification;
}
@Override
public void set(Float128Member other) {
this.num = other.num;
this.classification = other.classification;
}
@Override
public Float128Member duplicate() {
return new Float128Member(this);
}
@Override
public Float128Member allocate() {
return new Float128Member();
}
@Override
public int byteCount() {
return 16;
}
@Override
public void fromByteArray(byte[] arr, int index) {
decode(arr, index);
}
@Override
public void toByteArray(byte[] arr, int index) {
encode(arr, index);
}
@Override
public void getV(Float128Member value) {
get(value);
}
@Override
public void setV(Float128Member value) {
set(value);
}
@Override
public int hashCode() {
int v = 1;
v = Hasher.PRIME * v + Hasher.hashCode(num);
v = Hasher.PRIME * v + Hasher.hashCode(classification);
return v;
}
@Override
public boolean equals(Object o) {
if (o instanceof Float128Member) {
return G.QUAD.isEqual().call(this, (Float128Member) o);
}
return false;
}
@Override
public String toString() {
switch (classification) {
case NORMAL:
return num.toString();
case POSZERO:
return "0";
case NEGZERO:
return "-0";
case POSINF:
return "Infinity";
case NEGINF:
return "-Infinity";
case NAN:
return "NaN";
default:
throw new IllegalArgumentException("unknown number classification "+classification);
}
}
public boolean isNormal() {
return classification == NORMAL;
}
public boolean isPosZero() {
return classification == POSZERO;
}
public boolean isNegZero() {
return classification == NEGZERO;
}
public boolean isPosInf() {
return classification == POSINF;
}
public boolean isNegInf() {
return classification == NEGINF;
}
public boolean isNan() {
return classification == NAN;
}
public boolean isFinite() {
return classification == NORMAL || classification == POSZERO || classification == NEGZERO;
}
public boolean isInfinite() {
return classification == POSINF || classification == NEGINF;
}
public boolean isZero() {
return classification == POSZERO || classification == NEGZERO;
}
public boolean isPositive() {
return classification == POSINF ||
(classification == NORMAL && num.signum() > 0);
}
public boolean isNegative() {
return classification == NEGINF ||
(classification == NORMAL && num.signum() < 0);
}
public boolean hasPositiveSign() {
return classification == POSZERO || isPositive();
}
public boolean hasNegativeSign() {
return classification == NEGZERO || isNegative();
}
// DO NOT MAKE THIS ONE PUBLIC: use num.setV(BigDecimal)
// because it does some data classification and clamping.
// If people started using this method arbitrarily they
// could violate the internal consistency of how the
// numbers are handled and bad numerical results could
// sneak in.
void setNormal(BigDecimal value) {
num = value;
classification = NORMAL;
}
public void setPosZero() {
num = BigDecimal.ZERO;
classification = POSZERO;
}
public void setNegZero() {
num = BigDecimal.ZERO;
classification = NEGZERO;
}
public void setPosInf() {
num = BigDecimal.ZERO;
classification = POSINF;
}
public void setNegInf() {
num = BigDecimal.ZERO;
classification = NEGINF;
}
public void setNan() {
num = BigDecimal.ZERO;
classification = NAN;
}
// Take my classification and BigDecimal values and encode them as
// an IEEE128 in the 16 bytes of arr starting at offset
void encode(byte[] arr, int offset) {
switch (classification) {
case NORMAL:
BigInteger ff = BigInteger.valueOf(255);
BigDecimal tmp = num.abs();
int signBit = (num.signum() < 0) ? 0x80 : 0;
if (tmp.compareTo(BigDecimal.ONE) == 0) {
arr[offset + 15] = (byte) (signBit | 0x3f);
arr[offset + 14] = (byte) 0xff;
for (int i = 13; i >= 0; i
arr[offset + i] = 0;
}
}
// is it a subnormal?
else if (tmp.compareTo(MIN_SUBNORMAL) >= 0 && tmp.compareTo(MAX_SUBNORMAL) <= 0) {
BigInteger fraction = findFraction(MIN_SUBNORMAL, MAX_SUBNORMAL, tmp);
arr[offset + 15] = (byte) signBit;
arr[offset + 14] = 0;
for (int i = 0; i < 14; i++) {
byte b = fraction.and(ff).byteValue();
fraction = fraction.shiftRight(8);
arr[offset + i] = b;
}
}
// is it between zero and one?
else if (tmp.compareTo(BigDecimal.ZERO) > 0 && tmp.compareTo(BigDecimal.ONE) < 0) {
// it's a number > 0 and < 1
//BigDecimal lg2 = BigDecimalMath.log2(tmp, Float128Algebra.CONTEXT);
//int exponent = lg2.intValue();
int exponent = -(BigDecimal.ONE.divide(tmp, Float128Algebra.CONTEXT).toBigInteger().bitLength()-1);
BigDecimal lowerBound = TWO.pow(exponent-1, Float128Algebra.CONTEXT);
BigDecimal upperBound = TWO.pow(exponent, Float128Algebra.CONTEXT);
BigInteger fraction = findFraction(lowerBound, upperBound, tmp);
exponent += 16382;
int ehi = (exponent & 0xff00) >> 8;
int elo = (exponent & 0x00ff) >> 0;
arr[offset + 15] = (byte) (signBit | ehi);
arr[offset + 14] = (byte) (elo);
for (int i = 0; i < 14; i++) {
byte b = fraction.and(ff).byteValue();
fraction = fraction.shiftRight(8);
arr[offset + i] = b;
}
}
else {
// it's a number > 1 and <= MAXBOUND
BigInteger bi = tmp.toBigInteger();
int exponent = bi.bitLength() - 1;
BigDecimal lowerBound = TWO.pow(exponent, Float128Algebra.CONTEXT);
BigDecimal upperBound = TWO.pow(exponent+1, Float128Algebra.CONTEXT);
BigInteger fraction = findFraction(lowerBound, upperBound, tmp);
exponent += 16383;
int ehi = (exponent & 0xff00) >> 8;
int elo = (exponent & 0x00ff) >> 0;
arr[offset + 15] = (byte) (signBit | ehi);
arr[offset + 14] = (byte) (elo);
for (int i = 0; i < 14; i++) {
byte b = fraction.and(ff).byteValue();
fraction = fraction.shiftRight(8);
arr[offset + i] = b;
}
}
break;
case POSZERO:
// encode a regular (positive) 0
for (int i = 15; i >= 0; i
arr[offset + i] = 0;
}
break;
case NEGZERO:
// encode a negative 0
arr[offset + 15] = (byte) 0x80;
for (int i = 14; i >= 0; i
arr[offset + i] = 0;
}
break;
case POSINF:
// +1 / 0
// encode a positive infinity in the remaining 16 bytes
arr[offset + 15] = (byte) 0x7f;
arr[offset + 14] = (byte) 0xff;
for (int i = 13; i >= 0; i
arr[offset + i] = 0;
}
break;
case NEGINF:
// -1 / 0
// encode a negative infinity in the remaining 16 bytes
arr[offset + 15] = (byte) 0xff;
arr[offset + 14] = (byte) 0xff;
for (int i = 13; i >= 0; i
arr[offset + i] = 0;
}
break;
case NAN:
// 0 / 0
// encode a NaN in the remaining 16 bytes
arr[offset + 15] = (byte) 0x7f;
arr[offset + 14] = (byte) 0xff;
for (int i = 13; i >= 0; i
// Any non zero value tells the OS this is a nan rather than
// an inf.
// TODO : do I have to deal with signaling versus nonsignaling
// or is that only applicable to hardware implementations?
arr[offset + i] = 1;
}
break;
default:
throw new IllegalArgumentException("unknown number classification "+classification);
}
}
// Take the 16 bytes stored in arr starting at offset and decode them
// into my denom and BigDecimal values.
void decode(byte[] buffer, int offset) {
int sign = (buffer[offset + 15] & 0x80);
int exponent = ((buffer[offset + 15] & 0x7f) << 8) + (buffer[offset + 14] & 0xff);
BigInteger fraction = BigInteger.ZERO;
for (int i = 13; i >= 0; i
fraction = fraction.shiftLeft(8).add(BigInteger.valueOf(buffer[offset + i] & 0xff));
}
if (exponent > 0 && exponent < 0x7fff) {
// a regular number
BigDecimal value = new BigDecimal(fraction).divide(FULL_RANGE_BD, Float128Algebra.CONTEXT);
value = value.add(BigDecimal.ONE);
value = value.multiply(TWO.pow(exponent - 16383, Float128Algebra.CONTEXT));
if (sign != 0)
value = value.negate();
setNormal(value);
}
else if (exponent == 0) {
// a special number : zeroes and subnormals
if (fraction.compareTo(BigInteger.ZERO) == 0) {
// a zero
if (sign != 0)
setNegZero();
else
setPosZero();
}
else {
// subnormal number
BigDecimal value = new BigDecimal(fraction).divide(FULL_RANGE_BD, Float128Algebra.CONTEXT);
value = value.multiply(TWO.pow(-16382, Float128Algebra.CONTEXT));
if (sign != 0)
value = value.negate();
// setV() rather than setNormal() to clamp off roundoff issues
setV(value);
}
}
else if (exponent == 0x7fff) {
// a special number; infinities and nan
if (fraction.compareTo(BigInteger.ZERO) == 0) {
// an infinity
if (sign != 0)
setNegInf();
else
setPosInf();
}
else {
// a nan
setNan();
}
}
else
throw new IllegalArgumentException("illegal exponent "+exponent);
}
private BigInteger findFraction(BigDecimal lowerBound, BigDecimal upperBound, BigDecimal value) {
BigDecimal numer = value.subtract(lowerBound);
BigDecimal denom = upperBound.subtract(lowerBound);
BigDecimal ratio = numer.divide(denom, Float128Algebra.CONTEXT);
// adding half to make sure we are correctly rounding
BigInteger fraction = FULL_RANGE_BD.multiply(ratio).add(BigDecimalUtils.ONE_HALF).toBigInteger();
// due to rounding quirks with java you might actually reach or surpass 1.0 so clamp it
if (fraction.compareTo(FULL_FRACTION) > 0)
fraction = FULL_FRACTION;
return fraction;
}
private void clamp() {
if (classification == NORMAL) {
if (num.compareTo(MIN_NORMAL) < 0) {
setNegInf();
}
else if (num.compareTo(MAX_NORMAL) > 0) {
setPosInf();
}
else if (num.abs().compareTo(MIN_SUBNORMAL) < 0) {
if (num.signum() < 0)
setNegZero();
else
setPosZero();
}
}
}
@Override
public BigDecimal[] getAsBigDecimalArray() {
return new BigDecimal[] {v()};
}
}
|
package org.fedorahosted.flies.webtrans.client;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import net.customware.gwt.dispatch.client.DispatchAsync;
import net.customware.gwt.presenter.client.EventBus;
import net.customware.gwt.presenter.client.place.Place;
import net.customware.gwt.presenter.client.place.PlaceRequest;
import net.customware.gwt.presenter.client.widget.WidgetDisplay;
import net.customware.gwt.presenter.client.widget.WidgetPresenter;
import org.fedorahosted.flies.common.ContentState;
import org.fedorahosted.flies.gwt.model.DocName;
import org.fedorahosted.flies.gwt.model.DocumentId;
import org.fedorahosted.flies.gwt.model.DocumentStatus;
import org.fedorahosted.flies.gwt.model.ProjectContainerId;
import org.fedorahosted.flies.gwt.rpc.GetDocsList;
import org.fedorahosted.flies.gwt.rpc.GetDocsListResult;
import org.fedorahosted.flies.gwt.rpc.GetProjectStatusCount;
import org.fedorahosted.flies.gwt.rpc.GetProjectStatusCountResult;
import org.fedorahosted.flies.webtrans.client.NotificationEvent.Severity;
import org.fedorahosted.flies.webtrans.client.events.TransUnitUpdatedEvent;
import org.fedorahosted.flies.webtrans.client.events.TransUnitUpdatedEventHandler;
import org.fedorahosted.flies.webtrans.client.rpc.CachingDispatchAsync;
import org.fedorahosted.flies.webtrans.client.ui.HasFilter;
import org.fedorahosted.flies.webtrans.client.ui.HasTreeNodes;
import org.fedorahosted.flies.webtrans.client.ui.TreeNode;
import org.fedorahosted.flies.webtrans.editor.ProjectStatusPresenter;
import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
public class DocumentListPresenter extends WidgetPresenter<DocumentListPresenter.Display>
implements HasDocumentSelectionHandlers {
private final DispatchAsync dispatcher;
private final ProjectStatusPresenter prStatusPresenter;
private final WorkspaceContext workspaceContext;
private final ProjectContainerId projectContainerId;
private final Map<DocumentId, DocumentStatus> statuscache = new HashMap<DocumentId, DocumentStatus>();
private DocumentId currentDoc;
@Inject
public DocumentListPresenter(Display display, EventBus eventBus,
WorkspaceContext workspaceContext,
CachingDispatchAsync dispatcher,
ProjectStatusPresenter prStatusPresenter) {
super(display, eventBus);
this.workspaceContext = workspaceContext;
this.projectContainerId = workspaceContext.getProjectContainerId();
this.dispatcher = dispatcher;
this.prStatusPresenter = prStatusPresenter;
Log.info("DocumentListPresenter()");
loadDocsList();
}
public static final Place PLACE = new Place("DocumentListList");
public interface Display extends WidgetDisplay {
HasTreeNodes<DocumentId, DocName> getTree();
HasFilter<DocName> getFilter();
void setProjectStatusBar(Widget widget);
HasClickHandlers getReloadButton();
}
@Override
public Place getPlace() {
return PLACE;
}
@Override
protected void onBind() {
prStatusPresenter.bind();
display.setProjectStatusBar(prStatusPresenter.getDisplay().asWidget());
registerHandler(eventBus.addHandler(TransUnitUpdatedEvent.getType(), new TransUnitUpdatedEventHandler() {
@Override
public void onTransUnitUpdated(TransUnitUpdatedEvent event) {
DocumentStatus doc = statuscache.get(event.getDocumentId());
if (doc == null)
return; // GetProjectStatusCount hasn't returned yet!
ContentState status = event.getPreviousStatus();
doc.setStatus(status, doc.getStatus(status)-1);
status = event.getNewStatus();
doc.setStatus(status, doc.getStatus(status)+1);
TreeNode<DocName> node = display.getTree().getNodeByKey(doc.getDocumentid());
node.setName(node.getObject().getName() + " ("+ calPercentage(doc.getUntranslated(), doc.getFuzzy(), doc.getTranslated()) +"%)");
}
}));
registerHandler(getDisplay().getTree().addSelectionHandler(new SelectionHandler<TreeItem>() {
@Override
public void onSelection(SelectionEvent<TreeItem> event) {
DocName selectedDocName = (DocName) event.getSelectedItem().getUserObject();
if (selectedDocName != null) // folders have null names
setValue(selectedDocName.getId(), true);
}
}));
registerHandler(display.getReloadButton().addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
refreshDisplay();
}
}));
}
private long calPercentage (long untranslated, long fuzzy, long translated) {
if (translated < 0 || untranslated < 0 || fuzzy < 0
|| (translated + untranslated + fuzzy) == 0) {
return 0;
} else {
long value = (long)((translated * 100) / (fuzzy + untranslated + translated));
return value;
}
}
@Override
protected void onPlaceRequest(PlaceRequest request) {
// TODO Auto-generated method stub
}
@Override
protected void onUnbind() {
}
@Override
public void refreshDisplay() {
loadDocsList();
prStatusPresenter.refreshDisplay();
}
@Override
public void revealDisplay() {
// TODO Auto-generated method stub
}
public void setValue(DocumentId value, boolean fireEvents) {
DocumentId oldValue = currentDoc;
currentDoc = value;
if (oldValue != currentDoc) {
fireEvent(new DocumentSelectionEvent(currentDoc));
}
}
@Override
public HandlerRegistration addDocumentSelectionHandler(
DocumentSelectionHandler handler) {
return eventBus.addHandler(DocumentSelectionEvent.getType(), handler);
}
@Override
public void fireEvent(GwtEvent<?> event) {
eventBus.fireEvent(event);
}
public void setDocNameList(ArrayList<DocName> docNames) {
ArrayList<DocName> sortedList = new ArrayList<DocName>(docNames);
Collections.sort(sortedList, new Comparator<DocName>() {
@Override
public int compare(DocName o1, DocName o2) {
String path1 = o1.getPath();
if(path1 == null)
path1 = "";
String path2 = o2.getPath();
if(path2 == null)
path2 = "";
int pathCompare = path1.compareTo(path2);
if(pathCompare == 0)
return o1.getName().compareTo(o2.getName());
return pathCompare;
}});
display.getFilter().setList(sortedList);
}
private void loadDocsList() {
loadDocsStatus();
// switch doc list to the new project
dispatcher.execute(
new GetDocsList(projectContainerId),
new AsyncCallback<GetDocsListResult>() {
@Override
public void onFailure(Throwable caught) {
eventBus.fireEvent( new NotificationEvent(Severity.Error, "Failed to load data from Server"));
}
@Override
public void onSuccess(GetDocsListResult result) {
final ArrayList<DocName> docNames = result.getDocNames();
Log.info("Received doc list for "+result.getProjectContainerId()+": "+docNames.size()+" elements");
setDocNameList(docNames);
}
});
}
private void loadDocsStatus() {
dispatcher.execute(
new GetProjectStatusCount(projectContainerId , workspaceContext.getLocaleId()),
new AsyncCallback<GetProjectStatusCountResult>() {
@Override
public void onFailure(Throwable caught) {
Log.info("load Doc Status failure "+caught.getMessage());
}
@Override
public void onSuccess(GetProjectStatusCountResult result) {
ArrayList<DocumentStatus> liststatus = result.getStatus();
Log.info("Received project status for "+result.getProjectContainerId()+": "+liststatus.size()+" elements");
statuscache.clear();
for(DocumentStatus doc : liststatus) {
statuscache.put(doc.getDocumentid(), doc);
TreeNode<DocName> node = display.getTree().getNodeByKey(doc.getDocumentid());
node.setName(node.getObject().getName() + " ("+ calPercentage(doc.getUntranslated(), doc.getFuzzy(), doc.getTranslated()) +"%)");
}
}
});
}
}
|
package org.amc.game.chessserver.messaging;
import org.amc.game.chess.Player;
import org.apache.log4j.Logger;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EmailMessageService implements GameMessageService<String> {
static final String TO_ADDRESS = "to.address";
static final String SMTP_USERNAME = "smtp.username";
static final String SMTP_PASSWORD = "smtp.password";
static final String MAIL_SMTP_AUTH = "mail.smtp.auth";
static final String MAIL_SMTP_STARTTLS_ENABLE = "mail.smtp.starttls.enable";
static final String MAIL_SMTP_HOST = "mail.smtp.host";
static final String MAIL_SMTP_PORT = "mail.smtp.port";
static final String SUBJECT_LINE = "AMCChessGame Update";
private final static Logger log = Logger.getLogger(EmailMessageService.class);
private static EmailTransport transport=new JavamailTransport();
private Properties javamailProperties;
public EmailMessageService() {
// TODO Auto-generated constructor stub
}
/**
* Initialise the EmailDispatcher instance by load properties from a file
* @param propertiesFilePath Path to Properties file
* @throws IOException if file not found
*/
public final void init(String propertiesFilePath) throws IOException{
this.javamailProperties=new Properties();
javamailProperties.load(getPropertyFileReader(propertiesFilePath));
log.debug("Email Dispatcher initialised");
}
/**
* Checks the file path and then creates a {@link java.io.Reader Reader} for that file.
*
* @param propertiesFilePath String path of file
* @return java.io.BufferedReader for the file
* @throws IOException
*/
private final Reader getPropertyFileReader(String propertiesFilePath) throws IOException
{
InputStream inputStream = this.getClass().getResourceAsStream(propertiesFilePath);
if(inputStream==null){
StringBuilder sb=new StringBuilder();
sb.append(propertiesFilePath);
sb.append(": Couldn't be found or opened");
throw new IOException(sb.toString());
}
Reader reader=new BufferedReader(new InputStreamReader(inputStream));
return reader;
}
static final void setEmailTransport(EmailTransport transport){
EmailMessageService.transport=transport;
}
@Override
public void send(Player player, String message) throws Exception {
player.getUserName();
Message emailMessage = createMessage(player.getUserName(), message);
}
private final Message createMessage(String fromAddress,String messageTextBody)throws MessagingException{
final String toAddress=javamailProperties.getProperty(TO_ADDRESS);
final String userName=javamailProperties.getProperty(SMTP_USERNAME);
final String password=javamailProperties.getProperty(SMTP_PASSWORD);
Session session=Session.getInstance(javamailProperties,new javax.mail.Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(userName, password);
}
});
Message message=new MimeMessage(session);
message.setFrom(new InternetAddress(fromAddress));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress));
message.setSubject(SUBJECT_LINE);
message.setText(messageTextBody);
return message;
}
}
|
package org.csstudio.alarm.beast.annunciator.ui;
import org.csstudio.alarm.beast.annunciator.Messages;
import org.csstudio.alarm.beast.annunciator.Preferences;
import org.csstudio.alarm.beast.annunciator.model.AnnunciationMessage;
import org.csstudio.alarm.beast.annunciator.model.JMSAnnunciator;
import org.csstudio.alarm.beast.annunciator.model.JMSAnnunciatorListener;
import org.csstudio.alarm.beast.annunciator.model.Severity;
import org.csstudio.apputil.ringbuffer.RingBuffer;
import org.csstudio.platform.ui.swt.AutoSizeColumn;
import org.csstudio.platform.ui.swt.AutoSizeControlListener;
import org.eclipse.jface.viewers.CellLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Table;
import org.eclipse.ui.part.ViewPart;
/** Eclipse view for the Annunciator
* @author Kay Kasemir
*/
public class AnnunciatorView extends ViewPart implements JMSAnnunciatorListener
{
/** View ID registered in plugin.xml */
final public static String ID = "org.csstudio.alarm.beast.annunciator.view"; //$NON-NLS-1$
/** Annunciator that performs the actual annunciations. */
private volatile JMSAnnunciator annunciator = null;
/** Table of recent annunciations */
private TableViewer message_table;
/** List of recent annunciations, shown in message_table.
* Synchronize on access
*/
final private RingBuffer<AnnunciationMessage> messages =
new RingBuffer<AnnunciationMessage>(Preferences.getRingBufferSize());
@Override
public void createPartControl(final Composite parent)
{
// TODO Better handling of the JMSAnnunciator start/stop?
// On OS X, closing the AnnunciatorView will just hide & deactivate
// the view, just as if it's 'hidden' behind another view.
// When the opening the view again, that just re-activates the
// existing view.
// To the user that means: Annunciations continue even after closing
// the view.
// On Linux, the view seems to really close when the visible view
// is closed.
// Tried IPartListener2, but no good solution at this point.
// final IPartService service =
// (IPartService) getSite().getService(IPartService.class);
// service.addPartListener(new IPartListener2()
createGUI(parent);
// Fake initial message that shows up in table
messages.add(new AnnunciationMessage(Severity.forInfo(), Messages.ConnectMsg));
// Connect table to message list
message_table.setContentProvider(new MessageRingBufferContentProvider());
message_table.setInput(messages);
// Start connection in background job because it hangs when
// there's no JMS
final ConnectJob connect_job = new ConnectJob(this);
connect_job.schedule();
// ConnectJob would set annunciator. Cleanup when view is disposed.
parent.addDisposeListener(new DisposeListener()
{
public void widgetDisposed(DisposeEvent e)
{
if (annunciator != null)
{
annunciator.close();
annunciator = null;
}
}
});
}
/** Create GUI Elements
* @param parent
*/
private void createGUI(final Composite parent)
{
parent.setLayout(new FillLayout());
// List of annunciations
message_table = new TableViewer(parent ,
SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.FULL_SELECTION
| SWT.VIRTUAL);
final Table table = message_table.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableViewerColumn col;
// Time
col = AutoSizeColumn.make(message_table, Messages.Time, 150, 10);
col.setLabelProvider(new CellLabelProvider()
{
@Override
public void update(final ViewerCell cell)
{
final AnnunciationMessage message = (AnnunciationMessage) cell.getElement();
cell.setText(message.getTimestamp().toString());
}
});
// Severity
col = AutoSizeColumn.make(message_table, Messages.Severity, 80, 1);
col.setLabelProvider(new CellLabelProvider()
{
@Override
public void update(final ViewerCell cell)
{
final AnnunciationMessage message = (AnnunciationMessage) cell.getElement();
cell.setText(message.getSeverity().getName());
}
});
// Message
col = AutoSizeColumn.make(message_table, Messages.Message, 100, 100);
col.setLabelProvider(new CellLabelProvider()
{
@Override
public void update(final ViewerCell cell)
{
final AnnunciationMessage message = (AnnunciationMessage) cell.getElement();
cell.setText(message.getMessage());
}
});
new AutoSizeControlListener(table);
}
@Override
public void setFocus()
{
// NOP
}
/** Called by ConnectJob on success */
public void setAnnunciator(final JMSAnnunciator annunciator)
{
final Control control = message_table.getControl();
if (control.isDisposed())
return;
control.getDisplay().asyncExec(new Runnable()
{
public void run()
{
synchronized (messages)
{
messages.clear();
}
AnnunciatorView.this.annunciator = annunciator;
annunciator.start();
}
});
}
/** {@inheritDoc} */
public void performedAnnunciation(final AnnunciationMessage annunciation)
{
logAnnunciation(annunciation);
}
/** Called by ConnectJob or later Annunciator on error
* {@inheritDoc}
*/
public void annunciatorError(final Exception ex)
{
logAnnunciation(new AnnunciationMessage(Severity.forError(), ex.getMessage()));
ex.printStackTrace();
}
/** @param annunciation Annunciation to add to list of messages */
private void logAnnunciation(final AnnunciationMessage annunciation)
{
final Control control = message_table.getControl();
if (control.isDisposed())
return;
// Messages 'scroll', so every line in the table changes.
// Overall table refresh is accomplished by setting the item count.
// Sync & fetch count in this thread
final int count;
synchronized (messages)
{
messages.add(annunciation);
count = messages.size();
}
// Update table in UI thread
control.getDisplay().asyncExec(new Runnable()
{
public void run()
{
if (control.isDisposed())
return;
message_table.setItemCount(count);
message_table.refresh();
}
});
}
}
|
package org.fedorahosted.flies.webtrans.client;
import org.fedorahosted.flies.gwt.model.DocName;
import org.fedorahosted.flies.webtrans.client.ui.CaptionPanel;
import org.fedorahosted.flies.webtrans.client.ui.HasTreeNodes;
import org.fedorahosted.flies.webtrans.client.ui.TreeImpl;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.HasKeyUpHandlers;
import com.google.gwt.event.logical.shared.HasValueChangeHandlers;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.ImageBundle;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.TreeImages;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
public class DocumentListView extends CaptionPanel
implements DocumentListPresenter.Display {
public interface Images extends ImageBundle, TreeImages {
@Resource("org/fedorahosted/flies/webtrans/images/silk/folder.png")
AbstractImagePrototype treeOpen();
@Resource("org/fedorahosted/flies/webtrans/images/silk/folder_page_white.png")
AbstractImagePrototype treeClosed();
@Resource("org/fedorahosted/flies/webtrans/images/silk/page_white_text.png")
AbstractImagePrototype treeLeaf();
}
private static Images images = (Images) GWT.create(Images.class);
private TreeImpl<DocName> tree;
private TextBox filterTextBox = new TextBox();
public DocumentListView() {
super();
GWT.log("DocumentListView()", null);
tree = new TreeImpl<DocName>(images);
VerticalPanel treePanel = new VerticalPanel();
treePanel.setWidth("100%");
treePanel.setHeight("150px");
treePanel.add(new ScrollPanel(tree));
setTitle("Documents");
filterTextBox.setText("search");
filterTextBox.setWidth("100%");
addBody(filterTextBox);
addBody(treePanel);
filterTextBox.addFocusHandler(new FocusHandler() {
@Override
public void onFocus(FocusEvent event) {
filterTextBox.setText("");
}
});
filterTextBox.addBlurHandler(new BlurHandler() {
@Override
public void onBlur(BlurEvent event) {
filterTextBox.setText("search");
}
});
}
@Override
public Widget asWidget() {
return this;
}
@Override
public void startProcessing() {
// TODO Auto-generated method stub
}
@Override
public void stopProcessing() {
// TODO Auto-generated method stub
}
@Override
public HasTreeNodes<DocName> getTree() {
return tree;
}
@Override
public HasValueChangeHandlers<String> getFilterChangeSource() {
return filterTextBox;
}
@Override
public HasKeyUpHandlers getFilterKeyUpSource() {
return filterTextBox;
}
@Override
public HasText getFilterText() {
return filterTextBox;
}
}
|
package org.csstudio.channel.widgets;
import java.util.List;
import org.csstudio.utility.pvmanager.widgets.VTableCellLabelProvider;
import org.csstudio.utility.pvmanager.widgets.VTableContentProvider;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.wb.swt.SWTResourceManager;
public class PVTableByPropertyCellLabelProvider extends VTableCellLabelProvider {
private final List<List<String>> channels;
public PVTableByPropertyCellLabelProvider(List<List<String>> channels) {
this.channels = channels;
}
@Override
public void update(ViewerCell cell) {
super.update(cell);
if (cell.getColumnIndex() > 0) {
String channelName = channels.get(cell.getColumnIndex() - 1).get(((VTableContentProvider.VTableRow) cell.getElement()).getRow());
if (channelName == null) {
cell.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
cell.setForeground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
}
}
}
@Override
public String getToolTipText(Object element, int row, int column) {
if (column > 0) {
return channels.get(column - 1).get(row);
} else {
return null;
}
}
}
|
package org.blockartistry.DynSurround.registry;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nonnull;
import org.blockartistry.DynSurround.DSurround;
import org.blockartistry.DynSurround.ModOptions;
import org.blockartistry.DynSurround.data.Profiles;
import org.blockartistry.DynSurround.data.xface.DataScripts;
import org.blockartistry.DynSurround.data.xface.ModConfigurationFile;
import org.blockartistry.DynSurround.event.RegistryEvent;
import org.blockartistry.lib.SideLocal;
import com.google.common.collect.ImmutableList;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.IResourcePack;
import net.minecraft.client.resources.ResourcePackRepository;
import net.minecraft.util.IThreadListener;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public final class RegistryManager {
private static final SideLocal<RegistryManager> managers = new SideLocal<RegistryManager>() {
@Override
protected RegistryManager initialValue(@Nonnull final Side side) {
return new RegistryManager(side);
}
};
@Nonnull
public static RegistryManager get() {
return managers.get();
}
public static void reloadResources() {
reloadResources(Side.CLIENT);
reloadResources(Side.SERVER);
}
public static void reloadResources(@Nonnull final Side side) {
// Reload can be called on either side so make sure we queue
// up a scheduled task appropriately.
if (managers.hasValue(side)) {
final IThreadListener tl = side == Side.SERVER ? FMLCommonHandler.instance().getMinecraftServerInstance()
: Minecraft.getMinecraft();
if (tl == null)
managers.clear(side);
else
tl.addScheduledTask(new Runnable() {
public void run() {
managers.get().reload();
}
});
}
}
protected final Side side;
protected final ResourceLocation SCRIPT;
protected final Map<Class<? extends Registry>, Registry> registries = new IdentityHashMap<>();
protected final List<Registry> initOrder = new ArrayList<>();
protected boolean initialized;
RegistryManager(final Side side) {
this.side = side;
if (side == Side.CLIENT) {
this.SCRIPT = new ResourceLocation(DSurround.RESOURCE_ID, "configure.json");
} else {
this.SCRIPT = null;
}
}
@SuppressWarnings("unchecked")
public <T> T get(@Nonnull final Class<? extends Registry> reg) {
final Registry o = this.registries.get(reg);
if (o == null)
throw new RuntimeException(
"Attempt to get a registry that has not been configured [" + reg.getName() + "]");
return (T) this.registries.get(reg);
}
public void register(@Nonnull final Registry reg) {
this.registries.put(reg.getClass(), reg);
this.initOrder.add(reg);
}
@SideOnly(Side.CLIENT)
private boolean checkCompatible(@Nonnull final ResourcePackRepository.Entry pack) {
return pack.getResourcePack().resourceExists(SCRIPT);
}
@SideOnly(Side.CLIENT)
private InputStream openScript(@Nonnull final IResourcePack pack) throws IOException {
return pack.getInputStream(SCRIPT);
}
protected void processConfiguration(@Nonnull final ModConfigurationFile cfg) {
for (final Registry r : this.initOrder)
if (r != null)
r.configure(cfg);
}
public void reload() {
for (final Registry r : this.initOrder)
if (r != null)
r.init();
for (final ModContainer mod : Loader.instance().getActiveModList()) {
final ModConfigurationFile cfg = DataScripts.loadFromArchive(mod.getModId());
if (cfg != null) {
DSurround.log().info("Loading from archive [%s]", mod.getModId());
processConfiguration(cfg);
}
}
final List<InputStream> resources = getAdditionalScripts();
for (final InputStream stream : resources) {
try (final InputStreamReader reader = new InputStreamReader(stream)) {
final ModConfigurationFile cfg = DataScripts.loadFromStream(reader);
if (cfg != null)
processConfiguration(cfg);
} catch (@Nonnull final Throwable ex) {
DSurround.log().error("Unable to read script from resource pack!", ex);
}
}
// Load scripts specified in the configuration
final String[] configFiles = ModOptions.externalScriptFiles;
for (final String file : configFiles) {
final ModConfigurationFile cfg = DataScripts.loadFromDirectory(file);
if (cfg != null) {
DSurround.log().info("Loading from directory [%s]", file);
processConfiguration(cfg);
}
}
for (final Registry r : this.initOrder)
if (r != null)
r.initComplete();
MinecraftForge.EVENT_BUS.post(new RegistryEvent.Reload(this.side));
}
// NOTE: Server side has no resource packs so the client specific
// code is not executed when initializing a server side registry.
protected List<InputStream> getAdditionalScripts() {
if (this.side == Side.SERVER)
return ImmutableList.of();
final List<ResourcePackRepository.Entry> repo = Minecraft.getMinecraft().getResourcePackRepository()
.getRepositoryEntries();
final List<InputStream> streams = new ArrayList<InputStream>();
// Look in other resource packs for more configuration data
for (final ResourcePackRepository.Entry pack : repo) {
if (checkCompatible(pack)) {
DSurround.log().debug("Found script in resource pack: %s", pack.getResourcePackName());
try {
final InputStream stream = openScript(pack.getResourcePack());
if (stream != null)
streams.add(stream);
} catch (final Throwable t) {
DSurround.log().error("Unable to open script in resource pack", t);
}
}
}
// Tack on built-in profiles
streams.addAll(Profiles.getProfileStreams());
return streams;
}
}
|
package org.eclipse.smarthome.core.thing.binding;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.concurrent.ScheduledExecutorService;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.smarthome.config.core.Configuration;
import org.eclipse.smarthome.config.core.validation.ConfigDescriptionValidator;
import org.eclipse.smarthome.config.core.validation.ConfigValidationException;
import org.eclipse.smarthome.core.common.ThreadPoolManager;
import org.eclipse.smarthome.core.thing.Bridge;
import org.eclipse.smarthome.core.thing.Channel;
import org.eclipse.smarthome.core.thing.ChannelUID;
import org.eclipse.smarthome.core.thing.Thing;
import org.eclipse.smarthome.core.thing.ThingRegistry;
import org.eclipse.smarthome.core.thing.ThingStatus;
import org.eclipse.smarthome.core.thing.ThingStatusDetail;
import org.eclipse.smarthome.core.thing.ThingStatusInfo;
import org.eclipse.smarthome.core.thing.ThingTypeUID;
import org.eclipse.smarthome.core.thing.ThingUID;
import org.eclipse.smarthome.core.thing.binding.builder.ThingBuilder;
import org.eclipse.smarthome.core.thing.binding.builder.ThingStatusInfoBuilder;
import org.eclipse.smarthome.core.thing.type.ThingType;
import org.eclipse.smarthome.core.thing.type.ThingTypeRegistry;
import org.eclipse.smarthome.core.thing.util.ThingHandlerHelper;
import org.eclipse.smarthome.core.types.Command;
import org.eclipse.smarthome.core.types.RefreshType;
import org.eclipse.smarthome.core.types.State;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@NonNullByDefault
public abstract class BaseThingHandler implements ThingHandler {
private static final String THING_HANDLER_THREADPOOL_NAME = "thingHandler";
private final Logger logger = LoggerFactory.getLogger(BaseThingHandler.class);
protected final ScheduledExecutorService scheduler = ThreadPoolManager
.getScheduledPool(THING_HANDLER_THREADPOOL_NAME);
@Deprecated // this must not be used by bindings!
@NonNullByDefault({})
protected ThingRegistry thingRegistry;
@Deprecated // this must not be used by bindings!
@NonNullByDefault({})
protected ThingTypeRegistry thingTypeRegistry;
@Deprecated // this must not be used by bindings!
@NonNullByDefault({})
protected ConfigDescriptionValidator configDescriptionValidator;
@Deprecated // this must not be used by bindings!
@NonNullByDefault({})
protected BundleContext bundleContext;
protected Thing thing;
@SuppressWarnings("rawtypes")
@NonNullByDefault({})
private ServiceTracker thingRegistryServiceTracker;
@SuppressWarnings("rawtypes")
@NonNullByDefault({})
private ServiceTracker thingTypeRegistryServiceTracker;
@SuppressWarnings("rawtypes")
@NonNullByDefault({})
private ServiceTracker configDescriptionValidatorServiceTracker;
private @Nullable ThingHandlerCallback callback;
/**
* Creates a new instance of this class for the {@link Thing}.
*
* @param thing the thing that should be handled, not null
*/
public BaseThingHandler(Thing thing) {
this.thing = thing;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public void setBundleContext(final BundleContext bundleContext) {
this.bundleContext = bundleContext;
thingRegistryServiceTracker = new ServiceTracker(this.bundleContext, ThingRegistry.class.getName(), null) {
@Override
public Object addingService(final @Nullable ServiceReference reference) {
thingRegistry = (ThingRegistry) bundleContext.getService(reference);
return thingRegistry;
}
@Override
public void removedService(final @Nullable ServiceReference reference, final @Nullable Object service) {
synchronized (BaseThingHandler.this) {
thingRegistry = null;
}
}
};
thingRegistryServiceTracker.open();
thingTypeRegistryServiceTracker = new ServiceTracker(this.bundleContext, ThingTypeRegistry.class.getName(),
null) {
@Override
public Object addingService(final @Nullable ServiceReference reference) {
thingTypeRegistry = (ThingTypeRegistry) bundleContext.getService(reference);
return thingTypeRegistry;
}
@Override
public void removedService(final @Nullable ServiceReference reference, final @Nullable Object service) {
synchronized (BaseThingHandler.this) {
thingTypeRegistry = null;
}
}
};
thingTypeRegistryServiceTracker.open();
configDescriptionValidatorServiceTracker = new ServiceTracker(this.bundleContext,
ConfigDescriptionValidator.class.getName(), null) {
@Override
public Object addingService(final @Nullable ServiceReference reference) {
configDescriptionValidator = (ConfigDescriptionValidator) bundleContext.getService(reference);
return configDescriptionValidator;
}
@Override
public void removedService(final @Nullable ServiceReference reference, final @Nullable Object service) {
synchronized (BaseThingHandler.this) {
configDescriptionValidator = null;
}
}
};
configDescriptionValidatorServiceTracker.open();
}
public void unsetBundleContext(final BundleContext bundleContext) {
thingRegistryServiceTracker.close();
thingTypeRegistryServiceTracker.close();
this.bundleContext = null;
}
@Override
public void handleRemoval() {
// can be overridden by subclasses
updateStatus(ThingStatus.REMOVED);
}
@Override
public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
if (!isModifyingCurrentConfig(configurationParameters)) {
return;
}
validateConfigurationParameters(configurationParameters);
// can be overridden by subclasses
Configuration configuration = editConfiguration();
for (Entry<String, Object> configurationParameter : configurationParameters.entrySet()) {
configuration.put(configurationParameter.getKey(), configurationParameter.getValue());
}
if (isInitialized()) {
// persist new configuration and reinitialize handler
dispose();
updateConfiguration(configuration);
initialize();
} else {
// persist new configuration and notify Thing Manager
updateConfiguration(configuration);
callback.configurationUpdated(getThing());
}
}
/**
* Checks whether a given list of parameters would mean any change to the existing Thing configuration if applied to
* it.
* Note that the passed parameters might be a subset of the existing configuration.
*
* @param configurationParameters the parameters to check against the current configuration
* @return true if the parameters would result in a modified configuration, false otherwise
*/
protected boolean isModifyingCurrentConfig(Map<String, Object> configurationParameters) {
Configuration currentConfig = getConfig();
for (Entry<String, Object> entry : configurationParameters.entrySet()) {
if (!Objects.equals(currentConfig.get(entry.getKey()), entry.getValue())) {
return true;
}
}
return false;
}
@Override
public void dispose() {
// can be overridden by subclasses
}
@Override
public Thing getThing() {
return this.thing;
}
@Override
@Deprecated
public void handleUpdate(ChannelUID channelUID, State newState) {
// can be overridden by subclasses
}
@Override
@Deprecated
public void initialize() {
// should be overridden by subclasses!
updateStatus(ThingStatus.ONLINE);
logger.warn(
"BaseThingHandler.initialize() will be removed soon, ThingStatus can be set manually via updateStatus(ThingStatus.ONLINE)");
}
@Override
public void thingUpdated(Thing thing) {
dispose();
this.thing = thing;
initialize();
}
@Override
public void setCallback(@Nullable ThingHandlerCallback thingHandlerCallback) {
synchronized (this) {
this.callback = thingHandlerCallback;
}
}
/**
* Get the {@link ThingHandlerCallback} instance.
*
* @return the {@link ThingHandlerCallback} instance. Only returns {@code null} while the handler is not
* initialized.
*/
protected @Nullable ThingHandlerCallback getCallback() {
return this.callback;
}
@Override
public void channelLinked(ChannelUID channelUID) {
// can be overridden by subclasses
// standard behavior is to refresh the linked channel,
// so the newly linked items will receive a state update.
handleCommand(channelUID, RefreshType.REFRESH);
}
@Override
public void channelUnlinked(ChannelUID channelUID) {
// can be overridden by subclasses
}
/**
* Validates the given configuration parameters against the configuration description.
*
* @param configurationParameters the configuration parameters to be validated
* @throws ConfigValidationException if one or more of the given configuration parameters do not match
* their declarations in the configuration description
*/
protected void validateConfigurationParameters(Map<String, Object> configurationParameters) {
ThingType thingType = thingTypeRegistry.getThingType(getThing().getThingTypeUID());
if (thingType != null && thingType.getConfigDescriptionURI() != null) {
configDescriptionValidator.validate(configurationParameters, thingType.getConfigDescriptionURI());
}
}
/**
* Returns the configuration of the thing.
*
* @return configuration of the thing
*/
protected Configuration getConfig() {
return getThing().getConfiguration();
}
/**
* Returns the configuration of the thing and transforms it to the given
* class.
*
* @param configurationClass configuration class
* @return configuration of thing in form of the given class
*/
protected <T> T getConfigAs(Class<T> configurationClass) {
return getConfig().as(configurationClass);
}
/**
*
* Updates the state of the thing.
*
* @param channelUID unique id of the channel, which was updated
* @param state new state
*/
protected void updateState(ChannelUID channelUID, State state) {
synchronized (this) {
if (this.callback != null) {
this.callback.stateUpdated(channelUID, state);
} else {
logger.warn(
"Handler {} of thing {} tried updating channel {} although the handler was already disposed.",
this.getClass().getSimpleName(), channelUID.getThingUID(), channelUID.getId());
}
}
}
/**
*
* Updates the state of the thing. Will use the thing UID to infer the
* unique channel UID from the given ID.
*
* @param channel ID id of the channel, which was updated
* @param state new state
*/
protected void updateState(String channelID, State state) {
ChannelUID channelUID = new ChannelUID(this.getThing().getUID(), channelID);
updateState(channelUID, state);
}
/**
* Emits an event for the given channel.
*
* @param channelUID UID of the channel over which the event will be emitted
* @param event Event to emit
*/
protected void triggerChannel(ChannelUID channelUID, String event) {
synchronized (this) {
if (this.callback != null) {
this.callback.channelTriggered(this.getThing(), channelUID, event);
} else {
logger.warn(
"Handler {} of thing {} tried triggering channel {} although the handler was already disposed.",
this.getClass().getSimpleName(), channelUID.getThingUID(), channelUID.getId());
}
}
}
/**
* Emits an event for the given channel. Will use the thing UID to infer the
* unique channel UID from the given ID.
*
* @param channelID ID of the channel over which the event will be emitted
* @param event Event to emit
*/
protected void triggerChannel(String channelID, String event) {
triggerChannel(new ChannelUID(this.getThing().getUID(), channelID), event);
}
/**
* Emits an event for the given channel. Will use the thing UID to infer the
* unique channel UID.
*
* @param channelUID UID of the channel over which the event will be emitted
*/
protected void triggerChannel(String channelUID) {
triggerChannel(new ChannelUID(this.getThing().getUID(), channelUID), "");
}
/**
* Emits an event for the given channel. Will use the thing UID to infer the
* unique channel UID.
*
* @param channelUID UID of the channel over which the event will be emitted
*/
protected void triggerChannel(ChannelUID channelUID) {
triggerChannel(channelUID, "");
}
/**
* Sends a command for a channel of the thing.
*
* @param channelID id of the channel, which sends the command
* @param command command
*/
protected void postCommand(String channelID, Command command) {
ChannelUID channelUID = new ChannelUID(this.getThing().getUID(), channelID);
postCommand(channelUID, command);
}
/**
* Sends a command for a channel of the thing.
*
* @param channelUID unique id of the channel, which sends the command
* @param command command
*/
protected void postCommand(ChannelUID channelUID, Command command) {
synchronized (this) {
if (this.callback != null) {
this.callback.postCommand(channelUID, command);
} else {
logger.warn(
"Handler {} of thing {} tried posting a command to channel {} although the handler was already disposed.",
this.getClass().getSimpleName(), channelUID.getThingUID(), channelUID.getId());
}
}
}
/**
* Updates the status of the thing.
*
* @param status the status
* @param statusDetail the detail of the status
* @param description the description of the status
*/
protected void updateStatus(ThingStatus status, ThingStatusDetail statusDetail, @Nullable String description) {
synchronized (this) {
if (this.callback != null) {
ThingStatusInfoBuilder statusBuilder = ThingStatusInfoBuilder.create(status, statusDetail);
ThingStatusInfo statusInfo = statusBuilder.withDescription(description).build();
this.callback.statusUpdated(this.thing, statusInfo);
} else {
logger.warn("Handler {} tried updating the thing status although the handler was already disposed.",
this.getClass().getSimpleName());
}
}
}
/**
* Updates the status of the thing.
*
* @param status the status
* @param statusDetail the detail of the status
*/
protected void updateStatus(ThingStatus status, ThingStatusDetail statusDetail) {
updateStatus(status, statusDetail, null);
}
/**
* Updates the status of the thing. The detail of the status will be 'NONE'.
*
* @param status the status
*/
protected void updateStatus(ThingStatus status) {
updateStatus(status, ThingStatusDetail.NONE, null);
}
/**
* Creates a thing builder, which allows to modify the thing. The method
* {@link BaseThingHandler#updateThing(Thing)} must be called to persist the changes.
*
* @return {@link ThingBuilder} which builds an exact copy of the thing (not null)
*/
protected ThingBuilder editThing() {
return ThingBuilder.create(this.thing.getThingTypeUID(), this.thing.getUID())
.withBridge(this.thing.getBridgeUID()).withChannels(this.thing.getChannels())
.withConfiguration(this.thing.getConfiguration()).withLabel(this.thing.getLabel())
.withLocation(this.thing.getLocation()).withProperties(this.thing.getProperties());
}
/**
* Informs the framework, that a thing was updated. This method must be called after the configuration or channels
* was changed.
*
* @param thing thing, that was updated and should be persisted
*/
protected void updateThing(Thing thing) {
if (thing == this.thing) {
throw new IllegalArgumentException(
"Changes must not be done on the current thing - create a copy, e.g. via editThing()");
}
synchronized (this) {
if (this.callback != null) {
this.thing = thing;
this.callback.thingUpdated(thing);
} else {
logger.warn("Handler {} tried updating thing {} although the handler was already disposed.",
this.getClass().getSimpleName(), thing.getUID());
}
}
}
/**
* Returns a copy of the configuration, that can be modified. The method
* {@link BaseThingHandler#updateConfiguration(Configuration)} must be called to persist the configuration.
*
* @return copy of the thing configuration (not null)
*/
protected Configuration editConfiguration() {
Map<String, Object> properties = this.thing.getConfiguration().getProperties();
return new Configuration(new HashMap<>(properties));
}
/**
* Updates the configuration of the thing and informs the framework about it.
*
* @param configuration configuration, that was updated and should be persisted
*/
protected void updateConfiguration(Configuration configuration) {
Map<String, Object> old = this.thing.getConfiguration().getProperties();
try {
this.thing.getConfiguration().setProperties(configuration.getProperties());
synchronized (this) {
if (this.callback != null) {
this.callback.thingUpdated(thing);
} else {
logger.warn(
"Handler {} tried updating its configuration although the handler was already disposed.",
this.getClass().getSimpleName());
}
}
} catch (RuntimeException e) {
logger.warn(
"Error while applying configuration changes: '{}: {}' - reverting configuration changes on thing '{}'.",
e.getClass().getSimpleName(), e.getMessage(), this.thing.getUID().getAsString());
this.thing.getConfiguration().setProperties(old);
throw e;
}
}
/**
* Returns a copy of the properties map, that can be modified. The method {@link
* BaseThingHandler#updateProperties(Map<String, String> properties)} must be called to persist the properties.
*
* @return copy of the thing properties (not null)
*/
protected Map<String, String> editProperties() {
Map<String, String> properties = this.thing.getProperties();
return new HashMap<>(properties);
}
/**
* Informs the framework, that the given properties map of the thing was updated. This method performs a check, if
* the properties were updated. If the properties did not change, the framework is not informed about changes.
*
* @param properties properties map, that was updated and should be persisted
*/
protected void updateProperties(Map<String, String> properties) {
boolean propertiesUpdated = false;
for (Entry<String, String> property : properties.entrySet()) {
String propertyName = property.getKey();
String propertyValue = property.getValue();
String existingPropertyValue = thing.getProperties().get(propertyName);
if (existingPropertyValue == null || !existingPropertyValue.equals(propertyValue)) {
this.thing.setProperty(propertyName, propertyValue);
propertiesUpdated = true;
}
}
if (propertiesUpdated) {
synchronized (this) {
if (this.callback != null) {
this.callback.thingUpdated(thing);
} else {
logger.warn(
"Handler {} tried updating its thing's properties although the handler was already disposed.",
this.getClass().getSimpleName());
}
}
}
}
/**
* <p>
* Updates the given property value for the thing that is handled by this thing handler instance. The value is only
* set for the given property name if there has not been set any value yet or if the value has been changed. If the
* value of the property to be set is null then the property is removed.
*
* This method also informs the framework about the updated thing, which in fact will persists the changes. So, if
* multiple properties should be changed at the same time, the {@link BaseThingHandler#editProperties()} method
* should be used.
*
* @param name the name of the property to be set
* @param value the value of the property
*/
protected void updateProperty(String name, String value) {
String existingPropertyValue = thing.getProperties().get(name);
if (existingPropertyValue == null || !existingPropertyValue.equals(value)) {
thing.setProperty(name, value);
synchronized (this) {
if (this.callback != null) {
this.callback.thingUpdated(thing);
} else {
logger.warn(
"Handler {} tried updating its thing's properties although the handler was already disposed.",
this.getClass().getSimpleName());
}
}
}
}
/**
* Returns the bridge of the thing.
*
* @return returns the bridge of the thing or null if the thing has no
* bridge
*/
protected @Nullable Bridge getBridge() {
ThingUID bridgeUID = thing.getBridgeUID();
synchronized (this) {
if (bridgeUID != null && thingRegistry != null) {
return (Bridge) thingRegistry.get(bridgeUID);
} else {
return null;
}
}
}
/**
* Returns whether at least one item is linked for the given channel ID.
*
* @param channelId channel ID (must not be null)
* @return true if at least one item is linked, false otherwise
*/
protected boolean isLinked(String channelId) {
Channel channel = thing.getChannel(channelId);
if (channel != null) {
return isLinked(channel.getUID());
} else {
logger.debug("Channel with ID '{},' does not exists in thing '{}' and is therefore not linked.", channelId,
thing.getUID());
return false;
}
}
/**
* Returns whether at least one item is linked for the given UID of the channel.
*
* @param channelUID UID of the channel (must not be null)
* @return true if at least one item is linked, false otherwise
*/
protected boolean isLinked(ChannelUID channelUID) {
if (callback != null) {
return callback.isChannelLinked(channelUID);
} else {
logger.warn(
"Handler {} of thing {} tried checking if channel {} is linked although the handler was already disposed.",
this.getClass().getSimpleName(), channelUID.getThingUID(), channelUID.getId());
return false;
}
}
/**
* Returns whether the handler has already been initialized.
*
* @return true if handler is initialized, false otherwise
*/
protected boolean isInitialized() {
return ThingHandlerHelper.isHandlerInitialized(this);
}
@Override
public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
if (bridgeStatusInfo.getStatus() == ThingStatus.ONLINE
&& getThing().getStatusInfo().getStatusDetail() == ThingStatusDetail.BRIDGE_OFFLINE) {
updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
} else if (bridgeStatusInfo.getStatus() == ThingStatus.OFFLINE) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
}
}
protected void changeThingType(ThingTypeUID thingTypeUID, Configuration configuration) {
if (this.callback != null) {
this.callback.migrateThingType(getThing(), thingTypeUID, configuration);
} else {
logger.warn("Handler {} tried migrating the thing type although the handler was already disposed.",
this.getClass().getSimpleName());
}
}
}
|
package com.netflix.governator;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import com.google.inject.ProvisionException;
import com.netflix.governator.annotations.Configuration;
import com.netflix.governator.configuration.ConfigurationDocumentation;
import com.netflix.governator.configuration.ConfigurationMapper;
import com.netflix.governator.configuration.ConfigurationProvider;
import com.netflix.governator.lifecycle.LifecycleMethods;
/**
* Feature to enable @Configuration annotation processing.
*
* To enable install the ConfigurationModule.
*
* <pre>
* {@code
* install(new ConfigurationModule());
* }
* </pre>
* @author elandau
*
*/
@Singleton
public class ConfigurationLifecycleFeature implements LifecycleFeature {
public static class Mapper {
private ConfigurationMapper mapper;
private ConfigurationProvider configurationProvider;
private ConfigurationDocumentation configurationDocumentation;
Mapper(ConfigurationMapper mapper,
ConfigurationProvider configurationProvider,
ConfigurationDocumentation configurationDocumentation) {
this.mapper = mapper;
this.configurationProvider = configurationProvider;
this.configurationDocumentation = configurationDocumentation;
}
private void mapConfiguration(Object obj, LifecycleMethods methods) throws Exception {
mapper.mapConfiguration(configurationProvider, configurationDocumentation, obj, methods);
}
}
private volatile Provider<Mapper> mapper;
@Inject
public void initialize(Provider<Mapper> state) {
this.mapper = state;
}
@Override
public List<LifecycleAction> getActionsForType(final Class<?> type) {
final LifecycleMethods methods = new LifecycleMethods(type);
if (methods.annotatedFields(Configuration.class).length > 0) {
return Arrays.<LifecycleAction>asList(new LifecycleAction() {
@Override
public void call(Object obj) throws Exception {
if (mapper == null) {
throw new ProvisionException("Trying to map fields of type " + type.getName() + " before ConfigurationLifecycleFeature was fully initialized by the injector");
}
try {
mapper.get().mapConfiguration(obj, methods);
} catch (Exception e) {
throw new ProvisionException("Failed to map configuration for type " + type.getName(), e);
}
}
});
}
else {
return Collections.emptyList();
}
}
@Override
public String toString() {
return "ConfigurationLifecycleFeature[]";
}
}
|
package org.owasp.esapi.reference;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.Logger;
import org.owasp.esapi.SecurityConfiguration;
import org.owasp.esapi.errors.ConfigurationException;
// DISCUSS: Is there a good way for us to determine if they have changed the master key and salt, and if not,
// at _least_ log a warning? Need to distinguish the "as-shipped" versions from the current versions.
// Proposed solution: We will leave these 2 properties empty in the ESAPI.properties file and the
// installation instructions will show how to set them.
public class DefaultSecurityConfiguration implements SecurityConfiguration {
private Properties properties = null;
private String cipherXformFromESAPIProp = null; // New in ESAPI 2.0
private String cipherXformCurrent = null; // New in ESAPI 2.0
private static final String REMEMBER_TOKEN_DURATION = "Authenticator.RememberTokenDuration";
private static final String IDLE_TIMEOUT_DURATION = "Authenticator.IdleTimeoutDuration";
private static final String ABSOLUTE_TIMEOUT_DURATION = "Authenticator.AbsoluteTimeoutDuration";
private static final String ALLOWED_LOGIN_ATTEMPTS = "Authenticator.AllowedLoginAttempts";
private static final String USERNAME_PARAMETER_NAME = "Authenticator.UsernameParameterName";
private static final String PASSWORD_PARAMETER_NAME = "Authenticator.PasswordParameterName";
private static final String MAX_OLD_PASSWORD_HASHES = "Authenticator.MaxOldPasswordHashes";
private static final String ALLOW_MULTIPLE_ENCODING = "Encoder.AllowMultipleEncoding";
private static final String CANONICALIZATION_CODECS = "Encoder.DefaultCodecList";
private static final String DISABLE_INTRUSION_DETECTION = "IntrusionDetector.Disable";
private static final String MASTER_KEY = "Encryptor.MasterKey";
private static final String MASTER_SALT = "Encryptor.MasterSalt";
private static final String KEY_LENGTH = "Encryptor.EncryptionKeyLength";
private static final String ENCRYPTION_ALGORITHM = "Encryptor.EncryptionAlgorithm";
private static final String HASH_ALGORITHM = "Encryptor.HashAlgorithm";
private static final String HASH_ITERATIONS = "Encryptor.HashIterations";
private static final String CHARACTER_ENCODING = "Encryptor.CharacterEncoding";
private static final String RANDOM_ALGORITHM = "Encryptor.RandomAlgorithm";
private static final String DIGITAL_SIGNATURE_ALGORITHM = "Encryptor.DigitalSignatureAlgorithm";
private static final String DIGITAL_SIGNATURE_KEY_LENGTH = "Encryptor.DigitalSignatureKeyLength";
// New in ESAPI Java 2.0 //
private static final String CIPHERTEXT_USE_MAC = "Encryptor.CipherText.useMAC";
private static final String PLAINTEXT_OVERWRITE = "Encryptor.PlainText.overwrite";
private static final String IV_TYPE = "Encryptor.ChooseIVMethod";
private static final String FIXED_IV = "Encryptor.fixedIV";
private static final String WORKING_DIRECTORY = "Executor.WorkingDirectory";
private static final String APPROVED_EXECUTABLES = "Executor.ApprovedExecutables";
private static final String FORCE_HTTPONLYSESSION = "HttpUtilities.ForceHttpOnlySession";
private static final String FORCE_SECURESESSION = "HttpUtilities.SecureSession";
private static final String FORCE_HTTPONLYCOOKIES = "HttpUtilities.ForceHttpOnlyCookies";
private static final String FORCE_SECURECOOKIES = "HttpUtilities.ForceSecureCookies";
private static final String UPLOAD_DIRECTORY = "HttpUtilities.UploadDir";
private static final String UPLOAD_TEMP_DIRECTORY = "HttpUtilities.UploadTempDir";
private static final String APPROVED_UPLOAD_EXTENSIONS = "HttpUtilities.ApprovedUploadExtensions";
private static final String MAX_UPLOAD_FILE_BYTES = "HttpUtilities.MaxUploadFileBytes";
private static final String RESPONSE_CONTENT_TYPE = "HttpUtilities.ResponseContentType";
private static final String APPLICATION_NAME = "Logger.ApplicationName";
private static final String LOG_LEVEL = "Logger.LogLevel";
private static final String LOG_FILE_NAME = "Logger.LogFileName";
private static final String MAX_LOG_FILE_SIZE = "Logger.MaxLogFileSize";
private static final String LOG_ENCODING_REQUIRED = "Logger.LogEncodingRequired";
private static final String LOG_APPLICATION_NAME = "Logger.LogApplicationName";
private static final String LOG_SERVER_IP = "Logger.LogServerIP";
private static final String VALIDATION_PROPERTIES = "Validator.ConfigurationFile";
/**
* The default max log file size is set to 10,000,000 bytes (10 Meg). If the current log file exceeds the current
* max log file size, the logger will move the old log data into another log file. There currently is a max of
* 1000 log files of the same name. If that is exceeded it will presumably start discarding the oldest logs.
*/
public static final int DEFAULT_MAX_LOG_FILE_SIZE = 10000000;
protected final int MAX_REDIRECT_LOCATION = 1000;
protected final int MAX_FILE_NAME_LENGTH = 1000; // DISCUSS: Is this for given directory or refer to canonicalized full path name?
// Too long if the former! (Usually 255 is limit there.) Hard to tell since not used
// here in this class and it's protected, so not sure what it's intent is.
/*
* Implementation Keys
*/
private static final String LOG_IMPLEMENTATION = "ESAPI.Logger";
private static final String AUTHENTICATION_IMPLEMENTATION = "ESAPI.Authenticator";
private static final String ENCODER_IMPLEMENTATION = "ESAPI.Encoder";
private static final String ACCESS_CONTROL_IMPLEMENTATION = "ESAPI.AccessControl";
private static final String ENCRYPTION_IMPLEMENTATION = "ESAPI.Encryptor";
private static final String INTRUSION_DETECTION_IMPLEMENTATION = "ESAPI.IntrusionDetector";
private static final String RANDOMIZER_IMPLEMENTATION = "ESAPI.Randomizer";
private static final String EXECUTOR_IMPLEMENTATION = "ESAPI.Executor";
private static final String VALIDATOR_IMPLEMENTATION = "ESAPI.Validator";
private static final String HTTP_UTILITIES_IMPLEMENTATION = "ESAPI.HTTPUtilities";
// New in ESAPI Java 2.0 //
// Not implementation classes!!! //
private static final String PRINT_PROPERTIES_WHEN_LOADED = "ESAPI.printProperties";
private static final String CIPHER_TRANSFORMATION_IMPLEMENTATION = "Encryptor.CipherTransformation";
/*
* Default Implementations
*/
public static final String DEFAULT_LOG_IMPLEMENTATION = "org.owasp.esapi.reference.JavaLogFactory";
public static final String DEFAULT_AUTHENTICATION_IMPLEMENTATION = "org.owasp.esapi.reference.FileBasedAuthenticator";
public static final String DEFAULT_ENCODER_IMPLEMENTATION = "org.owasp.esapi.reference.DefaultEncoder";
public static final String DEFAULT_ACCESS_CONTROL_IMPLEMENTATION = "org.owasp.esapi.reference.accesscontrol.DefaultAccessController";
public static final String DEFAULT_ENCRYPTION_IMPLEMENTATION = "org.owasp.esapi.reference.JavaEncryptor";
public static final String DEFAULT_INTRUSION_DETECTION_IMPLEMENTATION = "org.owasp.esapi.reference.DefaultIntrusionDetector";
public static final String DEFAULT_RANDOMIZER_IMPLEMENTATION = "org.owasp.esapi.reference.DefaultRandomizer";
public static final String DEFAULT_EXECUTOR_IMPLEMENTATION = "org.owasp.esapi.reference.DefaultExecutor";
public static final String DEFAULT_HTTP_UTILITIES_IMPLEMENTATION = "org.owasp.esapi.reference.DefaultHTTPUtilities";
public static final String DEFAULT_VALIDATOR_IMPLEMENTATION = "org.owasp.esapi.reference.DefaultValidator";
private static final Map<String, Pattern> patternCache = new HashMap<String, Pattern>();
/*
* Absolute path to the userDirectory
*/
private static String userDirectory = System.getProperty("user.home" ) + "/.esapi";
/*
* Absolute path to the customDirectory
*/
private static String customDirectory = System.getProperty("org.owasp.esapi.resources");
/*
* Relative path to the resourceDirectory. Relative to the classpath.
* Specifically, ClassLoader.getResource(resourceDirectory + filename) will
* be used to load the file.
*/
private static String resourceDirectory = ".esapi";
// private static long lastModified = -1;
/**
* Instantiates a new configuration.
*/
public DefaultSecurityConfiguration() {
// load security configuration
try {
loadConfiguration();
// TODO: FUTURE: Replace by CryptoControls ???
// See SecurityConfiguration.setCipherTransformation() for
// explanation of this.
cipherXformFromESAPIProp =
getESAPIProperty(CIPHER_TRANSFORMATION_IMPLEMENTATION,
"AES/CBC/PKCS5Padding");
cipherXformCurrent = cipherXformFromESAPIProp;
} catch( IOException e ) {
logSpecial("Failed to load security configuration", e );
}
}
/**
* {@inheritDoc}
*/
public String getApplicationName() {
return getESAPIProperty(APPLICATION_NAME, "DefaultName");
}
/**
* {@inheritDoc}
*/
public String getLogImplementation() {
return getESAPIProperty(LOG_IMPLEMENTATION, DEFAULT_LOG_IMPLEMENTATION);
}
/**
* {@inheritDoc}
*/
public String getAuthenticationImplementation() {
return getESAPIProperty(AUTHENTICATION_IMPLEMENTATION, DEFAULT_AUTHENTICATION_IMPLEMENTATION);
}
/**
* {@inheritDoc}
*/
public String getEncoderImplementation() {
return getESAPIProperty(ENCODER_IMPLEMENTATION, DEFAULT_ENCODER_IMPLEMENTATION);
}
/**
* {@inheritDoc}
*/
public String getAccessControlImplementation() {
return getESAPIProperty(ACCESS_CONTROL_IMPLEMENTATION, DEFAULT_ACCESS_CONTROL_IMPLEMENTATION);
}
/**
* {@inheritDoc}
*/
public String getEncryptionImplementation() {
return getESAPIProperty(ENCRYPTION_IMPLEMENTATION, DEFAULT_ENCRYPTION_IMPLEMENTATION);
}
/**
* {@inheritDoc}
*/
public String getIntrusionDetectionImplementation() {
return getESAPIProperty(INTRUSION_DETECTION_IMPLEMENTATION, DEFAULT_INTRUSION_DETECTION_IMPLEMENTATION);
}
/**
* {@inheritDoc}
*/
public String getRandomizerImplementation() {
return getESAPIProperty(RANDOMIZER_IMPLEMENTATION, DEFAULT_RANDOMIZER_IMPLEMENTATION);
}
/**
* {@inheritDoc}
*/
public String getExecutorImplementation() {
return getESAPIProperty(EXECUTOR_IMPLEMENTATION, DEFAULT_EXECUTOR_IMPLEMENTATION);
}
/**
* {@inheritDoc}
*/
public String getHTTPUtilitiesImplementation() {
return getESAPIProperty(HTTP_UTILITIES_IMPLEMENTATION, DEFAULT_HTTP_UTILITIES_IMPLEMENTATION);
}
/**
* {@inheritDoc}
*/
public String getValidationImplementation() {
return getESAPIProperty(VALIDATOR_IMPLEMENTATION, DEFAULT_VALIDATOR_IMPLEMENTATION);
}
/**
* {@inheritDoc}
*/
public byte[] getMasterKey() {
byte[] key = getESAPIPropertyEncoded( MASTER_KEY, null );
if ( key == null || key.length == 0 ) {
throw new ConfigurationException("Property '" + MASTER_KEY +
"' missing or empty in ESAPI.properties file.");
}
return key;
}
/**
* {@inheritDoc}
*/
public void setResourceDirectory( String dir ) {
resourceDirectory = dir;
logSpecial( "Reset resource directory to: " + dir, null );
// reload configuration if necessary
try {
this.loadConfiguration();
} catch( IOException e ) {
logSpecial("Failed to load security configuration from " + dir, e);
}
}
public int getEncryptionKeyLength() {
return getESAPIProperty(KEY_LENGTH, 128 );
}
/**
* {@inheritDoc}
*/
public byte[] getMasterSalt() {
byte[] salt = getESAPIPropertyEncoded( MASTER_SALT, null );
if ( salt == null || salt.length == 0 ) {
throw new ConfigurationException("Property '" + MASTER_SALT +
"' missing or empty in ESAPI.properties file.");
}
return salt;
}
/**
* {@inheritDoc}
*/
public List<String> getAllowedExecutables() {
String def = "";
String[] exList = getESAPIProperty(APPROVED_EXECUTABLES,def).split(",");
return Arrays.asList(exList);
}
/**
* {@inheritDoc}
*/
public List<String> getAllowedFileExtensions() {
String def = ".zip,.pdf,.tar,.gz,.xls,.properties,.txt,.xml";
String[] extList = getESAPIProperty(APPROVED_UPLOAD_EXTENSIONS,def).split(",");
return Arrays.asList(extList);
}
/**
* {@inheritDoc}
*/
public int getAllowedFileUploadSize() {
return getESAPIProperty(MAX_UPLOAD_FILE_BYTES, 5000000);
}
private Properties loadPropertiesFromStream( InputStream is, String name ) throws IOException {
Properties config = new Properties();
try {
config.load(is);
logSpecial("Loaded '" + name + "' properties file", null);
} finally {
if ( is != null ) try { is.close(); } catch( Exception e ) {}
}
return config;
}
/**
* {@inheritDoc}
*/
public File getResourceFile( String filename ) {
File f = null;
logSpecial( "Seeking " + filename, null );
//Note: relative directories are relative to the SystemResource directory
// The SystemResource directory is defined by ClassLoader.getSystemResource(
// Relative directories use URLs, so they must be specified using / as
// the pathSeparator, not the file system dependent pathSeparator.
//First, load from the absolute directory specified in customDirectory
//Second, load from the relative directory specified in resourceDirectory
//Third, load from the relative resource-default-directory which is .esapi
//Fourth, load from the relative directory without directory specification.
//Finally, load from the user's home directory.
//TODO MHF consider the security implications of non-deterministic
// configuration resource locations.
if(filename == null)
return null; // not found.
// first, allow command line overrides. -Dorg.owasp.esapi.resources directory
f = new File( customDirectory, filename );
if ( customDirectory != null && f.canRead() ) {
logSpecial( " Found in 'org.owasp.esapi.resources' directory: " + f.getAbsolutePath(), null );
return f;
} else {
logSpecial( " Not found in 'org.owasp.esapi.resources' directory or file not readable: " + f.getAbsolutePath(), null );
}
// if not found, then try the programatically set resource directory (this defaults to SystemResource directory/.esapi
URL fileUrl = ClassLoader.getSystemResource(DefaultSecurityConfiguration.resourceDirectory + "/" + filename);
if(fileUrl != null) {
String fileLocation = fileUrl.getFile();
f = new File( fileLocation );
if ( f.exists() ) {
logSpecial( " Found in SystemResource Directory/resourceDirectory: " + f.getAbsolutePath(), null );
return f;
} else {
logSpecial( " Not found in SystemResource Directory/resourceDirectory (this should never happen): " + f.getAbsolutePath(), null );
}
} else {
logSpecial( " Not found in SystemResource Directory/resourceDirectory: " + DefaultSecurityConfiguration.resourceDirectory + "/" + filename, null );
}
// if not found, then try the default set resource directory
fileUrl = ClassLoader.getSystemResource(".esapi/" + filename);
if(fileUrl != null) {
String fileLocation = fileUrl.getFile();
f = new File( fileLocation );
if ( f.exists() ) {
logSpecial( " Found in SystemResource Directory/.esapi: " + f.getAbsolutePath(), null );
return f;
} else {
logSpecial( " Not found in SystemResource Directory/.esapi(this should never happen): " + f.getAbsolutePath(), null );
}
} else {
logSpecial( " Not found in SystemResource Directory/.esapi: " + ".esapi/" + filename, null );
}
// if not found, then try the resource directory without the .esapi
fileUrl = ClassLoader.getSystemResource(filename);
if(fileUrl != null) {
String fileLocation = fileUrl.getFile();
f = new File( fileLocation );
if ( f.exists() ) {
logSpecial( " Found in SystemResource Directory: " + f.getAbsolutePath(), null );
return f;
} else {
logSpecial( " Not found in SystemResource Directory (this should never happen): " + f.getAbsolutePath(), null );
}
} else {
logSpecial( " Not found in SystemResource Directory: " + filename, null );
}
// if not found, then try the user's home directory
f = new File( userDirectory, filename);
if ( userDirectory != null && f.exists() ) {
logSpecial( " Found in 'user.home' directory: " + f.getAbsolutePath(), null );
return f;
} else {
logSpecial( " Not found in 'user.home' directory: " + f.getAbsolutePath(), null );
}
// return null if not found
return null;
}
/**
* Utility method to get a resource as an InputStream. The search looks for an "esapi-resources" directory in
* the setResourceDirectory() location, then the System.getProperty( "org.owasp.esapi.resources" ) location,
* then the System.getProperty( "user.home" ) location, and then the classpath.
* @param filename
* @return An {@code InputStream} associated with the specified file name as a resource
* stream.
* @throws IOException If the file cannot be found or opened for reading.
*/
public InputStream getResourceStream( String filename ) throws IOException {
if (filename == null) {
System.out.println("getResourceStream filename is null");
return null;
}
try {
File f = getResourceFile( filename );
if ( f != null && f.exists() ) {
return new FileInputStream( f );
}
} catch( Exception e ) {
// continue
}
//old
//ClassLoader loader = getClass().getClassLoader();
//InputStream in = loader.getResourceAsStream( ".esapi/"+filename );
//new
ClassLoader loader = getClass().getClassLoader();
System.out.println("Loader: " + loader);
String filePathToLoad = ".esapi/"+filename;
System.out.println("filePathToLoad: " + filePathToLoad);
URL resourceURL = loader.getResource( filePathToLoad);
System.out.println("resourceURL: " + resourceURL);
String resource = resourceURL.getFile();
System.out.println("resource pre decode: " + resource);
resource = resource.replace( "%20", " " );
System.out.println("resource post decode: " + resource);
FileInputStream in = new FileInputStream( new File( resource ) );
if ( in != null ) {
logSpecial( " Found on classpath", null );
return in;
} else {
logSpecial( " Not found on classpath", null );
logSpecial( " Not found anywhere", null );
}
return null;
}
/**
* Load configuration and optionally print properties. Never prints
* the master encryption key and master salt properties though.
* @throws java.io.IOException if the file is inaccessible
*/
private void loadConfiguration() throws IOException {
properties = loadPropertiesFromStream( getResourceStream( "ESAPI.properties" ), "ESAPI.properties" );
// get validation properties and merge them into the main properties
String validationPropFname = getESAPIProperty(VALIDATION_PROPERTIES, "validation.properties");
Properties validationProperties = loadPropertiesFromStream( getResourceStream( validationPropFname ), validationPropFname );
Iterator<?> i = validationProperties.keySet().iterator();
while( i.hasNext() ) {
String key = (String)i.next();
String value = validationProperties.getProperty(key);
properties.put( key, value);
}
if ( shouldPrintProperties() ) {
//FIXME - make this chunk configurable
}
}
/**
* Used to log errors to the console during the loading of the properties file itself. Can't use
* standard logging in this case, since the Logger is not initialized yet. Output is sent to
* {@code PrintStream} {@code System.out}.
*
* @param message The message to send to the console.
* @param e The error that occurred (this value is currently ignored).
*/
private void logSpecial(String message, Throwable e) {
System.out.println(message);
}
/**
* {@inheritDoc}
*/
public String getPasswordParameterName() {
return getESAPIProperty(PASSWORD_PARAMETER_NAME, "password");
}
/**
* {@inheritDoc}
*/
public String getUsernameParameterName() {
return getESAPIProperty(USERNAME_PARAMETER_NAME, "username");
}
/**
* {@inheritDoc}
*/
public String getEncryptionAlgorithm() {
return getESAPIProperty(ENCRYPTION_ALGORITHM, "AES");
}
/**
* {@inheritDoc}
*/
public String getCipherTransformation() {
assert cipherXformCurrent != null : "Current cipher transformation is null";
return cipherXformCurrent;
}
/**
* {@inheritDoc}
*/
public String setCipherTransformation(String cipherXform) {
String previous = getCipherTransformation();
if ( cipherXform == null ) {
// Special case... means set it to original value from ESAPI.properties
cipherXformCurrent = cipherXformFromESAPIProp;
} else {
assert ! cipherXform.trim().equals("") :
"Cipher transformation cannot be just white space or empty string";
cipherXformCurrent = cipherXform; // Note: No other sanity checks!!!
}
return previous;
}
/**
* {@inheritDoc}
*/
public boolean useMACforCipherText() {
return getESAPIProperty(CIPHERTEXT_USE_MAC, true);
}
/**
* {@inheritDoc}
*/
public boolean overwritePlainText() {
return getESAPIProperty(PLAINTEXT_OVERWRITE, true);
}
/**
* {@inheritDoc}
*/
public String getIVType() {
String value = getESAPIProperty(IV_TYPE, "random");
if ( value.equalsIgnoreCase("fixed") || value.equalsIgnoreCase("random") ) {
return value;
} else if ( value.equalsIgnoreCase("specified") ) {
// This is planned for future implementation where setting
// Encryptor.ChooseIVMethod=specified will require setting some
// other TBD property that will specify an implementation class that
// will generate appropriate IVs. The intent of this would be to use
// such a class with various feedback modes where it is imperative
// that for a given key, any particular IV is *NEVER* reused. For
// now, we will assume that generating a random IV is usually going
// to be sufficient to prevent this.
throw new ConfigurationException("'" + IV_TYPE + "=specified' is not yet implemented. Use 'fixed' or 'random'");
} else {
// DISCUSS: Could just log this and then silently return "random" instead.
throw new ConfigurationException(value + " is illegal value for " + IV_TYPE +
". Use 'random' (preferred) or 'fixed'.");
}
}
/**
* {@inheritDoc}
*/
public String getFixedIV() {
if ( getIVType().equalsIgnoreCase("fixed") ) {
String ivAsHex = getESAPIProperty(FIXED_IV, ""); // No default
if ( ivAsHex == null || ivAsHex.trim().equals("") ) {
throw new ConfigurationException("Fixed IV requires property " +
FIXED_IV + " to be set, but it is not.");
}
return ivAsHex; // We do no further checks here as we have no context.
} else {
// DISCUSS: Should we just log a warning here and return null instead?
// If so, may cause NullPointException somewhere later.
throw new ConfigurationException("IV type not 'fixed' (set to '" +
getIVType() + "'), so no fixed IV applicable.");
}
}
/**
* {@inheritDoc}
*/
public String getHashAlgorithm() {
return getESAPIProperty(HASH_ALGORITHM, "SHA-512");
}
/**
* {@inheritDoc}
*/
public int getHashIterations() {
return getESAPIProperty(HASH_ITERATIONS, 1024);
}
/**
* {@inheritDoc}
*/
public String getCharacterEncoding() {
return getESAPIProperty(CHARACTER_ENCODING, "UTF-8");
}
/**
* {@inheritDoc}
*/
public boolean getAllowMultipleEncoding() {
return getESAPIProperty( ALLOW_MULTIPLE_ENCODING, false );
}
/**
* {@inheritDoc}
*/
public List<String> getDefaultCanonicalizationCodecs() {
List<String> def = new ArrayList<String>();
def.add( "org.owasp.esapi.codecs.HTMLEntityCodec" );
def.add( "org.owasp.esapi.codecs.PercentCodec" );
def.add( "org.owasp.esapi.codecs.JavaScriptCodec" );
return getESAPIProperty( CANONICALIZATION_CODECS, def );
}
/**
* {@inheritDoc}
*/
public String getDigitalSignatureAlgorithm() {
return getESAPIProperty(DIGITAL_SIGNATURE_ALGORITHM, "SHAwithDSA");
}
/**
* {@inheritDoc}
*/
public int getDigitalSignatureKeyLength() {
return getESAPIProperty(DIGITAL_SIGNATURE_KEY_LENGTH, 1024);
}
/**
* {@inheritDoc}
*/
public String getRandomAlgorithm() {
return getESAPIProperty(RANDOM_ALGORITHM, "SHA1PRNG");
}
/**
* {@inheritDoc}
*/
public int getAllowedLoginAttempts() {
return getESAPIProperty(ALLOWED_LOGIN_ATTEMPTS, 5);
}
/**
* {@inheritDoc}
*/
public int getMaxOldPasswordHashes() {
return getESAPIProperty(MAX_OLD_PASSWORD_HASHES, 12);
}
/**
* {@inheritDoc}
*/
public File getUploadDirectory() {
String dir = getESAPIProperty( UPLOAD_DIRECTORY, "UploadDir");
return new File( dir );
}
/**
* {@inheritDoc}
*/
public File getUploadTempDirectory() {
String dir = getESAPIProperty( UPLOAD_TEMP_DIRECTORY, "UploadTempDir");
return new File( dir );
}
/**
* {@inheritDoc}
*/
public boolean getDisableIntrusionDetection() {
String value = properties.getProperty( DISABLE_INTRUSION_DETECTION );
if ("true".equalsIgnoreCase(value)) return true;
return false; // Default result
}
/**
* {@inheritDoc}
*/
public Threshold getQuota(String eventName) {
int count = getESAPIProperty("IntrusionDetector." + eventName + ".count", 0);
int interval = getESAPIProperty("IntrusionDetector." + eventName + ".interval", 0);
List<String> actions = new ArrayList<String>();
String actionString = getESAPIProperty("IntrusionDetector." + eventName + ".actions", "");
if (actionString != null) {
String[] actionList = actionString.split(",");
actions = Arrays.asList(actionList);
}
if ( count > 0 && interval > 0 && actions.size() > 0 ) {
return new Threshold(eventName, count, interval, actions);
}
return null;
}
/**
* {@inheritDoc}
*/
public int getLogLevel() {
String level = getESAPIProperty(LOG_LEVEL, "WARNING" );
if (level.equalsIgnoreCase("OFF"))
return Logger.OFF;
if (level.equalsIgnoreCase("FATAL"))
return Logger.FATAL;
if (level.equalsIgnoreCase("ERROR"))
return Logger.ERROR ;
if (level.equalsIgnoreCase("WARNING"))
return Logger.WARNING;
if (level.equalsIgnoreCase("INFO"))
return Logger.INFO;
if (level.equalsIgnoreCase("DEBUG"))
return Logger.DEBUG;
if (level.equalsIgnoreCase("TRACE"))
return Logger.TRACE;
if (level.equalsIgnoreCase("ALL"))
return Logger.ALL;
// This error is NOT logged the normal way because the logger constructor calls getLogLevel() and if this error occurred it would cause
// an infinite loop.
logSpecial("The LOG-LEVEL property in the ESAPI properties file has the unrecognized value: " + level + ". Using default: WARNING", null);
return Logger.WARNING; // Note: The default logging level is WARNING.
}
/**
* {@inheritDoc}
*/
public String getLogFileName() {
return getESAPIProperty( LOG_FILE_NAME, "ESAPI_logging_file" );
}
/**
* {@inheritDoc}
*/
public int getMaxLogFileSize() {
return getESAPIProperty( MAX_LOG_FILE_SIZE, DEFAULT_MAX_LOG_FILE_SIZE );
}
/**
* {@inheritDoc}
*/
public boolean getLogEncodingRequired() {
return getESAPIProperty( LOG_ENCODING_REQUIRED, false );
}
/**
* {@inheritDoc}
*/
public boolean getLogApplicationName() {
return getESAPIProperty( LOG_APPLICATION_NAME, true );
}
/**
* {@inheritDoc}
*/
public boolean getLogServerIP() {
return getESAPIProperty( LOG_SERVER_IP, true );
}
/**
* {@inheritDoc}
*/
public boolean getForceHttpOnlySession() {
return getESAPIProperty( FORCE_HTTPONLYSESSION, true );
}
/**
* {@inheritDoc}
*/
public boolean getForceSecureSession() {
return getESAPIProperty( FORCE_SECURESESSION, true );
}
/**
* {@inheritDoc}
*/
public boolean getForceHttpOnlyCookies() {
return getESAPIProperty( FORCE_HTTPONLYCOOKIES, true );
}
/**
* {@inheritDoc}
*/
public boolean getForceSecureCookies() {
return getESAPIProperty( FORCE_SECURECOOKIES, true );
}
/**
* {@inheritDoc}
*/
public String getResponseContentType() {
return getESAPIProperty( RESPONSE_CONTENT_TYPE, "text/html; charset=UTF-8" );
}
/**
* {@inheritDoc}
*/
public long getRememberTokenDuration() {
int days = getESAPIProperty( REMEMBER_TOKEN_DURATION, 14 );
return (long) (1000 * 60 * 60 * 24 * days);
}
/**
* {@inheritDoc}
*/
public int getSessionIdleTimeoutLength() {
int minutes = getESAPIProperty( IDLE_TIMEOUT_DURATION, 20 );
return 1000 * 60 * minutes;
}
/**
* {@inheritDoc}
*/
public int getSessionAbsoluteTimeoutLength() {
int minutes = getESAPIProperty(ABSOLUTE_TIMEOUT_DURATION, 20 );
return 1000 * 60 * minutes;
}
/**
* getValidationPattern returns a single pattern based upon key
*
* @param key
* validation pattern name you'd like
* @return
* if key exists, the associated validation pattern, null otherwise
*/
public Pattern getValidationPattern( String key ) {
String value = getESAPIProperty( "Validator." + key, "" );
// check cache
Pattern p = patternCache.get( value );
if ( p != null ) return p;
// compile a new pattern
if ( value == null || value.equals( "" ) ) return null;
try {
Pattern q = Pattern.compile(value);
patternCache.put( value, q );
return q;
} catch ( PatternSyntaxException e ) {
logSpecial( "SecurityConfiguration for " + key + " not a valid regex in ESAPI.properties. Returning null", null );
return null;
}
}
/**
* getWorkingDirectory returns the default directory where processes will be executed
* by the Executor.
*/
public File getWorkingDirectory() {
String dir = getESAPIProperty( WORKING_DIRECTORY, System.getProperty( "user.dir") );
if ( dir != null ) {
return new File( dir );
}
return null;
}
private String getESAPIProperty( String key, String def ) {
String value = properties.getProperty(key);
if ( value == null ) {
logSpecial( "SecurityConfiguration for " + key + " not found in ESAPI.properties. Using default: " + def, null );
return def;
}
return value;
}
private boolean getESAPIProperty( String key, boolean def ) {
String property = properties.getProperty(key);
if ( property == null ) {
logSpecial( "SecurityConfiguration for " + key + " not found in ESAPI.properties. Using default: " + def, null );
return def;
}
if ( property.equalsIgnoreCase("true") || property.equalsIgnoreCase("yes" ) ) {
return true;
}
if ( property.equalsIgnoreCase("false") || property.equalsIgnoreCase( "no" ) ) {
return false;
}
logSpecial( "SecurityConfiguration for " + key + " not either \"true\" or \"false\" in ESAPI.properties. Using default: " + def, null );
return def;
}
private byte[] getESAPIPropertyEncoded( String key, byte[] def ) {
String property = properties.getProperty(key);
if ( property == null ) {
logSpecial( "SecurityConfiguration for " + key + " not found in ESAPI.properties. Using default: " + def, null );
return def;
}
try {
return ESAPI.encoder().decodeFromBase64(property);
} catch( IOException e ) {
logSpecial( "SecurityConfiguration for " + key + " not properly Base64 encoded in ESAPI.properties. Using default: " + def, null );
return null;
}
}
private int getESAPIProperty( String key, int def ) {
String property = properties.getProperty(key);
if ( property == null ) {
logSpecial( "SecurityConfiguration for " + key + " not found in ESAPI.properties. Using default: " + def, null );
return def;
}
try {
return Integer.parseInt( property );
} catch( NumberFormatException e ) {
logSpecial( "SecurityConfiguration for " + key + " not an integer in ESAPI.properties. Using default: " + def, null );
return def;
}
}
/**
* Returns a List representing the parsed, comma-separated property
* @param key
* @param def
* @return
*/
private List<String> getESAPIProperty( String key, List<String> def ) {
String property = properties.getProperty( key );
if ( property == null ) {
logSpecial( "SecurityConfiguration for " + key + " not found in ESAPI.properties. Using default: " + def, null );
return def;
}
String[] parts = property.split(",");
return Arrays.asList( parts );
}
private boolean shouldPrintProperties() {
return getESAPIProperty(PRINT_PROPERTIES_WHEN_LOADED, false);
}
}
|
package com.oracle.graal.debug.test;
import java.io.*;
import org.junit.*;
import com.oracle.graal.debug.*;
import com.oracle.graal.debug.internal.*;
public class DebugHistogramTest {
@Test
public void testEmptyHistogram() {
DebugHistogram histogram = Debug.createHistogram("TestHistogram");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
new DebugHistogramAsciiPrinter(new PrintStream(outputStream)).print(histogram);
String line = outputStream.toString().split("\r?\n")[0];
Assert.assertEquals("TestHistogram is empty.", line);
outputStream.reset();
new DebugHistogramRPrinter(new PrintStream(outputStream)).print(histogram);
Assert.assertEquals("", outputStream.toString());
}
@Test
public void testSingleEntryHistogram() {
DebugHistogram histogram = Debug.createHistogram("TestHistogram");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
histogram.add(new Integer(1));
histogram.add(new Integer(1));
new DebugHistogramAsciiPrinter(new PrintStream(outputStream)).print(histogram);
String[] lines = outputStream.toString().split("\r?\n");
// @formatter:off
String[] expected = {
"TestHistogram has 1 unique elements and 2 total elements:",
"
"| 1 | 2 | ==================================================================================================== |",
"
};
// @formatter:on
Assert.assertArrayEquals(expected, lines);
outputStream.reset();
new DebugHistogramRPrinter(new PrintStream(outputStream)).print(histogram);
lines = outputStream.toString().split("\r?\n");
// @formatter:off
expected = new String[] {
"TestHistogram <- c(2);",
"names(TestHistogram) <- c(\"1\");"
};
// @formatter:on
Assert.assertArrayEquals(expected, lines);
}
@Test
public void testMultipleEntryHistogram() {
DebugHistogram histogram = Debug.createHistogram("TestHistogram");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
histogram.add(new Integer(1));
histogram.add(new Integer(2));
histogram.add(new Integer(2));
new DebugHistogramAsciiPrinter(new PrintStream(outputStream)).print(histogram);
String[] lines = outputStream.toString().split("\r?\n");
// @formatter:off
String[] expected = new String[] {
"TestHistogram has 2 unique elements and 3 total elements:",
"
"| 2 | 2 | ==================================================================================================== |",
"| 1 | 1 | ================================================== |",
"
};
// @formatter:on
Assert.assertArrayEquals(expected, lines);
outputStream.reset();
new DebugHistogramRPrinter(new PrintStream(outputStream)).print(histogram);
lines = outputStream.toString().split("\r?\n");
// @formatter:off
expected = new String[] {
"TestHistogram <- c(2, 1);",
"names(TestHistogram) <- c(\"2\", \"1\");"
};
// @formatter:on
Assert.assertArrayEquals(expected, lines);
}
@Test
public void testTooLongValueString() {
DebugHistogram histogram = Debug.createHistogram("TestHistogram");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
histogram.add("MyCustomValue");
new DebugHistogramAsciiPrinter(new PrintStream(outputStream), Integer.MAX_VALUE, 10, 10, 1).print(histogram);
String[] lines = outputStream.toString().split("\r?\n");
Assert.assertEquals(4, lines.length);
Assert.assertEquals("TestHistogram has 1 unique elements and 1 total elements:", lines[0]);
Assert.assertEquals("
Assert.assertEquals("| MyCusto... | 1 | ========== |", lines[2]);
Assert.assertEquals("
}
}
|
package dynamake.models;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import dynamake.commands.Command;
import dynamake.commands.DualCommand;
import dynamake.commands.DualCommandPair;
import dynamake.delegates.Action1;
import dynamake.menubuilders.CompositeMenuBuilder;
import dynamake.models.factories.Factory;
import dynamake.tools.Tool;
import dynamake.transcription.DualCommandFactory;
import dynamake.transcription.RepaintRunBuilder;
import dynamake.transcription.TranscriberBranch;
public class LiveModel extends Model {
private static final long serialVersionUID = 1L;
// public static class ButtonToolBindingChanged {
// public final int button;
// public final int tool;
// public ButtonToolBindingChanged(int button, int tool) {
// this.button = button;
// this.tool = tool;
public static class ButtonsToolBindingChanged {
public final List<Integer> buttons;
public final int tool;
public ButtonsToolBindingChanged(List<Integer> buttons, int tool) {
this.buttons = buttons;
this.tool = tool;
}
}
private Model content;
// private Hashtable<Integer, Integer> buttonToToolMap = new Hashtable<Integer, Integer>();
private Hashtable<List<Integer>, Integer> buttonsToToolMap = new Hashtable<List<Integer>, Integer>();
public LiveModel(Model content) {
this.content = content;
}
@Override
public Model modelCloneIsolated() {
LiveModel clone = new LiveModel(content.cloneIsolated());
// clone.buttonToToolMap.putAll(clone.buttonToToolMap);
clone.buttonsToToolMap.putAll(clone.buttonsToToolMap);
return clone;
}
// public int getToolForButton(int button) {
// Integer tool = buttonToToolMap.get(button);
// return tool != null ? tool : -1;
// public int getButtonForTool(int tool) {
// for(Map.Entry<Integer, Integer> entry: buttonToToolMap.entrySet()) {
// if(entry.getValue() == tool)
// return entry.getKey();
// return -1;
// public void removeButtonToToolBinding(int button, int tool, PropogationContext propCtx, int propDistance, TranscriberBranch<Model> branch) {
// buttonToToolMap.remove(button);
// sendChanged(new ButtonToolBindingChanged(-1, tool), propCtx, propDistance, 0, branch);
// public void bindButtonToTool(int button, int tool, PropogationContext propCtx, int propDistance, TranscriberBranch<Model> branch) {
// buttonToToolMap.put(button, tool);
// sendChanged(new ButtonToolBindingChanged(button, tool), propCtx, propDistance, 0, branch);
public int getToolForButtons(List<Integer> buttons) {
Integer tool = buttonsToToolMap.get(buttons);
return tool != null ? tool : -1;
}
public List<Integer> getButtonsForTool(int tool) {
for(Map.Entry<List<Integer>, Integer> entry: buttonsToToolMap.entrySet()) {
if(entry.getValue() == tool)
return entry.getKey();
}
return Collections.emptyList();
}
// public static class BindButtonToToolCommand implements Command<Model> {
// private static final long serialVersionUID = 1L;
// private Location modelLocation;
// private int button;
// private int tool;
// public BindButtonToToolCommand(Location modelLocation, int button, int tool) {
// this.modelLocation = modelLocation;
// this.button = button;
// this.tool = tool;
// @Override
// public void executeOn(PropogationContext propCtx, Model prevalentSystem, Date executionTime, TranscriberBranch<Model> branch) {
// LiveModel liveModel = (LiveModel)modelLocation.getChild(prevalentSystem);
// liveModel.bindButtonToTool(button, tool, propCtx, 0, branch);
// public static class RemoveButtonToToolBindingCommand implements Command<Model> {
// private static final long serialVersionUID = 1L;
// private Location modelLocation;
// private int button;
// private int tool;
// public RemoveButtonToToolBindingCommand(Location modelLocation, int button, int tool) {
// this.modelLocation = modelLocation;
// this.button = button;
// this.tool = tool;
// @Override
// public void executeOn(PropogationContext propCtx, Model prevalentSystem, Date executionTime, TranscriberBranch<Model> branch) {
// LiveModel liveModel = (LiveModel)modelLocation.getChild(prevalentSystem);
// liveModel.removeButtonToToolBinding(button, tool, propCtx, 0, branch);
public void removeButtonsToToolBinding(List<Integer> buttons, int tool, PropogationContext propCtx, int propDistance, TranscriberBranch<Model> branch) {
buttonsToToolMap.remove(buttons);
sendChanged(new ButtonsToolBindingChanged(Collections.<Integer>emptyList(), tool), propCtx, propDistance, 0, branch);
}
public void bindButtonsToTool(List<Integer> buttons, int tool, PropogationContext propCtx, int propDistance, TranscriberBranch<Model> branch) {
buttonsToToolMap.put(buttons, tool);
sendChanged(new ButtonsToolBindingChanged(buttons, tool), propCtx, propDistance, 0, branch);
}
public static class BindButtonsToToolCommand implements Command<Model> {
private static final long serialVersionUID = 1L;
private Location modelLocation;
private List<Integer> buttons;
private int tool;
public BindButtonsToToolCommand(Location modelLocation, List<Integer> buttons, int tool) {
this.modelLocation = modelLocation;
this.buttons = buttons;
this.tool = tool;
}
@Override
public void executeOn(PropogationContext propCtx, Model prevalentSystem, Date executionTime, TranscriberBranch<Model> branch) {
LiveModel liveModel = (LiveModel)modelLocation.getChild(prevalentSystem);
liveModel.bindButtonsToTool(buttons, tool, propCtx, 0, branch);
}
}
public static class RemoveButtonsToToolBindingCommand implements Command<Model> {
private static final long serialVersionUID = 1L;
private Location modelLocation;
private List<Integer> buttons;
private int tool;
public RemoveButtonsToToolBindingCommand(Location modelLocation, List<Integer> buttons, int tool) {
this.modelLocation = modelLocation;
this.buttons = buttons;
this.tool = tool;
}
@Override
public void executeOn(PropogationContext propCtx, Model prevalentSystem, Date executionTime, TranscriberBranch<Model> branch) {
LiveModel liveModel = (LiveModel)modelLocation.getChild(prevalentSystem);
liveModel.removeButtonsToToolBinding(buttons, tool, propCtx, 0, branch);
}
}
public static class ContentLocator implements dynamake.models.ModelLocator {
@Override
public ModelLocation locate() {
return new FieldContentLocation();
}
}
private static class FieldContentLocation implements ModelLocation {
private static final long serialVersionUID = 1L;
@Override
public Object getChild(Object holder) {
return ((LiveModel)holder).content;
}
@Override
public Location getModelComponentLocation() {
return new ViewFieldContentLocation();
}
}
private static class ViewFieldContentLocation implements Location {
@Override
public Object getChild(Object holder) {
return ((LivePanel)holder).contentView.getBindingTarget();
}
}
private static final int BUTTON_FONT_SIZE = 13;
private static final Color TOP_BACKGROUND_COLOR = new Color(90, 90, 90);
private static final Color TOP_BUTTON_BACKGROUND_COLOR = TOP_BACKGROUND_COLOR;
private static final Color TOP_FOREGROUND_COLOR = Color.WHITE;
public static class ToolButton extends JPanel {
private static final long serialVersionUID = 1L;
private int tool;
// private int button;
private List<Integer> buttons;
private String text;
private LiveModel liveModel;
private ModelTranscriber modelTranscriber;
private JLabel labelToolName;
private JPanel panelButtons;
public ToolButton(int tool, List<Integer> buttons, String text, LiveModel liveModel, ModelTranscriber modelTranscriber) {
this.tool = tool;
this.buttons = buttons;
this.text = text;
this.liveModel = liveModel;
this.modelTranscriber = modelTranscriber;
setLayout(new BorderLayout(0, 0));
setBackground(TOP_BUTTON_BACKGROUND_COLOR);
labelToolName = new JLabel();
labelToolName.setHorizontalAlignment(SwingConstants.CENTER);
labelToolName.setForeground(TOP_FOREGROUND_COLOR);
labelToolName.setFont(new Font(labelToolName.getFont().getFontName(), Font.BOLD, BUTTON_FONT_SIZE));
add(labelToolName, BorderLayout.CENTER);
panelButtons = new JPanel();
panelButtons.setLayout(new FlowLayout(FlowLayout.CENTER, 2, 0));
panelButtons.setOpaque(false);
add(panelButtons, BorderLayout.NORTH);
this.setPreferredSize(new Dimension(72, 45));
update();
this.addMouseListener(new MouseAdapter() {
int buttonsDown = 0;
ArrayList<Integer> buttonsPressed = new ArrayList<Integer>();
@Override
public void mousePressed(MouseEvent e) {
int newButton = e.getButton();
buttonsDown++;
buttonsPressed.add(newButton);
Collections.sort(buttonsPressed);
if(buttonsDown == 1) {
setBackground(TOP_BUTTON_BACKGROUND_COLOR.brighter());
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
System.out.println("Update");
update(buttonsPressed);
ToolButton.this.repaint();
}
});
}
@Override
public void mouseReleased(MouseEvent e) {
buttonsDown
if(buttonsDown == 0) {
setBackground(TOP_BUTTON_BACKGROUND_COLOR);
final int newButton = buttonsPressed.get(0);
PropogationContext propCtx = new PropogationContext();
TranscriberBranch<Model> branch = ToolButton.this.modelTranscriber.createBranch();
final ArrayList<Integer> localButtonsPressed = (ArrayList<Integer>)buttonsPressed.clone();
branch.execute(propCtx, new DualCommandFactory<Model>() {
@Override
public void createDualCommands(List<DualCommand<Model>> dualCommands) {
// setBackground(TOP_BUTTON_BACKGROUND_COLOR.brighter());
List<Integer> currentButtons = ToolButton.this.buttons;
Location modelLocation = ToolButton.this.modelTranscriber.getModelLocation();
// int previousToolForNewButton = ToolButton.this.liveModel.getToolForButton(newButton);
// if(previousToolForNewButton != -1) {
// // If the new button is associated to another tool, then remove that binding
// dualCommands.add(new DualCommandPair<Model>(
// new RemoveButtonToToolBindingCommand(modelLocation, newButton, previousToolForNewButton),
// new BindButtonToToolCommand(modelLocation, newButton, previousToolForNewButton))
// if(currentButton != -1) {
// // If this tool is associated to button, then remove that binding before
// dualCommands.add(new DualCommandPair<Model>(
// new RemoveButtonToToolBindingCommand(modelLocation, currentButton, ToolButton.this.tool),
// new BindButtonToToolCommand(modelLocation, currentButton, ToolButton.this.tool))
// // adding the replacement binding
// dualCommands.add(new DualCommandPair<Model>(
// new BindButtonToToolCommand(modelLocation, newButton, ToolButton.this.tool),
// new RemoveButtonToToolBindingCommand(modelLocation, newButton, ToolButton.this.tool))
// } else {
// dualCommands.add(new DualCommandPair<Model>(
// new BindButtonToToolCommand(modelLocation, newButton, ToolButton.this.tool),
// new RemoveButtonToToolBindingCommand(modelLocation, newButton, ToolButton.this.tool)
int previousToolForNewButton = ToolButton.this.liveModel.getToolForButtons(localButtonsPressed);
if(previousToolForNewButton != -1) {
// If the new button is associated to another tool, then remove that binding
dualCommands.add(new DualCommandPair<Model>(
new RemoveButtonsToToolBindingCommand(modelLocation, localButtonsPressed, previousToolForNewButton),
new BindButtonsToToolCommand(modelLocation, localButtonsPressed, previousToolForNewButton))
);
}
if(currentButtons.size() > 0) {
// If this tool is associated to button, then remove that binding before
dualCommands.add(new DualCommandPair<Model>(
new RemoveButtonsToToolBindingCommand(modelLocation, currentButtons, ToolButton.this.tool),
new BindButtonsToToolCommand(modelLocation, currentButtons, ToolButton.this.tool))
);
// adding the replacement binding
dualCommands.add(new DualCommandPair<Model>(
new BindButtonsToToolCommand(modelLocation, localButtonsPressed, ToolButton.this.tool),
new RemoveButtonsToToolBindingCommand(modelLocation, localButtonsPressed, ToolButton.this.tool))
);
} else {
dualCommands.add(new DualCommandPair<Model>(
new BindButtonsToToolCommand(modelLocation, localButtonsPressed, ToolButton.this.tool),
new RemoveButtonsToToolBindingCommand(modelLocation, localButtonsPressed, ToolButton.this.tool)
));
}
}
});
branch.close();
buttonsPressed.clear();
}
}
});
// // Support for binding a key combination with a tool
// // It should be possible to both bind a key combination AND a mouse button to the same tool at the same time
// KeyListener keyListener = new KeyAdapter() {
// @Override
// public void keyPressed(KeyEvent e) {
//// System.out.println(e.isControlDown() + ":" + e.getKeyCode());
// @Override
// public void keyTyped(KeyEvent e) {
//// System.out.println(e.isControlDown() + ":" + e.getKeyCode());
setFocusable(true);
// this.addKeyListener(keyListener);
// labelToolName.addKeyListener(keyListener);
// labelButton.addKeyListener(keyListener);
}
private static final Color[] BUTTON_COLORS = new Color[] {
new Color(255, 120, 10),//Color.RED,
new Color(10, 220, 10), //Color.GREEN,
new Color(10, 10, 220), //Color.BLUE,
new Color(10, 220, 220), //Color.CYAN,
new Color(220, 220, 10), //Color.ORANGE
new Color(220, 10, 220),
};
public static Color getColorForButton(int button) {
return BUTTON_COLORS[button - 1];
}
private void update(List<Integer> buttons) {
labelToolName.setText(text);
Border innerBorder = BorderFactory.createEmptyBorder(0, 5, 0, 5);
Border outerBorder;
panelButtons.removeAll();
if(buttons.size() > 0) {
for(int button: buttons) {
JLabel buttonLabel = new JLabel();
buttonLabel.setHorizontalAlignment(SwingConstants.CENTER);
buttonLabel.setForeground(getColorForButton(button));
buttonLabel.setFont(new Font(buttonLabel.getFont().getFontName(), Font.ITALIC | Font.BOLD, 16));
buttonLabel.setText("" + button);
panelButtons.add(buttonLabel);
}
panelButtons.revalidate();
outerBorder = BorderFactory.createLoweredSoftBevelBorder();
} else {
JLabel buttonLabel = new JLabel();
buttonLabel.setText(" ");
buttonLabel.setForeground(null);
panelButtons.add(buttonLabel);
outerBorder = BorderFactory.createRaisedSoftBevelBorder();
}
setBorder(BorderFactory.createCompoundBorder(outerBorder, innerBorder));
}
private void update() {
// update(button != -1 ? Arrays.asList(button) : Collections.<Integer>emptyList());
update(buttons);
}
public void setButtons(List<Integer> buttons) {
this.buttons = buttons;
update();
}
}
private static JComponent createToolButton(final LiveModel model, final ModelTranscriber modelTranscriber, ButtonGroup group, List<Integer> buttons, final int tool, final String text) {
return new ToolButton(tool, buttons, text, model, modelTranscriber);
}
private static void updateToolButton(JComponent toolButton, List<Integer> buttons) {
((ToolButton)toolButton).setButtons(buttons);
}
public static class ProductionPanel extends JPanel {
private static final long serialVersionUID = 1L;
public static final Color TARGET_OVER_COLOR = new Color(35, 89, 184);
public static final Color BIND_COLOR = new Color(25, 209, 89);
public static final Color UNBIND_COLOR = new Color(240, 34, 54);
public static final Color SELECTION_COLOR = Color.GRAY;
public static class EditPanelMouseAdapter extends MouseAdapter {
public ProductionPanel productionPanel;
public int buttonPressed;
public static final int HORIZONTAL_REGION_WEST = 0;
public static final int HORIZONTAL_REGION_CENTER = 1;
public static final int HORIZONTAL_REGION_EAST = 2;
public static final int VERTICAL_REGION_NORTH = 0;
public static final int VERTICAL_REGION_CENTER = 1;
public static final int VERTICAL_REGION_SOUTH = 2;
public EditPanelMouseAdapter(ProductionPanel productionPanel) {
this.productionPanel = productionPanel;
}
private Tool getTool(int button) {
// int toolForButton = productionPanel.livePanel.model.getToolForButton(button);
int toolForButton = productionPanel.livePanel.model.getToolForButtons(Arrays.asList(button));
if(toolForButton != -1) {
return productionPanel.livePanel.viewManager.getTools()[toolForButton];
} else {
return new Tool() {
@Override
public void mouseReleased(ProductionPanel productionPanel, MouseEvent e, ModelComponent modelOver) { }
@Override
public void mousePressed(ProductionPanel productionPanel, MouseEvent e, ModelComponent modelOver) { }
@Override
public void mouseMoved(ProductionPanel productionPanel, MouseEvent e, ModelComponent modelOver) { }
@Override
public void mouseExited(ProductionPanel productionPanel, MouseEvent e) { }
@Override
public void mouseDragged(ProductionPanel productionPanel, MouseEvent e, ModelComponent modelOver) { }
@Override
public String getName() { return null; }
@Override
public void paint(Graphics g) { }
};
}
}
public ModelComponent getModelOver(MouseEvent e) {
Point pointInContentView = SwingUtilities.convertPoint((JComponent) e.getSource(), e.getPoint(), (JComponent)productionPanel.contentView.getBindingTarget());
JComponent componentOver = (JComponent)((JComponent)productionPanel.contentView.getBindingTarget()).findComponentAt(pointInContentView);
return ModelComponent.Util.closestModelComponent(componentOver);
}
public void mousePressed(final MouseEvent e) {
final ModelComponent modelOver = getModelOver(e);
productionPanel.editPanelMouseAdapter.buttonPressed = e.getButton();
final int localButtonPressed = productionPanel.editPanelMouseAdapter.buttonPressed;
// System.out.println("Pressed button " + localButtonPressed);
productionPanel.livePanel.getModelTranscriber().executeTransient(new Runnable() {
@Override
public void run() {
getTool(localButtonPressed).mousePressed(productionPanel, e, modelOver);
}
});
}
public void mouseDragged(final MouseEvent e) {
final ModelComponent modelOver = getModelOver(e);
if(modelOver != null) {
final int localButtonPressed = productionPanel.editPanelMouseAdapter.buttonPressed;
// System.out.println("Dragged button " + localButtonPressed);
productionPanel.livePanel.getModelTranscriber().executeTransient(new Runnable() {
@Override
public void run() {
getTool(localButtonPressed).mouseDragged(productionPanel, e, modelOver);
}
});
}
}
public void mouseReleased(final MouseEvent e) {
final ModelComponent modelOver = getModelOver(e);
if(modelOver != null) {
final int localButtonPressed = productionPanel.editPanelMouseAdapter.buttonPressed;
productionPanel.editPanelMouseAdapter.buttonPressed = 0;
// System.out.println("Released button " + localButtonPressed);
productionPanel.livePanel.getModelTranscriber().executeTransient(new Runnable() {
@Override
public void run() {
getTool(localButtonPressed).mouseReleased(productionPanel, e, modelOver);
}
});
}
}
@Override
public void mouseMoved(final MouseEvent e) {
final ModelComponent modelOver = getModelOver(e);
if(modelOver != null) {
productionPanel.livePanel.getModelTranscriber().executeTransient(new Runnable() {
@Override
public void run() {
// The tool associated to button 1 is used as a "master" tool
int button = 1;
getTool(button).mouseMoved(productionPanel, e, modelOver);
}
});
}
}
}
public LivePanel livePanel;
public Binding<ModelComponent> contentView;
public EditPanelMouseAdapter editPanelMouseAdapter;
public ProductionPanel(final LivePanel livePanel, final Binding<ModelComponent> contentView) {
this.setLayout(null);
this.livePanel = livePanel;
this.contentView = contentView;
// TODO: Consider the following:
// For a selected frame, it should be possible to scroll upwards to select its immediate parent
// - and scroll downwards to select its root parents
editPanelMouseAdapter = new EditPanelMouseAdapter(this);
this.addMouseListener(editPanelMouseAdapter);
this.addMouseMotionListener(editPanelMouseAdapter);
this.setOpaque(true);
this.setBackground(new Color(0, 0, 0, 0));
}
@Override
public void paint(Graphics g) {
super.paint(g);
editPanelMouseAdapter.getTool(editPanelMouseAdapter.buttonPressed).paint(g);
}
}
public static class LivePanel extends JPanel implements ModelComponent {
private static final long serialVersionUID = 1L;
public LiveModel model;
private JPanel topPanel;
private JLayeredPane contentPane;
private RemovableListener removableListener;
public ProductionPanel productionPanel;
public ViewManager viewManager;
private ModelTranscriber modelTranscriber;
private JComponent[] buttonTools;
private final Binding<ModelComponent> contentView;
public LivePanel(final ModelComponent rootView, LiveModel model, ModelTranscriber modelTranscriber, final ViewManager viewManager) {
this.setLayout(new BorderLayout());
this.model = model;
this.viewManager = viewManager;
this.modelTranscriber = modelTranscriber;
ViewManager newViewManager = new ViewManager() {
@Override
public Factory[] getFactories() {
return viewManager.getFactories();
}
@Override
public Tool[] getTools() {
return null;
}
};
contentView = model.getContent().createView(rootView, newViewManager, modelTranscriber.extend(new ContentLocator()));
productionPanel = new ProductionPanel(this, contentView);
topPanel = new JPanel();
topPanel.setBackground(TOP_BACKGROUND_COLOR);
topPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
contentPane = new JLayeredPane();
productionPanel.setSize(contentPane.getSize().width, contentPane.getSize().height - 1);
contentPane.addComponentListener(new ComponentListener() {
@Override
public void componentShown(ComponentEvent e) { }
@Override
public void componentResized(ComponentEvent e) {
((JComponent)contentView.getBindingTarget()).setSize(((JComponent)e.getSource()).getSize());
if(productionPanel != null) {
productionPanel.setSize(((JComponent)e.getSource()).getSize().width, ((JComponent)e.getSource()).getSize().height - 1);
}
}
@Override
public void componentMoved(ComponentEvent e) { }
@Override
public void componentHidden(ComponentEvent e) { }
});
contentPane.add((JComponent)contentView.getBindingTarget(), JLayeredPane.DEFAULT_LAYER);
this.add(topPanel, BorderLayout.NORTH);
this.add(contentPane, BorderLayout.CENTER);
removableListener = Model.RemovableListener.addObserver(model, new ObserverAdapter() {
{
initializeObserverAdapter();
}
private void initializeObserverAdapter() {
}
@Override
public void changed(Model sender, Object change, final PropogationContext propCtx, int propDistance, int changeDistance, TranscriberBranch<Model> branch) {
// if(change instanceof LiveModel.ButtonToolBindingChanged) {
// LiveModel.ButtonToolBindingChanged bindButtonChanged = (LiveModel.ButtonToolBindingChanged)change;
// if(bindButtonChanged.tool != -1) {
// JComponent buttonNewTool = buttonTools[bindButtonChanged.tool];
// updateToolButton(buttonNewTool, bindButtonChanged.button);
if(change instanceof LiveModel.ButtonsToolBindingChanged) {
LiveModel.ButtonsToolBindingChanged bindButtonChanged = (LiveModel.ButtonsToolBindingChanged)change;
if(bindButtonChanged.tool != -1) {
JComponent buttonNewTool = buttonTools[bindButtonChanged.tool];
updateToolButton(buttonNewTool, bindButtonChanged.buttons);
}
}
}
});
contentPane.add(productionPanel, JLayeredPane.MODAL_LAYER);
}
@Override
public void initialize() {
Tool[] tools = viewManager.getTools();
buttonTools = new JComponent[tools.length];
ButtonGroup group = new ButtonGroup();
for(int i = 0; i < tools.length; i++) {
Tool tool = tools[i];
// int button = model.getButtonForTool(i);
// buttonTools[i] = createToolButton(model, modelTranscriber, group, button, i, tool.getName());
List<Integer> buttons = model.getButtonsForTool(i);
buttonTools[i] = createToolButton(model, modelTranscriber, group, buttons, i, tool.getName());
}
for(JComponent buttonTool: buttonTools) {
topPanel.add(buttonTool);
}
TranscriberBranch<Model> initializationBranch = getModelTranscriber().createBranch();
initializationBranch.setOnFinishedBuilder(new RepaintRunBuilder(productionPanel.livePanel));
initializationBranch.close();
}
public Factory[] getFactories() {
return viewManager.getFactories();
}
@Override
public Model getModelBehind() {
return model;
}
@Override
public void appendContainerTransactions(LivePanel livePanel, CompositeMenuBuilder menuBuilder, ModelComponent child, TranscriberBranch<Model> branch) {
}
@Override
public void appendTransactions(ModelComponent livePanel, CompositeMenuBuilder menuBuilder, TranscriberBranch<Model> branch) {
}
@Override
public void appendDroppedTransactions(ModelComponent livePanel, ModelComponent target, Rectangle droppedBounds, CompositeMenuBuilder menuBuilder, TranscriberBranch<Model> branch) {
Model.appendGeneralDroppedTransactions(livePanel, this, target, droppedBounds, menuBuilder, branch);
}
@Override
public void appendDropTargetTransactions(
ModelComponent livePanel, ModelComponent dropped, Rectangle droppedBounds, Point dropPoint, CompositeMenuBuilder menuBuilder, TranscriberBranch<Model> branch) {
}
@Override
public ModelTranscriber getModelTranscriber() {
return modelTranscriber;
}
public void releaseBinding() {
removableListener.releaseBinding();
}
@Override
public DualCommandFactory<Model> getImplicitDropAction(ModelComponent target) {
return null;
}
@Override
public void visitTree(Action1<ModelComponent> visitAction) {
visitAction.run(this);
}
}
@Override
public Binding<ModelComponent> createView(ModelComponent rootView, ViewManager viewManager, ModelTranscriber modelTranscriber) {
this.setLocation(modelTranscriber.getModelLocator());
final LivePanel view = new LivePanel(rootView, this, modelTranscriber, viewManager);
return new Binding<ModelComponent>() {
@Override
public void releaseBinding() {
view.releaseBinding();
}
@Override
public ModelComponent getBindingTarget() {
return view;
}
};
}
public Model getContent() {
return content;
}
}
|
package org.spongepowered.api.util.metric;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.api.util.Tristate;
public interface MetricsConfigManager {
@Deprecated
boolean areMetricsEnabled(final PluginContainer container);
@Deprecated
default boolean areMetricsEnabled(final Object plugin) throws IllegalArgumentException {
return this.areMetricsEnabled(Sponge.getPluginManager().fromInstance(plugin)
.orElseThrow(() -> new IllegalArgumentException("The supplied object is not a plugin object.")));
}
/**
* Gets the current <em>global</em> state of collection. The collection state determines
* how data collection should be handled.
*
* Global state determines how an undefined state for a specific plugin should be handled.
* If a plugin has a state specified then it will override the global state.
*
* {@link Tristate#TRUE} Permits data collection
* {@link Tristate#FALSE} Disallows data collection, this has been explicitly set
* {@link Tristate#UNDEFINED} Disallows data collection, this is set by default
*
* @return The global state of collection
*/
Tristate getGlobalCollectionState();
/**
* Gets the current state of collection for the specified plugin. The collection state
* determines how data collection should be handled.
*
* {@link Tristate#TRUE} Permits data collection
* {@link Tristate#FALSE} Disallows data collection, this has been explicitly set
* {@link Tristate#UNDEFINED} Inherit from {@link MetricsConfigManager#getGlobalCollectionState()}, this is set by default
*
* @param container The {@link org.spongepowered.api.plugin.PluginContainer}
* @return The current collection state
*/
Tristate getCollectionState(final PluginContainer container);
}
|
package com.tinkerpop.gremlin.process.graph.step.filter;
import com.tinkerpop.gremlin.AbstractGremlinTest;
import com.tinkerpop.gremlin.LoadGraphWith;
import com.tinkerpop.gremlin.process.Traversal;
import com.tinkerpop.gremlin.structure.Vertex;
import com.tinkerpop.gremlin.util.StreamFactory;
import org.junit.Test;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import static com.tinkerpop.gremlin.LoadGraphWith.GraphData.CLASSIC;
import static org.junit.Assert.*;
public abstract class DedupTest extends AbstractGremlinTest {
public abstract Traversal<Vertex, String> get_g_V_both_dedup_name();
public abstract Traversal<Vertex, String> get_g_V_both_dedupXlangX_name();
public abstract Traversal<Vertex, String> get_g_V_both_name_orderXa_bX_dedup();
@Test
@LoadGraphWith(CLASSIC)
public void g_V_both_dedup_name() {
final Iterator<String> traversal = get_g_V_both_dedup_name();
System.out.println("Testing: " + traversal);
final List<String> names = StreamFactory.stream(traversal).collect(Collectors.toList());
assertEquals(6, names.size());
assertTrue(names.contains("marko"));
assertTrue(names.contains("vadas"));
assertTrue(names.contains("lop"));
assertTrue(names.contains("josh"));
assertTrue(names.contains("ripple"));
assertTrue(names.contains("peter"));
assertFalse(traversal.hasNext());
}
@Test
@LoadGraphWith(CLASSIC)
public void g_V_both_dedupXlangX_name() {
final Iterator<String> traversal = get_g_V_both_dedupXlangX_name();
System.out.println("Testing: " + traversal);
final List<String> names = StreamFactory.stream(traversal).collect(Collectors.toList());
assertEquals(2, names.size());
assertTrue(names.contains("marko") || names.contains("peter") || names.contains("josh") || names.contains("vadas"));
assertTrue(names.contains("lop") || names.contains("ripple"));
assertFalse(traversal.hasNext());
}
@Test
@LoadGraphWith(CLASSIC)
public void g_V_both_name_orderXa_bX_dedup() {
final Iterator<String> traversal = get_g_V_both_name_orderXa_bX_dedup();
System.out.println("Testing: " + traversal);
final List<String> names = StreamFactory.stream(traversal).collect(Collectors.toList());
assertEquals(6, names.size());
assertEquals("josh", names.get(0));
assertEquals("lop", names.get(1));
assertEquals("marko", names.get(2));
assertEquals("peter", names.get(3));
assertEquals("ripple", names.get(4));
assertEquals("vadas", names.get(5));
assertFalse(traversal.hasNext());
}
public static class JavaDedupTest extends DedupTest {
public Traversal<Vertex, String> get_g_V_both_dedup_name() {
return g.V().both().dedup().value("name");
}
public Traversal<Vertex, String> get_g_V_both_dedupXlangX_name() {
return g.V().both().dedup(v -> v.property("lang").orElse(null)).value("name");
}
public Traversal<Vertex, String> get_g_V_both_name_orderXa_bX_dedup() {
return g.V().both().property("name").order((a, b) -> ((String) a.get().value()).compareTo((String) b.get().value())).dedup().value();
}
}
}
|
package processing.app;
import static processing.app.I18n._;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.logging.impl.LogFactoryImpl;
import org.apache.commons.logging.impl.NoOpLog;
import cc.arduino.packages.DiscoveryManager;
import cc.arduino.packages.Uploader;
import processing.app.debug.Compiler;
import processing.app.debug.TargetBoard;
import processing.app.debug.TargetPackage;
import processing.app.debug.TargetPlatform;
import processing.app.debug.TargetPlatformException;
import processing.app.helpers.BasicUserNotifier;
import processing.app.helpers.CommandlineParser;
import processing.app.helpers.OSUtils;
import processing.app.helpers.PreferencesMap;
import processing.app.helpers.UserNotifier;
import processing.app.helpers.filefilters.OnlyDirs;
import processing.app.helpers.filefilters.OnlyFilesWithExtension;
import processing.app.legacy.PApplet;
import processing.app.packages.Library;
import processing.app.packages.LibraryList;
public class BaseNoGui {
/** Version string to be used for build */
public static final int REVISION = 10600;
/** Extended version string displayed on GUI */
static String VERSION_NAME = "1.6.0";
static File buildFolder;
// Current directory to use for relative paths specified on the
// commandline
static String currentDirectory = System.getProperty("user.dir");
private static DiscoveryManager discoveryManager = new DiscoveryManager();
// these are static because they're used by Sketch
static private File examplesFolder;
static private File toolsFolder;
// maps #included files to their library folder
public static Map<String, Library> importToLibraryTable;
// maps library name to their library folder
static private LibraryList libraries;
static private List<File> librariesFolders;
static UserNotifier notifier = new BasicUserNotifier();
static public Map<String, TargetPackage> packages;
static Platform platform;
static File portableFolder = null;
static final String portableSketchbookFolder = "sketchbook";
// Returns a File object for the given pathname. If the pathname
// is not absolute, it is interpreted relative to the current
// directory when starting the IDE (which is not the same as the
// current working directory!).
static public File absoluteFile(String path) {
if (path == null) return null;
File file = new File(path);
if (!file.isAbsolute()) {
file = new File(currentDirectory, path);
}
return file;
}
/**
* Get the number of lines in a file by counting the number of newline
* characters inside a String (and adding 1).
*/
static public int countLines(String what) {
int count = 1;
for (char c : what.toCharArray()) {
if (c == '\n') count++;
}
return count;
}
/**
* Get the path to the platform's temporary folder, by creating
* a temporary temporary file and getting its parent folder.
* <br/>
* Modified for revision 0094 to actually make the folder randomized
* to avoid conflicts in multi-user environments. (Bug 177)
*/
static public File createTempFolder(String name) {
try {
File folder = File.createTempFile(name, null);
//String tempPath = ignored.getParent();
//return new File(tempPath);
folder.delete();
folder.mkdirs();
return folder;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
static public String getAvrBasePath() {
String path = getHardwarePath() + File.separator + "tools" +
File.separator + "avr" + File.separator + "bin" + File.separator;
if (OSUtils.isLinux() && !(new File(path)).exists()) {
return ""; // use distribution provided avr tools if bundled tools missing
}
return path;
}
static public File getBuildFolder() {
if (buildFolder == null) {
String buildPath = PreferencesData.get("build.path");
if (buildPath != null) {
buildFolder = absoluteFile(buildPath);
if (!buildFolder.exists())
buildFolder.mkdirs();
} else {
//File folder = new File(getTempFolder(), "build");
//if (!folder.exists()) folder.mkdirs();
buildFolder = createTempFolder("build");
buildFolder.deleteOnExit();
}
}
return buildFolder;
}
static public PreferencesMap getBoardPreferences() {
TargetBoard board = getTargetBoard();
if (board == null)
return null;
String boardId = board.getId();
PreferencesMap prefs = new PreferencesMap(board.getPreferences());
String extendedName = prefs.get("name");
for (String menuId : board.getMenuIds()) {
if (!board.hasMenu(menuId))
continue;
// Get "custom_[MENU_ID]" preference (for example "custom_cpu")
String entry = PreferencesData.get("custom_" + menuId);
if (entry != null && entry.startsWith(boardId)) {
String selectionId = entry.substring(boardId.length() + 1);
prefs.putAll(board.getMenuPreferences(menuId, selectionId));
// Update the name with the extended configuration
extendedName += ", " + board.getMenuLabel(menuId, selectionId);
}
}
prefs.put("name", extendedName);
return prefs;
}
static public File getContentFile(String name) {
String path = System.getProperty("user.dir");
// Get a path to somewhere inside the .app folder
if (OSUtils.isMacOS()) {
// <key>javaroot</key>
// <string>$JAVAROOT</string>
String javaroot = System.getProperty("javaroot");
if (javaroot != null) {
path = javaroot;
}
}
File working = new File(path);
return new File(working, name);
}
static public TargetPlatform getCurrentTargetPlatformFromPackage(String pack) {
return getTargetPlatform(pack, PreferencesData.get("target_platform"));
}
static public File getDefaultSketchbookFolder() {
if (getPortableFolder() != null)
return new File(getPortableFolder(), getPortableSketchbookFolder());
File sketchbookFolder = null;
try {
sketchbookFolder = getPlatform().getDefaultSketchbookFolder();
} catch (Exception e) { }
return sketchbookFolder;
}
public static DiscoveryManager getDiscoveryManager() {
return discoveryManager;
}
static public File getExamplesFolder() {
return examplesFolder;
}
static public String getExamplesPath() {
return examplesFolder.getAbsolutePath();
}
static public File getHardwareFolder() {
// calculate on the fly because it's needed by Preferences.init() to find
// the boards.txt and programmers.txt preferences files (which happens
// before the other folders / paths get cached).
return getContentFile("hardware");
}
static public String getHardwarePath() {
return getHardwareFolder().getAbsolutePath();
}
static public LibraryList getLibraries() {
return libraries;
}
static public List<File> getLibrariesPath() {
return librariesFolders;
}
/**
* Return an InputStream for a file inside the Processing lib folder.
*/
static public InputStream getLibStream(String filename) throws IOException {
return new FileInputStream(new File(getContentFile("lib"), filename));
}
static public Platform getPlatform() {
return platform;
}
static public File getPortableFolder() {
return portableFolder;
}
static public String getPortableSketchbookFolder() {
return portableSketchbookFolder;
}
/**
* Convenience method to get a File object for the specified filename inside
* the settings folder.
* For now, only used by Preferences to get the preferences.txt file.
* @param filename A file inside the settings folder.
* @return filename wrapped as a File object inside the settings folder
*/
static public File getSettingsFile(String filename) {
return new File(getSettingsFolder(), filename);
}
static public File getSettingsFolder() {
if (getPortableFolder() != null)
return getPortableFolder();
File settingsFolder = null;
String preferencesPath = PreferencesData.get("settings.path");
if (preferencesPath != null) {
settingsFolder = absoluteFile(preferencesPath);
} else {
try {
settingsFolder = getPlatform().getSettingsFolder();
} catch (Exception e) {
showError(_("Problem getting data folder"),
_("Error getting the Arduino data folder."), e);
}
}
// create the folder if it doesn't exist already
if (!settingsFolder.exists()) {
if (!settingsFolder.mkdirs()) {
showError(_("Settings issues"),
_("Arduino cannot run because it could not\n" +
"create a folder to store your settings."), null);
}
}
return settingsFolder;
}
static public File getSketchbookFolder() {
if (portableFolder != null)
return new File(portableFolder, PreferencesData.get("sketchbook.path"));
return absoluteFile(PreferencesData.get("sketchbook.path"));
}
static public File getSketchbookHardwareFolder() {
return new File(getSketchbookFolder(), "hardware");
}
static public File getSketchbookLibrariesFolder() {
File libdir = new File(getSketchbookFolder(), "libraries");
if (!libdir.exists()) {
try {
libdir.mkdirs();
File readme = new File(libdir, "readme.txt");
FileWriter freadme = new FileWriter(readme);
freadme.write(_("For information on installing libraries, see: " +
"http://arduino.cc/en/Guide/Libraries\n"));
freadme.close();
} catch (Exception e) {
}
}
return libdir;
}
static public String getSketchbookPath() {
// Get the sketchbook path, and make sure it's set properly
String sketchbookPath = PreferencesData.get("sketchbook.path");
// If a value is at least set, first check to see if the folder exists.
// If it doesn't, warn the user that the sketchbook folder is being reset.
if (sketchbookPath != null) {
File sketchbookFolder;
if (getPortableFolder() != null)
sketchbookFolder = new File(getPortableFolder(), sketchbookPath);
else
sketchbookFolder = absoluteFile(sketchbookPath);
if (!sketchbookFolder.exists()) {
showWarning(_("Sketchbook folder disappeared"),
_("The sketchbook folder no longer exists.\n" +
"Arduino will switch to the default sketchbook\n" +
"location, and create a new sketchbook folder if\n" +
"necessary. Arduino will then stop talking about\n" +
"himself in the third person."), null);
sketchbookPath = null;
}
}
return sketchbookPath;
}
public static TargetBoard getTargetBoard() {
TargetPlatform targetPlatform = getTargetPlatform();
if (targetPlatform == null)
return null;
String boardId = PreferencesData.get("board");
return targetPlatform.getBoard(boardId);
}
/**
* Returns a specific TargetPackage
*
* @param packageName
* @return
*/
static public TargetPackage getTargetPackage(String packageName) {
return packages.get(packageName);
}
/**
* Returns the currently selected TargetPlatform.
*
* @return
*/
static public TargetPlatform getTargetPlatform() {
String packageName = PreferencesData.get("target_package");
String platformName = PreferencesData.get("target_platform");
return getTargetPlatform(packageName, platformName);
}
/**
* Returns a specific TargetPlatform searching Package/Platform
*
* @param packageName
* @param platformName
* @return
*/
static public TargetPlatform getTargetPlatform(String packageName,
String platformName) {
TargetPackage p = packages.get(packageName);
if (p == null)
return null;
return p.get(platformName);
}
static public File getToolsFolder() {
return toolsFolder;
}
static public String getToolsPath() {
return toolsFolder.getAbsolutePath();
}
static public LibraryList getUserLibs() {
if (libraries == null)
return new LibraryList();
return libraries.filterLibrariesInSubfolder(getSketchbookFolder());
}
/**
* Given a folder, return a list of the header files in that folder (but not
* the header files in its sub-folders, as those should be included from
* within the header files at the top-level).
*/
static public String[] headerListFromIncludePath(File path) throws IOException {
String[] list = path.list(new OnlyFilesWithExtension(".h"));
if (list == null) {
throw new IOException();
}
return list;
}
static public void init(String[] args) {
getPlatform().init();
String sketchbookPath = getSketchbookPath();
// If no path is set, get the default sketchbook folder for this platform
if (sketchbookPath == null) {
if (BaseNoGui.getPortableFolder() != null)
PreferencesData.set("sketchbook.path", getPortableSketchbookFolder());
else
showError(_("No sketchbook"), _("Sketchbook path not defined"), null);
}
BaseNoGui.initPackages();
// Setup board-dependent variables.
onBoardOrPortChange();
CommandlineParser parser = CommandlineParser.newCommandlineParser(args);
for (String path: parser.getFilenames()) {
// Correctly resolve relative paths
File file = absoluteFile(path);
// Fix a problem with systems that use a non-ASCII languages. Paths are
// being passed in with 8.3 syntax, which makes the sketch loader code
// unhappy, since the sketch folder naming doesn't match up correctly.
if (OSUtils.isWindows()) {
try {
file = file.getCanonicalFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if (!parser.isVerifyOrUploadMode() && !parser.isGetPrefMode())
showError(_("Mode not supported"), _("Only --verify, --upload or --get-pref are supported"), null);
if (!parser.isForceSavePrefs())
PreferencesData.setDoSave(false);
if (!file.exists()) {
String mess = I18n.format(_("Failed to open sketch: \"{0}\""), path);
// Open failure is fatal in upload/verify mode
showError(null, mess, 2);
}
}
// Save the preferences. For GUI mode, this happens in the quit
// handler, but for other modes we should also make sure to save
// them.
PreferencesData.save();
if (parser.isVerifyOrUploadMode()) {
// Set verbosity for command line build
PreferencesData.set("build.verbose", "" + parser.isDoVerboseBuild());
PreferencesData.set("upload.verbose", "" + parser.isDoVerboseUpload());
// Make sure these verbosity preferences are only for the
// current session
PreferencesData.setDoSave(false);
if (parser.isUploadMode()) {
if (parser.getFilenames().size() != 1)
{
showError(_("Multiple files not supported"), _("The --upload option supports only one file at a time"), null);
}
List<String> warningsAccumulator = new LinkedList<String>();
boolean success = false;
try {
// Editor constructor loads the sketch with handleOpenInternal() that
// creates a new Sketch that, in trun, calls load() inside its constructor
// This translates here as:
// SketchData data = new SketchData(file);
// File tempBuildFolder = getBuildFolder();
// data.load();
SketchData data = new SketchData(absoluteFile(parser.getFilenames().get(0)));
File tempBuildFolder = getBuildFolder();
data.load();
// Sketch.exportApplet()
// - calls Sketch.prepare() that calls Sketch.ensureExistence()
// - calls Sketch.build(verbose=false) that calls Sketch.ensureExistence(), set progressListener and calls Compiler.build()
// - calls Sketch.upload() (see later...)
if (!data.getFolder().exists()) showError(_("No sketch"), _("Can't find the sketch in the specified path"), null);
String suggestedClassName = Compiler.build(data, tempBuildFolder.getAbsolutePath(), tempBuildFolder, null, parser.isDoVerboseBuild());
if (suggestedClassName == null) showError(_("Error while verifying"), _("An error occurred while verifying the sketch"), null);
showMessage(_("Done compiling"), _("Done compiling"));
// - chiama Sketch.upload() ... to be continued ...
Uploader uploader = Compiler.getUploaderByPreferences(parser.isNoUploadPort());
if (uploader.requiresAuthorization() && !PreferencesData.has(uploader.getAuthorizationKey())) showError("...", "...", null);
try {
success = Compiler.upload(data, uploader, tempBuildFolder.getAbsolutePath(), suggestedClassName, parser.isDoUseProgrammer(), parser.isNoUploadPort(), warningsAccumulator);
showMessage(_("Done uploading"), _("Done uploading"));
} finally {
if (uploader.requiresAuthorization() && !success) {
PreferencesData.remove(uploader.getAuthorizationKey());
}
}
} catch (Exception e) {
showError(_("Error while verifying/uploading"), _("An error occurred while verifying/uploading the sketch"), e);
}
for (String warning : warningsAccumulator) {
System.out.print(_("Warning"));
System.out.print(": ");
System.out.println(warning);
}
if (!success) showError(_("Error while uploading"), _("An error occurred while uploading the sketch"), null);
} else {
for (String path : parser.getFilenames())
{
try {
// Editor constructor loads sketch with handleOpenInternal() that
// creates a new Sketch that calls load() in its constructor
// This translates here as:
// SketchData data = new SketchData(file);
// File tempBuildFolder = getBuildFolder();
// data.load();
SketchData data = new SketchData(absoluteFile(path));
File tempBuildFolder = getBuildFolder();
data.load();
// Sketch.prepare() calls Sketch.ensureExistence()
// Sketch.build(verbose) calls Sketch.ensureExistence() and set progressListener and, finally, calls Compiler.build()
// This translates here as:
// if (!data.getFolder().exists()) showError(...);
// String ... = Compiler.build(data, tempBuildFolder.getAbsolutePath(), tempBuildFolder, null, verbose);
if (!data.getFolder().exists()) showError(_("No sketch"), _("Can't find the sketch in the specified path"), null);
String suggestedClassName = Compiler.build(data, tempBuildFolder.getAbsolutePath(), tempBuildFolder, null, parser.isDoVerboseBuild());
if (suggestedClassName == null) showError(_("Error while verifying"), _("An error occurred while verifying the sketch"), null);
showMessage(_("Done compiling"), _("Done compiling"));
} catch (Exception e) {
showError(_("Error while verifying"), _("An error occurred while verifying the sketch"), e);
}
}
}
// No errors exit gracefully
System.exit(0);
}
else if (parser.isGetPrefMode()) {
String value = PreferencesData.get(parser.getGetPref(), null);
if (value != null) {
System.out.println(value);
System.exit(0);
} else {
System.exit(4);
}
}
}
static public void initLogger() {
System.setProperty(LogFactoryImpl.LOG_PROPERTY, NoOpLog.class.getCanonicalName());
Logger.getLogger("javax.jmdns").setLevel(Level.OFF);
}
static public void initPackages() {
packages = new HashMap<String, TargetPackage>();
loadHardware(getHardwareFolder());
loadHardware(getSketchbookHardwareFolder());
if (packages.size() == 0) {
System.out.println(_("No valid configured cores found! Exiting..."));
System.exit(3);
}
}
static protected void initPlatform() {
try {
Class<?> platformClass = Class.forName("processing.app.Platform");
if (OSUtils.isMacOS()) {
platformClass = Class.forName("processing.app.macosx.Platform");
} else if (OSUtils.isWindows()) {
platformClass = Class.forName("processing.app.windows.Platform");
} else if (OSUtils.isLinux()) {
platformClass = Class.forName("processing.app.linux.Platform");
}
platform = (Platform) platformClass.newInstance();
} catch (Exception e) {
showError(_("Problem Setting the Platform"),
_("An unknown error occurred while trying to load\n" +
"platform-specific code for your machine."), e);
}
}
static public void initPortableFolder() {
// Portable folder
portableFolder = getContentFile("portable");
if (!portableFolder.exists())
portableFolder = null;
}
static public void initVersion() {
// help 3rd party installers find the correct hardware path
PreferencesData.set("last.ide." + VERSION_NAME + ".hardwarepath", getHardwarePath());
PreferencesData.set("last.ide." + VERSION_NAME + ".daterun", "" + (new Date()).getTime() / 1000);
}
/**
* Return true if the name is valid for a Processing sketch.
*/
static public boolean isSanitaryName(String name) {
return sanitizeName(name).equals(name);
}
static protected void loadHardware(File folder) {
if (!folder.isDirectory()) return;
String list[] = folder.list(new OnlyDirs());
// if a bad folder or something like that, this might come back null
if (list == null) return;
// alphabetize list, since it's not always alpha order
// replaced hella slow bubble sort with this feller for 0093
Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
for (String target : list) {
// Skip reserved 'tools' folder.
if (target.equals("tools"))
continue;
File subfolder = new File(folder, target);
try {
packages.put(target, new TargetPackage(target, subfolder));
} catch (TargetPlatformException e) {
System.out.println("WARNING: Error loading hardware folder " + target);
System.out.println(" " + e.getMessage());
}
}
}
/**
* Grab the contents of a file as a string.
*/
static public String loadFile(File file) throws IOException {
String[] contents = PApplet.loadStrings(file);
if (contents == null) return null;
return PApplet.join(contents, "\n");
}
static public void main(String args[]) throws Exception {
if (args.length == 0)
showError(_("No parameters"), _("No command line parameters found"), null);
initPlatform();
initPortableFolder();
initParameters(args);
init(args);
}
static public void onBoardOrPortChange() {
examplesFolder = getContentFile("examples");
toolsFolder = getContentFile("tools");
librariesFolders = new ArrayList<File>();
librariesFolders.add(getContentFile("libraries"));
// Add library folder for the current selected platform
TargetPlatform targetPlatform = getTargetPlatform();
if (targetPlatform != null) {
String core = getBoardPreferences().get("build.core");
if (core.contains(":")) {
String referencedCore = core.split(":")[0];
TargetPlatform referencedPlatform = getTargetPlatform(referencedCore, targetPlatform.getId());
if (referencedPlatform != null) {
File referencedPlatformFolder = referencedPlatform.getFolder();
librariesFolders.add(new File(referencedPlatformFolder, "libraries"));
}
}
File platformFolder = targetPlatform.getFolder();
librariesFolders.add(new File(platformFolder, "libraries"));
librariesFolders.add(getSketchbookLibrariesFolder());
}
// Scan for libraries in each library folder.
// Libraries located in the latest folders on the list can override
// other libraries with the same name.
try {
scanAndUpdateLibraries(librariesFolders);
} catch (IOException e) {
showWarning(_("Error"), _("Error loading libraries"), e);
}
populateImportToLibraryTable();
}
static public void populateImportToLibraryTable() {
// Populate importToLibraryTable
importToLibraryTable = new HashMap<String, Library>();
for (Library lib : getLibraries()) {
try {
String headers[] = headerListFromIncludePath(lib.getSrcFolder());
for (String header : headers) {
Library old = importToLibraryTable.get(header);
if (old != null) {
// If a library was already found with this header, keep
// it if the library's name matches the header name.
String name = header.substring(0, header.length() - 2);
if (old.getFolder().getPath().endsWith(name))
continue;
}
importToLibraryTable.put(header, lib);
}
} catch (IOException e) {
showWarning(_("Error"), I18n
.format("Unable to list header files in {0}", lib.getSrcFolder()), e);
}
}
}
static public void initParameters(String args[]) {
String preferencesFile = null;
// Do a first pass over the commandline arguments, the rest of them
// will be processed by the Base constructor. Note that this loop
// does not look at the last element of args, to prevent crashing
// when no parameter was specified to an option. Later, Base() will
// then show an error for these.
for (int i = 0; i < args.length - 1; i++) {
if (args[i].equals("--preferences-file")) {
++i;
preferencesFile = args[i];
continue;
}
if (args[i].equals("--curdir")) {
i++;
currentDirectory = args[i];
continue;
}
}
// run static initialization that grabs all the prefs
PreferencesData.init(absoluteFile(preferencesFile));
}
/**
* Recursively remove all files within a directory,
* used with removeDir(), or when the contents of a dir
* should be removed, but not the directory itself.
* (i.e. when cleaning temp files from lib/build)
*/
static public void removeDescendants(File dir) {
if (!dir.exists()) return;
String files[] = dir.list();
for (int i = 0; i < files.length; i++) {
if (files[i].equals(".") || files[i].equals("..")) continue;
File dead = new File(dir, files[i]);
if (!dead.isDirectory()) {
if (!PreferencesData.getBoolean("compiler.save_build_files")) {
if (!dead.delete()) {
// temporarily disabled
System.err.println(I18n.format(_("Could not delete {0}"), dead));
}
}
} else {
removeDir(dead);
//dead.delete();
}
}
}
/**
* Remove all files in a directory and the directory itself.
*/
static public void removeDir(File dir) {
if (dir.exists()) {
removeDescendants(dir);
if (!dir.delete()) {
System.err.println(I18n.format(_("Could not delete {0}"), dir));
}
}
}
/**
* Produce a sanitized name that fits our standards for likely to work.
* <p/>
* Java classes have a wider range of names that are technically allowed
* (supposedly any Unicode name) than what we support. The reason for
* going more narrow is to avoid situations with text encodings and
* converting during the process of moving files between operating
* systems, i.e. uploading from a Windows machine to a Linux server,
* or reading a FAT32 partition in OS X and using a thumb drive.
* <p/>
* This helper function replaces everything but A-Z, a-z, and 0-9 with
* underscores. Also disallows starting the sketch name with a digit.
*/
static public String sanitizeName(String origName) {
char c[] = origName.toCharArray();
StringBuffer buffer = new StringBuffer();
// can't lead with a digit, so start with an underscore
if ((c[0] >= '0') && (c[0] <= '9')) {
buffer.append('_');
}
for (int i = 0; i < c.length; i++) {
if (((c[i] >= '0') && (c[i] <= '9')) ||
((c[i] >= 'a') && (c[i] <= 'z')) ||
((c[i] >= 'A') && (c[i] <= 'Z')) ||
((i > 0) && (c[i] == '-')) ||
((i > 0) && (c[i] == '.'))) {
buffer.append(c[i]);
} else {
buffer.append('_');
}
}
// let's not be ridiculous about the length of filenames.
// in fact, Mac OS 9 can handle 255 chars, though it can't really
// deal with filenames longer than 31 chars in the Finder.
// but limiting to that for sketches would mean setting the
// upper-bound on the character limit here to 25 characters
// (to handle the base name + ".class")
if (buffer.length() > 63) {
buffer.setLength(63);
}
return buffer.toString();
}
/**
* Spew the contents of a String object out to a file.
*/
static public void saveFile(String str, File file) throws IOException {
File temp = File.createTempFile(file.getName(), null, file.getParentFile());
PApplet.saveStrings(temp, new String[] { str });
if (file.exists()) {
boolean result = file.delete();
if (!result) {
throw new IOException(
I18n.format(
_("Could not remove old version of {0}"),
file.getAbsolutePath()));
}
}
boolean result = temp.renameTo(file);
if (!result) {
throw new IOException(
I18n.format(
_("Could not replace {0}"),
file.getAbsolutePath()));
}
}
static public void scanAndUpdateLibraries(List<File> folders) throws IOException {
libraries = scanLibraries(folders);
}
static public LibraryList scanLibraries(List<File> folders) throws IOException {
LibraryList res = new LibraryList();
for (File folder : folders)
res.addOrReplaceAll(scanLibraries(folder));
return res;
}
static public LibraryList scanLibraries(File folder) throws IOException {
LibraryList res = new LibraryList();
String list[] = folder.list(new OnlyDirs());
// if a bad folder or something like that, this might come back null
if (list == null)
return res;
for (String libName : list) {
File subfolder = new File(folder, libName);
if (!isSanitaryName(libName)) {
String mess = I18n.format(_("The library \"{0}\" cannot be used.\n"
+ "Library names must contain only basic letters and numbers.\n"
+ "(ASCII only and no spaces, and it cannot start with a number)"),
libName);
showMessage(_("Ignoring bad library name"), mess);
continue;
}
try {
Library lib = Library.create(subfolder);
// (also replace previously found libs with the same name)
if (lib != null)
res.addOrReplace(lib);
} catch (IOException e) {
System.out.println(I18n.format(_("Invalid library found in {0}: {1}"),
subfolder, e.getMessage()));
}
}
return res;
}
static public void selectBoard(TargetBoard targetBoard) {
TargetPlatform targetPlatform = targetBoard.getContainerPlatform();
TargetPackage targetPackage = targetPlatform.getContainerPackage();
PreferencesData.set("target_package", targetPackage.getId());
PreferencesData.set("target_platform", targetPlatform.getId());
PreferencesData.set("board", targetBoard.getId());
File platformFolder = targetPlatform.getFolder();
PreferencesData.set("runtime.platform.path", platformFolder.getAbsolutePath());
PreferencesData.set("runtime.hardware.path", platformFolder.getParentFile().getAbsolutePath());
}
public static void selectSerialPort(String port) {
PreferencesData.set("serial.port", port);
if (port.startsWith("/dev/"))
PreferencesData.set("serial.port.file", port.substring(5));
else
PreferencesData.set("serial.port.file", port);
}
public static void setBuildFolder(File newBuildFolder) {
buildFolder = newBuildFolder;
}
static public void showError(String title, String message, int exit_code) {
showError(title, message, null, exit_code);
}
static public void showError(String title, String message, Throwable e) {
notifier.showError(title, message, e, 1);
}
/**
* Show an error message that's actually fatal to the program.
* This is an error that can't be recovered. Use showWarning()
* for errors that allow P5 to continue running.
*/
static public void showError(String title, String message, Throwable e, int exit_code) {
notifier.showError(title, message, e, exit_code);
}
/**
* "No cookie for you" type messages. Nothing fatal or all that
* much of a bummer, but something to notify the user about.
*/
static public void showMessage(String title, String message) {
notifier.showMessage(title, message);
}
/**
* Non-fatal error message with optional stack trace side dish.
*/
static public void showWarning(String title, String message, Exception e) {
notifier.showWarning(title, message, e);
}
}
|
package org.koala.runnersFramework.runners.bot.listener;
import ibis.ipl.IbisProperties;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import org.koala.runnersFramework.runners.bot.BoTRunner;
import org.koala.runnersFramework.runners.bot.Executor;
import org.koala.runnersFramework.runners.bot.Schedule;
public class BatsServiceApiImpl implements BatsServiceApi {
private final String schedulesFolderString;
private final File schedulesFolder;
private final Object lock;
private final String logFile = "exceptions.log";
private static final Logger exceptionsLogger =
Logger.getAnonymousLogger();
private BoTRunner serviceBoT;
/**
* Cache object. Read by this class, updated inside the service.
*/
public static volatile State serviceState = new State(State.RUNNING);
/**
* Demo object.
*/
private DemoWrapper demo;
/**
* Boolean which determines if demo is on or off.
*/
public static long longestATU = 0;
public BatsServiceApiImpl() {
lock = new Object();
try {
Handler handler = new FileHandler(BoTRunner.path + File.separator + logFile);
handler.setFormatter(new SimpleFormatter());
exceptionsLogger.addHandler(handler);
exceptionsLogger.log(Level.INFO, "Service started\n");
} catch (Exception ex) {
Logger.getLogger(BatsServiceApiImpl.class.getName()).log(
Level.SEVERE, null, ex);
}
schedulesFolderString = BoTRunner.path + File.separator + "schedules";
schedulesFolder = new File(schedulesFolderString);
/*
* Create, if non-existing, the schedules dump folder
*/
schedulesFolder.mkdirs();
demo = new DemoWrapper();
serviceState.moneySpent = 0;
serviceState.moneySpentSampling = 0;
}
@Override
public MethodReport start_sampling(String filesLocationUrl, String inputFile) {
if (serviceState.mode.equals(State.MODE_DEMO)) {
return demo.start_sampling(inputFile);
}
try {
synchronized (lock) {
if (State.ADAPTING.equals(serviceState.state)) {
return new MethodReportError("Sampling failed! Service already running.");
}
serviceState.state = State.ADAPTING;
}
serviceBoT = new BoTRunner(5, 0, 60, 24, 400,
inputFile, ""); //clusterConfFile is set to default value.
BoTRunner.schedulesFile = schedulesFolderString + File.separator
+ System.currentTimeMillis();
// old code:
// BoTRunner.schedulesFile = schedulesFile;
BoTRunner.filesLocationUrl = filesLocationUrl;
Thread thread = new Thread() {
@Override
public void run() {
try {
serviceBoT.run();
} catch (Exception ex) {
exceptionsLogger.log(Level.SEVERE,
"Sampling failed because of:\n{0}\n",
ex.getLocalizedMessage());
}
synchronized (lock) {
serviceState.state = org.koala.runnersFramework.runners.bot.listener.State.RUNNING;
}
}
};
thread.setPriority(Thread.MAX_PRIORITY);
thread.start();
} catch (Exception ex) {
synchronized (lock) {
serviceState.state = State.RUNNING;
return new MethodReportError(ex.getLocalizedMessage());
}
}
return new MethodReportSuccess("Sampling started.");
}
private String create_json_schedules(List<SamplingResult> list)
{
String schedulesJson = "";
for (int i = 0; i < list.size(); i++) {
SamplingResult samplingResult = list.get(i);
schedulesJson += "{";
schedulesJson += "\"timestamp\": " + samplingResult.timestamp + ",";
schedulesJson += "\"schedules\": [";
for(int j = 0; j < samplingResult.schedules.size(); j++)
{
String sched = samplingResult.schedules.get(j);
StringTokenizer st = new StringTokenizer(sched, " \t");
st.nextToken(); // first one is budget and we don't care about that
int cost = (int)(Double.parseDouble(st.nextToken()));
int time = (int)(Double.parseDouble(st.nextToken()));
if(time > 1000)
{
// to prevent a bug in the optimization code when
// there are not enough schedule points
if(j == (samplingResult.schedules.size() - 1))
{
schedulesJson = schedulesJson.substring(0, schedulesJson.length() - 2);
schedulesJson += "}";
}
continue;
}
schedulesJson += "{";
schedulesJson += "\"cost\": " + cost + ",";
schedulesJson += "\"time\": " + time * longestATU ;
if(j == (samplingResult.schedules.size() - 1))
{
schedulesJson += "}";
}
else
{
schedulesJson += "},";
}
}
schedulesJson += "]";
if(i == (list.size() - 1))
{
schedulesJson += "}";
}
else
{
schedulesJson += "},";
}
}
return schedulesJson;
}
@Override
public Object get_sampling_results() {
List<SamplingResult> list = new ArrayList<SamplingResult>();
if (serviceState.mode.equals(State.MODE_DEMO)) {
list = (List<SamplingResult>)demo.get_sampling_result();
return create_json_schedules(list);
}
for (File file : schedulesFolder.listFiles()) {
if (file.length() <= 0) {
continue;
}
List<Schedule> schedules = null;
try {
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
// read the BoT, but no need to store it
ois.readObject();
schedules = (List<Schedule>) ois.readObject();
ois.close();
} catch (Exception ex) {
Logger.getLogger(BatsServiceApiImpl.class.getName()).log(Level.SEVERE, null, ex);
}
if (schedules == null) {
continue;
}
/**
* Return an array of schedules files names with their corresponding
* schedules. Element of the array format: [schedule time stamp]
* [sched0] [sched1] ...
*
* Schedule format: budget cost atus
*/
List<String> schedulesString = new ArrayList<String>(schedules.size());
for (int i = 0; i < schedules.size(); i++) {
schedulesString.add(schedules.get(i).toString());
}
list.add(new SamplingResult(file.getName(), schedulesString));
}
if (list.isEmpty()) {
// return new MethodReportError("No schedules files available.");
// Claudiu asked for this method not to return an error, but an empty non-error message.
return new MethodReportSuccess();
}
return create_json_schedules(list);
}
@Override
public State get_service_info() {
if (serviceState.mode.equals(State.MODE_DEMO)) {
return demo.get_service_info();
}
return serviceState;
}
@Override
public MethodReport start_execution(long schedulesFileTimeStamp, int scheduleNo) {
if (serviceState.mode.equals(State.MODE_DEMO)) {
return demo.start_execution(scheduleNo);
}
File schedFile = null;
try {
synchronized (lock) {
schedFile = getSchedulesFile(schedulesFileTimeStamp);
if (schedFile == null) {
return new MethodReportError("Execution failed! No schedules file present.");
}
if (State.ADAPTING.equals(serviceState.state)) {
return new MethodReportError("Execution failed! Service already running.");
}
serviceState.state = State.ADAPTING;
}
String[] args = {"" + scheduleNo, schedFile.getPath()};
final Executor execute = new Executor(args);
serviceBoT = execute.bot;
/*
* work-around such that the "Sampling&Execution-in-the-same-VM"
* works well
*/
Properties initialIbisProps = execute.bot.myIbisProps;
execute.bot.poolName = initialIbisProps.get(IbisProperties.POOL_NAME) + "-executionPhase";
execute.bot.myIbisProps.setProperty(IbisProperties.POOL_NAME,
execute.bot.poolName);
execute.bot.electionName = initialIbisProps.get("ibis.election.name") + "-executionPhase";
execute.bot.myIbisProps.setProperty("ibis.election.name",
execute.bot.electionName);
Thread thread = new Thread() {
@Override
public void run() {
try {
execute.go();
} catch (Exception ex) {
exceptionsLogger.log(Level.SEVERE,
"Execution failed because of:\n{0}\n", ex.getLocalizedMessage());
}
synchronized (lock) {
serviceState.state = org.koala.runnersFramework.runners.bot.listener.State.RUNNING;
}
}
};
thread.setPriority(Thread.MAX_PRIORITY);
thread.start();
} catch (Exception ex) {
synchronized (lock) {
serviceState.state = State.STOPPED;
return new MethodReportError(ex.getLocalizedMessage());
}
}
return new MethodReportSuccess("Ok.");
}
@Override
public MethodReport terminate_workers() {
if (serviceState.mode.equals(State.MODE_DEMO)) {
return demo.terminate_workers();
}
MethodReport retVal = new MethodReportSuccess();
int totalNoWorkersTerminated = 0;
try {
synchronized (lock) {
if (serviceBoT == null) {
serviceState.state = State.STOPPED;
retVal.append(totalNoWorkersTerminated + "\n");
retVal.append("Ok.");
return retVal;
}
}
System.out.println("terminating workers!");
totalNoWorkersTerminated = serviceBoT.terminate();
retVal.append(totalNoWorkersTerminated + "\n");
serviceState.state = State.STOPPED;
} catch (IOException ioe) {
return new MethodReportError(ioe.getLocalizedMessage());
}
retVal.append("Ok.");
return retVal;
}
private File getSchedulesFile(long schedulesFileTimeStamp) {
String schedulesFile = "" + schedulesFileTimeStamp;
File file = new File(schedulesFile);
if (file.exists()) {
return file;
}
schedulesFile = schedulesFolder + File.separator + schedulesFile;
file = new File(schedulesFile);
if (file.exists()) {
return file;
}
return null;
}
@Override
public MethodReport get_log() {
if (serviceState.mode.equals(State.MODE_DEMO)) {
return demo.get_log();
}
MethodReport retVal = new MethodReportSuccess();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(BoTRunner.path + "/" + logFile)));
String line;
while ((line = br.readLine()) != null) {
retVal.append(line + "\n");
}
br.close();
} catch (IOException ex) {
return new MethodReportError(ex.getLocalizedMessage());
}
return retVal;
}
@Override
public MethodReport set_service_mode(String mode) {
if(mode.equals(State.MODE_DEMO) || mode.equals(State.MODE_REAL))
{
serviceState.mode = mode;
}
else
{
return new MethodReportError("Invalid service mode");
}
return new MethodReportSuccess();
}
}
|
package org.wkh.swarmscale.optimization;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.DoubleStream;
public class ParticleSwarmOptimizer {
/* Standard constants derived by Maurice Clerc */
/**
* Inertia
*/
private static final double w = 0.729;
/**
* Personal best coefficient
*/
private static final double c1 = 1.494;
/**
* Global best coefficient
*/
private static final double c2 = 1.494;
/**
* Position
*/
private final double[][] x;
/**
* Velocity
*/
private final double[][] v;
/**
* Personal bests
*/
private final double[][] pbest;
/**
* Cached value of pbest fitness
*/
private final double[] pbestFitness;
/**
* Dimension bounds
*/
private final double[][] bounds;
/**
* Global best
*/
private double[] gbest;
/**
* Cached value of gbest fitness
*/
private double gbestFitness;
private final ObjectiveFunction objective;
private final int populationSize;
private final int dim;
private final Random rng;
private final List<EpochListener> epochListeners;
/**
*
* @param populationSize Number of individuals to create
* @param dim Dimension. Must match bounds and objective function.
* @param bounds upper and lower bounds in each dimension. Should be
* `dim` x 2 in size.
* @param objective Objective function. Needs to match bounds in the array
* elements it references.
*/
public ParticleSwarmOptimizer(
final int populationSize,
final int dim,
final double[][] bounds,
final ObjectiveFunction objective) {
if (bounds.length != dim) {
throw new IllegalArgumentException("Got bounds of length " + bounds.length + " != dim " + dim);
}
rng = new Random();
this.populationSize = populationSize;
this.objective = objective;
this.dim = dim;
this.bounds = bounds;
x = new double[populationSize][dim];
v = new double[populationSize][dim];
pbest = new double[populationSize][dim];
pbestFitness = new double[populationSize];
gbest = new double[dim];
epochListeners = new ArrayList<>();
}
public void addEpochListener(EpochListener listener) {
epochListeners.add(listener);
}
public void initializePopulation() {
for(int i = 0; i < populationSize; i++) {
for(int j = 0; j < dim; j++) {
final double lowerBound = bounds[j][0];
final double upperBound = bounds[j][1];
final double velocityRange = Math.abs(upperBound - lowerBound);
x[i][j] = randomDoubleInRange(lowerBound, upperBound);
pbest[i][j] = x[i][j];
v[i][j] = randomDoubleInRange(
-velocityRange,
velocityRange
);
}
/* arbitrarily initialize gbest to the first individual */
if (i == 0) {
gbest = x[0];
gbestFitness = objective.evaluate(gbest, 0);
}
pbestFitness[i] = objective.evaluate(x[i], 0);
if (pbestFitness[i] < gbestFitness) {
double[] individual = x[i];
gbest = Arrays.copyOf(individual, dim);
}
}
}
public List<EpochPerformanceResult> runForIterations(int iterations) {
final List<EpochPerformanceResult> results = new ArrayList<>(iterations);
for(int epoch = 1; epoch <= iterations; epoch++) {
final double[] fitnessValues = new double[populationSize];
for(int i = 0; i < populationSize; i++) {
for(int d = 0; d < dim; d++) {
final double r1 = rng.nextDouble();
final double r2 = rng.nextDouble();
v[i][d] = w*v[i][d] + c1*r1*(pbest[i][d] - x[i][d]) + c2*r2*(gbest[d] - x[i][d]);
x[i][d] = x[i][d] + v[i][d];
}
final double currentFitness = objective.evaluate(x[i], epoch);
fitnessValues[i] = currentFitness;
if (currentFitness < pbestFitness[i]) {
pbestFitness[i] = currentFitness;
pbest[i] = Arrays.copyOf(x[i], dim);
}
if (currentFitness < gbestFitness) {
gbestFitness = currentFitness;
gbest = Arrays.copyOf(x[i], dim);
}
}
final EpochPerformanceResult result = new EpochPerformanceResult(fitnessValues, gbest, gbestFitness);
final int epochDummy = epoch;
epochListeners.forEach(listener -> listener.onEpochComplete(result, epochDummy));
results.add(result);
}
return results;
}
private double randomDoubleInRange(double lowerBound, double upperBound) {
return rng.nextDouble()*(upperBound-lowerBound) + lowerBound;
}
public static void main(String[] args) {
final int populationSize = 500;
final double[][] bounds = {
{-5.12, 5.12},
{-5.12, 5.12},
{-5.12, 5.12},
{-5.12, 5.12},
{-5.12, 5.12},
{-5.12, 5.12},
{-5.12, 5.12},
{-5.12, 5.12},
{-5.12, 5.12},
{-5.12, 5.12},
{-5.12, 5.12},
{-5.12, 5.12},
};
/* simple 2D function with global minimum at (0, 0) */
ObjectiveFunction sphere2d = (x, iteration) -> x[0] * x[0] + x[1] * x[1];
final int dim = 12;
ObjectiveFunction rastrigin = (x, iteration) -> {
double sum = 0.0;
for(int i = 0; i < dim; i++) {
sum += x[i]*x[i] - 10*Math.cos(Math.PI*2*x[i]);
}
return 10*dim + sum;
};
ParticleSwarmOptimizer optimizer = new ParticleSwarmOptimizer(
populationSize,
dim,
bounds,
rastrigin
);
optimizer.initializePopulation();
/*
optimizer.addEpochListener((result, epoch) -> {
System.out.println("At epoch " + epoch + ":");
System.out.println("Best result: " + result.gbestFitness);
});
*/
final int iterations = 1000;
final List<EpochPerformanceResult> results = optimizer.runForIterations(iterations);
System.out.println("Best result: " + Arrays.toString(results.get(iterations-1).gbest));
System.out.println(results.get(iterations-1).gbestFitness);
}
}
|
package ru.evgeniyosipov.jbelly.service;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import ru.evgeniyosipov.jbelly.entity.User;
import ru.evgeniyosipov.jbelly.repository.UserRepository;
import java.util.Set;
import java.util.stream.Collectors;
@Service("blogUserDetailsService")
public class BlogUserDetailsService implements UserDetailsService {
private final UserRepository userRepository;
public BlogUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
User user = userRepository.findByEmail(email);
if (user == null) {
throw new UsernameNotFoundException("Invalid User");
} else {
Set<GrantedAuthority> grantedAuthorities = user.getRoles()
.stream()
.map(role -> new SimpleGrantedAuthority(role.getName()))
.collect(Collectors.toSet());
return new org
.springframework
.security
.core
.userdetails
.User(user.getEmail(), user.getPassword(), grantedAuthorities);
}
}
}
|
package sailpoint.services.plugin;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.log4j.Logger;
import sailpoint.rest.plugin.AllowAll;
import sailpoint.rest.plugin.BasePluginResource;
import sailpoint.tools.GeneralException;
@Path("saml-logout")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
@AllowAll
public class PasswordPronunciationService extends BasePluginResource {
public static String SQL_INSERT_QUERY = "INSERT INTO PASSWORD_PRONUNCIATION_MAPPING(KEY,VALUE) VALUES(?,?)";
public static String SQL_UPDATE_QUERY = "UPDATE PASSWORD_PRONUNCIATION_MAPPING SET KEY=?, VALUE=? WHERE ID=?";
public static String SQL_DELETE_QUERY = "DELETE FROM PASSWORD_PRONUNCIATION_MAPPING WHERE ID=?";
public static String SQL_SELECT_ALL_QUERY = "SELECT ID,KEY,VALUE FROM PASSWORD_PRONUNCIATION_MAPPING";
public static String SQL_SELECT_QUERY = "SELECT ID,KEY,VALUE FROM PASSWORD_PRONUNCIATION_MAPPING WHERE ID=?";
public static final Logger _logger = Logger.getLogger(PasswordPronunciationService.class);
@Override
public String getPluginName() {
return "password-pronunciation-plugin";
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("data")
public Response getAllData() {
if(_logger.isDebugEnabled()) {
_logger.debug(String.format("ENTERING method %s()", "getAllData"));
}
List<Map<String, Object>> result = null;
try {
result = readEntries();
} catch (GeneralException e) {
_logger.error(e.getMessage());
}
if(_logger.isDebugEnabled()) {
_logger.debug(String.format("LEAVING method %s (returns: %s)", "getData", result));
}
return Response.ok().entity(result).build();
}
/**
* @param id
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("data/{id}")
public void getData(@PathParam("id") int id) {
if(_logger.isDebugEnabled()) {
_logger.debug(String.format("ENTERING method %s(id = %s)", "getData", id));
}
if(_logger.isDebugEnabled()) {
_logger.debug(String.format("LEAVING method %s (returns: %s)", "getData", null));
}
}
/**
* @param id
* @param key
* @param value
* @return
*/
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("data")
public Response updateData(@FormParam("id") int id, @FormParam("key") String key, @FormParam("value") String value) {
if(_logger.isDebugEnabled()) {
_logger.debug(String.format("ENTERING method %s(id = %s, key = %s, value = %s)", "updateData", id, key, value));
}
int result = 0;
Response response = null;
try {
result = updateEntry(id, key, value);
} catch (GeneralException e) {
_logger.error(e.getMessage());
}
if(result >= 1) {
response = Response.ok().build();
} else {
response = Response.status(Status.BAD_REQUEST).build();
}
if(_logger.isDebugEnabled()) {
_logger.debug(String.format("LEAVING method %s (returns: %s)", "updateData", response));
}
return response;
}
/**
* @param id
* @param key
* @param value
* @return
*/
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@Path("data")
public Response createData(@FormParam("key") String key, @FormParam("value") String value) {
if(_logger.isDebugEnabled()) {
_logger.debug(String.format("ENTERING method %s(key = %s, value = %s)", "createData", key, value));
}
Response response = null;
Boolean result = false;
try {
result = createEntry(key, value);
} catch (GeneralException e) {
_logger.error(e.getMessage());
}
if(result) {
response = Response.ok().build();
} else {
response = Response.status(Status.INTERNAL_SERVER_ERROR).build();
}
if(_logger.isDebugEnabled()) {
_logger.debug(String.format("LEAVING method %s (returns: %s)", "createData", result));
}
return response;
}
/**
* @param file
* @return
*/
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@Path("uploadData")
public String uploadData(@FormParam("file") File file) {
if(_logger.isDebugEnabled()) {
_logger.debug(String.format("ENTERING method %s()", "uploadData"));
}
String result = null;
if(_logger.isDebugEnabled()) {
_logger.debug(String.format("LEAVING method %s (returns: %s)", "uploadData", result));
}
return result;
}
/**
* @param id
* @return
*/
@DELETE
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@Path("data/{id}")
public Response deleteData(@PathParam("id") int id) {
if(_logger.isDebugEnabled()) {
_logger.debug(String.format("ENTERING method %s()", "deleteData"));
}
Response response = null;
Boolean result = false;
try {
result = deleteEntry(id);
} catch (GeneralException e) {
_logger.error(e.getMessage());
}
if(result) {
response = Response.ok().build();
}else {
response = Response.status(Status.NOT_FOUND).build();
}
if(_logger.isDebugEnabled()) {
_logger.debug(String.format("LEAVING method %s (returns: %s)", "deleteData", response));
}
return response;
}
/**
* @param key
* @param value
* @return
* @throws GeneralException
* @throws SQLException
*/
private Boolean createEntry(String key, String value) throws GeneralException {
if(_logger.isDebugEnabled()) {
_logger.debug(String.format("ENTERING method %s(key = %s, value = %s)", "createEntry", key, value));
}
boolean success = false;
Connection connection = getConnection();
PreparedStatement prepStatement = null;
try {
prepStatement = connection.prepareStatement(SQL_INSERT_QUERY);
prepStatement.setString(1, key);
prepStatement.setString(2, value);
success = prepStatement.execute();
} catch (SQLException e) {
_logger.error(e.getMessage());
} finally {
if(prepStatement != null) {
try {
prepStatement.close();
} catch (SQLException e) {
_logger.error(e.getMessage());
}
}
if(connection != null) {
try {
connection.close();
} catch (SQLException e) {
_logger.error(e.getMessage());
}
}
}
if(_logger.isDebugEnabled()) {
_logger.debug(String.format("LEAVING method %s (returns: %s)", "createEntry", success));
}
return success;
}
/**
* @return
* @throws GeneralException
* @throws SQLException
*/
private List<Map<String, Object>> readEntries() throws GeneralException {
if(_logger.isDebugEnabled()) {
_logger.debug(String.format("ENTERING method %s()", "readEntries"));
}
List<Map<String, Object>> result = new ArrayList<>();
Connection connection = getConnection();
PreparedStatement prepStatement = null;
try {
prepStatement = connection.prepareStatement(SQL_SELECT_ALL_QUERY);
ResultSet rs = prepStatement.executeQuery();
if(rs.next()) {
Map<String, Object> resultObj = new HashMap<>();
resultObj.put("id", rs.getInt(1));
resultObj.put("key", rs.getString(2));
resultObj.put("value", rs.getString(3));
result.add(resultObj);
}
} catch (SQLException e) {
_logger.error(e.getMessage());
} finally {
if(prepStatement != null) {
try {
prepStatement.close();
} catch (SQLException e) {
_logger.error(e.getMessage());
}
}
if(connection != null) {
try {
connection.close();
} catch (SQLException e) {
_logger.error(e.getMessage());
}
}
}
if(_logger.isDebugEnabled()) {
_logger.debug(String.format("LEAVING method %s (returns: %s)", "readEntries", result));
}
return result;
}
@SuppressWarnings("unused")
private Map<String, Object> readEntry(int id) throws GeneralException {
if(_logger.isDebugEnabled()) {
_logger.debug(String.format("ENTERING method %s(id = %s)", "readEntry", id));
}
Map<String, Object> result = new HashMap<>();
Connection connection = getConnection();
PreparedStatement prepStatement = null;
try {
prepStatement = connection.prepareStatement(SQL_SELECT_QUERY);
prepStatement.setInt(1, id);
ResultSet rs = prepStatement.executeQuery();
if(rs.next()) {
result.put("id", rs.getInt(1));
result.put("key", rs.getString(2));
result.put("value", rs.getString(3));
}
} catch (SQLException e) {
_logger.error(e.getMessage());
} finally {
if(prepStatement != null) {
try {
prepStatement.close();
} catch (SQLException e) {
_logger.error(e.getMessage());
}
}
if(connection != null) {
try {
connection.close();
} catch (SQLException e) {
_logger.error(e.getMessage());
}
}
}
if(_logger.isDebugEnabled()) {
_logger.debug(String.format("LEAVING method %s (returns: %s)", "readEntry", result));
}
return result;
}
/**
* @param id
* @param key
* @param value
* @return
* @throws GeneralException
* @throws SQLException
*/
private int updateEntry(int id, String key, String value) throws GeneralException {
if(_logger.isDebugEnabled()) {
_logger.debug(String.format("ENTERING method %s(id = %s, key = %s, value = %s)", "updateEntry", id, key, value));
}
int updatedEntries = 0;
Connection connection = getConnection();
PreparedStatement prepStatement = null;
try {
prepStatement = connection.prepareStatement(SQL_UPDATE_QUERY);
prepStatement.setString(1, key);
prepStatement.setString(2, value);
prepStatement.setInt(3, id);
updatedEntries = prepStatement.executeUpdate();
} catch (SQLException e) {
_logger.error(e.getMessage());
} finally {
if(prepStatement != null) {
try {
prepStatement.close();
} catch (SQLException e) {
_logger.error(e.getMessage());
}
}
if(connection != null) {
try {
connection.close();
} catch (SQLException e) {
_logger.error(e.getMessage());
}
}
}
if(_logger.isDebugEnabled()) {
_logger.debug(String.format("LEAVING method %s (returns: %s)", "updateEntry", updatedEntries));
}
return updatedEntries;
}
/**
* @param id
* @return
* @throws GeneralException
* @throws SQLException
*/
private Boolean deleteEntry(int id) throws GeneralException {
if(_logger.isDebugEnabled()) {
_logger.debug(String.format("ENTERING method %s(id = %s)", "deleteEntry", id));
}
Boolean success = false;
Connection connection = getConnection();
PreparedStatement prepStatement = null;
try {
prepStatement = connection.prepareStatement(SQL_DELETE_QUERY);
prepStatement.setInt(1, id);
success = prepStatement.execute();
} catch (SQLException e) {
_logger.error(e.getMessage());
} finally {
if(prepStatement != null) {
try {
prepStatement.close();
} catch (SQLException e) {
_logger.error(e.getMessage());
}
}
if(connection != null) {
try {
connection.close();
} catch (SQLException e) {
_logger.error(e.getMessage());
}
}
}
if(_logger.isDebugEnabled()) {
_logger.debug(String.format("LEAVING method %s (returns: %s)", "deleteEntry", success));
}
return success;
}
}
|
package es.um.nosql.schemainference.json2dbschema.process.util;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.apache.commons.lang3.tuple.Pair;
/**
* @author dsevilla
*
*/
public class ReferenceMatcher<T>
{
// List of affixes to check for references
private static List<String> Affixes =
Arrays.asList("id", "ptr", "ref", "ids", "refs", "has", "");
private static List<String> StopChars =
Arrays.asList("_", ".", "-", "");
// Unlikely words to appear in a reference
private static List<String> UnlikelyWords = Arrays.asList("count");
private List<Pair<String,T>> idRegexps;
public ReferenceMatcher(Stream<Pair<String, T>> stream)
{
// Build the regexp that will allow checking if a field may be a reference
// to another entity
idRegexps = stream.flatMap(entry ->
Affixes.stream().flatMap(affix ->
Stream.concat(
// prefix
StopChars.stream().map(c ->
Pair.of(("^" + entry.getKey() + c + affix + ".*$").toLowerCase(), entry.getValue())),
Stream.concat(StopChars.stream().map(c ->
Pair.of(("^" + affix + c + entry.getKey() + ".*$").toLowerCase(), entry.getValue())),
// postfix
Stream.concat(StopChars.stream().filter(c -> !c.isEmpty() || !affix.isEmpty()).map(c ->
Pair.of(("^" + entry.getKey() + c + affix + ".*$").toLowerCase(), entry.getValue())),
StopChars.stream().filter(c -> !c.isEmpty() || !affix.isEmpty()).map(c ->
Pair.of(("^.*?" + affix + c + entry.getKey() + "$").toLowerCase(), entry.getValue()))))
)
)
).collect(Collectors.toList());
}
public Optional<T> maybeMatch(String id)
{
if (UnlikelyWords.stream().anyMatch(w -> id.toLowerCase().contains(w)))
return Optional.<T>empty();
return idRegexps.stream()
.filter(pair -> id.toLowerCase().matches(pair.getKey())).findFirst()
.map(Pair::getValue);
}
}
|
package org.kuali.rice.kew.impl.peopleflow;
import org.apache.commons.collections.CollectionUtils;
import org.kuali.rice.core.api.config.ConfigurationException;
import org.kuali.rice.kew.actionrequest.ActionRequestFactory;
import org.kuali.rice.kew.actionrequest.ActionRequestValue;
import org.kuali.rice.kew.actionrequest.KimGroupRecipient;
import org.kuali.rice.kew.actionrequest.KimPrincipalRecipient;
import org.kuali.rice.kew.actionrequest.Recipient;
import org.kuali.rice.kew.api.action.ActionRequestType;
import org.kuali.rice.kew.api.peopleflow.MemberType;
import org.kuali.rice.kew.api.peopleflow.PeopleFlowDefinition;
import org.kuali.rice.kew.api.peopleflow.PeopleFlowDelegate;
import org.kuali.rice.kew.api.peopleflow.PeopleFlowMember;
import org.kuali.rice.kew.engine.RouteContext;
import java.util.List;
public class PeopleFlowRequestGeneratorImpl implements PeopleFlowRequestGenerator {
@Override
public List<ActionRequestValue> generateRequests(RouteContext routeContext, PeopleFlowDefinition peopleFlow, ActionRequestType actionRequested) {
if (peopleFlow == null) {
throw new IllegalArgumentException("peopleFlow was null");
}
if (!peopleFlow.isActive()) {
throw new ConfigurationException("Attempted to route to a PeopleFlow that is not active! " + peopleFlow);
}
if (actionRequested == null) {
actionRequested = ActionRequestType.APPROVE;
}
ActionRequestFactory factory = new ActionRequestFactory(routeContext);
for (PeopleFlowMember member : peopleFlow.getMembers()) {
generateRequestForMember(factory, member.getResponsibilityId(), member, actionRequested);
}
return factory.getRequestGraphs();
}
protected void generateRequestForMember(ActionRequestFactory factory, String responsibilityId, PeopleFlowMember member, ActionRequestType actionRequested) {
// TODO - description, ruleId, annotation, request label
// defaulting all of these at the moment as per below
String actionRequestPolicyCode = null;
if (member.getActionRequestPolicy() != null) {
member.getActionRequestPolicy().getCode();
}
ActionRequestValue actionRequest = factory.addRootActionRequest(actionRequested.getCode(), member.getPriority(), toRecipient(member), "", responsibilityId, Boolean.TRUE, actionRequestPolicyCode, null);
if (CollectionUtils.isNotEmpty(member.getDelegates())) {
for (PeopleFlowDelegate delegate : member.getDelegates()) {
factory.addDelegationRequest(actionRequest, toRecipient(delegate), delegate.getResponsibilityId(), Boolean.TRUE, delegate.getDelegationType().getCode(), "", null);
}
}
}
private Recipient toRecipient(PeopleFlowMember member) {
Recipient recipient;
if (MemberType.PRINCIPAL == member.getMemberType()) {
recipient = new KimPrincipalRecipient(member.getMemberId());
} else if (MemberType.GROUP == member.getMemberType()) {
recipient = new KimGroupRecipient(member.getMemberId());
} else {
// TODO - what about roles!
throw new UnsupportedOperationException("implement me!!!");
}
return recipient;
}
private Recipient toRecipient(PeopleFlowDelegate delegate) {
Recipient recipient;
if (MemberType.PRINCIPAL == delegate.getMemberType()) {
recipient = new KimPrincipalRecipient(delegate.getMemberId());
} else if (MemberType.GROUP == delegate.getMemberType()) {
recipient = new KimGroupRecipient(delegate.getMemberId());
} else {
// TODO - what about roles!
throw new UnsupportedOperationException("implement me!!!");
}
return recipient;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.