answer
stringlengths 17
10.2M
|
|---|
import com.licel.jcardsim.base.Simulator;
import org.cryptonit.CryptonitApplet;
import javacard.framework.AID;
import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;
class test {
private static String toHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
if((i != 0) && ((i % 32) == 0)) {
sb.append("\n");
}
sb.append(String.format("%02X ", bytes[i]));
}
return sb.toString();
}
public static void main(String[] args) {
Simulator simulator = new Simulator();
byte[] appletAIDBytes = new byte[]{
(byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x03,
(byte) 0x08, (byte) 0x00, (byte) 0x00, (byte) 0x10,
(byte) 0x00
};
AID appletAID = new AID(appletAIDBytes, (short) 0, (byte) appletAIDBytes.length);
simulator.installApplet(appletAID, CryptonitApplet.class);
simulator.selectApplet(appletAID);
System.out.println("Select Applet");
ResponseAPDU response = new ResponseAPDU(simulator.transmitCommand((new CommandAPDU(0x00, 0xA4, 0x04, 0x00)).getBytes()));
System.out.println(response.toString());
System.out.println(toHex(response.getData()));
System.out.println("Verify PIN");
response = new ResponseAPDU(simulator.transmitCommand((new CommandAPDU(0x00, 0x20, 0x00, 0x80, new byte []{
0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38
})).getBytes()));
System.out.println(response.toString());
System.out.println(toHex(response.getData()));
System.out.println("Generate P-256 EC key (9D)");
response = new ResponseAPDU(simulator.transmitCommand((new CommandAPDU(0x00, 0x47, 0x00, 0x9D, new byte[]{
(byte) 0xAC, (byte) 0x03, (byte) 0x80, (byte) 0x01, (byte) 0x11
})).getBytes()));
System.out.println(response.toString());
System.out.println(toHex(response.getData()));
System.out.println("Generate 2048 bit RSA key (9A)");
response = new ResponseAPDU(simulator.transmitCommand((new CommandAPDU(0x00, 0x47, 0x00, 0x9A, new byte []{
(byte) 0xAC, (byte) 0x03, (byte) 0x80, (byte) 0x01, (byte) 0x07
}, 0x200)).getBytes()));
System.out.println(response.toString());
System.out.println(toHex(response.getData()));
System.out.println("Read 0x5FC105 file");
response = new ResponseAPDU(simulator.transmitCommand((new CommandAPDU(0x00, 0xCB, 0x3F, 0xFF, new byte []{
(byte) 0x5C, (byte) 0x03, (byte) 0x5F, (byte) 0xC1, (byte) 0x05
})).getBytes()));
System.out.println(response.toString());
}
}
|
// publication of such source code.
package com.ettrema.ftp;
import com.bradmcevoy.common.Path;
import com.bradmcevoy.http.CollectionResource;
import com.bradmcevoy.http.Resource;
import com.bradmcevoy.http.ResourceFactory;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.FileSystemFactory;
import org.apache.ftpserver.ftplet.FileSystemView;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.User;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.impl.DefaultFtpHandler;
import org.apache.ftpserver.listener.ListenerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author u370681
*/
public class MiltonFtpAdapter implements FileSystemFactory {
private static final Logger log = LoggerFactory.getLogger( MiltonFtpAdapter.class );
private final ResourceFactory resourceFactory;
private final FtpServer server;
/**
* Just sets dependencies. Does NOT start the server
*
* @param resourceFactory
* @param server
*/
public MiltonFtpAdapter( ResourceFactory resourceFactory, FtpServer server ) {
this.resourceFactory = resourceFactory;
this.server = server;
}
public MiltonFtpAdapter( ResourceFactory wrapped, UserManager userManager ) throws FtpException {
this( wrapped, userManager, null );
}
/**
* Creates and starts the FTP server on port 21
*
* @param wrapped
* @param userManager
* @param actionListener
* @throws FtpException
*/
public MiltonFtpAdapter( ResourceFactory wrapped, UserManager userManager, FtpActionListener actionListener ) throws FtpException {
this( wrapped, userManager, actionListener, 21, true );
}
/**
* Creates and starts the FTP server on the given port
*
* @param wrapped
* @param userManager
* @param port
* @throws FtpException
*/
public MiltonFtpAdapter( ResourceFactory wrapped, UserManager userManager, int port ) throws FtpException {
this( wrapped, userManager, null, port, true );
}
/**
* Creates and optionally starts the server
*
* @param wrapped
* @param userManager
* @param actionListener
* @param port
* @param autoStart - whether or not to start the server
* @throws FtpException
*/
public MiltonFtpAdapter( ResourceFactory wrapped, UserManager userManager, FtpActionListener actionListener, int port, boolean autoStart ) throws FtpException {
log.debug( "creating MiltonFtpAdapter.2" );
this.resourceFactory = wrapped;
FtpServerFactory serverFactory = new FtpServerFactory();
ListenerFactory factory;
if( actionListener != null ) {
log.debug( "using customised milton listener factory" );
MiltonFtpHandler ftpHandler = new MiltonFtpHandler( new DefaultFtpHandler(), actionListener );
factory = new MiltonListenerFactory( ftpHandler );
} else {
factory = new ListenerFactory();
}
factory.setPort( port );
serverFactory.addListener( "default", factory.createListener() );
// VERY IMPORTANT
serverFactory.setFileSystem( this );
serverFactory.setUserManager( userManager );
server = serverFactory.createServer();
if( autoStart ) {
log.debug( "starting the FTP server on port: " + port );
server.start();
}
}
public Resource getResource( Path path, String host ) {
return resourceFactory.getResource( host, path.toString() );
}
public FileSystemView createFileSystemView( User user ) throws FtpException {
MiltonUser mu = (MiltonUser) user;
Resource root = resourceFactory.getResource( mu.domain, "/" );
return new MiltonFsView( Path.root, (CollectionResource) root, resourceFactory, (MiltonUser) user );
}
}
|
package io.spine.code.proto;
import com.google.protobuf.Descriptors.Descriptor;
import io.spine.net.Uri;
import io.spine.net.Url;
import io.spine.test.code.proto.rejections.TestRejections;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.util.function.Function;
import static org.junit.jupiter.api.Assertions.assertTrue;
@DisplayName("MessageType should")
class MessageTypeTest {
@Nested
@DisplayName("Tell if message is")
class Tell {
@DisplayName("nested")
@Test
void nested() {
assertQuality(Uri.Protocol.getDescriptor(), MessageType::isNested);
}
@DisplayName("top-level")
@Test
void topLevel() {
assertQuality(Url.getDescriptor(), MessageType::isTopLevel);
}
void assertQuality(Descriptor descriptor, Function<MessageType, Boolean> method) {
MessageType type = MessageType.of(descriptor);
boolean result = method.apply(type);
assertTrue(result);
}
@DisplayName("a rejection")
@Test
void rejection() {
MessageType type = MessageType.of(TestRejections.MttSampleRejection.getDescriptor());
assertTrue(type.isRejection());
}
}
}
|
package org.basex.query.value.map;
import static org.basex.query.QueryText.*;
import static org.basex.query.util.Err.*;
import java.util.*;
import org.basex.query.*;
import org.basex.query.expr.*;
import org.basex.query.iter.*;
import org.basex.query.util.*;
import org.basex.query.util.collation.*;
import org.basex.query.value.*;
import org.basex.query.value.array.Array;
import org.basex.query.value.item.*;
import org.basex.query.value.node.*;
import org.basex.query.value.seq.*;
import org.basex.query.value.type.*;
import org.basex.query.var.*;
import org.basex.util.*;
public final class Map extends FItem {
/** The empty map. */
public static final Map EMPTY = new Map(TrieNode.EMPTY, 0);
/** Number of bits per level, maximum is 5 because {@code 1 << 5 == 32}. */
static final int BITS = 5;
/** Wrapped immutable map. */
private final TrieNode root;
/** Key sequence. */
private Value keys;
/** Date/time entries (negative: without timezone). */
private final int dt;
/**
* Constructor.
* @param root map
* @param dt number of date/time entries (negative: without timezone)
*/
private Map(final TrieNode root, final int dt) {
super(SeqType.ANY_MAP, new Ann());
this.root = root;
this.dt = dt;
}
@Override
public int arity() {
return 1;
}
@Override
public QNm funcName() {
return null;
}
@Override
public QNm argName(final int pos) {
return new QNm("key", "");
}
@Override
public FuncType funcType() {
return MapType.get(AtomType.AAT, SeqType.ITEM_ZM);
}
@Override
public int stackFrameSize() {
return 0;
}
@Override
public Item invItem(final QueryContext qc, final InputInfo ii, final Value... args)
throws QueryException {
return invValue(qc, ii, args).item(qc, ii);
}
@Override
public Value invValue(final QueryContext qc, final InputInfo ii, final Value... args)
throws QueryException {
final Item key = args[0].item(qc, ii);
if(key == null) throw EMPTYFOUND.get(ii);
return get(key, ii);
}
/**
* Deletes a key from this map.
* @param key key to delete (must not be {@code null})
* @param ii input info
* @return updated map if changed, {@code this} otherwise
* @throws QueryException query exception
*/
public Map delete(final Item key, final InputInfo ii) throws QueryException {
final TrieNode del = root.delete(key.hash(ii), key, 0, ii);
if(del == root) return this;
if(del == null) return EMPTY;
// update date counter
int t = dt;
if(key instanceof ADate) {
final boolean tz = ((ADate) key).zon() != Short.MAX_VALUE;
t += tz ? -1 : +1;
}
return new Map(del, t);
}
/**
* Gets the value from this map.
* @param key key to look for (must not be {@code null})
* @param ii input info
* @return bound value if found, the empty sequence {@code ()} otherwise
* @throws QueryException query exception
*/
public Value get(final Item key, final InputInfo ii) throws QueryException {
final Value v = root.get(key.hash(ii), key, 0, ii);
return v == null ? Empty.SEQ : v;
}
/**
* Checks if the given key exists in the map.
* @param key key to look for (must not be {@code null})
* @param ii input info
* @return {@code true()}, if the key exists, {@code false()} otherwise
* @throws QueryException query exception
*/
public boolean contains(final Item key, final InputInfo ii) throws QueryException {
return root.contains(key.hash(ii), key, 0, ii);
}
/**
* Adds all bindings from the given map into {@code this}.
* @param map map to add
* @param ii input info
* @return updated map if changed, {@code this} otherwise
* @throws QueryException query exception
*/
public Map addAll(final Map map, final InputInfo ii) throws QueryException {
if(map == EMPTY) return this;
final TrieNode upd = root.addAll(map.root, 0, ii);
if(upd == map.root) return map;
if(map.dt != 0 && dt != 0 && (map.dt > 0 ? dt < 0 : dt > 0)) throw MAPTZ.get(ii);
return new Map(upd, map.dt + dt);
}
/**
* Checks if the map has the given type.
* @param mt type
* @return {@code true} if the type fits, {@code false} otherwise
*/
public boolean hasType(final MapType mt) {
return root.hasType(mt.keyType == AtomType.AAT ? null : mt.keyType,
mt.retType.eq(SeqType.ITEM_ZM) ? null : mt.retType);
}
@Override
public Map coerceTo(final FuncType ft, final QueryContext qc, final InputInfo ii,
final boolean opt) throws QueryException {
if(!(ft instanceof MapType) || !hasType((MapType) ft)) throw castError(ii, this, ft);
return this;
}
/**
* Inserts the given value into this map.
* @param key key to insert (must not be {@code null})
* @param value value to insert
* @param ii input info
* @return updated map if changed, {@code this} otherwise
* @throws QueryException query exception
*/
public Map insert(final Item key, final Value value, final InputInfo ii) throws QueryException {
final TrieNode ins = root.insert(key.hash(ii), key, value, 0, ii);
// update date counter
int t = dt;
if(key instanceof ADate) {
final boolean tz = ((ADate) key).zon() != Short.MAX_VALUE;
if(tz ? t < 0 : t > 0) throw MAPTZ.get(ii);
t += tz ? 1 : -1;
}
return ins == root ? this : new Map(ins, t);
}
/**
* Number of values contained in this map.
* @return size
*/
public int mapSize() {
return root.size;
}
/**
* All keys defined in this map.
* @return list of keys
*/
public Value keys() {
if(keys == null) {
final ValueBuilder res = new ValueBuilder(root.size);
root.keys(res);
keys = res.value();
}
return keys;
}
/**
* All values defined in this map.
* @return list of keys
*/
public ValueBuilder values() {
final ValueBuilder res = new ValueBuilder(root.size);
root.values(res);
return res;
}
/**
* Applies a function on all entries.
* @param func function to apply on keys and values
* @param qc query context
* @param ii input info
* @return resulting value
* @throws QueryException query exception
*/
public ValueBuilder apply(final FItem func, final QueryContext qc, final InputInfo ii)
throws QueryException {
final ValueBuilder vb = new ValueBuilder(root.size);
root.apply(vb, func, qc, ii);
return vb;
}
@Override
public boolean deep(final Item item, final InputInfo ii, final Collation coll)
throws QueryException {
if(item instanceof Map) return root.deep(ii, ((Map) item).root, coll);
return item instanceof FItem && !(item instanceof Array) && super.deep(item, ii, coll);
}
/**
* Returns a string representation of the map.
* @param ii input info
* @return string
* @throws QueryException query exception
*/
public byte[] serialize(final InputInfo ii) throws QueryException {
final TokenBuilder tb = new TokenBuilder();
string(tb, 0, ii);
return tb.finish();
}
@Override
public HashMap<Object, Object> toJava() throws QueryException {
final HashMap<Object, Object> map = new HashMap<>();
final ValueIter vi = keys().iter();
for(Item k; (k = vi.next()) != null;) {
map.put(k.toJava(), get(k, null).toJava());
}
return map;
}
@Override
public int hash(final InputInfo ii) throws QueryException {
return root.hash(ii);
}
@Override
public String description() {
return CURLY1 + DOTS + CURLY2;
}
@Override
public void plan(final FElem plan) {
final int s = mapSize();
final FElem el = planElem(SIZE, s);
final Value ks = keys();
try {
final int max = Math.min(s, 5);
for(long i = 0; i < max; i++) {
final Item key = ks.itemAt(i);
final Value val = get(key, null);
key.plan(el);
val.plan(el);
}
} catch(final QueryException ex) {
throw Util.notExpected(ex);
}
addPlan(plan, el);
}
/**
* Returns a string representation of the map.
* @param tb token builder
* @param level current level
* @param ii input info
* @throws QueryException query exception
*/
public void string(final TokenBuilder tb, final int level, final InputInfo ii)
throws QueryException {
tb.add("{");
int c = 0;
for(final Item key : keys()) {
if(c++ > 0) tb.add(',');
tb.add('\n');
indent(tb, level + 1);
tb.add(key.toString());
tb.add(": ");
final Value v = get(key, ii);
if(v.size() != 1) tb.add('(');
int cc = 0;
for(final Item it : v) {
if(cc++ > 0) tb.add(", ");
if(it instanceof Map) ((Map) it).string(tb, level + 1, ii);
else if(it instanceof Array) ((Array) it).string(tb, ii);
else tb.add(it.toString());
}
if(v.size() != 1) tb.add(')');
}
tb.add('\n');
indent(tb, level);
tb.add('}');
}
/**
* Adds some indentation.
* @param tb token builder
* @param level level
*/
private static void indent(final TokenBuilder tb, final int level) {
for(int l = 0; l < level; l++) tb.add(" ");
}
@Override
public Expr inlineExpr(final Expr[] exprs, final QueryContext qc, final VarScope scp,
final InputInfo ii) {
return null;
}
@Override
public String toString() {
final StringBuilder sb = root.toString(new StringBuilder(MAPSTR).append(" { "));
// remove superfluous comma
if(root.size > 0) sb.deleteCharAt(sb.length() - 2);
return sb.append('}').toString();
}
}
|
package org.iatrix.widgets;
import java.util.Hashtable;
import java.util.List;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.iatrix.data.KonsTextLock;
import org.iatrix.dialogs.ChooseKonsRevisionDialog;
import org.iatrix.util.Heartbeat;
import org.iatrix.util.Heartbeat.IatrixHeartListener;
import org.iatrix.util.Helpers;
import org.iatrix.views.JournalView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.elexis.core.data.activator.CoreHub;
import ch.elexis.core.data.events.ElexisEventDispatcher;
import ch.elexis.core.data.util.Extensions;
import ch.elexis.core.ui.UiDesk;
import ch.elexis.core.ui.constants.ExtensionPointConstantsUi;
import ch.elexis.core.ui.icons.Images;
import ch.elexis.core.ui.text.EnhancedTextField;
import ch.elexis.core.ui.util.IKonsExtension;
import ch.elexis.core.ui.util.IKonsMakro;
import ch.elexis.core.ui.util.SWTHelper;
import ch.elexis.data.Anwender;
import ch.elexis.data.Konsultation;
import ch.elexis.data.PersistentObject;
import ch.rgw.tools.TimeTool;
import ch.rgw.tools.VersionedResource;
import ch.rgw.tools.VersionedResource.ResourceItem;
public class KonsText implements IJournalArea {
private static Konsultation actKons = null;
private static int konsTextSaverCount = 0;
private static Logger log = LoggerFactory.getLogger(org.iatrix.widgets.KonsText.class);
private static EnhancedTextField text;
private static Label lVersion = null;
private static Label lKonsLock = null;
private static KonsTextLock konsTextLock = null;
int displayedVersion;
private Action purgeAction;
private Action saveAction;
private Action chooseVersionAction;
private Action versionFwdAction;
private Action versionBackAction;
private static final String PATIENT_KEY = "org.iatrix.patient";
private boolean konsEditorHasFocus = false;
private final FormToolkit tk;
private Composite parent;
private Hashtable<String, IKonsExtension> hXrefs;
public KonsText(Composite parentComposite){
parent = parentComposite;
tk = UiDesk.getToolkit();
SashForm konsultationSash = new SashForm(parent, SWT.HORIZONTAL);
konsultationSash.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true));
Composite konsultationTextComposite = tk.createComposite(konsultationSash);
konsultationTextComposite.setLayout(new GridLayout(1, true));
text = new EnhancedTextField(konsultationTextComposite);
hXrefs = new Hashtable<>();
@SuppressWarnings("unchecked")
List<IKonsExtension> listKonsextensions = Extensions.getClasses(
Extensions.getExtensions(ExtensionPointConstantsUi.KONSEXTENSION), "KonsExtension", //$NON-NLS-1$ //$NON-NLS-2$
false);
for (IKonsExtension x : listKonsextensions) {
String provider = x.connect(text);
hXrefs.put(provider, x);
}
text.setXrefHandlers(hXrefs);
@SuppressWarnings("unchecked")
List<IKonsMakro> makros = Extensions.getClasses(
Extensions.getExtensions(ExtensionPointConstantsUi.KONSEXTENSION), "KonsMakro", false); //$NON-NLS-1$
text.setExternalMakros(makros);
text.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true));
makeActions();
text.getControl().addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e){
logEvent("widgetDisposed removeKonsTextLock");
updateEintrag();
removeKonsTextLock();
konsEditorHasFocus = false;
}
});
text.getControl().addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e){
logEvent("focusGained");
konsEditorHasFocus = true;
}
@Override
public void focusLost(FocusEvent e){
logEvent("focusLost updateEintrag");
updateEintrag();
konsEditorHasFocus = false;
}
});
Control control = text.getControl();
if (control instanceof StyledText) {
StyledText styledText = (StyledText) control;
styledText.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e){
// create new consultation if required
// handleInitialKonsText();
}
});
}
tk.adapt(text);
lVersion = tk.createLabel(konsultationTextComposite, "<aktuell>");
lVersion.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false));
lKonsLock = tk.createLabel(konsultationTextComposite, "");
lKonsLock.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false));
lKonsLock.setForeground(lKonsLock.getDisplay().getSystemColor(SWT.COLOR_RED));
lKonsLock.setVisible(false);
registerUpdateHeartbeat();
}
public Action getPurgeAction(){
return purgeAction;
}
public Action getSaveAction(){
return saveAction;
}
public Action getChooseVersionAction(){
return chooseVersionAction;
}
public Action getVersionForwardAction(){
return versionFwdAction;
}
public Action getVersionBackAction(){
return versionBackAction;
}
public synchronized void updateEintrag(){
if (actKons != null) {
if (actKons.getFall() == null) {
return;
}
if (text.isDirty() || textChanged()) {
logEvent("updateEintrag " + actKons.getId());
if (hasKonsTextLock()) {
actKons.updateEintrag(text.getContentsAsXML(), false);
int new_version = actKons.getHeadVersion();
logEvent("updateEintrag saved rev. " + new_version + " "
+ text.getContentsPlaintext());
text.setDirty(false);
// update kons version label
// (we would get an objectChanged event, but this event isn't processed
// in case the kons text field has the focus.)
updateKonsVersionLabel();
JournalView.updateAllKonsAreas(actKons, KonsActions.ACTIVATE_KONS);
// ElexisEventDispatcher.fireSelectionEvent(actKons);
} else {
// should never happen...
if (konsTextLock == null) {
logEvent("updateEintrag Konsultation gesperrt. konsTextLock null.");
} else {
logEvent("updateEintrag Konsultation gesperrt. " + " key "
+ konsTextLock.getKey() + " lock " + konsTextLock.getLockValue());
SWTHelper.alert("Konsultation gesperrt",
"Der Text kann nicht gespeichert werden, weil die Konsultation durch einen anderen Benutzer gesperrt ist."
+ "(info: " + konsTextLock.getKey()
+ ". Dieses Problem ist ein Programmfehler. Bitte informieren Sie die Entwickler.)");
}
}
}
}
}
/**
* Check whether the text in the text field has changed compared to the database entry.
*
* @return true, if the text changed, false else
*/
private boolean textChanged(){
if (actKons == null) {
return false;
}
String dbEintrag = actKons.getEintrag().getHead();
String textEintrag = text.getContentsAsXML();
if (textEintrag != null) {
if (!textEintrag.equals(dbEintrag)) {
// text differs from db entry
logEvent("saved text != db entry");
return true;
}
}
return false;
}
private void updateKonsLockLabel(){
if (konsTextLock == null || hasKonsTextLock()) {
lKonsLock.setVisible(false);
lKonsLock.setText("");
} else {
Anwender user = konsTextLock.getLockValue().getUser();
StringBuilder text = new StringBuilder();
if (user != null && user.exists()) {
text.append(
"Konsultation wird von Benutzer \"" + user.getLabel() + "\" bearbeitet.");
} else {
text.append("Konsultation wird von anderem Benutzer bearbeitet.");
}
text.append(" Rechner \"" + konsTextLock.getLockValue().getHost() + "\".");
log.debug("updateKonsLockLabel: " + text.toString());
lKonsLock.setText(text.toString());
lKonsLock.setVisible(true);
}
lKonsLock.getParent().layout();
}
// helper method to create a KonsTextLock object in a save way
// should be called when a new konsultation is set
private synchronized void createKonsTextLock(){
// remove old lock
removeKonsTextLock();
if (actKons != null && CoreHub.actUser != null) {
konsTextLock = new KonsTextLock(actKons, CoreHub.actUser);
} else {
konsTextLock = null;
}
if (konsTextLock != null) {
konsTextLock.lock();
// boolean success = konsTextLock.lock();
// logEvent(
// "createKonsTextLock: konsText locked (" + success + ")" + konsTextLock.getKey());
}
}
// helper method to release a KonsTextLock
// should be called before a new konsultation is set
// or the program/view exits
private synchronized void removeKonsTextLock(){
if (konsTextLock != null) {
konsTextLock.unlock();
// boolean success = konsTextLock.unlock();
// logEvent(
// "removeKonsTextLock: konsText unlocked (" + success + ") " + konsTextLock.getKey());
konsTextLock = null;
}
}
/**
* Check whether we own the lock
*
* @return true, if we own the lock, false else
*/
private synchronized boolean hasKonsTextLock(){
return (konsTextLock != null && konsTextLock.isLocked());
}
@Override
public synchronized void visible(boolean mode){
}
private void makeActions(){
// Konsultationstext
purgeAction = new Action("Alte Eintragsversionen entfernen") {
@Override
public void run(){
actKons.purgeEintrag();
ElexisEventDispatcher.fireSelectionEvent(actKons);
}
};
versionBackAction = new Action("Vorherige Version") {
@Override
public void run(){
if (MessageDialog.openConfirm(
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
"Konsultationstext ersetzen",
"Wollen Sie wirklich den aktuellen Konsultationstext gegen eine frühere Version desselben Eintrags ersetzen?")) {
setKonsText(actKons, displayedVersion - 1, false);
text.setDirty(true);
}
}
};
versionFwdAction = new Action("nächste Version") {
@Override
public void run(){
if (MessageDialog.openConfirm(
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
"Konsultationstext ersetzen",
"Wollen Sie wirklich den aktuellen Konsultationstext gegen eine spätere Version desselben Eintrags ersetzen?")) {
setKonsText(actKons, displayedVersion + 1, false);
text.setDirty(true);
}
}
};
chooseVersionAction = new Action("Version wählen...") {
@Override
public void run(){
ChooseKonsRevisionDialog dlg = new ChooseKonsRevisionDialog(
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), actKons);
if (dlg.open() == ChooseKonsRevisionDialog.OK) {
int selectedVersion = dlg.getSelectedVersion();
if (MessageDialog.openConfirm(
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
"Konsultationstext ersetzen",
"Wollen Sie wirklich den aktuellen Konsultationstext gegen die Version "
+ selectedVersion + " desselben Eintrags ersetzen?")) {
setKonsText(actKons, selectedVersion, false);
text.setDirty(true);
}
}
}
};
saveAction = new Action("Eintrag sichern") {
{
setImageDescriptor(Images.IMG_DISK.getImageDescriptor());
setToolTipText("Text explizit speichern");
}
@Override
public void run(){
logEvent("saveAction: ");
updateEintrag();
JournalView.updateAllKonsAreas(actKons, KonsActions.ACTIVATE_KONS);
}
};
};
private void updateKonsultation(boolean updateText){
if (actKons != null) {
if (updateText) {
setKonsText(actKons, actKons.getHeadVersion(), true);
}
logEvent("updateKonsultation: " + actKons.getId());
} else {
setKonsText(null, 0, true);
logEvent("updateKonsultation: null");
}
}
/**
* Aktuelle Konsultation setzen.
*
* Wenn eine Konsultation gesetzt wird stellen wir sicher, dass der gesetzte Patient zu dieser
* Konsultation gehoert. Falls nicht, wird ein neuer Patient gesetzt.
*
* @param putCaretToEnd
* if true, activate text field ant put caret to the end
*/
@Override
public synchronized void setKons(Konsultation k, KonsActions op){
if (op == KonsActions.SAVE_KONS) {
if (text.isDirty() || textChanged()) {
logEvent("setKons.SAVE_KONS text.isDirty or changed saving Kons from "
+ actKons.getDatum() + " is '" + text.getContentsPlaintext() + "'");
updateEintrag();
text.setData(PATIENT_KEY, null);
text.setText("saved kons");
removeKonsTextLock();
actKons = null; // Setting it to null made clicking twice for a kons in the kons history the kontext disapper
} else {
if (actKons != null && text != null) {
logEvent("setKons.SAVE_KONS nothing to save for Kons from " + actKons.getDatum()
+ " is '" + text.getContentsPlaintext() + "'");
}
}
return;
}
if (op == KonsActions.ACTIVATE_KONS) {
// make sure to unlock the kons edit field and release the lock
if (text != null && actKons != null) {
logEvent("setKons.ACTIVATE_KONS text.isDirty " + text.isDirty() + " textChanged "
+ textChanged() + " actKons vom: " + actKons.getDatum());
}
removeKonsTextLock();
if (k == null) {
actKons = k;
logEvent("setKons null");
} else {
logEvent("setKons " + (actKons == null ? "null" : actKons.getId()) +
" => " + k.getId());
actKons = k;
boolean konsEditable = Helpers.hasRightToChangeConsultations(actKons, false);
if (!konsEditable) {
// isEditable(true) would give feedback to user why consultation
// cannot be edited, but this often very shortlived as we create/switch
// to a newly created kons of today
logEvent("setKons actKons is not editable");
text.setEnabled(false);
setKonsText(k, 0, true);
updateKonsultation(true);
updateKonsLockLabel();
lVersion.setText(lVersion.getText() + " Nicht editierbar. (Keine Zugriffsrechte oder schon verrechnet)");
return;
} else {
text.setEnabled(true);
}
createKonsTextLock();
setKonsText(k, 0, true);
}
updateKonsultation(true);
updateKonsLockLabel();
updateKonsVersionLabel();
saveAction.setEnabled(konsTextLock == null || hasKonsTextLock());
}
}
/**
* Set the version label to reflect the current kons' latest version Called by: updateEintrag()
*/
private void updateKonsVersionLabel(){
if (actKons != null) {
int version = actKons.getHeadVersion();
logEvent("Update Version Label: " + version);
VersionedResource vr = actKons.getEintrag();
ResourceItem entry = vr.getVersion(version);
StringBuilder sb = new StringBuilder();
if (entry != null) {
String revisionTime = new TimeTool(entry.timestamp).toString(TimeTool.FULL_GER);
String revisionDate = new TimeTool(entry.timestamp).toString(TimeTool.DATE_GER);
if (!actKons.getDatum().equals(revisionDate)) {
sb.append("Kons vom " + actKons.getDatum() + ": ");
}
sb.append("rev. ").append(version).append(" vom ")
.append(revisionTime).append(" (")
.append(entry.remark).append(")");
}
lVersion.setText(sb.toString());
} else {
lVersion.setText("");
}
}
private synchronized void setKonsText(Konsultation b, int version, boolean putCaretToEnd){
if (b != null) {
String ntext = "";
if ((version >= 0) && (version <= b.getHeadVersion())) {
VersionedResource vr = b.getEintrag();
ResourceItem entry = vr.getVersion(version);
ntext = entry.data;
StringBuilder sb = new StringBuilder();
sb.append("rev. ").append(version).append(" vom ")
.append(new TimeTool(entry.timestamp).toString(TimeTool.FULL_GER)).append(" (")
.append(entry.remark).append(")");
lVersion.setText(sb.toString());
} else {
lVersion.setText("");
}
text.setText(PersistentObject.checkNull(ntext));
text.setKons(b);
text.setEnabled(hasKonsTextLock());
displayedVersion = version;
versionBackAction.setEnabled(version != 0);
versionFwdAction.setEnabled(version != b.getHeadVersion());
boolean locked = hasKonsTextLock();
int strlen = text.getContentsPlaintext().length();
int maxLen = strlen < 120 ? strlen : 120;
String label = (konsTextLock == null) ? "null " : konsTextLock.getLabel();
if (!locked)
logEvent("setKonsText availabee " + b.getId() + " " + label + " putCaretToEnd " + putCaretToEnd +
" " + lVersion.getText() + " '" + text.getContentsPlaintext().substring(0, maxLen) + "'");
else
logEvent("setKonsText (locked) " + b.getId() + " " + label + " putCaretToEnd " + putCaretToEnd +
" " + lVersion.getText() + " '" + text.getContentsPlaintext().substring(0, maxLen) + "'");
if (putCaretToEnd) {
// set focus and put caret at end of text
text.putCaretToEnd();
}
} else {
lVersion.setText("");
text.setText("");
text.setKons(null);
text.setEnabled(false);
displayedVersion = -1;
versionBackAction.setEnabled(false);
versionFwdAction.setEnabled(false);
logEvent("setKonsText null " + lVersion.getText() + " " + text.getContentsPlaintext());
}
}
private void logEvent(String msg){
StringBuilder sb = new StringBuilder(msg + ": ");
if (actKons == null) {
sb.append("actKons null");
} else {
sb.append(actKons.getId());
sb.append(" kons rev. " + actKons.getHeadVersion());
sb.append(" vom " + actKons.getDatum());
if (actKons.getFall() != null) {
sb.append(" " + actKons.getFall().getPatient().getPersonalia());
}
}
log.debug(sb.toString());
}
@Override
public synchronized void activation(boolean mode){
}
public synchronized void registerUpdateHeartbeat(){
Heartbeat heat = Heartbeat.getInstance();
heat.addListener(new IatrixHeartListener() {
private int konsTextSaverPeriod;
@Override
public void heartbeat(){
logEvent("Period: " + konsTextSaverPeriod);
if (!(konsTextSaverPeriod > 0)) {
// auto-save disabled
return;
}
// inv: konsTextSaverPeriod > 0
// increment konsTextSaverCount, but stay inside period
konsTextSaverCount++;
konsTextSaverCount %= konsTextSaverPeriod;
logEvent("konsTextSaverCount = " + konsTextSaverCount + " konsEditorHasFocus: "
+ konsEditorHasFocus);
if (konsTextSaverCount == 0) {
if (konsEditorHasFocus) {
logEvent("Auto Save Kons Text");
updateEintrag();
}
}
}
});
}
public String getPlainText(){
if (text == null ) {
return "";
}
return text.getContentsPlaintext();
}
}
|
package com.xpn.xwiki.web;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class EditForm extends XWikiForm
{
private String content;
private String web;
private String name;
private String parent;
private String creator;
private String template;
private String language;
private String defaultLanguage;
private String defaultTemplate;
private String title;
private String comment;
private boolean isMinorEdit = false;
private String tags;
private boolean lockForce;
private String syntaxId;
@Override
public void readRequest()
{
XWikiRequest request = getRequest();
setContent(request.getParameter("content"));
setWeb(request.getParameter("web"));
setName(request.getParameter("name"));
setParent(request.getParameter("parent"));
setTemplate(request.getParameter("template"));
setDefaultTemplate(request.getParameter("default_template"));
setCreator(request.getParameter("creator"));
setLanguage(request.getParameter("language"));
setTitle(request.getParameter("title"));
setComment(request.getParameter("comment"));
setDefaultLanguage(request.getParameter("default_language"));
setTags(request.getParameterValues("tags"));
setLockForce("1".equals(request.getParameter("force")));
setMinorEdit(request.getParameter("minor_edit") != null);
setSyntaxId(request.getParameter("syntaxId"));
}
public void setTags(String[] parameter)
{
if (parameter == null) {
this.tags = null;
return;
}
StringBuffer tags = new StringBuffer();
boolean first = true;
for (int i = 0; i < parameter.length; ++i) {
if (!parameter[i].equals("")) {
if (first) {
first = false;
} else {
tags.append("|");
}
tags.append(parameter[i]);
}
}
this.tags = tags.toString();
}
public String getTags()
{
return this.tags;
}
public String getContent()
{
return this.content;
}
public void setContent(String content)
{
this.content = content;
}
public String getWeb()
{
return this.web;
}
public void setWeb(String web)
{
this.web = web;
}
public String getName()
{
return this.name;
}
public void setName(String name)
{
this.name = name;
}
public String getLanguage()
{
return this.language;
}
public void setLanguage(String language)
{
this.language = language;
}
public int getObjectNumbers(String prefix)
{
String nb = getRequest().getParameter(prefix + "_nb");
if ((nb == null) || (nb.equals(""))) {
return 0;
}
return Integer.parseInt(nb);
}
public Map getObject(String prefix)
{
Map map = getRequest().getParameterMap();
HashMap map2 = new HashMap();
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
String name = (String) it.next();
if (name.startsWith(prefix + "_")) {
String newname = name.substring(prefix.length() + 1);
map2.put(newname, map.get(name));
}
}
return map2;
}
public String getParent()
{
return this.parent;
}
public void setParent(String parent)
{
this.parent = parent;
}
public String getCreator()
{
return this.creator;
}
public void setCreator(String creator)
{
this.creator = creator;
}
public String getTemplate()
{
return this.template;
}
public void setTemplate(String template)
{
this.template = template;
}
public String getDefaultTemplate()
{
return this.defaultTemplate;
}
public void setDefaultTemplate(String defaultTemplate)
{
this.defaultTemplate = defaultTemplate;
}
public String getDefaultLanguage()
{
return this.defaultLanguage;
}
public void setDefaultLanguage(String defaultLanguage)
{
this.defaultLanguage = defaultLanguage;
}
public String getTitle()
{
return this.title;
}
public void setTitle(String title)
{
this.title = title;
}
public String getComment()
{
return this.comment;
}
public void setComment(String comment)
{
this.comment = comment;
}
public boolean isMinorEdit()
{
return this.isMinorEdit;
}
public void setMinorEdit(boolean isMinorEdit)
{
this.isMinorEdit = isMinorEdit;
}
public boolean isLockForce()
{
return this.lockForce;
}
public void setLockForce(boolean lockForce)
{
this.lockForce = lockForce;
}
public String getSyntaxId()
{
return this.syntaxId;
}
public void setSyntaxId(String syntaxId)
{
this.syntaxId = syntaxId;
}
}
|
package org.jboss.as.demos;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.client.helpers.standalone.DeploymentPlan;
import org.jboss.as.controller.client.helpers.standalone.DeploymentPlanBuilder;
import org.jboss.as.controller.client.helpers.standalone.DuplicateDeploymentNameException;
import org.jboss.as.controller.client.helpers.standalone.ServerDeploymentManager;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ArchivePath;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.container.ResourceContainer;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.jboss.as.protocol.StreamUtils.safeClose;
/**
* Used to deploy/undeploy deployments to a running <b>standalone</b> application server
*
* TODO Use the real deployment API once that is complete
*
* @author <a href="kabir.khan@jboss.com">Kabir Khan</a>
* @version $Revision: 1.1 $
*/
public class DeploymentUtils implements Closeable {
public static final long DEFAULT_TIMEOUT = 15000;
private final List<AbstractDeployment> deployments = new ArrayList<AbstractDeployment>();
private final ModelControllerClient client;
private final ServerDeploymentManager manager;
private long timeout = DEFAULT_TIMEOUT;
public DeploymentUtils() throws UnknownHostException {
client = ModelControllerClient.Factory.create(InetAddress.getByName("localhost"), 9999);
manager = ServerDeploymentManager.Factory.create(client);
}
public DeploymentUtils(String archiveName, Package... pkg) throws UnknownHostException {
this();
addDeployment(archiveName, pkg);
}
public DeploymentUtils(Archive archive) throws UnknownHostException {
this();
deployments.add(new ArbitraryDeployment(archive,false));
}
public DeploymentUtils(String archiveName, boolean show, Package... pkgs) throws UnknownHostException {
this();
addDeployment(archiveName, show, pkgs);
}
public synchronized void addDeployment(String archiveName, Package... pkgs) {
addDeployment(archiveName, false, pkgs);
}
public synchronized void addDeployment(String archiveName, boolean show, Package... pkgs) {
deployments.add(new Deployment(archiveName, pkgs, show));
}
public synchronized void addWarDeployment(String archiveName, Package... pkgs) {
addWarDeployment(archiveName, false, pkgs);
}
public synchronized void addWarDeployment(String archiveName, boolean show, Package... pkgs) {
deployments.add(new WarDeployment(archiveName, pkgs, show));
}
public synchronized void deploy() throws DuplicateDeploymentNameException, IOException, ExecutionException, InterruptedException, TimeoutException {
DeploymentPlanBuilder builder = manager.newDeploymentPlan().withRollback();
for (AbstractDeployment deployment : deployments) {
builder = deployment.addDeployment(manager, builder);
}
try {
manager.execute(builder.build()).get(timeout, TimeUnit.MILLISECONDS);
} finally {
markDeploymentsDeployed();
}
}
private void markDeploymentsDeployed() {
for (AbstractDeployment deployment : deployments) {
deployment.deployed = true;
}
}
public synchronized void undeploy() throws ExecutionException, InterruptedException, TimeoutException {
DeploymentPlanBuilder builder = manager.newDeploymentPlan();
for (AbstractDeployment deployment : deployments) {
builder = deployment.removeDeployment(builder);
}
DeploymentPlan plan = builder.build();
if (plan.getDeploymentActions().size() > 0) {
manager.execute(builder.build()).get(timeout, TimeUnit.MILLISECONDS);
}
}
public MBeanServerConnection getConnection() throws Exception {
return JMXConnectorFactory.connect(new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1090/jmxrmi"),
new HashMap<String, Object>()).getMBeanServerConnection();
}
public String showJndi() throws Exception {
return (String)getConnection().invoke(new ObjectName("jboss:type=JNDIView"), "list", new Object[] {true}, new String[] {"boolean"});
}
public long getTimeout() {
return timeout;
}
public void setTimeout(long timeout) {
this.timeout = timeout;
}
@Override
public void close() throws IOException {
safeClose(client);
}
private abstract class AbstractDeployment{
boolean deployed;
String deployment;
public synchronized DeploymentPlanBuilder addDeployment(ServerDeploymentManager manager, DeploymentPlanBuilder builder) throws DuplicateDeploymentNameException, IOException, ExecutionException, InterruptedException {
deployment = getRealArchive().getName();
System.out.println("Deploying " + deployment);
return builder.add(deployment, getRealArchive()).deploy(deployment);
}
public synchronized DeploymentPlanBuilder removeDeployment(DeploymentPlanBuilder builder) {
if (deployed) {
System.out.println("Undeploying " + deployment);
return builder.undeploy(deployment).remove(deployment);
}
else {
return builder;
}
}
protected void addFiles(ResourceContainer<?> archive, File dir, ArchivePath dest) {
for (String name : dir.list()) {
File file = new File(dir, name);
if (file.isDirectory()) {
addFiles(archive, file, ArchivePaths.create(dest, name));
} else {
archive.addResource(file, ArchivePaths.create(dest, name));
}
}
}
protected File getSourceMetaInfDir(String archiveName) {
String name = "archives/" + archiveName + "/META-INF/MANIFEST.MF";
URL url = Thread.currentThread().getContextClassLoader().getResource(name);
if (url == null) {
throw new IllegalArgumentException("No resource called " + name);
}
try {
File file = new File(url.toURI());
return file.getParentFile();
} catch (URISyntaxException e) {
throw new RuntimeException("Could not get file for " + url);
}
}
protected File getSourceWebInfDir(String archiveName) {
String name = "archives/" + archiveName + "/WEB-INF";
URL url = Thread.currentThread().getContextClassLoader().getResource(name);
if (url == null) {
return null;
}
try {
return new File(url.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Could not get file for " + url);
}
}
protected File getOutputDir() {
File file = new File("target");
if (!file.exists()) {
throw new IllegalStateException("target/ does not exist");
}
if (!file.isDirectory()) {
throw new IllegalStateException("target/ is not a directory");
}
file = new File(file, "archives");
if (file.exists()) {
if (!file.isDirectory()) {
throw new IllegalStateException("target/archives/ already exists and is not a directory");
}
} else {
file.mkdir();
}
return file.getAbsoluteFile();
}
protected File createArchive(Archive<?> archive) {
File realArchive = new File(getOutputDir(), archive.getName());
archive.as(ZipExporter.class).exportZip(realArchive, true);
return realArchive;
}
protected abstract File getRealArchive();
}
private class Deployment extends AbstractDeployment {
final File realArchive;
public Deployment(String archiveName, Package[] pkgs, boolean show) {
ArchivePath metaInf = ArchivePaths.create("META-INF");
JavaArchive archive = ShrinkWrap.create(JavaArchive.class, archiveName);
for(Package pkg : pkgs) {
archive.addPackage(pkg);
}
File sourceMetaInf = getSourceMetaInfDir(archiveName);
addFiles(archive, sourceMetaInf, metaInf);
System.out.println(archive.toString(show));
realArchive = createArchive(archive);
}
@Override
protected File getRealArchive() {
return realArchive;
}
}
private class WarDeployment extends AbstractDeployment {
final File realArchive;
public WarDeployment(String archiveName, Package[] pkgs, boolean show) {
ArchivePath metaInf = ArchivePaths.create("META-INF");
WebArchive archive = ShrinkWrap.create(WebArchive.class, archiveName);
for(Package pkg : pkgs) {
archive.addPackage(pkg);
}
File sourceMetaInf = getSourceMetaInfDir(archiveName);
addFiles(archive, sourceMetaInf, metaInf);
File sourceWebInf = getSourceWebInfDir(archiveName);
if (sourceWebInf != null) {
addFiles(archive, sourceWebInf, ArchivePaths.create("WEB-INF"));
}
System.out.println(archive.toString(show));
realArchive = createArchive(archive);
}
@Override
protected File getRealArchive() {
return realArchive;
}
}
private class ArbitraryDeployment extends AbstractDeployment {
final File realArchive;
public ArbitraryDeployment(Archive archive, boolean show) {
ArchivePath metaInf = ArchivePaths.create("META-INF");
System.out.println(archive.toString(show));
realArchive = createArchive(archive);
}
@Override
protected File getRealArchive() {
return realArchive;
}
}
}
|
package polytheque.view;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Date;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import com.toedter.calendar.JDateChooser;
import polytheque.model.pojos.Adherent;
import polytheque.model.pojos.Emprunt;
import polytheque.model.pojos.Extension;
import polytheque.model.pojos.Jeu;
import polytheque.model.pojos.Reservation;
/**
* Classe permettant l'administrateur de crer un emprunt
* @author laure
*
*/
@SuppressWarnings("serial")
public class AffichageCreationEmprunt extends JPanel implements ActionListener{
private JTextField gameName;
private JTextField extensionName;
private JTextField userPseudo;
private JDateChooser dateChooser;
private JButton boutonValider;
/**
* Une tache d'affichage de l'application.
*/
private TacheDAffichage tacheDAffichageDeLApplication;
/**
* Creation de la page d'accueil.
*
* @param tacheDAffichageDeLApplication
* Une tache d'affichage de l'application.
* @return
*/
public AffichageCreationEmprunt(TacheDAffichage afficheAppli) {
this.tacheDAffichageDeLApplication = afficheAppli;
this.setLayout(null);
ajouterChamps();
creerPanneauDate();
ajouterBoutons();
}
public void ajouterChamps() {
/*JPanel grosPanel = new JPanel();
grosPanel.setLayout(new BorderLayout());
JPanel titrePanel = new JPanel();*/
JLabel titrePrincipal = new JLabel("Emprunter un jeu et/ou une extension");
titrePrincipal.setHorizontalAlignment(SwingConstants.CENTER);
titrePrincipal.setBounds(480, 20, 260, 30);
//titrePanel.add(titrePrincipal);
//this.add(titrePanel, BorderLayout.NORTH);
this.add(titrePrincipal);
//grosPanel.add(titrePanel, BorderLayout.NORTH);
//JPanel userInfoPanel = new JPanel();
JLabel labelGameName = new JLabel("Nom du jeu :");
labelGameName.setBounds(150, 150, 100, 30);
//userInfoPanel.add(labelUserName);
this.add(labelGameName);
this.gameName = new JTextField();
this.gameName.setBounds(300, 150, 100, 30);
//userInfoPanel.add(this.userName);
//this.add(userInfoPanel,BorderLayout.WEST);
this.add(gameName);
JLabel labelExtensionName = new JLabel("Nom de l'extension :");
labelExtensionName.setBounds(150, 200, 150, 30);
//userInfoPanel.add(labelUserFirstName);
this.add(labelExtensionName);
this.extensionName = new JTextField();
this.extensionName.setBounds(300, 200, 100, 30);
//userInfoPanel.add(this.userFirstName);
//this.add(userInfoPanel,BorderLayout.WEST);
//grosPanel.add(userInfoPanel, BorderLayout.WEST);
this.add(extensionName);
JLabel labelUserPseudo = new JLabel("Pseudo de l'adherent :");
labelUserPseudo.setBounds(150, 250, 150, 30);
this.add(labelUserPseudo);
this.userPseudo = new JTextField();
this.userPseudo.setBounds(300, 250, 100, 30);
this.add(this.userPseudo);
//this.add(this.userInfoPanel, BorderLayout.WEST);
}
private void creerPanneauDate() {
//JPanel DatePanel = new JPanel();
//DatePanel.setPreferredSize(new Dimension(TacheDAffichage.LARGEUR, 50));
JLabel labelDateEmprunt = new JLabel("Date de l'emprunt :");
labelDateEmprunt.setBounds(850, 150, 150, 30);
this.add(labelDateEmprunt);
this.dateChooser = new JDateChooser();
this.dateChooser.setBounds(850, 200, 150, 30);
this.add(this.dateChooser);
//this.add(DatePanel, BorderLayout.EAST);
}
public void ajouterBoutons(){
//JPanel panelButton = new JPanel();
this.boutonValider = new JButton("Valider");
this.boutonValider.setBounds(480, 500, 200, 30);
this.boutonValider.addActionListener(this);
this.add(this.boutonValider);
//this.add(panelButton, BorderLayout.SOUTH);
}
@Override
public void actionPerformed(ActionEvent event) {
JButton boutonSelectionne = (JButton) event.getSource();
if (boutonSelectionne == this.boutonValider)
{
if (this.gameName.getText() != null && this.userPseudo.getText() != null && this.dateChooser.getDate() != null)
{
Date dateEmprunt = new Date(this.dateChooser.getDate().getTime());
Adherent adherent = this.tacheDAffichageDeLApplication.getAdherent(userPseudo.getText());
Jeu jeu = this.tacheDAffichageDeLApplication.getJeu(gameName.getText());
Extension extention = this.tacheDAffichageDeLApplication.getExt(extensionName.getText());
Reservation reservation = new Reservation(adherent.getIdAdherent(),jeu.getIdJeu(),extention.getIdExtension(),dateEmprunt);
Emprunt emprunt = reservation.validerReservation();
if (this.tacheDAffichageDeLApplication.creerEmprunt(emprunt) == false){
this.tacheDAffichageDeLApplication.afficherMessage("Erreur lors de l'emprunt", "Erreur de cration", JOptionPane.ERROR_MESSAGE);
}
else {
this.tacheDAffichageDeLApplication.afficherMessage("Un emprunt a t effectu !", "Cration termine", JOptionPane.INFORMATION_MESSAGE);
return;
}
}
else {
this.tacheDAffichageDeLApplication.afficherMessage("Veuillez renseigner tous les champs !", "Erreur champ(s) vide(s)", JOptionPane.ERROR_MESSAGE);
}
}
return;
}
}
|
package com.androidsx.rateme;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.LayerDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RatingBar;
import com.androidsx.libraryrateme.R;
public class DialogRateMe extends DialogFragment {
private static final String TAG = DialogRateMe.class.getSimpleName();
private static final String EXTRA_PACKAGE_NAME = "package-name";
private static final String MARKET_CONSTANT = "market://details?id=";
private static final String GOOGLE_PLAY_CONSTANT = "http://play.google.com/store/apps/details?id=";
private String appPackageName;
private View mView;
private View tView;
private View confirDialogView;
private Button close;
private RatingBar ratingBar;
private LayerDrawable stars;
private Button rateMe;
private Button noThanks;
private Button share;
public static DialogRateMe newInstance(String packageName) {
DialogRateMe dialogo = new DialogRateMe();
Bundle args = new Bundle();
args.putString(EXTRA_PACKAGE_NAME, packageName);
dialogo.setArguments(args);
return dialogo;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
appPackageName = getArguments().getString(EXTRA_PACKAGE_NAME);
initializeUiFields();
Log.d(TAG, "initialize correctly all the components");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
stars.getDrawable(2).setColorFilter(Color.YELLOW, PorterDuff.Mode.SRC_ATOP);
ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
if (rating >= 4.0) {
rateMe.setVisibility(View.VISIBLE);
noThanks.setVisibility(View.GONE);
} else {
noThanks.setVisibility(View.VISIBLE);
rateMe.setVisibility(View.GONE);
}
}
});
configureButtons();
close.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
RateMeDialogTimer.clearSharedPreferences(getActivity());
Log.d(TAG, "clear preferences");
}
});
share.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(shareApp(appPackageName));
Log.d(TAG, "share App");
}
});
builder.setView(mView).setCustomTitle(tView).setCancelable(false);
return builder.create();
}
private void initializeUiFields() {
mView = getActivity().getLayoutInflater().inflate(R.layout.library, null);
tView = getActivity().getLayoutInflater().inflate(R.layout.title, null);
confirDialogView = getActivity().getLayoutInflater().inflate(R.layout.confirmationtitledialog, null);
close = (Button) tView.findViewById(R.id.buttonClose);
share = (Button) tView.findViewById(R.id.buttonShare);
rateMe = (Button) mView.findViewById(R.id.buttonRateMe);
noThanks = (Button) mView.findViewById(R.id.buttonThanks);
ratingBar = (RatingBar) mView.findViewById(R.id.ratingBar);
stars = (LayerDrawable) ratingBar.getProgressDrawable();
}
private void configureButtons() {
rateMe.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
rateApp();
Log.d(TAG, "go to Google Play Store for Rate-Me");
RateMeDialogTimer.setOptOut(getActivity(), true);
}
});
noThanks.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
confirmGoToMailDialog(getArguments()).show();
Log.d(TAG, "got to Mail for explain what is the problem");
}
});
}
private void rateApp() {
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(MARKET_CONSTANT + appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(GOOGLE_PLAY_CONSTANT + appPackageName)));
}
}
private void goToMail() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("plain/text");
intent.putExtra(Intent.EXTRA_EMAIL, new String[] { "some@email.com" });
intent.putExtra(Intent.EXTRA_SUBJECT, R.string.subjectmail);
try {
startActivity(Intent.createChooser(intent, ""));
} catch (android.content.ActivityNotFoundException ex) {
rateApp();
}
}
private Dialog confirmGoToMailDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setCustomTitle(confirDialogView).setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
goToMail();
}
}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dismiss();
}
});
return builder.create();
}
private Intent shareApp(String appPackageName) {
Intent shareApp = new Intent();
shareApp.setAction(Intent.ACTION_SEND);
try {
shareApp.putExtra(Intent.EXTRA_TEXT, MARKET_CONSTANT + appPackageName);
} catch (android.content.ActivityNotFoundException anfe) {
shareApp.putExtra(Intent.EXTRA_TEXT, GOOGLE_PLAY_CONSTANT + appPackageName);
}
shareApp.setType("text/plain");
return shareApp;
}
}
|
package org.bdgp.MMSlide.DB;
import javax.swing.tree.DefaultMutableTreeNode;
import org.bdgp.MMSlide.Modules.Interfaces.Module;
import com.j256.ormlite.field.DataType;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
/**
* Class for defining workflows. Each step has a unique String ID,
* a module to execute, and the ID of the parent step. Also check
* that the given module name is valid.
*/
@SuppressWarnings("serial")
@DatabaseTable
public class WorkflowModule extends DefaultMutableTreeNode {
@DatabaseField(canBeNull=false,dataType=DataType.LONG_STRING)
private String id;
@DatabaseField(canBeNull=false,useGetSet=true,dataType=DataType.LONG_STRING)
private String moduleName;
@DatabaseField(dataType=DataType.LONG_STRING)
private String parentId;
@DatabaseField(canBeNull=false,dataType=DataType.LONG_STRING)
private TaskType taskType;
public static enum TaskType {SERIAL, PARALLEL};
private Class<Module> module;
public WorkflowModule() {
super();
}
public WorkflowModule(String id, String moduleName, String parentId, TaskType taskType) {
super(id);
this.id = id;
setModuleName(moduleName);
this.parentId = parentId;
}
public String getId() {
return id;
}
public String getModuleName() {
return moduleName;
}
@SuppressWarnings("unchecked")
public void setModuleName(String moduleName) {
this.moduleName = moduleName;
// assign the module class
try {
Class<?> module = Class.forName(moduleName);
if (!Module.class.isAssignableFrom(module)) {
throw new RuntimeException("Module "+moduleName
+" does not inherit Module interface.");
}
this.module = Module.class.getClass().cast(module);
}
catch (ClassNotFoundException e) {
throw new RuntimeException("Module "+moduleName+" is an unknown module.", e);
}
}
public Class<Module> getModule() {
return module;
}
public String getParentId() {
return parentId;
}
public TaskType getTaskType() {
return taskType;
}
}
|
package org.opentreeoflife.smasher;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Collection;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Collections;
import java.util.Comparator;
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
import java.io.PrintStream;
import java.io.IOException;
import org.opentreeoflife.taxa.Node;
import org.opentreeoflife.taxa.Taxon;
import org.opentreeoflife.taxa.Synonym;
import org.opentreeoflife.taxa.Taxonomy;
import org.opentreeoflife.taxa.Answer;
import org.opentreeoflife.taxa.QualifiedId;
public class AlignmentByName extends Alignment {
public AlignmentByName(Taxonomy source, Taxonomy target) {
super(source, target);
}
AlignmentByName(Alignment a) {
super(a);
}
private int debug = 0;
// this is pretty gross. needs to be moved & rewritten.
// method is invoked from python.
public void reallyAlign() {
this.alignByName();
}
// Treat all taxa equally - tips same as internal - random order
public void alignByName() {
if (EXPERIMENTALP) {
this.tryThisOut();
return;
} else {
assignBrackets();
for (Taxon node : source.taxa())
alignTaxon(node);
}
}
// Map unambiguous tips first(?), then retry ambiguous(?), then internal nodes
int tipMappings = 0;
void tryThisOut() {
for (Taxon root : source.roots())
alignTipsOnly(root);
System.out.format("| %s quasi-tips\n", tipMappings);
this.USE_ALIGNMENT = true;
assignBrackets();
for (Taxon root : source.roots())
alignInternal(root);
}
// return true iff any quasi-tip under node
boolean alignTipsOnly(Taxon node) {
boolean anyMapped = false;
for (Taxon child : node.getChildren()) {
if (alignTipsOnly(child))
anyMapped = true;
}
if (anyMapped)
return true;
// Potential quasi-tip
Answer answer = alignTaxon(node);
if (answer != null && answer.isYes()) {
tipMappings++;
return true;
}
return false;
}
// align internal nodes (above quasi-tips)
void alignInternal(Taxon node) {
for (Taxon child : node.getChildren())
alignInternal(child);
// Cf. computeLubs
alignTaxon(node);
}
// Find answer for a single node, and put it in table
public Answer alignTaxon(Taxon node) {
Answer a = getAnswer(node);
if (a == null) {
a = findAlignment(node);
if (a != null) {
if (a.isYes()) {
alignWith(node, a.target, a);
// logDivisions(a); -- too much noise now.
} else
this.setAnswer(node, a);
}
}
return a;
}
void logDivisions(Answer a) {
Taxon node = a.subject;
Taxon unode = a.target;
Taxon xdiv = node.getDivision();
Taxon ydiv = unode.getDivision();
if (xdiv != ydiv && xdiv != null && ydiv != null && !xdiv.noMrca() && !ydiv.noMrca())
System.out.format("* Weakly divided: %s %s|%s %s because %s\n",
node, xdiv.name, ydiv.name, unode, a.reason);
}
static Comparator<Answer> compareAnswers = new Comparator<Answer>() {
public int compare(Answer x, Answer y) {
return x.target.compareTo(y.target);
}
};
// Alignment - single source taxon -> target taxon or 'no'
public Answer findAlignment(Taxon node) {
Map<Taxon, String> candidateMap = getCandidates(node);
if (candidateMap.size() == 0)
return null;
ArrayList<Answer> initialCandidates = new ArrayList<Answer>();
for (Taxon cand : candidateMap.keySet())
initialCandidates.add(Answer.noinfo(node, cand, candidateMap.get(cand), null));
Collections.sort(initialCandidates, compareAnswers);
// For logging. Ugly names, redundant data structures, needs cleaning up.
List<Answer> order = new ArrayList<Answer>();
// Loop state
Answer anyCandidate = null; // kludge for by-elimination
int count = 0; // number of candidates that have the max value
Answer result = null;
int score = -100;
List<Answer> candidates = initialCandidates;
// Precondition: at least one candidate
for (Heuristic heuristic : criteria) {
List<Answer> answers = new ArrayList<Answer>(candidates.size());
score = -100;
for (Answer cand : candidates) {
Answer a = heuristic.assess(node, cand.target);
if (a.target != cand.target) // a is Answer.NOINFO
a = new Answer(node, cand.target, a.value, a.reason, a.witness);
answers.add(a); // in parallel with candidates
if (a.value > score) {
score = a.value;
count = 1;
anyCandidate = cand;
} else if (a.value == score) {
count++;
}
}
List<Answer> winners = new ArrayList<Answer>();
for (Answer a : answers) {
if (a.value >= score && score >= Answer.DUNNO)
winners.add(a);
else
order.add(a);
}
if (winners.size() == 0) {
result = new Answer(node, null, score, "rejected", null);
break;
}
if (score > Answer.DUNNO && winners.size() == 1) {
// could just anyCandidate, but stats code likes normalization
order.add(anyCandidate);
if (candidates.size() > 1)
result = new Answer(node, anyCandidate.target, score,
heuristic.toString(),
anyCandidate.witness);
else
result = new Answer(node, anyCandidate.target, score,
"confirmed",
anyCandidate.reason);
break;
}
candidates = winners;
}
if (result == null) {
// fell through with all noinfo or multiple yes
if (candidates.size() == 1) {
result = Answer.yes(node, anyCandidate.target, "by elimination", null);
order.add(result);
} else {
order.addAll(candidates);
String r = node.hasChildren() ? "ambiguous internal" : "ambiguous tip";
result = Answer.noinfo(node, null, r, Integer.toString(candidates.size()));
order.add(result);
}
}
// Decide after the fact whether the dance was interesting enough to log
if (initialCandidates.size() > 1 ||
result.isNo() ||
target.eventLogger.namesOfInterest.contains(node.name)) {
target.eventLogger.namesOfInterest.add(node.name);
target.eventLogger.log(order);
}
return result;
}
private static boolean allowSynonymSynonymMatches = false;
// Given a source taxonomy return, return a set of target
// taxonomy nodes that it might plausibly match
Map<Taxon, String> getCandidates(Taxon node) {
Map<Taxon, String> candidateMap = new HashMap<Taxon, String>();
getCandidatesViaName(node, "C", candidateMap); // canonical
for (Synonym syn : node.getSynonyms())
getCandidatesViaName(syn, "S", candidateMap);
return candidateMap;
}
Map<Taxon, String> getCandidatesViaName(Node node, String mode, Map<Taxon, String> candidateMap) {
if (node.name != null) {
Collection<Node> unodes = target.lookup(node.name);
if (unodes != null)
for (Node unode : unodes)
addCandidate(candidateMap, unode, mode);
}
// Add nodes that share a qid with this one (for idsource alignment)
if (node.sourceIds != null) {
String mode2 = mode + "I";
for (QualifiedId qid : node.sourceIds) {
Node unode = target.lookupQid(qid);
if (unode != null) {
Taxon utaxon = unode.taxon();
if (!utaxon.prunedp) {
String xmode = mode2 + ((utaxon.sourceIds != null &&
utaxon.sourceIds.get(0).equals(qid)) ?
"I" : "J");
addCandidate(candidateMap, unode, xmode);
}
}
mode2 = mode + "J";
}
}
return candidateMap;
}
void addCandidate(Map<Taxon, String> candidateMap, Node unode, String mode) {
Taxon utaxon = unode.taxon();
mode = mode + (unode instanceof Taxon ? "C" : "S");
String modes = candidateMap.get(utaxon);
if (modes == null)
modes = mode;
else
modes = modes + " " + mode;
candidateMap.put(utaxon, modes);
}
static Heuristic[] criteria = {
Heuristic.division, // fail if disjoint divisions
Heuristic.ranks, // fail if incompatible ranks
Heuristic.lineage, // prefer shared lineage
Heuristic.subsumption, // prefer shared membership
Heuristic.sameDivisionPreferred, // prefer same division
Heuristic.byPrimaryName, // prefer same name
Heuristic.sameSourceId, // prefer same source id
Heuristic.anySourceId, // prefer candidate with any source id the same
};
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package creation;
import java.util.ArrayList;
/**
*
* @author cibikle
*/
public class Dice {
private ArrayList<Die> dice = new ArrayList<Die>();
private String name;
private boolean percentageDice = false;
public Dice(int n, int d) {
name = n+"d"+d;
for(int i = 0; i < n; i++) {
dice.add(new Die(d));
}
}
public Dice(int[] n, int[] d) throws Exception {
if(n.length != d.length) {
throw new Exception("Number of number of dice did not match number of number of dice sizes: "+n+", "+d+".");
}
for(int i = 0; i < n.length; i++) {
name += " + "+n[i]+"d"+d[i];
for(int j = 0; j < n[i]; j++) {
dice.add(new Die(d[i]));
}
}
name = name.substring(name.indexOf(" + "));
}
public Dice(boolean percentageDice) {
this.percentageDice = true;
name = "percentage dice";
dice.add(new Die(10));
}
public int rollDice() {
int roll = 0;
if(percentageDice) {
roll = dice.get(0).roll() * 10;
roll += dice.get(0).roll();
return roll;
} else {
for(Die d : dice) {
roll += d.roll();
}
return roll;
}
}
public String toString() {
return name;
}
}
|
package org.elkoserver.server.context;
import java.security.SecureRandom;
import java.util.concurrent.Callable;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import org.elkoserver.foundation.actor.RefTable;
import org.elkoserver.foundation.json.DispatchTarget;
import org.elkoserver.foundation.json.MessageHandlerException;
import org.elkoserver.foundation.net.Connection;
import org.elkoserver.foundation.server.Server;
import org.elkoserver.foundation.server.ShutdownWatcher;
import org.elkoserver.foundation.server.metadata.HostDesc;
import org.elkoserver.json.JSONArray;
import org.elkoserver.json.JSONDecodingException;
import org.elkoserver.json.JSONLiteral;
import org.elkoserver.json.JSONObject;
import org.elkoserver.json.Parser;
import org.elkoserver.json.Referenceable;
import org.elkoserver.json.SyntaxError;
import org.elkoserver.objdb.ObjDB;
import org.elkoserver.util.ArgRunnable;
import org.elkoserver.util.HashMapMulti;
import org.elkoserver.util.trace.Trace;
/**
* Main state data structure in a Context Server.
*/
public class Contextor extends RefTable {
/** Database that persistent objects are stored in. */
private ObjDB myODB;
/** Trace object for diagnostics. */
private Trace tr;
/** The server object. */
private Server myServer;
/** The generic 'session' object for talking to this server. */
private Session mySession;
/** Sets of entities awaiting objects from the object database, by object
reference string. */
private Map<String, Set<ArgRunnable>> myPendingGets;
/** Open contexts. */
private Set<Context> myContexts;
/** Cloned contexts, by base reference string. */
private HashMapMulti<String, Context> myContextClones;
/** Currently connected users. */
private Set<User> myUsers;
/** Send group for currently connected directors. */
private DirectorGroup myDirectorGroup;
/** Send group for currently connected presence servers. */
private PresencerGroup myPresencerGroup;
/** Time user has to enter before being kicked off, in milliseconds. */
private int myEntryTimeout;
/** Default enter timeout value, in seconds. */
private static final int DEFAULT_ENTER_TIMEOUT = 15;
/** Maximum number of users allowed on this server. */
private int myLimit;
/** Static objects loaded from the ODB and available in all contexts. */
private Map<String, Object> myStaticObjects;
/** Context families served by this server. Names prefixed by '$'
represent restricted contexts. */
private Set<String> myContextFamilies;
/** User names gathered from presence notification metadata. */
private Map<String, String> myUserNames;
/** Context names gathered from presence notification metadata. */
private Map<String, String> myContextNames;
/** Random number generator, for creating unique IDs and sub-IDs. */
static private SecureRandom theRandom = new SecureRandom();
/** Mods on completed objects awaiting notification that they're ready. */
private List<ObjectCompletionWatcher> myPendingObjectCompletionWatchers;
/**
* Constructor.
*
* @param server Server object.
* @param appTrace Trace object for diagnostics.
*/
Contextor(Server server, Trace appTrace) {
this(server.openObjectDatabase("conf.context"), server, appTrace);
}
/**
* Internal constructor.
*
* This constructor exists only because of a Java limitation: it needs to
* create the object database object and then both save it in an instance
* variable AND pass it to the superclass constructor. However, Java
* requires that the first statement in a constructor MUST be a call to
* the superclass constructor or to another constructor of the same class.
* It is possible to create the database and pass it to the superclass
* constructor or to save it in an instance variable, but not both. To get
* around this, the public constructor creates the database object in a
* parameter expression in a call to this internal constructor, which will
* then possess it in a parameter variable whence it can be both passed to
* the superclass constructor and saved in an instance variable.
*
* @param odb Database for persistent object storage.
* @param server Server object.
* @param appTrace Trace object for diagnostics.
*/
private Contextor(ObjDB odb, Server server, Trace appTrace) {
super(odb);
tr = appTrace;
if (odb == null) {
tr.fatalError("no database specified");
}
myODB = odb;
myODB.addClass("context", Context.class);
myODB.addClass("item", Item.class);
myODB.addClass("user", User.class);
myODB.addClass("serverdesc", ServerDesc.class);
myODB.addClass("geopos", GeoPosition.class);
myODB.addClass("cartpos", CartesianPosition.class);
mySession = new Session(this, server);
addRef(mySession);
myServer = server;
server.setServiceRefTable(this);
myEntryTimeout = 1000 *
server.props().intProperty("conf.context.entrytimeout",
DEFAULT_ENTER_TIMEOUT);
myLimit = server.props().intProperty("conf.context.userlimit", 0);
myContexts = new HashSet<Context>();
myContextClones = new HashMapMulti<String, Context>();
myUsers = new HashSet<User>();
myDirectorGroup = null;
myPresencerGroup = null;
myUserNames = new HashMap<String, String>();
myContextNames = new HashMap<String, String>();
myPendingObjectCompletionWatchers = null;
initializeContextFamilies();
myPendingGets = new HashMap<String, Set<ArgRunnable>>();
myStaticObjects = new HashMap<String, Object>();
loadStaticObjects(server.props().getProperty("conf.context.statics"));
server.registerShutdownWatcher(new ShutdownWatcher() {
public void noteShutdown() {
/* List copy to avert ConcurrentModificationException */
List<User> saveUsers = new LinkedList<User>(myUsers);
for (User user : saveUsers) {
user.exitContext("server shutting down", "shutdown",
false);
}
if (myDirectorGroup != null) {
myDirectorGroup.disconnectHosts();
}
if (myPresencerGroup != null) {
myPresencerGroup.disconnectHosts();
}
checkpointAll();
myODB.shutdown();
}
});
}
private void initializeContextFamilies() {
myContextFamilies = new HashSet<String>();
myContextFamilies.add("c");
myContextFamilies.add("ctx");
myContextFamilies.add("context");
myContextFamilies.add("$rc");
myContextFamilies.add("$rctx");
myContextFamilies.add("$rcontext");
String families =
myServer.props().getProperty("conf.context.contexts");
if (families != null) {
StringTokenizer tags = new StringTokenizer(families, " ,;:");
while (tags.hasMoreTokens()) {
myContextFamilies.add(tags.nextToken());
}
}
}
private boolean isValidContextRef(String ref) {
int delim = ref.indexOf('-');
if (delim < 0) {
return false;
} else {
String family = ref.substring(0, delim);
return myContextFamilies.contains(family) ||
myContextFamilies.contains("$" + family);
}
}
/**
* Add to the list of Mods awaiting notification that their objects are
* done.
*
* @param watcher The watching Mod to be notified.
*/
void addPendingObjectCompletionWatcher(ObjectCompletionWatcher watcher) {
if (myPendingObjectCompletionWatchers == null) {
myPendingObjectCompletionWatchers = new LinkedList<>();
}
myPendingObjectCompletionWatchers.add(watcher);
}
/**
* Notify any Mods still awaiting notification that their objects are done.
*
* As a side effect, this will clear the list of who is waiting.
*/
void notifyPendingObjectCompletionWatchers() {
if (myPendingObjectCompletionWatchers != null) {
List<ObjectCompletionWatcher> targets =
myPendingObjectCompletionWatchers;
myPendingObjectCompletionWatchers = null;
for (ObjectCompletionWatcher target : targets) {
target.objectIsComplete();
}
}
}
/**
* Activate an item that is contained by another object as part of its
* being loaded.
*
* @param container The container into which the item is placed.
* @param subID Sub-ID string for cloned objects. This should be an empty
* string if clones are not being generated.
* @param Item Inactive item that is being activated.
*/
void activateContentsItem(BasicObject container, String subID, Item item) {
String ref = item.ref() + subID;
item.activate(ref, subID, container.isEphemeral(), this);
item.setContainerPrim(container);
item.objectIsComplete();
}
/**
* Take note that somebody is waiting for an object from the object
* database.
*
* @param ref Reference string for the object being fetched.
* @param handler Handler to be invoked on result object.
*
* @return true if this is the first pending get for the requested object.
*/
private boolean addPendingGet(String ref, ArgRunnable handler) {
Set<ArgRunnable> handlerSet = myPendingGets.get(ref);
boolean isFirst = false;
if (handlerSet == null) {
handlerSet = new HashSet<ArgRunnable>();
myPendingGets.put(ref, handlerSet);
isFirst = true;
}
handlerSet.add(handler);
return isFirst;
}
/**
* Add an object to the static object table.
*
* @param key Name by which this object will be known within the server
* @param obj The object itself
*/
void addStaticObject(String key, Object obj) {
myStaticObjects.put(key, obj);
if (obj instanceof InternalObject) {
InternalObject internal = (InternalObject) obj;
internal.activate(key, this);
if (internal instanceof AdminObject) {
addRef(internal);
}
}
}
/**
* Obtain the application trace object for this context server.
*
* @return the context server's trace object.
*/
public Trace appTrace() {
return tr;
}
/**
* Save all changed objects that need saving.
*/
void checkpointAll() {
for (DispatchTarget candidate : this) {
if (candidate instanceof BasicObject) {
BasicObject object = (BasicObject) candidate;
object.checkpointWithoutContents();
}
}
}
/**
* Get a read-only view of the collection of context families.
*
* @return the current set of context families.
*/
Set<String> contextFamilies() {
return Collections.unmodifiableSet(myContextFamilies);
}
/**
* Get a read-only view of the context set.
*
* @return the current set of open contexts.
*/
Set<Context> contexts() {
return Collections.unmodifiableSet(myContexts);
}
/**
* Common initialization logic for createItem and createGeoItem.
*/
private void initializeItem(Item item, BasicObject container) {
item.activate(uniqueID("i"), "", false, this);
item.markAsChanged();
item.setContainer(container);
}
/**
* Return a newly minted Item (i.e., one created at runtime rather than
* loaded from the object database). The new item will have no contents,
* no mods, and no position. If it is a container, it will be open.
*
* @param name The name for the new item, or null if the name doesn't
* matter.
* @param container The object that is to be the new item's container.
* @param isPossibleContainer Flag that is true if the new item may itself
* be used as a container.
* @param isDeletable Flag that is true if the new item may be deleted by
* users.
*/
Item createItem(String name, BasicObject container,
boolean isPossibleContainer, boolean isDeletable)
{
Item item =
new Item(name, isPossibleContainer, isDeletable, false, null);
initializeItem(item, container);
return item;
}
/**
* Return a newly minted geo-positioned Item (i.e., one created at runtime
* rather than loaded from the object database). The new item will have
* neither any contents nor any mods.
*
* @param name The name for the new item, or null if the name doesn't
* matter.
* @param container The object that is to be the new item's container.
* @param isPossibleContainer Flag that is true if the new item may itself
* be used as a container.
* @param isDeletable Flag that is true if the new item may be deleted by
* users.
* @param lat Position latitude, in decimal degrees.
* @param lon Position longitude, in decimal degrees.
*/
Item createGeoItem(String name, BasicObject container,
boolean isPossibleContainer, boolean isDeletable,
double lat, double lon)
{
Item item = new Item(name, isPossibleContainer, isDeletable, false,
new GeoPosition(lat, lon));
initializeItem(item, container);
return item;
}
/**
* Return a newly minted Item (i.e., one created at runtime rather than
* loaded from the object database). The new item will be born with no
* contents, no mods, and no container.
*
* @param name The name for the new item, or null if the name doesn't
* matter.
* @param isPossibleContainer Flag that is true if the new item may itself
* be used as a container.
* @param isDeletable Flag that is true if the new item may be deleted by
* users.
*/
public Item createItem(String name, boolean isPossibleContainer,
boolean isDeletable)
{
return createItem(name, null, isPossibleContainer, isDeletable);
}
/**
* Return a newly minted geo-positioned Item (i.e., one created at runtime
* rather than loaded from the object database). The new item will be born
* with no contents, no mods, and no container.
*
* @param name The name for the new item, or null if the name doesn't
* matter.
* @param isPossibleContainer Flag that is true if the new item may itself
* be used as a container.
* @param isDeletable Flag that is true if the new item may be deleted by
* users.
* @param lat Position latitude, in decimal degrees.
* @param lon Position longitude, in decimal degrees.
*/
public Item createGeoItem(String name, boolean isPossibleContainer,
boolean isDeletable, double lat, double lon)
{
return createGeoItem(name, null, isPossibleContainer, isDeletable,
lat, lon);
}
/**
* Create a new (offline) object and store its description in the object
* database.
*
* @param ref Reference string for the new object, or null to have one
* generated automatically.
* @param contRef Reference string for the new object's container, or null
* to not have it put into a container.
* @param obj The new object.
*/
public void createObjectRecord(String ref, String contRef, BasicObject obj)
{
if (ref == null) {
ref = uniqueID(obj.type());
}
myODB.putObject(ref, obj, null, false, null);
}
/**
* Delete a user record from the object database.
*
* @param ref Reference string identifying the user to be deleted.
*/
void deleteUserRecord(String ref) {
myODB.removeObject(ref, null, null);
}
/**
* Deliver a relayed message to an instance of an object.
*
* @param destination Object instance to deliver to.
* @param message The message to deliver.
*/
void deliverMessage(BasicObject destination, JSONObject message) {
try {
dispatchMessage(null, destination, message);
} catch (MessageHandlerException e) {
tr.eventm("ignoring error from internal msg relay: " + e);
}
}
/**
* Return the entry timeout value.
*
* @return the entry timeout interval, in milliseconds.
*/
int entryTimeout() {
return myEntryTimeout;
}
/**
* Extract the base ID from an object reference that might refer to a
* clone.
*
* @param ref The reference to extract from.
*
* @return the base reference string embedded in 'ref', assuming it is a
* clone reference (if it is not a clone reference, 'ref' itself will be
* returned).
*/
static String extractBaseRef(String ref) {
int dash = ref.indexOf('-');
dash = ref.indexOf('-', dash + 1);
if (dash < 0) {
return ref;
} else {
return ref.substring(0, dash);
}
}
/**
* Locate an available clone of some context.
*
* @param ref Base reference of the context sought.
*
* @return a reference to a clone of the context named by 'ref' that has
* room for a new user, or null if 'ref' does not refer to a cloneable
* context or if all the clones are full.
*/
Context findContextClone(String ref) {
for (Context context : myContextClones.getMulti(ref)) {
if (context.userCount() < context.baseCapacity() &&
!context.gateIsClosed()) {
return context;
}
}
return null;
}
/**
* Find or make a connection to an external service.
*
* @param serviceName Name of the service being sought.
* @param handler A runnable that will be invoked with the relevant
* service link once the connection is located or created. The handler
* will be passed a null if no connection was possible.
*/
public void findServiceLink(String serviceName, ArgRunnable handler) {
myServer.findServiceLink("workshop-service-" + serviceName, handler);
}
/**
* Obtain a context, either by obtaining a pointer to an already loaded
* context or, if needed, by loading it.
*
* @param contextRef Reference string identifying the context sought.
* @param contextTemplate Optional reference the template context from
* which the context should be derived.
* @param contextHandler Handler to invoke with resulting context.
* @param opener Director that requested this context be opened, or null
* if not relevant.
*
* @return a Context object that is the requested context, or null if it
* could not be obtained.
*/
void getOrLoadContext(String contextRef, String contextTemplate,
ArgRunnable contextHandler, DirectorActor opener)
{
if (isValidContextRef(contextRef)) {
Context result = findContextClone(contextRef);
if (result == null) {
result = (Context) get(contextRef);
}
if (result == null) {
if (contextTemplate == null) {
contextTemplate = contextRef;
}
ArgRunnable getHandler =
new GetContextHandler(contextTemplate, contextRef, opener);
final ContentsHandler contentsHandler =
new ContentsHandler(null, getHandler);
ArgRunnable contextReceiver = new ArgRunnable() {
public void run(Object obj) {
contentsHandler.receiveContainer((BasicObject) obj);
}
};
if (addPendingGet(contextTemplate, contextHandler)) {
myODB.getObject(contextTemplate, null, contextReceiver);
loadContentsOfContainer(contextRef, contentsHandler);
}
} else {
contextHandler.run(result);
}
} else {
contextHandler.run(null);
}
}
/**
* Thunk class to receive the contents of a container object. When a
* top-level container (i.e., a context or a user) is loaded, we need to
* also load the container's contents, and the contents of the contents,
* and so on. We don't want to signal the top-level container as being
* successfully loaded until all the things that are descended from it are
* also loaded. This class manages that process. Each instance of this
* class represents a container that is being loaded; it tracks the loading
* of its contents and then notifies the container that contains *it*.
*/
private class ContentsHandler implements ArgRunnable {
/** Contents handler for the enclosing container, or null if this is
the top level. */
private ContentsHandler myParentHandler;
/** Number of objects whose loading is being awaited. Initially, this
is the number of contained objects plus two: the container itself,
the array of contents objects, and the contents of each of those
contents objects. It counts down as loading completes. */
private int myWaitCount;
/** The container object this handler is handling the loading of
contents for. Initially, this is null; it acquires a value when
the external entity that actually fetches the container object
calls the receiveContainer() method. */
private BasicObject myContainer;
/** Flag indicating that 'myContainer' has been set. */
private boolean haveContainer;
/** Array of contents objects whose contents this handler is overseeing
the recursive loading of. Initially, this is null; it acquires a
value when the external entity that actually fetches the contents
objects calls the receiveContents() method. */
private Item[] myContents;
/** Flag indicating that 'myContents' has been set. */
private boolean haveContents;
/** Runnable that will be invoked with the root of the entire tree of
contained objects, once all those objects have been successfully
loaded. */
private ArgRunnable myTopHandler;
/**
* Constructor.
*
* @param parentHandler ContentsHandler for the enclosing parent
* container, or null if we are the top level container.
* @param topHandler Thunk to be notified with the complete result once
* it is available.
*/
ContentsHandler(ContentsHandler parentHandler, ArgRunnable topHandler)
{
myParentHandler = parentHandler;
myTopHandler = topHandler;
myWaitCount = 2;
myContents = null;
haveContents = false;
myContainer = null;
haveContainer = false;
}
/**
* Indicate that an additional quantity of objects await being loaded.
*
* @param count The number of additional objects to wait for.
*/
private void expectMore(int count) {
myWaitCount += count;
}
/**
* Indicate that some number of objects have been successfully loaded.
*
* @param count The number of objects that have been loaded (typically
* this will be 1) or -1 to indicate that all objects that are ever
* going to be loaded have been (typically, because an error of some
* kind has terminated loading).
*/
private void somethingArrived(int count) {
if (myWaitCount >= 0) {
if (count < 0) {
myWaitCount = 0;
} else {
myWaitCount -= count;
}
if (myWaitCount == 0) {
if (haveContents && haveContainer) {
if (myContents != null && myContainer != null) {
myContainer.addPassiveContents(myContents);
}
}
myWaitCount = -1;
if (myParentHandler == null) {
myTopHandler.run(myContainer);
} else {
myParentHandler.somethingArrived(1);
}
}
}
}
/**
* Note the arrival of the container object itself.
*
* @param container The container object.
*/
void receiveContainer(BasicObject container) {
myContainer = container;
haveContainer = true;
somethingArrived(1);
}
/**
* Note the arrival of the contents objects themselves.
*
* @param contents Array of contents objects (but not *their*
* contents).
*/
void receiveContents(Item[] contents) {
myContents = contents;
haveContents = true;
somethingArrived(1);
}
/**
* Runnable invoked by the ODB to accept the delivery of stuff fetched
* from the database.
*
* @param obj The thing that was obtained from the database. In the
* current case, this will *always* be an array of objects
* representing the contents of the container object this handler is
* handling.
*/
public void run(Object obj) {
Item[] contents = null;
if (obj != null) {
Object[] rawContents = (Object[]) obj;
if (rawContents.length == 0) {
somethingArrived(-1);
} else {
expectMore(rawContents.length);
contents = new Item[rawContents.length];
for (int i = 0; i < rawContents.length; ++i) {
Item item = (Item) rawContents[i];
contents[i] = item;
if (item.isContainer() && !item.isClosed()) {
ContentsHandler subHandler =
new ContentsHandler(this, myTopHandler);
subHandler.receiveContainer(item);
loadContentsOfContainer(item.ref(), subHandler);
} else {
somethingArrived(1);
}
}
receiveContents(contents);
}
} else {
somethingArrived(-1);
}
}
}
/**
* Fetch the (direct) contents of a container from the repository.
*
* @param containerRef Ref of the container object.
* @param handler Runnable to be invoked with the retrieved objects.
*/
private void loadContentsOfContainer(String containerRef,
ArgRunnable handler)
{
queryObjects(contentsQuery(extractBaseRef(containerRef)), null, 0,
handler);
}
/**
* Generate and return a MongoDB query to fetch an object's contents.
*
* @param ref The ref of the container whose contents are of interest.
*
* @return a JSON object representing the above described query.
*/
static JSONObject contentsQuery(String ref) {
// { type: "item", in: REF }
JSONObject query = new JSONObject();
query.addProperty("type", "item");
query.addProperty("in", ref);
return query;
}
/**
* Thunk class to receive a context object fetched from the database. At
* the point this is invoked, the context and all of its contents are
* loaded but not activated.
*/
private class GetContextHandler implements ArgRunnable {
/** The ref of the context template. This is the ref of the object
that is loaded from the database.*/
private String myContextTemplate;
/** The ref of the context itself. This is the base ref of the context
that actually results. It will be the same as the template ref if
the context is not actually templated. */
private String myContextRef;
/** The director that requested this context to be activated. */
private DirectorActor myOpener;
/**
* Constructor
*
* @param contextTemplate The ref of the context template.
* @param contextRef The ref of the context itself.
* @param opener The director who requested the context activation.
*/
GetContextHandler(String contextTemplate, String contextRef,
DirectorActor opener)
{
myContextTemplate = contextTemplate;
myContextRef = contextRef;
myOpener = opener;
}
/**
* Callback that will be invoked when the context is loaded.
*
* @param obj The object that was fetched. This will be a Context
* object with a fully expanded (but unactivated) contents tree.
*/
public void run(Object obj) {
Context context = null;
if (obj instanceof Context) {
context = (Context) obj;
}
if (context != null) {
boolean spawningTemplate =
!myContextRef.equals(myContextTemplate);
boolean spawningClone = context.baseCapacity() > 0;
if (!spawningTemplate && context.isMandatoryTemplate()) {
tr.errorm("context '" + myContextRef +
"' may only be used as a template");
context = null;
} else if (!spawningTemplate ||
context.isAllowableTemplate()) {
String subID = "";
if (spawningClone || spawningTemplate) {
subID = uniqueID("");
}
if (spawningClone) {
myContextRef += subID;
}
context.activate(myContextRef, subID,
!myContextRef.equals(myContextTemplate),
Contextor.this, myContextTemplate,
myOpener, tr);
context.objectIsComplete();
notifyPendingObjectCompletionWatchers();
} else {
tr.errorm("context '" + myContextTemplate +
"' may not be used as a template");
context = null;
}
}
if (context == null) {
tr.errorm("unable to load context '" + myContextTemplate +
"' as '" + myContextRef + "'");
resolvePendingGet(myContextTemplate, null);
} else if (context.isReady()) {
resolvePendingGet(myContextTemplate, context);
}
}
}
void resolvePendingInit(BasicObject obj) {
if (obj.isReady()) {
resolvePendingGet(obj.baseRef(), obj);
}
}
/**
* Obtain an item, either by obtaining a pointer to an already loaded item
* or, if needed, by loading it.
*
* @param itemRef Reference string identifying the item sought.
* @param itemHandler Handler to invoke with the resulting item.
*
* @return a Item object that is the requested item, or null if it could
* not be obtained.
*/
void getOrLoadItem(String itemRef, ArgRunnable itemHandler) {
if (itemRef.startsWith("item-") || itemRef.startsWith("i-")) {
Item result = (Item) get(itemRef);
if (result == null) {
if (addPendingGet(itemRef, itemHandler)) {
myODB.getObject(itemRef, null,
new GetItemHandler(itemRef));
}
} else {
itemHandler.run(result);
}
} else {
itemHandler.run(null);
}
}
private class GetItemHandler implements ArgRunnable {
private String myItemRef;
GetItemHandler(String itemRef) {
myItemRef = itemRef;
}
public void run(Object obj) {
Item item = null;
if (obj != null) {
item = (Item) obj;
item.activate(myItemRef, "", false, Contextor.this);
item.objectIsComplete();
}
if (item.isReady()) {
resolvePendingGet(myItemRef, item);
}
}
}
/**
* Lookup an object in the static object table.
*
* @param ref Reference string denoting the object of interest.
*
* @return the object named 'ref' from the static object table, or null if
* there is no such object.
*/
public Object getStaticObject(String ref) {
return myStaticObjects.get(ref);
}
/**
* Return the limit on how many users are allowed to connect to this
* server.
*/
int limit() {
return myLimit;
}
/**
* Load the contents of a previously closed container.
*
* @param item The item whose contents are to be loaded.
* @param handler Handler to be notified once the contents are laoded.
*/
void loadItemContents(Item item, ArgRunnable handler) {
ContentsHandler contentsHandler = new ContentsHandler(null, handler);
contentsHandler.receiveContainer(item);
loadContentsOfContainer(item.ref(), contentsHandler);
}
/**
* Load the static objects indicated by one or more static object list
* objects.
*
* @param staticListRefs A comma separated list of statis object list
* object names.
*/
private void loadStaticObjects(String staticListRefs) {
myODB.addClass("statics", StaticObjectList.class);
myODB.getObject("statics", null,
new StaticObjectListReceiver("statics"));
if (staticListRefs != null) {
StringTokenizer tags = new StringTokenizer(staticListRefs, " ,;:");
while (tags.hasMoreTokens()) {
String tag = tags.nextToken();
myODB.getObject(tag, null, new StaticObjectListReceiver(tag));
}
}
}
private class StaticObjectListReceiver implements ArgRunnable {
String myTag;
StaticObjectListReceiver(String tag) {
myTag = tag;
}
public void run(Object obj) {
StaticObjectList statics = (StaticObjectList) obj;
if (statics != null) {
tr.eventi("loading static object list '" + myTag + "'");
statics.fetchFromODB(myODB, Contextor.this, tr);
} else {
tr.errori("unable to load static object list '" + myTag + "'");
}
}
}
/**
* Lookup a User object in the object database.
*
* @param userRef Reference string identifying the user sought.
* @param scope Application scope for filtering mods
* @param userHandler Handler to invoke with the resulting user object or
* with null if the user object could not be obtained.
*/
void loadUser(final String userRef, String scope,
ArgRunnable userHandler)
{
if (userRef.startsWith("user-") || userRef.startsWith("u-")) {
if (scope != null) {
userHandler = new ScopedModAttacher(scope, userHandler);
}
ArgRunnable getHandler = new ArgRunnable() {
public void run(Object obj) {
resolvePendingGet(userRef, obj);
}
};
final ContentsHandler contentsHandler =
new ContentsHandler(null, getHandler);
ArgRunnable userReceiver = new ArgRunnable() {
public void run(Object obj) {
contentsHandler.receiveContainer((BasicObject) obj);
}
};
if (addPendingGet(userRef, userHandler)) {
myODB.getObject(userRef, null, userReceiver);
loadContentsOfContainer(userRef, contentsHandler);
}
} else {
userHandler.run(null);
}
}
/**
* Generate and return a MongoDB query to fetch an object's non-embedded,
* application-scoped mods. These mods are stored in the ODB as
* independent objects. Such a mod is identified by a "refx" property and
* a "scope" property. The "refx" property corresponds to the ref of the
* object the mod should be attached to. The "scope" property matches if
* its value is a path prefix match for the query's scope parameter. For
* example,
*
* scopeQuery("foo", "com-example-thing")
*
* would translate to the query pattern:
*
* { refx: "foo",
* $or: [
* { scope: "com" },
* { scope: "com-example" },
* { scope: "com-example-thing" }
* ]
* }
*
* Note that in the future we may decide (based on what's actually the most
* efficient in the underlying database) to replace the "$or" in the query
* with a regex property match or some other way of fetching based on a
* path prefix, so don't take the above expansion as the literal final
* word.
*
* @param ref The ref of the object in question.
* @param scope The application scope
*
* @return a JSON object representing the above described query.
*/
static JSONObject scopeQuery(String ref, String scope) {
JSONArray orList = new JSONArray();
String[] frags = scope.split("-");
String scopePart = null;
for (String frag : frags) {
if (scopePart == null) {
scopePart = frag;
} else {
scopePart += '-' + frag;
}
JSONObject orTerm = new JSONObject();
orTerm.addProperty("scope", scopePart);
orList.add(orTerm);
}
JSONObject query = new JSONObject();
query.addProperty("refx", ref);
query.addProperty("$or", orList);
return query;
}
/**
* Thunk to intercept the return of a basic object from the database,
* generate a query to fetch that object's application-scoped mods, and
* attach those mods to the object before passing the object to whoever
* actually asked for it originally.
*/
private class ScopedModAttacher implements ArgRunnable {
private String myScope;
private ArgRunnable myOuterHandler;
private BasicObject myObj;
/**
* Constructor.
*
* @param scope The application scope to be queried against.
* @param outerHandler The original handler to which the modified
* object should be passed.
*/
ScopedModAttacher(String scope, ArgRunnable outerHandler) {
myScope = scope;
myOuterHandler = outerHandler;
myObj = null;
}
/**
* Callback that will receive the scoped mod query results.
*
* In normal operation, this will end up getting invoked twice.
*
* The first time this is called, the arg will be a BasicObject. This
* will be the object that was originally requested. If it is null,
* then the original query failed and the null will be passed to the
* outer handler and our work here is done (albeit in a failure state).
* Otherwise, the ref of the object combined with the scope passed to
* our constructor are used to form a query to fetch the object's
* scoped mods.
*
* The second time this is called, the arg will be an array of Mod
* objects (though it may be null or an empty array, which means that
* the set of mods is empty). These mods (if there are any) are
* attached to the object from the first callback and then the object
* is passed to the outer handler.
*
* @param arg The object or objects fetched from the database, per
* the above description.
*/
public void run(Object arg) {
if (myObj == null) {
if (arg == null) {
myOuterHandler.run(null);
} else {
myObj = (BasicObject) arg;
queryObjects(scopeQuery(myObj.ref(), myScope), null, 0,
this);
}
} else {
if (arg != null) {
Object[] rawMods = (Object[]) arg;
for (Object rawMod : rawMods) {
myObj.attachMod((Mod) rawMod);
}
}
myOuterHandler.run(myObj);
}
}
}
/**
* Lookup a reservation.
*
* @param who Whose reservation?
* @param where For where?
* @param authCode The alleged authCode.
*
* @return the requested reservation if there is one, or null if not.
*/
Reservation lookupReservation(String who, String where, String authCode) {
return myDirectorGroup.lookupReservation(who, where, authCode);
}
/**
* Do record keeping associated with tracking the set of open contexts:
* tell the directors that a context has been opened or closed and update
* the context clone collection.
*
* @param context The context.
* @param open true if opened, false if closed.
*/
void noteContext(Context context, boolean open) {
if (open) {
myContexts.add(context);
if (context.baseCapacity() > 0) {
myContextClones.add(context.baseRef(), context);
}
} else {
myContexts.remove(context);
if (context.baseCapacity() > 0) {
myContextClones.remove(context.baseRef(), context);
}
}
if (myDirectorGroup != null) {
myDirectorGroup.noteContext(context, open);
}
if (myPresencerGroup != null) {
myPresencerGroup.noteContext(context, open);
}
}
/**
* Tell the directors that a context gate has been opened or closed.
*
* @param context The context whose gate is being opened or closed
* @param open Flag indicating open or closed
* @param reason Reason for closing the gate
*/
void noteContextGate(Context context, boolean open, String reason) {
if (myDirectorGroup != null) {
myDirectorGroup.noteContextGate(context, open, reason);
}
}
/**
* Tell the directors that a user has come or gone.
*
* @param user The user.
* @param on true if now online, false if now offline.
*/
void noteUser(User user, boolean on) {
if (on) {
myUsers.add(user);
} else {
myUsers.remove(user);
}
if (myDirectorGroup != null) {
myDirectorGroup.noteUser(user, on);
}
if (myPresencerGroup != null) {
myPresencerGroup.noteUser(user, on);
}
}
/**
* Take notice for someone that a user elsewhere has come or gone.
*
* @param contextRef Ref of context of user who cares
* @param observerRef Ref of user who cares
* @param domain Presence domain of relationship between observer & who
* @param whoRef Ref of user who came or went
* @param whoMeta Optional metatdata about user who came or went
* @param whereRef Ref of the context entered or exited
* @param whereMeta Optional metadata about the context entered or exited
* @param on True if they came, false if they left
*/
void observePresenceChange(String contextRef, String observerRef,
String domain, String whoRef,
JSONObject whoMeta, String whereRef,
JSONObject whereMeta, boolean on)
{
if (whoMeta != null) {
try {
String name = whoMeta.getString("name");
myUserNames.put(whoRef, name);
} catch (JSONDecodingException e) {
}
}
if (whereMeta != null) {
try {
String name = whereMeta.getString("name");
myContextNames.put(whereRef, name);
} catch (JSONDecodingException e) {
}
}
Context subscriber = (Context) get(contextRef);
if (subscriber != null) {
subscriber.observePresenceChange(observerRef, domain, whoRef,
whereRef, on);
} else {
tr.warningi("presence change of " + whoRef +
(on ? " entering " : " exiting ") + whereRef +
" for " + observerRef +
" directed to unknown context " + contextRef);
}
}
/**
* Obtain the name metadata for a context, as most recently reported by the
* presence server.
*
* @param contextRef The context for which the name metadata is sought.
*
* @return the name for the given context, or null if none has ever been
* reported.
*/
public String getMetadataContextName(String contextRef) {
return myContextNames.get(contextRef);
}
/**
* Obtain the name metadata for a user, as most recently reported by the
* presence server.
*
* @param userRef The user for whom metadata is sought.
*
* @return the name for the given user, or null if none has ever been
* reported.
*/
public String getMetadataUserName(String userRef) {
return myUserNames.get(userRef);
}
/**
* Return a reference to the attached object store.
*
* XXX Is this a POLA violation??
*/
public ObjDB odb() {
return myODB;
}
/**
* Push a user to a different context: obtain a reservation for the new
* context, send it to the user, and then kick them out. If we're not
* using a director, just send them directly without a reservation.
*
* @param who The user being pushed
* @param contextRef The ref of the context to push them to.
*/
void pushNewContext(User who, String contextRef) {
if (myDirectorGroup != null) {
myDirectorGroup.pushNewContext(who, contextRef);
} else {
who.exitWithContextChange(contextRef, null, null);
}
}
/**
* Query the attached object store.
*
* @param template Query template indicating the object(s) desired.
* @param collectionName Name of collection to query, or null to take the
* configured default.
* @param maxResults Maximum number of result objects to return, or 0 to
* indicate no fixed limit.
* @param handler Handler to be called with the results. The results will
* be an array of the object(s) requested, or null if no objects could
* be retrieved.
*
* XXX Is this a POLA violation??
*/
public void queryObjects(JSONObject template, String collectionName,
int maxResults, ArgRunnable handler) {
myODB.queryObjects(template, collectionName, maxResults, handler);
}
/**
* Generate a high-quality random number.
*
* @return a random long.
*/
public long randomLong() {
return theRandom.nextLong();
}
/**
* Register this server's list of listeners with its list of directors.
*
* @param directors List of HostDesc objects describing directors with
* whom to register.
* @param listeners List of HostDesc objects describing active
* listeners to register with the indicated directors.
*/
void registerWithDirectors(List<HostDesc> directors,
List<HostDesc> listeners)
{
DirectorGroup group =
new DirectorGroup(myServer, this, directors, listeners, tr);
if (group.isLive()) {
myDirectorGroup = group;
}
}
/**
* Register this server with its list of presence servers.
*
* @param presencers List of HostDesc objects describing presence servers
* with whom to register.
*/
void registerWithPresencers(List<HostDesc> presencers)
{
PresencerGroup group =
new PresencerGroup(myServer, this, presencers, tr);
if (group.isLive()) {
myPresencerGroup = group;
}
}
/**
* Reinitialize the server.
*/
void reinitServer() {
myServer.reinit();
}
/**
* Relay a message from an object to its clones.
*
* @param source Object that is sending the message.
* @param message The message itself.
*/
void relay(BasicObject source, JSONLiteral message) {
if (source.isClone()) {
String baseRef = source.baseRef();
String contextRef = null;
String userRef = null;
if (source instanceof Context) {
contextRef = baseRef;
} else if (source instanceof User) {
userRef = baseRef;
} else {
throw new Error("relay from inappropriate object");
}
JSONObject msgObject = null;
for (DispatchTarget target : clones(baseRef)) {
BasicObject obj = (BasicObject) target;
if (obj != source) {
if (msgObject == null) {
/* Generating the text form of the message and then
parsing it internally may seem like a ludicrously
inefficient way to do this, but it saves a vast
amount of complication that would otherwise result
if internal message relay had to be treated as a
special case. Note that the expensive operations
are conditional inside the loop, so that if there is
no local relaying to do, no parsing is done, and it
is only ever done once in any case. If this
actually turns out to be a performance issue in
practice (unlikely, IMHO), this can be revisited. */
try {
msgObject =
new Parser(message.sendableString()).
parseObjectLiteral();
} catch (SyntaxError e) {
tr.errorm(
"syntax error in internal JSON message: " +
e.getMessage());
break;
}
}
deliverMessage(obj, msgObject);
}
}
if (myDirectorGroup != null) {
myDirectorGroup.relay(baseRef, contextRef, userRef, message);
}
}
}
/**
* Remove an object and all of its contents (recursively) from the table.
*
* @param object The object to remove.
*/
void remove(BasicObject object) {
for (Item item : object.contents()) {
remove(item);
}
super.remove(object);
}
/**
* Inform everybody who has been waiting for an object from the object
* database that the object is here.
*
* @param ref The reference string for the object that arrived.
* @param obj The object itself, or null if it could not be obtained.
*/
private void resolvePendingGet(String ref, Object obj) {
ref = extractBaseRef(ref);
Set<ArgRunnable> handlerSet = myPendingGets.get(ref);
if (handlerSet != null) {
myPendingGets.remove(ref);
for (ArgRunnable handler : handlerSet) {
handler.run(obj);
}
}
}
/**
* Obtain the server object for this Context Server.
*
* @return this Context Server's server object.
*/
public Server server() {
return myServer;
}
/**
* Get the server name.
*
* @return the server's name.
*/
String serverName() {
return myServer.serverName();
}
/**
* @return the session object for this server.
*/
Session session() {
return mySession;
}
/**
* Convert an array of Items into the contents of a container. This
* routine does not fiddle with the changed flags and is for use during
* object construction only.
*
* @param container The container into which the items are being placed.
* @param subID Sub-ID string for cloned objects. This should be an empty
* string if clones are not being generated.
* @param contents Array of inactive items to be added to the container.
*/
void setContents(BasicObject container, String subID, Item contents[]) {
if (contents != null) {
for (Item item : contents) {
if (item != null) {
activateContentsItem(container, subID, item);
}
}
}
}
/**
* Cause the server to be shutdown.
*
* @param kill If true, shutdown immediately instead of cleaning up.
*/
void shutdownServer(boolean kill) {
myServer.shutdown(kill);
}
/**
* Synthesize a User object by having a factory object (from the static
* object table) produce it.
*
* @param connection The connection over which the new user presented
* themself.
* @param factoryTag Tag identifying the factory to use
* @param param Arbitrary parameter object, which should be consistent
* with the factory indicated by 'factoryTag'
* @param contextRef Ref of context the new synthesized user will be
* placed into
* @param contextTemplate Ref of the context template for the context
* @param scope Application scope for filtering mods
* @param userHandler Handler to invoke with the resulting user object or
* with null if the user object could not be produced.
*/
void synthesizeUser(Connection connection, String factoryTag,
final JSONObject param, final String contextRef,
final String contextTemplate, String scope,
ArgRunnable userHandler)
{
Object rawFactory = getStaticObject(factoryTag);
if (rawFactory == null) {
tr.errori("user factory '" + factoryTag + "' not found");
userHandler.run(null);
} else if (rawFactory instanceof EphemeralUserFactory) {
EphemeralUserFactory factory = (EphemeralUserFactory) rawFactory;
User user = factory.provideUser(this, connection, param,
contextRef, contextTemplate);
user.markAsEphemeral();
userHandler.run(user);
} else if (rawFactory instanceof UserFactory) {
UserFactory factory = (UserFactory) rawFactory;
factory.provideUser(this, connection, param, userHandler);
} else {
tr.errori("factory tag '" + factoryTag +
"' does not designate a user factory object");
userHandler.run(null);
}
}
/**
* Generate a unique object ID.
*
* @param root
*
* @return a reference string for a new object with the given root.
*/
public String uniqueID(String root) {
return root + '-' + Math.abs(theRandom.nextLong());
}
/**
* Get the current number of users.
*
* @return the number of users currently in all contexts.
*/
int userCount() {
return myUsers.size();
}
/**
* Get a read-only view of the user set.
*
* @return the current set of open users.
*/
Set<User> users() {
return Collections.unmodifiableSet(myUsers);
}
/**
* Record an object deletion in the object database.
*
* @param ref Reference string designating the deleted object.
*/
void writeObjectDelete(String ref) {
writeObjectDelete(ref, null);
}
/**
* Record an object deletion in the object database, with completion
* handler.
*
* @param ref Reference string designating the deleted object.
* @param handler Completion handler.
*/
void writeObjectDelete(String ref, ArgRunnable handler) {
myODB.removeObject(ref, null, handler);
}
/**
* Write an object's state to the object database.
*
* @param ref Reference string of the object to write.
* @param state The object state to be written.
*/
void writeObjectState(String ref, BasicObject state) {
writeObjectState(ref, state, null);
}
/**
* Write an object's state to the object database, with completion handler.
*
* @param ref Reference string of the object to write.
* @param state The object state to be written.
* @param handler Completion handler
*/
void writeObjectState(String ref, BasicObject state, ArgRunnable handler) {
myODB.putObject(ref, state, null, false, handler);
}
}
|
package com.exedio.cope.lib;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
abstract class Database
{
private final List tables = new ArrayList();
private final HashMap uniqueConstraintsByID = new HashMap();
private final HashMap itemColumnsByIntegrityConstraintName = new HashMap();
private boolean buildStage = true;
private final boolean useDefineColumnTypes;
private final ConnectionPool connectionPool;
protected Database(final Properties properties)
{
this.useDefineColumnTypes = this instanceof DatabaseColumnTypesDefinable;
this.connectionPool = new ConnectionPool(properties);
//System.out.println("using database "+getClass());
}
final void addTable(final Table table)
{
if(!buildStage)
throw new RuntimeException();
tables.add(table);
}
final void addUniqueConstraint(final String constraintID, final UniqueConstraint constraint)
{
if(!buildStage)
throw new RuntimeException();
final Object collision = uniqueConstraintsByID.put(constraintID, constraint);
if(collision!=null)
throw new RuntimeException("ambiguous unique constraint "+constraint+" trimmed to >"+constraintID+"< colliding with "+collision);
}
final void addIntegrityConstraint(final ItemColumn column)
{
if(!buildStage)
throw new RuntimeException();
if(itemColumnsByIntegrityConstraintName.put(column.integrityConstraintName, column)!=null)
throw new RuntimeException("there is more than one integrity constraint with name "+column.integrityConstraintName);
}
protected final List getTables()
{
return tables;
}
protected final Statement createStatement()
{
return new Statement(useDefineColumnTypes);
}
//private static int createTableTime = 0, dropTableTime = 0, checkEmptyTableTime = 0;
void createDatabase()
{
buildStage = false;
//final long time = System.currentTimeMillis();
for(Iterator i = tables.iterator(); i.hasNext(); )
createTable((Table)i.next());
for(Iterator i = tables.iterator(); i.hasNext(); )
createForeignKeyConstraints((Table)i.next());
//final long amount = (System.currentTimeMillis()-time);
//createTableTime += amount;
//System.out.println("CREATE TABLES "+amount+"ms accumulated "+createTableTime);
}
//private static int checkTableTime = 0;
void checkDatabase()
{
buildStage = false;
//final long time = System.currentTimeMillis();
final Statement bf = createStatement();
bf.append("select count(*) from ").defineColumnInteger();
boolean first = true;
for(Iterator i = tables.iterator(); i.hasNext(); )
{
if(first)
first = false;
else
bf.append(',');
final Table table = (Table)i.next();
bf.append(table.protectedID);
}
final Long testDate = new Long(System.currentTimeMillis());
bf.append(" where ");
first = true;
for(Iterator i = tables.iterator(); i.hasNext(); )
{
if(first)
first = false;
else
bf.append(" and ");
final Table table = (Table)i.next();
final Column primaryKey = table.getPrimaryKey();
bf.append(table.protectedID).
append('.').
append(primaryKey.protectedID).
append('=').
append(Type.NOT_A_PK);
for(Iterator j = table.getColumns().iterator(); j.hasNext(); )
{
final Column column = (Column)j.next();
bf.append(" and ").
append(table.protectedID).
append('.').
append(column.protectedID).
append('=');
if(column instanceof IntegerColumn)
bf.appendValue(column, ((IntegerColumn)column).longInsteadOfInt ? (Number)new Long(1) : new Integer(1));
else if(column instanceof DoubleColumn)
bf.appendValue(column, new Double(2.2));
else if(column instanceof StringColumn)
bf.appendValue(column, "z");
else if(column instanceof TimestampColumn)
bf.appendValue(column, testDate);
else
throw new RuntimeException(column.toString());
}
}
//System.out.println("checkDatabase:"+bf.toString());
executeSQLQuery(bf,
new ResultSetHandler()
{
public void run(final ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new RuntimeException();
}
},
false
);
//final long amount = (System.currentTimeMillis()-time);
//checkTableTime += amount;
//System.out.println("CHECK TABLES "+amount+"ms accumulated "+checkTableTime);
}
void dropDatabase()
{
buildStage = false;
//final long time = System.currentTimeMillis();
// must delete in reverse order, to obey integrity constraints
for(ListIterator i = tables.listIterator(tables.size()); i.hasPrevious(); )
dropForeignKeyConstraints((Table)i.previous());
for(ListIterator i = tables.listIterator(tables.size()); i.hasPrevious(); )
dropTable((Table)i.previous());
//final long amount = (System.currentTimeMillis()-time);
//dropTableTime += amount;
//System.out.println("DROP TABLES "+amount+"ms accumulated "+dropTableTime);
}
void tearDownDatabase()
{
buildStage = false;
System.err.println("TEAR DOWN ALL DATABASE");
for(Iterator i = tables.iterator(); i.hasNext(); )
{
try
{
final Table table = (Table)i.next();
System.err.print("DROPPING FOREIGN KEY CONSTRAINTS "+table+"... ");
dropForeignKeyConstraints(table);
System.err.println("done.");
}
catch(NestingRuntimeException e2)
{
System.err.println("failed:"+e2.getMessage());
}
}
for(Iterator i = tables.iterator(); i.hasNext(); )
{
try
{
final Table table = (Table)i.next();
System.err.print("DROPPING TABLE "+table+" ... ");
dropTable(table);
System.err.println("done.");
}
catch(NestingRuntimeException e2)
{
System.err.println("failed:"+e2.getMessage());
}
}
}
void checkEmptyDatabase()
{
buildStage = false;
//final long time = System.currentTimeMillis();
for(Iterator i = tables.iterator(); i.hasNext(); )
{
final Table table = (Table)i.next();
final int count = countTable(table);
if(count>0)
throw new RuntimeException("there are "+count+" items left for table "+table.id);
}
//final long amount = (System.currentTimeMillis()-time);
//checkEmptyTableTime += amount;
//System.out.println("CHECK EMPTY TABLES "+amount+"ms accumulated "+checkEmptyTableTime);
}
final ArrayList search(final Query query)
{
buildStage = false;
final Statement bf = createStatement();
bf.append("select ");
final Selectable[] selectables = query.selectables;
final Column[] selectColumns = new Column[selectables.length];
final Type[] selectTypes = new Type[selectables.length];
for(int selectableIndex = 0; selectableIndex<selectables.length; selectableIndex++)
{
final Selectable selectable = selectables[selectableIndex];
final Column selectColumn;
final Type selectType;
final Table selectTable;
final Column selectPrimaryKey;
if(selectable instanceof Function)
{
final Function selectAttribute = (Function)selectable;
selectType = selectAttribute.getType();
if(selectableIndex>0)
bf.append(',');
if(selectable instanceof ObjectAttribute)
{
selectColumn = ((ObjectAttribute)selectAttribute).getMainColumn();
selectTable = selectColumn.table;
selectPrimaryKey = selectTable.getPrimaryKey();
bf.append(selectColumn.table.protectedID).
append('.').
append(selectColumn.protectedID).defineColumn(selectColumn);
}
else
{
selectColumn = null;
final ComputedFunction computedFunction = (ComputedFunction)selectable;
bf.append(computedFunction).defineColumn(computedFunction);
}
}
else
{
selectType = (Type)selectable;
selectTable = selectType.getTable();
selectPrimaryKey = selectTable.getPrimaryKey();
selectColumn = selectPrimaryKey;
if(selectableIndex>0)
bf.append(',');
bf.append(selectColumn.table.protectedID).
append('.').
append(selectColumn.protectedID).defineColumn(selectColumn);
if(selectColumn.primaryKey)
{
final StringColumn selectTypeColumn = selectColumn.getTypeColumn();
if(selectTypeColumn!=null)
{
bf.append(',').
append(selectTable.protectedID).
append('.').
append(selectTypeColumn.protectedID).defineColumn(selectTypeColumn);
}
else
selectTypes[selectableIndex] = selectType;
}
else
selectTypes[selectableIndex] = selectType;
}
selectColumns[selectableIndex] = selectColumn;
}
bf.append(" from ").
append(query.type.getTable().protectedID);
final ArrayList queryJoins = query.joins;
if(queryJoins!=null)
{
for(Iterator i = queryJoins.iterator(); i.hasNext(); )
{
final Join join = (Join)i.next();
if("com.exedio.cope.lib.HsqldbDatabase".equals(getClass().getName()) &&
join.getKind()==Join.KIND_OUTER_RIGHT)
throw new RuntimeException("hsqldb not support right outer joins");
bf.append(' ').
append(join.getKindString()).
append(" join ").
append(join.type.getTable().protectedID).
append(" on ");
join.condition.appendStatement(bf);
}
}
if(query.condition!=null)
{
bf.append(" where ");
query.condition.appendStatement(bf);
}
boolean firstOrderBy = true;
if(query.orderBy!=null || query.deterministicOrder)
bf.append(" order by ");
if(query.orderBy!=null)
{
firstOrderBy = false;
bf.append(query.orderBy);
if(!query.orderAscending)
bf.append(" desc");
}
if(query.deterministicOrder)
{
if(!firstOrderBy)
bf.append(',');
final Table deterministicOrderTable = query.type.getTable();
bf.append("abs(").
append(deterministicOrderTable.protectedID).
append('.').
append(deterministicOrderTable.getPrimaryKey().protectedID).
append("*4+1)");
}
//System.out.println("searching "+bf.toString());
final SearchResultSetHandler handler =
new SearchResultSetHandler(query.start, query.count, selectables, selectColumns, selectTypes, query.model);
query.statementInfo = executeSQLQuery(bf, handler, query.makeStatementInfo);
return handler.result;
}
private static class SearchResultSetHandler implements ResultSetHandler
{
private final int start;
private final int count;
private final Selectable[] selectables;
private final Column[] selectColumns;
private final Type[] types;
private final Model model;
private final ArrayList result = new ArrayList();
SearchResultSetHandler(
final int start, final int count,
final Selectable[] selectables, final Column[] selectColumns, final Type[] types,
final Model model)
{
this.start = start;
this.count = count;
this.selectables = selectables;
this.selectColumns = selectColumns;
this.types = types;
this.model = model;
if(start<0)
throw new RuntimeException();
if(selectables.length!=selectColumns.length)
throw new RuntimeException();
if(selectables.length!=types.length)
throw new RuntimeException();
}
public void run(final ResultSet resultSet) throws SQLException
{
if(start>0)
{
// TODO: ResultSet.relative
// Would like to use
// resultSet.relative(start+1);
// but this throws a java.sql.SQLException:
// Invalid operation for forward only resultset : relative
for(int i = start; i>0; i
resultSet.next();
}
int i = (count>=0 ? count : Integer.MAX_VALUE);
while(resultSet.next() && (--i)>=0)
{
int columnIndex = 1;
final Object[] resultRow = (selectables.length > 1) ? new Object[selectables.length] : null;
for(int selectableIndex = 0; selectableIndex<selectables.length; selectableIndex++)
{
final Selectable selectable = selectables[selectableIndex];
final Object resultCell;
if(selectable instanceof ObjectAttribute)
{
final Object selectValue = selectColumns[selectableIndex].load(resultSet, columnIndex++);
final ObjectAttribute selectAttribute = (ObjectAttribute)selectable;
resultCell = selectAttribute.cacheToSurface(selectValue);
}
else if(selectable instanceof ComputedFunction)
{
final ComputedFunction selectFunction = (ComputedFunction)selectable;
resultCell = selectFunction.load(resultSet, columnIndex++);
}
else
{
final Number pk = (Number)resultSet.getObject(columnIndex++);
//System.out.println("pk:"+pk);
if(pk==null)
{
// can happen when using right outer joins
resultCell = null;
}
else
{
final Type type = types[selectableIndex];
final Type currentType;
if(type==null)
{
final String typeID = resultSet.getString(columnIndex++);
currentType = model.findTypeByID(typeID);
if(currentType==null)
throw new RuntimeException("no type with type id "+typeID);
}
else
currentType = type;
resultCell = currentType.getItem(pk.intValue());
}
}
if(resultRow!=null)
resultRow[selectableIndex] = resultCell;
else
result.add(resultCell);
}
if(resultRow!=null)
result.add(Collections.unmodifiableList(Arrays.asList(resultRow)));
}
}
}
void load(final Row row)
{
buildStage = false;
final Statement bf = createStatement();
bf.append("select ");
boolean first = true;
for(Type type = row.type; type!=null; type = type.getSupertype())
{
final Table table = type.getTable();
final List columns = table.getColumns();
for(Iterator i = columns.iterator(); i.hasNext(); )
{
if(first)
first = false;
else
bf.append(',');
final Column column = (Column)i.next();
bf.append(table.protectedID).
append('.').
append(column.protectedID).defineColumn(column);
}
}
bf.append(" from ");
first = true;
for(Type type = row.type; type!=null; type = type.getSupertype())
{
if(first)
first = false;
else
bf.append(',');
bf.append(type.getTable().protectedID);
}
bf.append(" where ");
first = true;
for(Type type = row.type; type!=null; type = type.getSupertype())
{
if(first)
first = false;
else
bf.append(" and ");
final Table table = type.getTable();
bf.append(table.protectedID).
append('.').
append(table.getPrimaryKey().protectedID).
append('=').
append(row.pk);
}
//System.out.println("loading "+bf.toString());
executeSQLQuery(bf, new LoadResultSetHandler(row), false);
}
private static class LoadResultSetHandler implements ResultSetHandler
{
private final Row row;
LoadResultSetHandler(final Row row)
{
this.row = row;
}
public void run(ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new RuntimeException("no such pk"); // TODO use a dedicated runtime exception
int columnIndex = 1;
for(Type type = row.type; type!=null; type = type.getSupertype())
{
for(Iterator i = type.getTable().getColumns().iterator(); i.hasNext(); )
((Column)i.next()).load(resultSet, columnIndex++, row);
}
return;
}
}
boolean check(final Type type, final int pk)
{
buildStage = false;
final Statement bf = createStatement();
final Table table = type.getTable();
final Column primaryKey = table.getPrimaryKey();
final String tableProtectedID = table.protectedID;
final String primaryKeyProtectedID = primaryKey.protectedID;
bf.append("select ").
append(tableProtectedID).
append('.').
append(primaryKeyProtectedID).defineColumnInteger().
append(" from ").
append(tableProtectedID).
append(" where ").
append(tableProtectedID).
append('.').
append(primaryKeyProtectedID).
append('=').
append(pk);
//System.out.println("loading "+bf.toString());
final CheckResultSetHandler handler = new CheckResultSetHandler();
executeSQLQuery(bf, handler, false);
return handler.result;
}
private static class CheckResultSetHandler implements ResultSetHandler
{
private boolean result = false;
public void run(ResultSet resultSet) throws SQLException
{
result = resultSet.next();
}
}
void store(final Row row)
throws UniqueViolationException
{
store(row, row.type);
}
private void store(final Row row, final Type type)
throws UniqueViolationException
{
buildStage = false;
final Type supertype = type.getSupertype();
if(supertype!=null)
store(row, supertype);
final Table table = type.getTable();
final List columns = table.getColumns();
final Statement bf = createStatement();
if(row.present)
{
bf.append("update ").
append(table.protectedID).
append(" set ");
boolean first = true;
for(Iterator i = columns.iterator(); i.hasNext(); )
{
if(first)
first = false;
else
bf.append(',');
final Column column = (Column)i.next();
bf.append(column.protectedID).
append('=');
final Object value = row.store(column);
bf.append(column.cacheToDatabase(value));
}
bf.append(" where ").
append(table.getPrimaryKey().protectedID).
append('=').
append(row.pk);
}
else
{
bf.append("insert into ").
append(table.protectedID).
append("(").
append(table.getPrimaryKey().protectedID);
final StringColumn typeColumn = table.getTypeColumn();
if(typeColumn!=null)
{
bf.append(',').
append(typeColumn.protectedID);
}
for(Iterator i = columns.iterator(); i.hasNext(); )
{
bf.append(',');
final Column column = (Column)i.next();
bf.append(column.protectedID);
}
bf.append(")values(").
append(row.pk);
if(typeColumn!=null)
{
bf.append(",'").
append(row.type.getID()).
append('\'');
}
for(Iterator i = columns.iterator(); i.hasNext(); )
{
bf.append(',');
final Column column = (Column)i.next();
final Object value = row.store(column);
bf.append(column.cacheToDatabase(value));
}
bf.append(')');
}
try
{
//System.out.println("storing "+bf.toString());
executeSQLUpdate(bf, 1);
}
catch(UniqueViolationException e)
{
throw e;
}
catch(ConstraintViolationException e)
{
throw new NestingRuntimeException(e);
}
}
void delete(final Type type, final int pk)
throws IntegrityViolationException
{
buildStage = false;
for(Type currentType = type; currentType!=null; currentType = currentType.getSupertype())
{
final Table currentTable = currentType.getTable();
final Statement bf = createStatement();
bf.append("delete from ").
append(currentTable.protectedID).
append(" where ").
append(currentTable.getPrimaryKey().protectedID).
append('=').
append(pk);
//System.out.println("deleting "+bf.toString());
try
{
executeSQLUpdate(bf, 1);
}
catch(IntegrityViolationException e)
{
throw e;
}
catch(ConstraintViolationException e)
{
throw new NestingRuntimeException(e);
}
}
}
static interface ResultSetHandler
{
public void run(ResultSet resultSet) throws SQLException;
}
private final static int convertSQLResult(final Object sqlInteger)
{
// IMPLEMENTATION NOTE
// Whether the returned object is an Integer, a Long or a BigDecimal,
// depends on the database used and for oracle on whether
// OracleStatement.defineColumnType is used or not, so we support all
// here.
return ((Number)sqlInteger).intValue();
}
static final String GET_TABLES = "getTables";
static final String GET_COLUMNS = "getColumns";
//private static int timeExecuteQuery = 0;
protected final StatementInfo executeSQLQuery(
final Statement statement,
final ResultSetHandler resultSetHandler,
final boolean makeStatementInfo)
{
Connection connection = null;
java.sql.Statement sqlStatement = null;
ResultSet resultSet = null;
try
{
connection = connectionPool.getConnection(this);
final String sqlText = statement.getText();
if(GET_TABLES.equals(sqlText))
{
resultSet = connection.getMetaData().getTables(null, null, null, new String[]{"TABLE"});
}
else if(GET_COLUMNS.equals(sqlText))
{
resultSet = connection.getMetaData().getColumns(null, null, null, null);
}
else
{
// TODO: use prepared statements and reuse the statement.
sqlStatement = connection.createStatement();
if(useDefineColumnTypes)
((DatabaseColumnTypesDefinable)this).defineColumnTypes(statement.columnTypes, sqlStatement);
//long time = System.currentTimeMillis();
resultSet = sqlStatement.executeQuery(sqlText);
//long interval = System.currentTimeMillis() - time;
//timeExecuteQuery += interval;
//System.out.println("executeQuery: "+interval+"ms sum "+timeExecuteQuery+"ms");
}
resultSetHandler.run(resultSet);
if(resultSet!=null)
{
resultSet.close();
resultSet = null;
}
if(sqlStatement!=null)
{
sqlStatement.close();
sqlStatement = null;
}
if(makeStatementInfo)
return makeStatementInfo(statement, connection);
else
return null;
}
catch(SQLException e)
{
throw new NestingRuntimeException(e, statement.toString());
}
finally
{
if(resultSet!=null)
{
try
{
resultSet.close();
}
catch(SQLException e)
{
// exception is already thrown
}
}
if(sqlStatement!=null)
{
try
{
sqlStatement.close();
}
catch(SQLException e)
{
// exception is already thrown
}
}
if(connection!=null)
{
try
{
connectionPool.putConnection(connection);
}
catch(SQLException e)
{
// exception is already thrown
}
}
}
}
protected final void executeSQLUpdate(final Statement statement, final int expectedRows)
throws ConstraintViolationException
{
Connection connection = null;
java.sql.Statement sqlStatement = null;
try
{
connection = connectionPool.getConnection(this);
// TODO: use prepared statements and reuse the statement.
final String sqlText = statement.getText();
sqlStatement = connection.createStatement();
final int rows = sqlStatement.executeUpdate(sqlText);
//System.out.println("("+rows+"): "+statement.getText());
//if(rows!=expectedRows) TODO
//throw new RuntimeException("expected "+expectedRows+" rows, but got "+rows);
}
catch(SQLException e)
{
final ConstraintViolationException wrappedException = wrapException(e);
if(wrappedException!=null)
throw wrappedException;
else
throw new NestingRuntimeException(e, statement.toString());
}
finally
{
if(sqlStatement!=null)
{
try
{
sqlStatement.close();
}
catch(SQLException e)
{
// exception is already thrown
}
}
if(connection!=null)
{
try
{
connectionPool.putConnection(connection);
}
catch(SQLException e)
{
// exception is already thrown
}
}
}
}
protected StatementInfo makeStatementInfo(final Statement statement, final Connection connection)
{
return new StatementInfo(statement.getText());
}
protected abstract String extractUniqueConstraintName(SQLException e);
protected abstract String extractIntegrityConstraintName(SQLException e);
private final ConstraintViolationException wrapException(final SQLException e)
{
{
final String uniqueConstraintID = extractUniqueConstraintName(e);
if(uniqueConstraintID!=null)
{
final UniqueConstraint constraint =
(UniqueConstraint)uniqueConstraintsByID.get(uniqueConstraintID);
if(constraint==null)
throw new NestingRuntimeException(e, "no unique constraint found for >"+uniqueConstraintID
+"<, has only "+uniqueConstraintsByID.keySet());
return new UniqueViolationException(e, null, constraint);
}
}
{
final String integrityConstraintName = extractIntegrityConstraintName(e);
if(integrityConstraintName!=null)
{
final ItemColumn column =
(ItemColumn)itemColumnsByIntegrityConstraintName.get(integrityConstraintName);
if(column==null)
throw new NestingRuntimeException(e, "no column attribute found for >"+integrityConstraintName
+"<, has only "+itemColumnsByIntegrityConstraintName.keySet());
final ItemAttribute attribute = column.attribute;
if(attribute==null)
throw new NestingRuntimeException(e, "no item attribute for column "+column);
return new IntegrityViolationException(e, null, attribute);
}
}
return null;
}
protected static final String trimString(final String longString, final int maxLength)
{
if(maxLength<=0)
throw new RuntimeException("maxLength must be greater zero");
if(longString.length()==0)
throw new RuntimeException("longString must not be empty");
if(longString.length()<=maxLength)
return longString;
int longStringLength = longString.length();
final int[] trimPotential = new int[maxLength];
final ArrayList words = new ArrayList();
{
final StringBuffer buf = new StringBuffer();
for(int i=0; i<longString.length(); i++)
{
final char c = longString.charAt(i);
if((c=='_' || Character.isUpperCase(c) || Character.isDigit(c)) && buf.length()>0)
{
words.add(buf.toString());
int potential = 1;
for(int j = buf.length()-1; j>=0; j--, potential++)
trimPotential[j] += potential;
buf.setLength(0);
}
if(buf.length()<maxLength)
buf.append(c);
else
longStringLength
}
if(buf.length()>0)
{
words.add(buf.toString());
int potential = 1;
for(int j = buf.length()-1; j>=0; j--, potential++)
trimPotential[j] += potential;
buf.setLength(0);
}
}
final int expectedTrimPotential = longStringLength - maxLength;
//System.out.println("expected trim potential = "+expectedTrimPotential);
int wordLength;
int remainder = 0;
for(wordLength = trimPotential.length-1; wordLength>=0; wordLength
{
//System.out.println("trim potential ["+wordLength+"] = "+trimPotential[wordLength]);
remainder = trimPotential[wordLength] - expectedTrimPotential;
if(remainder>=0)
break;
}
final StringBuffer result = new StringBuffer(longStringLength);
for(Iterator i = words.iterator(); i.hasNext(); )
{
final String word = (String)i.next();
//System.out.println("word "+word+" remainder:"+remainder);
if((word.length()>wordLength) && remainder>0)
{
result.append(word.substring(0, wordLength+1));
remainder
}
else if(word.length()>wordLength)
result.append(word.substring(0, wordLength));
else
result.append(word);
}
if(result.length()!=maxLength)
throw new RuntimeException(result.toString()+maxLength);
return result.toString();
}
/**
* Trims a name to length for being a suitable qualifier for database entities,
* such as tables, columns, indexes, constraints, partitions etc.
*/
String trimName(final String longName)
{
return trimString(longName, 25);
}
/**
* Protects a database name from being interpreted as a SQL keyword.
* This is usually done by enclosing the name with some (database specific) delimiters.
* The default implementation uses double quotes as delimiter.
*/
protected String protectName(final String name)
{
return '"' + name + '"';
}
abstract String getIntegerType(int precision);
abstract String getDoubleType(int precision);
abstract String getStringType(int maxLength);
void createTable(final Table table)
{
final Statement bf = createStatement();
bf.append("create table ").
append(table.protectedID).
append('(');
boolean firstColumn = true;
for(Iterator i = table.getAllColumns().iterator(); i.hasNext(); )
{
if(firstColumn)
firstColumn = false;
else
bf.append(',');
final Column column = (Column)i.next();
bf.append(column.protectedID).
append(' ').
append(column.getDatabaseType());
}
// attribute constraints
for(Iterator i = table.getAllColumns().iterator(); i.hasNext(); )
{
final Column column = (Column)i.next();
if(column.primaryKey)
{
bf.append(",constraint ").
append(protectName(column.getPrimaryKeyConstraintID())).
append(" primary key(").
append(column.protectedID).
append(')');
}
else
{
final String checkConstraint = column.getCheckConstraint();
if(checkConstraint!=null)
{
bf.append(",constraint ").
append(protectName(column.getCheckConstraintID())).
append(" check(").
append(checkConstraint).
append(')');
}
}
}
for(Iterator i = table.getUniqueConstraints().iterator(); i.hasNext(); )
{
final UniqueConstraint uniqueConstraint = (UniqueConstraint)i.next();
bf.append(",constraint ").
append(protectName(uniqueConstraint.getDatabaseID())).
append(" unique(");
boolean first = true;
for(Iterator j = uniqueConstraint.getUniqueAttributes().iterator(); j.hasNext(); )
{
if(first)
first = false;
else
bf.append(',');
final Attribute uniqueAttribute = (Attribute)j.next();
bf.append(uniqueAttribute.getMainColumn().protectedID);
}
bf.append(')');
}
bf.append(')');
try
{
//System.out.println("createTable:"+bf.toString());
executeSQLUpdate(bf, 0);
}
catch(ConstraintViolationException e)
{
throw new NestingRuntimeException(e);
}
}
private void createForeignKeyConstraints(final Table table)
{
//System.out.println("createForeignKeyConstraints:"+bf);
for(Iterator i = table.getAllColumns().iterator(); i.hasNext(); )
{
final Column column = (Column)i.next();
//System.out.println("createForeignKeyConstraints("+column+"):"+bf);
if(column instanceof ItemColumn)
{
final ItemColumn itemColumn = (ItemColumn)column;
final Statement bf = createStatement();
bf.append("alter table ").
append(table.protectedID).
append(" add constraint ").
append(protectName(itemColumn.integrityConstraintName)).
append(" foreign key (").
append(column.protectedID).
append(") references ").
append(itemColumn.getForeignTableNameProtected());
try
{
//System.out.println("createForeignKeyConstraints:"+bf);
executeSQLUpdate(bf, 0);
}
catch(ConstraintViolationException e)
{
throw new NestingRuntimeException(e);
}
}
}
}
private void dropTable(final Table table)
{
final Statement bf = createStatement();
bf.append("drop table ").
append(table.protectedID);
try
{
executeSQLUpdate(bf, 0);
}
catch(ConstraintViolationException e)
{
throw new NestingRuntimeException(e);
}
}
private int countTable(final Table table)
{
final Statement bf = createStatement();
bf.append("select count(*) from ").defineColumnInteger().
append(table.protectedID);
final CountResultSetHandler handler = new CountResultSetHandler();
executeSQLQuery(bf, handler, false);
return handler.result;
}
private static class CountResultSetHandler implements ResultSetHandler
{
int result;
public void run(ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new RuntimeException();
result = convertSQLResult(resultSet.getObject(1));
}
}
protected boolean supportsForeignKeyConstraints()
{
return true;
}
private void dropForeignKeyConstraints(final Table table)
{
if(!supportsForeignKeyConstraints())
return;
for(Iterator i = table.getColumns().iterator(); i.hasNext(); )
{
final Column column = (Column)i.next();
//System.out.println("dropForeignKeyConstraints("+column+")");
if(column instanceof ItemColumn)
{
final ItemColumn itemColumn = (ItemColumn)column;
final Statement bf = createStatement();
boolean hasOne = false;
bf.append("alter table ").
append(table.protectedID).
append(" drop constraint ").
append(protectName(itemColumn.integrityConstraintName));
//System.out.println("dropForeignKeyConstraints:"+bf);
try
{
executeSQLUpdate(bf, 0);
}
catch(ConstraintViolationException e)
{
throw new NestingRuntimeException(e);
}
}
}
}
int[] getMinMaxPK(final Table table)
{
buildStage = false;
final Statement bf = createStatement();
final String primaryKeyProtectedID = table.getPrimaryKey().protectedID;
bf.append("select min(").
append(primaryKeyProtectedID).defineColumnInteger().
append("),max(").
append(primaryKeyProtectedID).defineColumnInteger().
append(") from ").
append(table.protectedID);
final NextPKResultSetHandler handler = new NextPKResultSetHandler();
executeSQLQuery(bf, handler, false);
//System.err.println("select max("+type.primaryKey.trimmedName+") from "+type.trimmedName+" : "+handler.result);
return handler.result;
}
private static class NextPKResultSetHandler implements ResultSetHandler
{
int[] result;
public void run(ResultSet resultSet) throws SQLException
{
if(!resultSet.next())
throw new RuntimeException();
final Object oLo = resultSet.getObject(1);
if(oLo!=null)
{
result = new int[2];
result[0] = convertSQLResult(oLo);
final Object oHi = resultSet.getObject(2);
result[1] = convertSQLResult(oHi);
}
}
}
private final String getColumnType(final int dataType, final ResultSet resultSet)
throws SQLException
{
switch(dataType)
{
case Types.INTEGER:
return "integer";
case Types.BIGINT:
return "bigint";
case Types.DOUBLE:
return "double";
case Types.TIMESTAMP:
return "timestamp";
case Types.VARCHAR:
final int dataLength = resultSet.getInt("COLUMN_SIZE");
return "varchar("+dataLength+')';
default:
return null;
}
}
public final Report reportDatabase()
{
final Report report = new Report(this, getTables());
fillReport(report);
report.finish();
return report;
}
void fillReport(final Report report)
{
{
final com.exedio.cope.lib.Statement bf = createStatement();
bf.append(GET_TABLES);
executeSQLQuery(bf, new MetaDataTableHandler(report), false);
}
{
final com.exedio.cope.lib.Statement bf = createStatement();
bf.append(GET_COLUMNS);
executeSQLQuery(bf, new MetaDataColumnHandler(report), false);
}
}
private static class MetaDataTableHandler implements ResultSetHandler
{
private final Report report;
MetaDataTableHandler(final Report report)
{
this.report = report;
}
public void run(ResultSet resultSet) throws SQLException
{
while(resultSet.next())
{
final String tableName = resultSet.getString("TABLE_NAME");
final ReportTable table = report.notifyExistentTable(tableName);
//System.out.println("EXISTS:"+tableName);
}
}
}
private class MetaDataColumnHandler implements ResultSetHandler
{
private final Report report;
MetaDataColumnHandler(final Report report)
{
this.report = report;
}
public void run(ResultSet resultSet) throws SQLException
{
while(resultSet.next())
{
final String tableName = resultSet.getString("TABLE_NAME");
final String columnName = resultSet.getString("COLUMN_NAME");
final int dataType = resultSet.getInt("DATA_TYPE");
final ReportTable table = report.getTable(tableName);
if(table!=null)
{
String columnType = getColumnType(dataType, resultSet);
if(columnType==null)
columnType = String.valueOf(dataType);
table.notifyExistentColumn(columnName, columnType);
}
//System.out.println("EXISTS:"+tableName);
}
}
}
final void renameTable(final String oldTableName, final String newTableName)
{
final Statement bf = createStatement();
bf.append("alter table ").
append(protectName(oldTableName)).
append(" rename to ").
append(protectName(newTableName));
try
{
//System.out.println("renameTable:"+bf);
executeSQLUpdate(bf, 0);
}
catch(ConstraintViolationException e)
{
throw new NestingRuntimeException(e);
}
}
final void dropTable(final String tableName)
{
final Statement bf = createStatement();
bf.append("drop table ").
append(protectName(tableName));
try
{
//System.out.println("dropTable:"+bf);
executeSQLUpdate(bf, 0);
}
catch(ConstraintViolationException e)
{
throw new NestingRuntimeException(e);
}
}
final void analyzeTable(final String tableName)
{
final Statement bf = createStatement();
bf.append("analyze table ").
append(protectName(tableName)).
append(" compute statistics");
try
{
//System.out.println("analyzeTable:"+bf);
executeSQLUpdate(bf, 0);
}
catch(ConstraintViolationException e)
{
throw new NestingRuntimeException(e);
}
}
final void dropColumn(final String tableName, final String columnName)
{
final Statement bf = createStatement();
bf.append("alter table ").
append(protectName(tableName)).
append(" drop column ").
append(protectName(columnName));
try
{
//System.out.println("dropColumn:"+bf);
executeSQLUpdate(bf, 0);
}
catch(ConstraintViolationException e)
{
throw new NestingRuntimeException(e);
}
}
abstract Statement getRenameColumnStatement(String tableName, String oldColumnName, String newColumnName, String columnType);
final void renameColumn(final String tableName,
final String oldColumnName, final String newColumnName, final String columnType)
{
final Statement bf =
getRenameColumnStatement(
protectName(tableName),
protectName(oldColumnName),
protectName(newColumnName),
columnType);
try
{
//System.err.println("renameColumn:"+bf);
executeSQLUpdate(bf, 0);
}
catch(ConstraintViolationException e)
{
throw new NestingRuntimeException(e);
}
}
abstract Statement getCreateColumnStatement(final String tableName, final String columnName, final String columnType);
final void createColumn(final Column column)
{
final Statement bf =
getCreateColumnStatement(
column.table.protectedID,
column.protectedID,
column.getDatabaseType());
try
{
//System.out.println("createColumn:"+bf);
executeSQLUpdate(bf, 0);
}
catch(ConstraintViolationException e)
{
throw new NestingRuntimeException(e);
}
}
abstract Statement getModifyColumnStatement(final String tableName, final String columnName, final String newColumnType);
final void modifyColumn(final String tableName, final String columnName, final String newColumnType)
{
final Statement bf =
getModifyColumnStatement(
protectName(tableName),
protectName(columnName),
newColumnType);
try
{
//System.out.println("modifyColumn:"+bf);
executeSQLUpdate(bf, 0);
}
catch(ConstraintViolationException e)
{
throw new NestingRuntimeException(e);
}
}
static final ResultSetHandler logHandler = new ResultSetHandler()
{
public void run(ResultSet resultSet) throws SQLException
{
final int columnCount = resultSet.getMetaData().getColumnCount();
System.out.println("columnCount:"+columnCount);
final ResultSetMetaData meta = resultSet.getMetaData();
for(int i = 1; i<=columnCount; i++)
{
System.out.println(meta.getColumnName(i)+"|");
}
while(resultSet.next())
{
for(int i = 1; i<=columnCount; i++)
{
System.out.println(resultSet.getObject(i)+"|");
}
}
}
};
}
|
package am.app.mappingEngine;
import java.util.ArrayList;
import java.util.Iterator;
import am.app.ontology.Node;
public class AlignmentSet<E extends Alignment>
{
protected ArrayList<E> collection = null;
public AlignmentSet()
{
collection = new ArrayList<E>();
}
public void addAlignment(E alignment)
{
if( alignment != null ) collection.add(alignment);
}
public void addAll(AlignmentSet<E> a)
{
if(a != null) {
for(int i= 0; i<a.size();i++) {
E alignment = a.getAlignment(i);
collection.add(alignment);
}
}
}
// adds all the alignments in the set a, but checking for duplicates, making sure it doesn't add duplicate alignments
public void addAllNoDuplicate(AlignmentSet<E> a)
{
if(a != null) {
for(int i= 0; i<a.size();i++) {
E alignment = a.getAlignment(i);
if( !contains( alignment ) ) addAlignment(alignment);
}
}
}
public E getAlignment(int index)
{
if (index >= 0 && index < size()) {
return collection.get(index);
} else {
System.err.println("getAlignmentError: Index is out of bound.");
return null;
}
}
public double getSimilarity(Node left, Node right)
{
E align = contains(left, right);
if (align == null) {
return 0;
} else {
return align.getSimilarity();
}
}
public void setSimilarity(Node left, Node right, double sim)
{
E align = contains(left, right);
if (align == null) {
System.err.println("setSimilarityError: Cannot find such alignment.");
} else {
align.setSimilarity(sim);
}
}
public boolean removeAlignment(int index)
{
if (index >= 0 && index < size()) {
collection.remove(index);
return true;
} else {
System.err.println("removeAlignmentError: Index is out of bound.");
return false;
}
}
public boolean removeAlignment(Node left, Node right)
{
for (int i = 0, n = size(); i < n; i++) {
Alignment align = (Alignment) collection.get(i);
if (align.getEntity1().equals(left) && align.getEntity2().equals(right)) {
collection.remove(i);
return true;
}
}
System.err.println("removeAlignmentError: Cannot find such alignment.");
return false;
}
public E contains(Node left, Node right)
{
for (int i = 0, n = size(); i < n; i++) {
E align = collection.get(i);
if (align.getEntity1().equals(left) && align.getEntity2().equals(right)) {
return align;
}
}
return null;
}
public E contains(Node nod)
{
for (int i = 0, n = size(); i < n; i++) {
E align = collection.get(i);
if (align.getEntity1().equals(nod) || align.getEntity2().equals(nod)) {
return align;
}
}
return null;
}
public boolean contains( E alignment ) {
for (int i = 0, n = size(); i < n; i++) {
E align = collection.get(i);
Node left = alignment.getEntity1();
Node right = alignment.getEntity2();
if (align.getEntity1().equals(left) && align.getEntity2().equals(right)) {
return true;
}
}
return false;
}
public AlignmentSet<E> cut(double threshold)
{
for (int i = 0; i < size(); i++) {
E align = collection.get(i);
if (align.getSimilarity() <= threshold) {
removeAlignment(i);
i
}
}
return this;
}
public int size()
{
return collection.size();
}
public int size(double threshold)
{
int count = 0;
for (int i = 0, n = size(); i < n; i++) {
E align = collection.get(i);
if (align.getSimilarity() > threshold) {
count++;
}
}
return count;
}
public void show()
{
for (int i = 0, n = size(); i < n; i++) {
E align = collection.get(i);
System.out.println("entity1=" + align.getEntity1().toString());
System.out.println("entity2=" + align.getEntity2().toString());
System.out.println("similarity=" + align.getSimilarity());
System.out.println("relation=" + align.getRelation() + "\n");
}
}
public String getStringList() {
String result = "";
E a;
for(int i = 0; i < collection.size(); i++) {
a = collection.get(i);
result += a.getString();
if(i == collection.size()-1)
result+= "\n";
}
return result;
}
public Iterator<E> iterator() {
return collection.iterator();
}
}
|
package org.opennms.netmgt.dao.support;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.opennms.core.utils.LazyList;
import org.opennms.netmgt.dao.api.ResourceDao;
import org.opennms.netmgt.model.OnmsResource;
import org.opennms.netmgt.model.OnmsResourceType;
import com.google.common.base.Preconditions;
public class LazyChildResourceLoader implements LazyList.Loader<OnmsResource> {
private final ResourceDao m_resourceDao;
private OnmsResource m_parent;
public LazyChildResourceLoader(ResourceDao resourceDao) {
m_resourceDao = resourceDao;
}
public void setParent(OnmsResource parent) {
m_parent = parent;
}
@Override
public List<OnmsResource> load() {
Preconditions.checkNotNull(m_parent, "parent attribute");
// Gather the lists of children from all the available resource types and merge them
// into a single list
List<OnmsResource> children = getAvailableResourceTypes().stream()
.map(t -> t.getResourcesForParent(m_parent))
.flatMap(rs -> rs.stream())
.collect(Collectors.toList());
// Set the parent field on all of the resources
children.stream().forEach(c -> c.setParent(m_parent));
return children;
}
private Collection<OnmsResourceType> getAvailableResourceTypes() {
return m_resourceDao.getResourceTypes().stream()
.filter(t -> t.isResourceTypeOnParent(m_parent))
.collect(Collectors.toList());
}
}
|
// base classes
import java.util.Vector;
import java.util.StringTokenizer;
import com.sun.star.ucb.*;
import com.sun.star.beans.*;
import com.sun.star.uno.UnoRuntime;
/**
* Setting Property Values of a UCB Content
*/
public class PropertiesComposer {
/**
* Member properties
*/
private Helper m_helper;
private XContent m_content;
private String m_connectString = "";
private String m_contenturl = "";
private Vector m_propNames = new Vector();
private Vector m_propValues = new Vector();
/**
* Constructor.
*
*@param String[] This construtor requires the arguments:
* -connect=socket,host=..., port=...
* -url=..
* -propNames=... (optional).
* -propValues=... (optional).
* See Help (method printCmdLineUsage()).
* Without the arguments a new connection to a
* running office cannot created.
*@exception java.lang.Exception
*/
public PropertiesComposer( String args[] ) throws java.lang.Exception {
// Parse arguments
parseArguments( args );
String connect = getConnect();
String url = getContentURL();
// Init
m_helper = new Helper( connect, url );
// Create UCB content
m_content = m_helper.createUCBContent();
}
/**
* Set values of the properties.
* This method requires the main and the optional arguments to be set in order to work.
* See Constructor.
*
*@return Object[] Returns null or instance object of com.sun.star.uno.Any
* if values successfully seted, properties otherwise
*@exception com.sun.star.ucb.CommandAbortedException
*@exception com.sun.star.uno.Exception
*/
public Object[] setProperties()
throws com.sun.star.ucb.CommandAbortedException, com.sun.star.uno.Exception {
Vector properties = getProperties();
Vector propertyValues = getPropertyValues();
return setProperties( properties, propertyValues );
}
/**
* Set values of the properties.
*
*@param Vector Properties
*@param Vector Properties value
*@return Object[] Returns null or instance object of com.sun.star.uno.Any
* if values successfully seted, properties otherwise
*@exception com.sun.star.ucb.CommandAbortedException
*@exception com.sun.star.uno.Exception
*/
public Object[] setProperties( Vector properties, Vector propertiesValues )
throws com.sun.star.ucb.CommandAbortedException, com.sun.star.uno.Exception {
Object[] result = null;
if ( m_content != null && !properties.isEmpty() &&
!propertiesValues.isEmpty() &&
properties.size() == propertiesValues.size() ) {
int size = properties.size();
PropertyValue[] props = new PropertyValue[ size ];
for ( int index = 0 ; index < size; index++ ) {
String propName = ( String )properties.get( index );
Object propValue = propertiesValues.get( index );
// Define property sequence.
PropertyValue prop = new PropertyValue();
prop.Name = propName;
prop.Handle = -1;
prop.Value = propValue;
props[ index ] = prop;
}
// Execute command "setPropertiesValues".
Object[] obj =
( Object[] )m_helper.executeCommand( m_content, "setPropertyValues", props );
if ( obj.length == size )
result = obj;
}
return result;
}
/**
* Get properties names.
*
*@return Vector That contains the properties names
*/
public Vector getProperties() {
return m_propNames;
}
/**
* Get properties values.
*
*@return Vector That contains the properties values
*/
public Vector getPropertyValues() {
return m_propValues;
}
/**
* Get connect URL.
*
*@return String That contains the connect URL
*/
public String getContentURL() {
return m_contenturl;
}
/**
* Get source data connection.
*
*@return String That contains the source data connection
*/
public String getConnect() {
return m_connectString;
}
/**
* Parse arguments
*
*@param String[] Arguments
*@exception java.lang.Exception
*/
public void parseArguments( String[] args ) throws java.lang.Exception {
for ( int i = 0; i < args.length; i++ ) {
if ( args[i].startsWith( "-connect=" )) {
m_connectString = args[i].substring( 9 );
} else if ( args[i].startsWith( "-url=" )) {
m_contenturl = args[i].substring( 5 );
} else if ( args[i].startsWith( "-propNames=" )) {
StringTokenizer tok
= new StringTokenizer( args[i].substring( 11 ), ";" );
while ( tok.hasMoreTokens() )
m_propNames.add( tok.nextToken() );
} else if ( args[i].startsWith( "-propValues=" )) {
StringTokenizer tok
= new StringTokenizer( args[i].substring( 12 ), ";" );
while ( tok.hasMoreTokens() )
m_propValues.add( tok.nextToken() );
} else if ( args[i].startsWith( "-help" ) ||
args[i].startsWith( "-?" )) {
printCmdLineUsage();
System.exit( 0 );
}
}
if ( m_connectString == null || m_connectString.equals( "" )) {
m_connectString = "socket,host=localhost,port=2083";
}
if ( m_contenturl == null || m_contenturl.equals( "" )) {
m_contenturl = Helper.createTargetDataFile();
}
if ( m_propNames.size() == 0 ) {
m_propNames.add( "Title" );
}
if ( m_propValues.size() == 0 ) {
m_propValues.add(
"renamed-" + m_contenturl.substring(
m_contenturl.lastIndexOf( "/" ) + 1 ) );
}
}
/**
* Print the commands options
*/
public void printCmdLineUsage() {
System.out.println(
"Usage : PropertiesComposer -connect=socket,host=...,port=... -url=... -propNames=... -propValues=..." );
System.out.println(
"Defaults: -connect=socket,host=localhost,port=2083 -url=<workdir>/resource-<uniquepostfix> -propNames=Title -propValues=renamed-resource-<uniquepostfix>" );
System.out.println(
"\nExample : -propNames=Title;Foo -propValues=MyRenamedFile.txt;bar" );
}
/**
* Create a new connection with the specific args to a running office and
* set properties of a resource.
*
*@param String[] Arguments
*/
public static void main ( String args[] ) {
System.out.println( "\n" );
System.out.println(
"
System.out.println(
"PropertiesComposer - sets property values of a resource." );
System.out.println(
"
try {
PropertiesComposer setProp = new PropertiesComposer( args );
Vector properties = setProp.getProperties();
Vector propertiesValues = setProp.getPropertyValues();
Object[] result = setProp.setProperties( properties, propertiesValues );
String tempPrint = "\nSetting properties of resource " + setProp.getContentURL();
int size = tempPrint.length();
System.out.println( tempPrint );
tempPrint = "";
for( int i = 0; i < size; i++ ) {
tempPrint += "-";
}
System.out.println( tempPrint );
if ( result != null ) {
for ( int index = 0; index < result.length; index++ ) {
Object obj = result[ index ];
if( obj == null || obj instanceof com.sun.star.uno.Any )
System.out.println(
"Setting property " + properties.get( index ) + " succeeded." );
else
System.out.println(
"Setting property " + properties.get( index ) + " failed." );
}
}
} catch ( com.sun.star.ucb.CommandAbortedException e ) {
System.out.println( "Error: " + e );
} catch ( com.sun.star.uno.Exception e ) {
System.out.println( "Error: " + e );
} catch ( java.lang.Exception e ) {
System.out.println( "Error: " + e );
}
System.exit( 0 );
}
}
|
package com.intellij.openapi.vcs.changes.ui;
import com.intellij.diff.util.DiffPlaces;
import com.intellij.diff.util.DiffUserDataKeysEx;
import com.intellij.ide.HelpIdProvider;
import com.intellij.ide.ui.UISettings;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.*;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vcs.changes.*;
import com.intellij.openapi.vcs.changes.actions.diff.lst.LocalChangeListDiffTool;
import com.intellij.openapi.vcs.checkin.BaseCheckinHandlerFactory;
import com.intellij.openapi.vcs.checkin.BeforeCheckinDialogHandler;
import com.intellij.openapi.vcs.checkin.CheckinEnvironment;
import com.intellij.openapi.vcs.checkin.CheckinHandler;
import com.intellij.openapi.vcs.impl.LineStatusTrackerManager;
import com.intellij.openapi.vcs.ui.CommitMessage;
import com.intellij.openapi.vcs.ui.Refreshable;
import com.intellij.openapi.vcs.ui.RefreshableOnComponent;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.JBColor;
import com.intellij.ui.SplitterWithSecondHideable;
import com.intellij.ui.components.JBLabel;
import com.intellij.util.Alarm;
import com.intellij.util.EventDispatcher;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.AbstractLayoutManager;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.components.BorderLayoutPanel;
import com.intellij.vcsUtil.VcsUtil;
import one.util.streamex.StreamEx;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.List;
import java.util.*;
import static com.intellij.openapi.diagnostic.Logger.getInstance;
import static com.intellij.openapi.util.text.StringUtil.escapeXmlEntities;
import static com.intellij.openapi.util.text.StringUtil.isEmptyOrSpaces;
import static com.intellij.openapi.vcs.VcsBundle.message;
import static com.intellij.openapi.vcs.changes.ui.CommitOptionsPanel.*;
import static com.intellij.openapi.vcs.changes.ui.DialogCommitWorkflow.getCommitHandlerFactories;
import static com.intellij.openapi.vcs.changes.ui.SingleChangeListCommitter.moveToFailedList;
import static com.intellij.ui.components.JBBox.createHorizontalBox;
import static com.intellij.util.ArrayUtil.isEmpty;
import static com.intellij.util.ObjectUtils.chooseNotNull;
import static com.intellij.util.ObjectUtils.notNull;
import static com.intellij.util.containers.ContainerUtil.*;
import static com.intellij.util.ui.SwingHelper.buildHtml;
import static com.intellij.util.ui.UIUtil.*;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.util.Collections.emptyList;
import static java.util.Collections.*;
public class CommitChangeListDialog extends DialogWrapper implements CheckinProjectPanel, SingleChangeListCommitWorkflowUi {
private static final Logger LOG = getInstance(CommitChangeListDialog.class);
public static final String DIALOG_TITLE = message("commit.dialog.title");
private static final String HELP_ID = "reference.dialogs.vcs.commit";
private static final int LAYOUT_VERSION = 2;
private static final String SPLITTER_PROPORTION_OPTION = "CommitChangeListDialog.SPLITTER_PROPORTION_" + LAYOUT_VERSION;
private static final String DETAILS_SPLITTER_PROPORTION_OPTION = "CommitChangeListDialog.DETAILS_SPLITTER_PROPORTION_" + LAYOUT_VERSION;
private static final String DETAILS_SHOW_OPTION = "CommitChangeListDialog.DETAILS_SHOW_OPTION_";
private static final float SPLITTER_PROPORTION_OPTION_DEFAULT = 0.5f;
private static final float DETAILS_SPLITTER_PROPORTION_OPTION_DEFAULT = 0.6f;
private static final boolean DETAILS_SHOW_OPTION_DEFAULT = true;
@NotNull private final Project myProject;
@NotNull private final VcsConfiguration myVcsConfiguration;
@NotNull private final DialogCommitWorkflow myWorkflow;
@NotNull private final EventDispatcher<CommitExecutorListener> myExecutorEventDispatcher =
EventDispatcher.create(CommitExecutorListener.class);
@NotNull private final List<DataProvider> myDataProviders = newArrayList();
@NotNull private final String myCommitActionName;
@NotNull private final Map<String, String> myListComments = new HashMap<>();
@NotNull private final List<CommitExecutorAction> myExecutorActions;
@NotNull private final CommitOptionsPanel myCommitOptions;
@NotNull private final ChangeInfoCalculator myChangesInfoCalculator;
@NotNull private final CommitDialogChangesBrowser myBrowser;
@NotNull private final JComponent myBrowserBottomPanel = createHorizontalBox();
@NotNull private final MyChangeProcessor myDiffDetails;
@NotNull private final CommitMessage myCommitMessageArea;
@NotNull private final CommitLegendPanel myLegend;
@NotNull private final Splitter mySplitter;
@NotNull private final SplitterWithSecondHideable myDetailsSplitter;
@NotNull private final JBLabel myWarningLabel;
@Nullable private final String myHelpId;
@Nullable private final CommitAction myCommitAction;
@NotNull private final Alarm myOKButtonUpdateAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD);
@NotNull private final Runnable myUpdateButtonsRunnable = () -> {
updateButtons();
updateLegend();
};
private boolean myDisposed = false;
private boolean myUpdateDisabled = false;
private String myLastKnownComment = "";
private String myLastSelectedListName;
public static boolean commitChanges(@NotNull Project project,
@NotNull Collection<? extends Change> changes,
@Nullable LocalChangeList initialSelection,
@Nullable CommitExecutor executor,
@Nullable String comment) {
return commitChanges(project, changes, changes, initialSelection, executor, comment);
}
public static boolean commitChanges(@NotNull Project project,
@NotNull Collection<? extends Change> changes,
@NotNull Collection<?> included,
@Nullable LocalChangeList initialSelection,
@Nullable CommitExecutor executor,
@Nullable String comment) {
if (executor == null) {
return commitChanges(project, new ArrayList<>(changes), included, initialSelection, collectExecutors(project, changes), true, null,
comment, null, true);
}
else {
return commitChanges(project, new ArrayList<>(changes), included, initialSelection, singletonList(executor), false, null, comment, null,
true);
}
}
/**
* Shows the commit dialog, and performs the selected action: commit, commit & push, create patch, etc.
*
* @param customResultHandler If this is not null, after commit is completed, custom result handler is called instead of
* showing the default notification in case of commit or failure.
* @return true if user agreed to commit, false if he pressed "Cancel".
*/
public static boolean commitChanges(@NotNull Project project,
@NotNull Collection<? extends Change> changes,
@Nullable LocalChangeList initialSelection,
@NotNull List<? extends CommitExecutor> executors,
boolean showVcsCommit,
@Nullable String comment,
@Nullable CommitResultHandler customResultHandler) {
return commitChanges(project, new ArrayList<>(changes), initialSelection, executors, showVcsCommit, comment, customResultHandler, true);
}
public static boolean commitChanges(@NotNull Project project,
@NotNull List<Change> changes,
@Nullable LocalChangeList initialSelection,
@NotNull List<? extends CommitExecutor> executors,
boolean showVcsCommit,
@Nullable String comment,
@Nullable CommitResultHandler customResultHandler,
boolean cancelIfNoChanges) {
return commitChanges(project, changes, changes, initialSelection, executors, showVcsCommit, null, comment, customResultHandler,
cancelIfNoChanges);
}
public static boolean commitChanges(@NotNull Project project,
@NotNull List<Change> changes,
@NotNull Collection<?> included,
@Nullable LocalChangeList initialSelection,
@NotNull List<? extends CommitExecutor> executors,
boolean showVcsCommit,
@Nullable AbstractVcs forceCommitInVcs,
@Nullable String comment,
@Nullable CommitResultHandler customResultHandler,
boolean cancelIfNoChanges) {
ChangeListManager manager = ChangeListManager.getInstance(project);
LocalChangeList defaultList = manager.getDefaultChangeList();
List<LocalChangeList> changeLists = manager.getChangeListsCopy();
Set<AbstractVcs<?>> affectedVcses = new HashSet<>();
if (forceCommitInVcs != null) affectedVcses.add(forceCommitInVcs);
for (LocalChangeList list : changeLists) {
//noinspection unchecked
affectedVcses.addAll((Set)ChangesUtil.getAffectedVcses(list.getChanges(), project));
}
if (showVcsCommit) {
List<VirtualFile> unversionedFiles = ChangeListManagerImpl.getInstanceImpl(project).getUnversionedFiles();
//noinspection unchecked
affectedVcses.addAll((Set)ChangesUtil.getAffectedVcsesForFiles(unversionedFiles, project));
}
if (cancelIfNoChanges && affectedVcses.isEmpty()) {
Messages.showInfoMessage(project, message("commit.dialog.no.changes.detected.text"),
message("commit.dialog.no.changes.detected.title"));
return false;
}
for (BaseCheckinHandlerFactory factory : getCommitHandlerFactories(project)) {
BeforeCheckinDialogHandler handler = factory.createSystemReadyHandler(project);
if (handler != null && !handler.beforeCommitDialogShown(project, changes, (Iterable<CommitExecutor>)executors, showVcsCommit)) {
return false;
}
}
boolean isDefaultChangeListFullyIncluded = new HashSet<>(changes).containsAll(defaultList.getChanges());
DialogCommitWorkflow workflow =
new DialogCommitWorkflow(project, included, initialSelection, executors, showVcsCommit, forceCommitInVcs, affectedVcses,
isDefaultChangeListFullyIncluded, comment, customResultHandler);
return workflow.showDialog();
}
@NotNull
public static List<CommitExecutor> collectExecutors(@NotNull Project project, @NotNull Collection<? extends Change> changes) {
List<CommitExecutor> result = new ArrayList<>();
for (AbstractVcs<?> vcs : ChangesUtil.getAffectedVcses(changes, project)) {
result.addAll(vcs.getCommitExecutors());
}
result.addAll(ChangeListManager.getInstance(project).getRegisteredExecutors());
return result;
}
CommitChangeListDialog(@NotNull DialogCommitWorkflow workflow) {
super(workflow.getProject(), true, (Registry.is("ide.perProjectModality")) ? IdeModalityType.PROJECT : IdeModalityType.IDE);
myWorkflow = workflow;
myProject = myWorkflow.getProject();
myVcsConfiguration = notNull(VcsConfiguration.getInstance(myProject));
List<? extends CommitExecutor> executors = myWorkflow.getExecutors();
if (!isDefaultCommitEnabled() && ContainerUtil.isEmpty(executors)) {
throw new IllegalArgumentException("nothing found to execute commit with");
}
setTitle(isDefaultCommitEnabled() ? DIALOG_TITLE : getExecutorPresentableText(executors.get(0)));
myCommitActionName = getCommitActionName(getWorkflowVcses());
myExecutorActions = createExecutorActions(executors);
if (isDefaultCommitEnabled()) {
myCommitAction = new CommitAction(myCommitActionName);
myCommitAction.setOptions(myExecutorActions);
}
else {
myCommitAction = null;
myExecutorActions.get(0).putValue(DEFAULT_ACTION, Boolean.TRUE);
}
myHelpId = isDefaultCommitEnabled() ? HELP_ID : getHelpId(executors);
myDiffDetails = new MyChangeProcessor(myProject, myWorkflow.isPartialCommitEnabled());
myCommitMessageArea = new CommitMessage(myProject, true, true, isDefaultCommitEnabled());
myBrowser = myWorkflow.createBrowser();
myChangesInfoCalculator = new ChangeInfoCalculator();
myLegend = new CommitLegendPanel(myChangesInfoCalculator);
mySplitter = new Splitter(true);
myCommitOptions = new CommitOptionsPanel(this);
myWarningLabel = new JBLabel();
JPanel mainPanel = new JPanel(new MyOptionsLayout(mySplitter, myCommitOptions, JBUI.scale(150), JBUI.scale(400)));
mainPanel.add(mySplitter);
mainPanel.add(myCommitOptions);
JPanel rootPane = JBUI.Panels.simplePanel(mainPanel).addToBottom(myWarningLabel);
myDetailsSplitter = createDetailsSplitter(rootPane);
}
@Override
protected void init() {
beforeInit();
super.init();
afterInit();
}
private void beforeInit() {
myBrowserBottomPanel.add(myLegend.getComponent());
BorderLayoutPanel topPanel = JBUI.Panels.simplePanel().addToCenter(myBrowser).addToBottom(myBrowserBottomPanel);
mySplitter.setHonorComponentsMinimumSize(true);
mySplitter.setFirstComponent(topPanel);
mySplitter.setSecondComponent(myCommitMessageArea);
mySplitter.setProportion(PropertiesComponent.getInstance().getFloat(SPLITTER_PROPORTION_OPTION, SPLITTER_PROPORTION_OPTION_DEFAULT));
if (!myVcsConfiguration.CLEAR_INITIAL_COMMIT_MESSAGE) {
initComment(myWorkflow.getInitialCommitMessage());
}
initOptions();
myWarningLabel.setForeground(JBColor.RED);
myWarningLabel.setBorder(JBUI.Borders.empty(5, 5, 0, 5));
updateWarning();
}
private void initOptions() {
if (isDefaultCommitEnabled()) {
myCommitOptions.setVcsOptions(getVcsOptions(this, getWorkflowVcses(), myWorkflow.getAdditionalDataConsumer()));
}
myCommitOptions.setBeforeOptions(getBeforeOptions(getHandlers()));
myCommitOptions.setAfterOptions(getAfterOptions(getHandlers(), getDisposable()));
restoreState();
}
private void afterInit() {
updateButtons();
updateLegend();
updateOnListSelection();
myCommitMessageArea.requestFocusInMessage();
for (EditChangelistSupport support : EditChangelistSupport.EP_NAME.getExtensions(myProject)) {
support.installSearch(myCommitMessageArea.getEditorField(), myCommitMessageArea.getEditorField());
}
showDetailsIfSaved();
}
@NotNull
private SplitterWithSecondHideable createDetailsSplitter(@NotNull JPanel rootPane) {
SplitterWithSecondHideable.OnOffListener listener = new SplitterWithSecondHideable.OnOffListener() {
@Override
public void on(int hideableHeight) {
if (hideableHeight == 0) return;
myDiffDetails.refresh(false);
mySplitter.skipNextLayout();
myDetailsSplitter.getComponent().skipNextLayout();
Dimension dialogSize = getSize();
setSize(dialogSize.width, dialogSize.height + hideableHeight);
repaint();
}
@Override
public void off(int hideableHeight) {
if (hideableHeight == 0) return;
myDiffDetails.clear();
mySplitter.skipNextLayout();
myDetailsSplitter.getComponent().skipNextLayout();
Dimension dialogSize = getSize();
setSize(dialogSize.width, dialogSize.height - hideableHeight);
repaint();
}
};
// TODO: there are no reason to use such heavy interface for a simple task.
return new SplitterWithSecondHideable(true, "Diff", rootPane, listener) {
@Override
protected RefreshablePanel createDetails() {
JPanel panel = JBUI.Panels.simplePanel(myDiffDetails.getComponent());
return new RefreshablePanel() {
@Override
public void refresh() {
}
@Override
public JPanel getPanel() {
return panel;
}
};
}
@Override
protected float getSplitterInitialProportion() {
float value = PropertiesComponent.getInstance().getFloat(DETAILS_SPLITTER_PROPORTION_OPTION, DETAILS_SPLITTER_PROPORTION_OPTION_DEFAULT);
return value <= 0.05 || value >= 0.95 ? DETAILS_SPLITTER_PROPORTION_OPTION_DEFAULT : value;
}
};
}
@NotNull
private List<CommitExecutorAction> createExecutorActions(@NotNull List<? extends CommitExecutor> executors) {
if(executors.isEmpty()) return emptyList();
List<CommitExecutorAction> result = new ArrayList<>();
if (isDefaultCommitEnabled() && UISettings.getShadowInstance().getAllowMergeButtons()) {
ActionGroup group = (ActionGroup)ActionManager.getInstance().getAction("Vcs.CommitExecutor.Actions");
result.addAll(map(group.getChildren(null), CommitExecutorAction::new));
result.addAll(map(filter(executors, CommitExecutor::useDefaultAction), CommitExecutorAction::new));
}
else {
result.addAll(map(executors, CommitExecutorAction::new));
}
return result;
}
@Nullable
private static String getHelpId(@NotNull List<? extends CommitExecutor> executors) {
return StreamEx.of(executors).select(HelpIdProvider.class).map(HelpIdProvider::getHelpId).nonNull().findFirst().orElse(null);
}
private void initComment(@Nullable String comment) {
LocalChangeList list = getChangeList();
myLastSelectedListName = list.getName();
if (comment == null) {
comment = getCommentFromChangelist(list);
if (isEmptyOrSpaces(comment)) {
myLastKnownComment = myVcsConfiguration.LAST_COMMIT_MESSAGE;
comment = chooseNotNull(getInitialMessageFromVcs(), myVcsConfiguration.LAST_COMMIT_MESSAGE);
}
}
else {
myLastKnownComment = comment;
}
myCommitMessageArea.setText(comment);
}
private void showDetailsIfSaved() {
boolean showDetails = PropertiesComponent.getInstance().getBoolean(DETAILS_SHOW_OPTION, DETAILS_SHOW_OPTION_DEFAULT);
if (showDetails) {
myDetailsSplitter.initOn();
runWhenWindowOpened(getWindow(), () -> myDetailsSplitter.setInitialProportion());
}
changeDetails(false);
}
private void updateOnListSelection() {
if (!myVcsConfiguration.CLEAR_INITIAL_COMMIT_MESSAGE) {
updateComment();
}
myCommitMessageArea.setChangeList(getChangeList());
myCommitOptions.onChangeListSelected(getChangeList(), ChangeListManagerImpl.getInstanceImpl(myProject).getUnversionedFiles());
}
private void updateWarning() {
// check for null since can be called from constructor before field initialization
//noinspection ConstantConditions
if (myWarningLabel != null) {
myWarningLabel.setVisible(false);
VcsException updateException = ChangeListManagerImpl.getInstanceImpl(myProject).getUpdateException();
if (updateException != null) {
String[] messages = updateException.getMessages();
if (!isEmpty(messages)) {
String message = "Warning: not all local changes may be shown due to an error: " + messages[0];
String htmlMessage = buildHtml(getCssFontDeclaration(getLabelFont()), getHtmlBody(escapeXmlEntities(message)));
myWarningLabel.setText(htmlMessage);
myWarningLabel.setVisible(true);
}
}
}
}
@Nullable
@Override
protected String getHelpId() {
return myHelpId;
}
private class CommitAction extends AbstractAction implements OptionAction {
@NotNull private Action[] myOptions = new Action[0];
private CommitAction(String okActionText) {
super(okActionText);
putValue(DEFAULT_ACTION, Boolean.TRUE);
}
@Override
public void actionPerformed(ActionEvent e) {
myExecutorEventDispatcher.getMulticaster().executorCalled(null);
}
@NotNull
@Override
public Action[] getOptions() {
return myOptions;
}
public void setOptions(@NotNull List<? extends Action> actions) {
myOptions = actions.toArray(new Action[0]);
}
}
@NotNull
@Override
protected Action getOKAction() {
return myCommitAction != null ? myCommitAction : myExecutorActions.get(0);
}
@Override
@NotNull
protected Action[] createActions() {
List<Action> result = new ArrayList<>();
if (myCommitAction != null) {
result.add(myCommitAction);
}
else {
result.addAll(myExecutorActions);
}
result.add(getCancelAction());
if (myHelpId != null) {
result.add(getHelpAction());
}
return result.toArray(new Action[0]);
}
void executeDefaultCommitSession(@Nullable CommitExecutor executor) {
if (!saveCommitOptions()) return;
saveComments(true);
ensureDataIsActual(() -> {
try {
DefaultListCleaner defaultListCleaner = new DefaultListCleaner();
stopUpdate();
CheckinHandler.ReturnResult result = performBeforeCommitChecks(executor);
if (result == CheckinHandler.ReturnResult.CANCEL) {
restartUpdate();
}
else if (result == CheckinHandler.ReturnResult.CLOSE_WINDOW) {
ChangeList changeList = getChangeList();
moveToFailedList(myProject, changeList, getCommitMessage(), getIncludedChanges(),
message("commit.dialog.rejected.commit.template", changeList.getName()));
doCancelAction();
}
else if (result == CheckinHandler.ReturnResult.COMMIT) {
close(OK_EXIT_CODE);
myWorkflow.doCommit(getChangeList(), getIncludedChanges(), getCommitMessage());
defaultListCleaner.clean();
}
}
catch (InputException ex) {
ex.show();
}
});
}
void execute(@NotNull CommitExecutor commitExecutor, @NotNull CommitSession session) {
if (!saveCommitOptions()) return;
saveComments(true);
if (session instanceof CommitSessionContextAware) {
((CommitSessionContextAware)session).setContext(getCommitContext());
}
ensureDataIsActual(() -> {
JComponent configurationUI = SessionDialog.createConfigurationUI(session, getIncludedChanges(), getCommitMessage());
if (configurationUI != null) {
DialogWrapper sessionDialog =
new SessionDialog(getExecutorPresentableText(commitExecutor), getProject(), session, getIncludedChanges(), getCommitMessage(),
configurationUI);
if (!sessionDialog.showAndGet()) {
session.executionCanceled();
return;
}
}
DefaultListCleaner defaultListCleaner = new DefaultListCleaner();
stopUpdate();
CheckinHandler.ReturnResult result = performBeforeCommitChecks(commitExecutor);
if (result == CheckinHandler.ReturnResult.CANCEL) {
restartUpdate();
}
else if (result == CheckinHandler.ReturnResult.CLOSE_WINDOW) {
ChangeList changeList = getChangeList();
moveToFailedList(myProject, changeList, getCommitMessage(), getIncludedChanges(),
message("commit.dialog.rejected.commit.template", changeList.getName()));
doCancelAction();
}
else if (result == CheckinHandler.ReturnResult.COMMIT) {
boolean success = false;
try {
boolean completed = ProgressManager.getInstance()
.runProcessWithProgressSynchronously(() -> session.execute(getIncludedChanges(), getCommitMessage()),
commitExecutor.getActionText(), true, getProject());
if (completed) {
LOG.debug("Commit successful");
getHandlers().forEach(CheckinHandler::checkinSuccessful);
success = true;
defaultListCleaner.clean();
close(OK_EXIT_CODE);
}
else {
LOG.debug("Commit canceled");
session.executionCanceled();
}
}
catch (Throwable e) {
Messages.showErrorDialog(message("error.executing.commit", commitExecutor.getActionText(), e.getLocalizedMessage()),
commitExecutor.getActionText());
getHandlers().forEach(handler -> handler.checkinFailed(singletonList(new VcsException(e))));
}
finally {
CommitResultHandler resultHandler = myWorkflow.getResultHandler();
if (resultHandler != null) {
if (success) {
resultHandler.onSuccess(getCommitMessage());
}
else {
resultHandler.onFailure();
}
}
}
}
});
}
@Nullable
private String getInitialMessageFromVcs() {
Ref<String> result = new Ref<>();
ChangesUtil.processChangesByVcs(myProject, getIncludedChanges(), (vcs, changes) -> {
if (result.isNull()) {
CheckinEnvironment checkinEnvironment = vcs.getCheckinEnvironment();
if (checkinEnvironment != null) {
FilePath[] paths = ChangesUtil.getPaths(changes).toArray(new FilePath[0]);
result.set(checkinEnvironment.getDefaultMessageFor(paths));
}
}
});
return result.get();
}
private void saveCommentIntoChangeList() {
if (myLastSelectedListName != null) {
myListComments.put(myLastSelectedListName, myCommitMessageArea.getComment());
}
}
private void updateComment() {
LocalChangeList list = getChangeList();
if (!list.getName().equals(myLastSelectedListName)) {
saveCommentIntoChangeList();
myLastSelectedListName = list.getName();
myCommitMessageArea.setText(chooseNotNull(getCommentFromChangelist(list), myLastKnownComment));
}
}
@Nullable
private String getCommentFromChangelist(@NotNull LocalChangeList list) {
for (CommitMessageProvider provider : CommitMessageProvider.EXTENSION_POINT_NAME.getExtensionList()) {
String message = provider.getCommitMessage(list, getProject());
if (message != null) return message;
}
String changeListComment = list.getComment();
if (!isEmptyOrSpaces(changeListComment)) return changeListComment;
if (!list.hasDefaultName()) return list.getName();
return null;
}
@Override
public void dispose() {
myDisposed = true;
Disposer.dispose(myCommitOptions);
Disposer.dispose(myBrowser);
Disposer.dispose(myCommitMessageArea);
Disposer.dispose(myOKButtonUpdateAlarm);
super.dispose();
Disposer.dispose(myDiffDetails);
PropertiesComponent.getInstance().setValue(SPLITTER_PROPORTION_OPTION, mySplitter.getProportion(), SPLITTER_PROPORTION_OPTION_DEFAULT);
float usedProportion = myDetailsSplitter.getUsedProportion();
if (usedProportion > 0) {
PropertiesComponent.getInstance().setValue(DETAILS_SPLITTER_PROPORTION_OPTION, usedProportion, DETAILS_SPLITTER_PROPORTION_OPTION_DEFAULT);
}
PropertiesComponent.getInstance().setValue(DETAILS_SHOW_OPTION, myDetailsSplitter.isOn(), DETAILS_SHOW_OPTION_DEFAULT);
}
@NotNull
@Override
public String getCommitActionName() {
return myCommitActionName;
}
@NotNull
private static String getCommitActionName(@NotNull Collection<? extends AbstractVcs<?>> affectedVcses) {
Set<String> names = map2SetNotNull(affectedVcses, vcs -> {
CheckinEnvironment checkinEnvironment = vcs.getCheckinEnvironment();
return checkinEnvironment != null ? checkinEnvironment.getCheckinOperationName() : null;
});
if (names.size() == 1) {
return notNull(getFirstItem(names));
}
return VcsBundle.getString("commit.dialog.default.commit.operation.name");
}
private void stopUpdate() {
myUpdateDisabled = true;
}
private void restartUpdate() {
myUpdateDisabled = false;
myUpdateButtonsRunnable.run();
}
@NotNull
private CheckinHandler.ReturnResult performBeforeCommitChecks(@Nullable CommitExecutor executor) {
Ref<CheckinHandler.ReturnResult> compoundResultRef = Ref.create();
Runnable proceedRunnable = () -> {
FileDocumentManager.getInstance().saveAllDocuments();
compoundResultRef.set(runBeforeCheckinHandlers(executor));
};
Runnable runnable = myWorkflow.wrapWithCommitMetaHandlers(proceedRunnable);
myWorkflow.doRunBeforeCommitChecks(getChangeList(), runnable);
return notNull(compoundResultRef.get(), CheckinHandler.ReturnResult.CANCEL);
}
@NotNull
private CheckinHandler.ReturnResult runBeforeCheckinHandlers(@Nullable CommitExecutor executor) {
for (CheckinHandler handler : getHandlers()) {
if (!handler.acceptExecutor(executor)) continue;
LOG.debug("CheckinHandler.beforeCheckin: " + handler);
CheckinHandler.ReturnResult result = handler.beforeCheckin(executor, myWorkflow.getAdditionalDataConsumer());
if (result != CheckinHandler.ReturnResult.COMMIT) return result;
}
return CheckinHandler.ReturnResult.COMMIT;
}
private boolean saveCommitOptions() {
try {
saveState();
return true;
}
catch(InputException ex) {
ex.show();
return false;
}
}
private class DefaultListCleaner {
private final boolean myToClean;
private DefaultListCleaner() {
int selectedSize = getIncludedChanges().size();
LocalChangeList selectedList = getChangeList();
int totalSize = selectedList.getChanges().size();
myToClean = totalSize == selectedSize && selectedList.hasDefaultName();
}
void clean() {
if (myToClean) {
ChangeListManager.getInstance(myProject).editComment(LocalChangeList.DEFAULT_NAME, "");
}
}
}
private void saveComments(boolean isOk) {
saveCommentIntoChangeList();
if (isOk) {
myVcsConfiguration.saveCommitMessage(getCommitMessage());
int selectedSize = getIncludedChanges().size();
int totalSize = getChangeList().getChanges().size();
if (totalSize > selectedSize) {
myListComments.remove(myLastSelectedListName);
}
}
ChangeListManager changeListManager = ChangeListManager.getInstance(myProject);
myListComments.forEach((changeListName, comment) -> changeListManager.editComment(changeListName, comment));
}
@Override
public void doCancelAction() {
myCommitOptions.saveChangeListComponentsState();
saveComments(false);
LineStatusTrackerManager.getInstanceImpl(myProject).resetExcludedFromCommitMarkers();
super.doCancelAction();
}
@NotNull
@Override
protected JComponent createCenterPanel() {
return myDetailsSplitter.getComponent();
}
@Deprecated
@NotNull
public Set<? extends AbstractVcs> getAffectedVcses() {
return isDefaultCommitEnabled() ? getWorkflowVcses() : emptySet();
}
@NotNull
@Override
public Collection<VirtualFile> getRoots() {
ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(myProject);
return map2SetNotNull(getDisplayedPaths(), filePath -> vcsManager.getVcsRootFor(filePath));
}
@NotNull
@Override
public JComponent getComponent() {
return mySplitter;
}
@Override
public boolean hasDiffs() {
return !getIncludedChanges().isEmpty() || !getIncludedUnversionedFiles().isEmpty();
}
@NotNull
@Override
public Collection<VirtualFile> getVirtualFiles() {
return mapNotNull(getIncludedPaths(), filePath -> filePath.getVirtualFile());
}
@NotNull
@Override
public Collection<Change> getSelectedChanges() {
return new ArrayList<>(getIncludedChanges());
}
@NotNull
@Override
public Collection<File> getFiles() {
return map(getIncludedPaths(), filePath -> filePath.getIOFile());
}
@NotNull
@Override
public Project getProject() {
return myProject;
}
@Override
public boolean vcsIsAffected(String name) {
return ProjectLevelVcsManager.getInstance(myProject).checkVcsIsActive(name) &&
exists(getWorkflowVcses(), vcs -> Comparing.equal(vcs.getName(), name));
}
@Override
public void setCommitMessage(@Nullable String commitMessage) {
myLastKnownComment = commitMessage;
myCommitMessageArea.setText(commitMessage);
myCommitMessageArea.requestFocusInMessage();
}
@Override
public void refresh() {
ChangeListManager.getInstance(myProject).invokeAfterUpdate(() -> {
myBrowser.updateDisplayedChangeLists();
myCommitOptions.refresh();
}, InvokeAfterUpdateMode.SILENT, "commit dialog", ModalityState.current());
}
@Override
public void saveState() {
myCommitOptions.saveState();
}
@Override
public void restoreState() {
myCommitOptions.restoreState();
}
// Used in plugins
@SuppressWarnings("unused")
@NotNull
public List<RefreshableOnComponent> getAdditionalComponents() {
return myCommitOptions.getAdditionalComponents();
}
private void updateButtons() {
if (myDisposed || myUpdateDisabled) return;
boolean enabled = hasDiffs();
if (myCommitAction != null) {
myCommitAction.setEnabled(enabled);
}
myExecutorActions.forEach(action -> action.updateEnabled(enabled));
myOKButtonUpdateAlarm.cancelAllRequests();
myOKButtonUpdateAlarm.addRequest(myUpdateButtonsRunnable, 300, ModalityState.stateForComponent(myBrowser));
}
private void updateLegend() {
if (myDisposed || myUpdateDisabled) return;
myChangesInfoCalculator.update(myBrowser.getDisplayedChanges(), getIncludedChanges(),
myBrowser.getDisplayedUnversionedFiles().size(),
getIncludedUnversionedFiles().size());
myLegend.update();
}
@NotNull
private List<FilePath> getIncludedPaths() {
List<FilePath> paths = new ArrayList<>();
for (Change change : getIncludedChanges()) {
paths.add(ChangesUtil.getFilePath(change));
}
for (VirtualFile file : getIncludedUnversionedFiles()) {
paths.add(VcsUtil.getFilePath(file));
}
return paths;
}
@NotNull
private List<FilePath> getDisplayedPaths() {
List<FilePath> paths = new ArrayList<>();
for (Change change : myBrowser.getDisplayedChanges()) {
paths.add(ChangesUtil.getFilePath(change));
}
for (VirtualFile file : myBrowser.getDisplayedUnversionedFiles()) {
paths.add(VcsUtil.getFilePath(file));
}
return paths;
}
@Override
@NonNls
protected String getDimensionServiceKey() {
return "CommitChangelistDialog" + LAYOUT_VERSION;
}
@Override
public JComponent getPreferredFocusedComponent() {
return myCommitMessageArea.getEditorField();
}
@Nullable
@Override
public Object getData(@NotNull String dataId) {
if (Refreshable.PANEL_KEY.is(dataId)) return this;
return StreamEx.of(myDataProviders)
.map(provider -> provider.getData(dataId))
.nonNull()
.findFirst()
.orElseGet(() -> myBrowser.getData(dataId));
}
@Override
public void addDataProvider(@NotNull DataProvider provider) {
myDataProviders.add(provider);
}
@Override
public void addExecutorListener(@NotNull CommitExecutorListener listener, @NotNull Disposable parent) {
myExecutorEventDispatcher.addListener(listener, parent);
}
@NotNull
@Override
public LocalChangeList getChangeList() {
return myBrowser.getSelectedChangeList();
}
@NotNull
@Override
public List<Change> getIncludedChanges() {
return myBrowser.getIncludedChanges();
}
@NotNull
@Override
public List<VirtualFile> getIncludedUnversionedFiles() {
return myBrowser.getIncludedUnversionedFiles();
}
@Override
public void includeIntoCommit(@NotNull Collection<?> items) {
myBrowser.getViewer().includeChanges(items);
}
@NotNull
@Override
public String getCommitMessage() {
return myCommitMessageArea.getComment();
}
@Override
public boolean confirmCommitWithEmptyMessage() {
return Messages.YES == Messages.showYesNoDialog(
message("confirmation.text.check.in.with.empty.comment"),
message("confirmation.title.check.in.with.empty.comment"),
Messages.getWarningIcon()
);
}
@NotNull
private CommitContext getCommitContext() {
return myWorkflow.getCommitContext();
}
@NotNull
private List<CheckinHandler> getHandlers() {
return myWorkflow.getCommitHandlers();
}
private boolean isDefaultCommitEnabled() {
return myWorkflow.isDefaultCommitEnabled();
}
@NotNull
private Set<? extends AbstractVcs<?>> getWorkflowVcses() {
return myWorkflow.getAffectedVcses();
}
@NotNull
public CommitDialogChangesBrowser getBrowser() {
return myBrowser;
}
@NotNull
CommitMessage getCommitMessageComponent() {
return myCommitMessageArea;
}
@NotNull
JComponent getBrowserBottomPanel() {
return myBrowserBottomPanel;
}
void inclusionChanged() {
getHandlers().forEach(CheckinHandler::includedChangesChanged);
updateButtons();
}
void selectedChangeListChanged() {
updateOnListSelection();
updateWarning();
}
@NotNull
static String getExecutorPresentableText(@NotNull CommitExecutor executor) {
return trimEllipsis(removeMnemonic(executor.getActionText()));
}
@NotNull
static String trimEllipsis(@NotNull String title) {
return StringUtil.trimEnd(StringUtil.trimEnd(title, "..."), "\u2026");
}
private void ensureDataIsActual(@NotNull Runnable runnable) {
ChangeListManager.getInstance(myProject).invokeAfterUpdate(
() -> {
myBrowser.updateDisplayedChangeLists();
runnable.run();
},
InvokeAfterUpdateMode.SYNCHRONOUS_CANCELLABLE, "Refreshing changelists...", ModalityState.current());
}
private class CommitExecutorAction extends AbstractAction {
@Nullable private final CommitExecutor myCommitExecutor;
CommitExecutorAction(@NotNull AnAction anAction) {
putValue(OptionAction.AN_ACTION, anAction);
myCommitExecutor = null;
}
CommitExecutorAction(@NotNull CommitExecutor commitExecutor) {
super(commitExecutor.getActionText());
myCommitExecutor = commitExecutor;
}
@Override
public void actionPerformed(ActionEvent e) {
if (myCommitExecutor != null) {
myExecutorEventDispatcher.getMulticaster().executorCalled(myCommitExecutor);
}
}
public void updateEnabled(boolean hasDiffs) {
if (myCommitExecutor != null) {
setEnabled(
hasDiffs || myCommitExecutor instanceof CommitExecutorBase && !((CommitExecutorBase)myCommitExecutor).areChangesRequired());
}
}
}
void changeDetails(boolean fromModelRefresh) {
SwingUtilities.invokeLater(() -> {
if (myDetailsSplitter.isOn()) {
myDiffDetails.refresh(fromModelRefresh);
}
});
}
private class MyChangeProcessor extends ChangeViewDiffRequestProcessor {
MyChangeProcessor(@NotNull Project project, boolean enablePartialCommit) {
super(project, DiffPlaces.COMMIT_DIALOG);
putContextUserData(DiffUserDataKeysEx.SHOW_READ_ONLY_LOCK, true);
putContextUserData(LocalChangeListDiffTool.ALLOW_EXCLUDE_FROM_COMMIT, enablePartialCommit);
putContextUserData(DiffUserDataKeysEx.LAST_REVISION_WITH_LOCAL, true);
}
@NotNull
@Override
protected List<Wrapper> getSelectedChanges() {
return wrap(myBrowser.getSelectedChanges(), myBrowser.getSelectedUnversionedFiles());
}
@NotNull
@Override
protected List<Wrapper> getAllChanges() {
return wrap(myBrowser.getDisplayedChanges(), myBrowser.getDisplayedUnversionedFiles());
}
@Override
protected void selectChange(@NotNull Wrapper change) {
myBrowser.selectEntries(singletonList(change.getUserObject()));
}
@NotNull
private List<Wrapper> wrap(@NotNull Collection<? extends Change> changes, @NotNull Collection<? extends VirtualFile> unversioned) {
return concat(map(changes, ChangeWrapper::new), map(unversioned, UnversionedFileWrapper::new));
}
@Override
protected void onAfterNavigate() {
doCancelAction();
}
}
private static class MyOptionsLayout extends AbstractLayoutManager {
@NotNull private final JComponent myPanel;
@NotNull private final CommitOptionsPanel myOptions;
private final int myMinOptionsWidth;
private final int myMaxOptionsWidth;
MyOptionsLayout(@NotNull JComponent panel, @NotNull CommitOptionsPanel options, int minOptionsWidth, int maxOptionsWidth) {
myPanel = panel;
myOptions = options;
myMinOptionsWidth = minOptionsWidth;
myMaxOptionsWidth = maxOptionsWidth;
}
@Override
public Dimension preferredLayoutSize(Container parent) {
Dimension size1 = myPanel.getPreferredSize();
Dimension size2 = myOptions.getPreferredSize();
return new Dimension(size1.width + size2.width, max(size1.height, size2.height));
}
@Override
public void layoutContainer(@NotNull Container parent) {
Rectangle bounds = parent.getBounds();
int preferredWidth = myOptions.getPreferredSize().width;
int optionsWidth = myOptions.isEmpty() ? 0 : max(min(myMaxOptionsWidth, preferredWidth), myMinOptionsWidth);
myPanel.setBounds(new Rectangle(0, 0, bounds.width - optionsWidth, bounds.height));
myOptions.setBounds(new Rectangle(bounds.width - optionsWidth, 0, optionsWidth, bounds.height));
}
}
}
|
package org.openlca.app.cloud.ui.diff;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.jface.action.Action;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;
import org.openlca.app.App;
import org.openlca.app.cloud.CloudUtil;
import org.openlca.app.cloud.JsonLoader;
import org.openlca.app.cloud.index.Diff;
import org.openlca.app.cloud.index.DiffIndex;
import org.openlca.app.db.Database;
import org.openlca.app.navigation.CategoryElement;
import org.openlca.app.navigation.DatabaseElement;
import org.openlca.app.navigation.INavigationElement;
import org.openlca.app.navigation.ModelElement;
import org.openlca.app.navigation.ModelTypeElement;
import org.openlca.app.navigation.Navigator;
import org.openlca.app.util.Actions;
import org.openlca.app.util.Error;
import org.openlca.app.util.UI;
import org.openlca.app.util.viewers.Viewers;
import org.openlca.cloud.api.RepositoryClient;
import org.openlca.cloud.model.data.Dataset;
import org.openlca.cloud.model.data.FetchRequestData;
import org.openlca.core.model.Category;
import org.openlca.core.model.ModelType;
import org.openlca.core.model.descriptors.CategorizedDescriptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SyncView extends ViewPart {
public final static String ID = "views.cloud.sync";
private final static Logger log = LoggerFactory.getLogger(SyncView.class);
private JsonLoader jsonLoader;
private SyncDiffViewer viewer;
private DiffNode input;
private List<INavigationElement<?>> currentSelection;
private String currentCommitId;
@Override
public void createPartControl(Composite parent) {
Composite body = new Composite(parent, SWT.NONE);
UI.gridLayout(body, 1, 0, 0);
RepositoryClient client = Database.getRepositoryClient();
jsonLoader = CloudUtil.getJsonLoader(client);
viewer = new SyncDiffViewer(body, jsonLoader);
Actions.bind(viewer.getViewer(), new OverwriteAction());
}
public void update(List<INavigationElement<?>> elements, String commitId) {
if (!Database.isConnected())
return;
this.currentSelection = elements;
this.currentCommitId = commitId;
if (jsonLoader == null)
jsonLoader = CloudUtil.getJsonLoader(Database.getRepositoryClient());
else
jsonLoader.setClient(Database.getRepositoryClient());
jsonLoader.setCommitId(commitId);
App.runWithProgress("Comparing data sets", () -> loadInput(elements, commitId));
if (input != null)
viewer.setInput(Collections.singleton(input));
}
private void loadInput(List<INavigationElement<?>> elements, String commitId) {
try {
RepositoryClient client = Database.getRepositoryClient();
if (client == null)
input = null;
DiffIndex index = Database.getDiffIndex();
List<FetchRequestData> descriptors = client.sync(commitId);
List<DiffResult> differences = createDifferences(descriptors, elements);
input = new DiffNodeBuilder(client.getConfig().getDatabase(), index).build(differences);
} catch (Exception e) {
log.error("Error loading remote data", e);
input = null;
}
}
private boolean isContainedIn(Dataset dataset, List<INavigationElement<?>> elements) {
if (elements == null || elements.isEmpty())
return true;
for (INavigationElement<?> element : elements)
if (element instanceof DatabaseElement)
return true; // skip searching since db element contains all
for (INavigationElement<?> element : elements)
if (isContainedIn(dataset, element))
return true;
return false;
}
private boolean isContainedIn(Dataset dataset, INavigationElement<?> element) {
if (element instanceof DatabaseElement)
return true;
if (element instanceof ModelTypeElement) {
ModelType type = ((ModelTypeElement) element).getContent();
if (type == dataset.type)
return true;
}
if (element instanceof CategoryElement) {
Category category = ((CategoryElement) element).getContent();
if (dataset.type == ModelType.CATEGORY)
if (category.getRefId().equals(dataset.refId))
return true;
if (dataset.type == category.getModelType())
if (dataset.fullPath != null && dataset.fullPath.startsWith(CloudUtil.getFullPath(category) + "/"))
return true;
}
if (element instanceof ModelElement) {
CategorizedDescriptor descriptor = ((ModelElement) element).getContent();
if (descriptor.getRefId().equals(dataset.refId))
return true;
}
for (INavigationElement<?> child : element.getChildren())
if (isContainedIn(dataset, child))
return true;
return false;
}
private List<DiffResult> createDifferences(List<FetchRequestData> remotes, List<INavigationElement<?>> elements) {
DiffIndex index = Database.getDiffIndex();
List<DiffResult> differences = new ArrayList<>();
Set<String> added = new HashSet<>();
for (FetchRequestData identifier : remotes) {
Diff local = index.get(identifier.refId);
if (local != null && !isContainedIn(local.getDataset(), elements))
continue;
if (local == null && !isContainedIn(identifier, elements))
continue;
differences.add(new DiffResult(identifier, local));
added.add(identifier.refId);
}
for (Diff diff : index.getAll())
if (!added.contains(diff.getDataset().refId))
if (isContainedIn(diff.getDataset(), elements))
differences.add(new DiffResult(diff));
return differences;
}
@Override
public void setFocus() {
}
private class OverwriteAction extends Action {
private Exception error;
private OverwriteAction() {
setText("Overwrite local changes");
}
@Override
public void run() {
List<DiffNode> selected = Viewers.getAllSelected(viewer.getViewer());
List<Dataset> remotes = collectDatasets(selected);
RepositoryClient client = Database.getRepositoryClient();
App.runWithProgress("#Downloading data...", () -> {
try {
client.download(remotes, currentCommitId);
} catch (Exception e) {
error = e;
}
});
if (error != null)
Error.showBox("Error during download", error.getMessage());
else {
Navigator.refresh();
update(currentSelection, currentCommitId);
}
}
private List<Dataset> collectDatasets(List<DiffNode> nodes) {
List<Dataset> remotes = new ArrayList<>();
for (DiffNode node : nodes) {
if (node.getContent().remote != null)
remotes.add(node.getContent().getDataset());
remotes.addAll(collectDatasets(node.children));
}
return remotes;
}
}
}
|
package org.jpmml.sparkml;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.transform.stream.StreamSource;
import jakarta.xml.bind.JAXBException;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.spark.SparkContext;
import org.apache.spark.ml.Transformer;
import org.apache.spark.sql.SparkSession;
import org.jpmml.model.JAXBUtil;
public class ConverterFactory {
private Map<RegexKey, ? extends Map<String, ?>> options = null;
public ConverterFactory(Map<RegexKey, ? extends Map<String, ?>> options){
setOptions(options);
}
public TransformerConverter<?> newConverter(Transformer transformer){
Class<? extends Transformer> clazz = transformer.getClass();
Class<? extends TransformerConverter<?>> converterClazz = ConverterFactory.converters.get(clazz);
if(converterClazz == null){
throw new IllegalArgumentException("Transformer class " + clazz.getName() + " is not supported");
}
TransformerConverter<?> converter;
try {
Constructor<? extends TransformerConverter<?>> converterConstructor = converterClazz.getDeclaredConstructor(clazz);
converter = converterConstructor.newInstance(transformer);
} catch(ReflectiveOperationException roe){
throw new IllegalArgumentException("Transformer class " + clazz.getName() + " is not supported", roe);
}
if(converter != null){
Map<RegexKey, ? extends Map<String, ?>> options = getOptions();
Map<String, Object> converterOptions = new LinkedHashMap<>();
options.entrySet().stream()
.filter(entry -> (entry.getKey()).test(transformer.uid()))
.map(entry -> entry.getValue())
.forEach(converterOptions::putAll);
converter.setOptions(converterOptions);
}
return converter;
}
public Map<RegexKey, ? extends Map<String, ?>> getOptions(){
return this.options;
}
private void setOptions(Map<RegexKey, ? extends Map<String, ?>> options){
this.options = Objects.requireNonNull(options);
}
static
public void checkVersion(){
SparkSession sparkSession;
try {
sparkSession = SparkSession.active();
} catch(IllegalStateException ise){
logger.warn("Failed to check Apache Spark ML version", ise);
return;
}
SparkContext sparkContext = sparkSession.sparkContext();
int[] version = parseVersion(sparkContext.version());
if(!Arrays.equals(ConverterFactory.VERSION, version)){
throw new IllegalArgumentException("Expected Apache Spark ML version " + formatVersion(ConverterFactory.VERSION) + ", got version " + formatVersion(version) + " (" + sparkContext.version() + ")");
}
}
static
public void checkApplicationClasspath(){
String string = "<PMML xmlns=\"http:
try {
JAXBUtil.unmarshalPMML(new StreamSource(new StringReader(string)));
} catch(JAXBException je){
throw new IllegalArgumentException("Expected JPMML-Model version 1.5.X, got a legacy version. See https://issues.apache.org/jira/browse/SPARK-15526", je);
}
}
static
public void checkNoShading(){
Package _package = TransformerConverter.class.getPackage();
String name = _package.getName();
if(!(name).equals("org.jpmml.sparkml")){
throw new IllegalArgumentException("Expected JPMML-SparkML converter classes to have package name prefix \'org.jpmml.sparkml\', got package name prefix \'" + name + "\'");
}
}
static
private void init(ClassLoader classLoader){
Enumeration<URL> urls;
try {
urls = classLoader.getResources("META-INF/sparkml2pmml.properties");
} catch(IOException ioe){
logger.warn("Failed to find resources", ioe);
return;
}
while(urls.hasMoreElements()){
URL url = urls.nextElement();
logger.trace("Loading resource " + url);
try(InputStream is = url.openStream()){
Properties properties = new Properties();
properties.load(is);
init(classLoader, properties);
} catch(IOException ioe){
logger.warn("Failed to load resource", ioe);
}
}
}
static
private void init(ClassLoader classLoader, Properties properties){
if(properties.isEmpty()){
return;
}
Set<String> keys = properties.stringPropertyNames();
for(String key : keys){
String value = properties.getProperty(key);
logger.trace("Mapping transformer class " + key + " to transformer converter class " + value);
Class<? extends Transformer> clazz;
try {
clazz = (Class)classLoader.loadClass(key);
} catch(ClassNotFoundException cnfe){
logger.warn("Failed to load transformer class", cnfe);
continue;
}
if(!(Transformer.class).isAssignableFrom(clazz)){
throw new IllegalArgumentException("Transformer class " + clazz.getName() + " is not a subclass of " + Transformer.class.getName());
} // End if
Class<? extends TransformerConverter<?>> converterClazz;
try {
converterClazz = (Class)classLoader.loadClass(value);
} catch(ClassNotFoundException cnfe){
logger.warn("Failed to load transformer converter class", cnfe);
continue;
}
if(!(TransformerConverter.class).isAssignableFrom(converterClazz)){
throw new IllegalArgumentException("Transformer converter class " + converterClazz.getName() + " is not a subclass of " + TransformerConverter.class.getName());
}
ConverterFactory.converters.put(clazz, converterClazz);
}
}
static
private int[] parseVersion(String string){
Pattern pattern = Pattern.compile("^(\\d+)\\.(\\d+)(\\..*)?$");
Matcher matcher = pattern.matcher(string);
if(!matcher.matches()){
return new int[]{-1, -1};
}
return new int[]{Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2))};
}
static
private String formatVersion(int[] version){
return String.valueOf(version[0]) + "." + String.valueOf(version[1]);
}
private static final int[] VERSION = {3, 0};
private static final Map<Class<? extends Transformer>, Class<? extends TransformerConverter<?>>> converters = new LinkedHashMap<>();
private static final Logger logger = LogManager.getLogger(ConverterFactory.class);
static {
ClassLoader clazzLoader = ConverterFactory.class.getClassLoader();
ConverterFactory.init(clazzLoader);
}
}
|
package com.google.sps.utils;
import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.google.sps.data.Book;
import com.google.sps.data.BookQuery;
import java.util.ArrayList;
import org.apache.commons.lang3.SerializationUtils;
public class BooksMemoryUtils {
/**
* This function stores each Book object an ArrayList of Book objects in DataStore as a Book
* Entity with the corresponding properties
*
* @param books ArrayList of Book objects to store
* @param startIndex index to start order at
*/
public static void storeBooks(ArrayList<Book> books, int startIndex) {
for (int i = 0; i < books.size(); ++i) {
long timestamp = System.currentTimeMillis();
Entity bookEntity = new Entity("Book");
Key key = bookEntity.getKey();
Book currentBook = books.get(i);
currentBook.setOrder(i + startIndex);
byte[] bookData = SerializationUtils.serialize(currentBook);
Blob bookBlob = new Blob(bookData);
bookEntity.setProperty("title", currentBook.getTitle());
bookEntity.setProperty("book", bookBlob);
bookEntity.setProperty("order", i + startIndex);
bookEntity.setProperty("timestamp", timestamp);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
datastore.put(bookEntity);
}
}
/**
* This function stores a BookQuery Object in DataStore as a BookQuery Entity with the
* corresponding properties
*
* @param query BookQuery object to store
*/
public static void storeBookQuery(BookQuery query) {
long timestamp = System.currentTimeMillis();
Entity bookQueryEntity = new Entity("BookQuery");
byte[] bookQueryData = SerializationUtils.serialize(query);
Blob bookQueryBlob = new Blob(bookQueryData);
bookQueryEntity.setProperty("bookQuery", bookQueryBlob);
bookQueryEntity.setProperty("timestamp", timestamp);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
datastore.put(bookQueryEntity);
}
/**
* This function stores a the parameter integers in DataStore as a Indices Entity with the
* corresponding properties
*
* @param startIndex index to start retrieving Volume objects from
* @param resultsStored number of results stored
* @param totalResults total matches in Google Book API
* @param displayNum number of results displayed request
*/
public static void storeIndices(
int startIndex, int totalResults, int resultsStored, int displayNum) {
long timestamp = System.currentTimeMillis();
Entity indicesEntity = new Entity("Indices");
indicesEntity.setProperty("startIndex", startIndex);
indicesEntity.setProperty("resultsStored", resultsStored);
indicesEntity.setProperty("totalResults", totalResults);
indicesEntity.setProperty("displayNum", displayNum);
indicesEntity.setProperty("timestamp", timestamp);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
datastore.put(indicesEntity);
}
/** This function deletes all Entitys in Datastore of type BookQuery, Book, and Indices */
public static void deleteAllStoredBookInformation() {
deleteStoredEntities("BookQuery");
deleteStoredEntities("Book");
deleteStoredEntities("Indices");
}
/**
* This function deletes all Entitys in Datastore of type specified by parameter
*
* @param entityName name of Entity to delete
*/
public static void deleteStoredEntities(String entityName) {
Query query = new Query(entityName).addSort("timestamp", SortDirection.DESCENDING);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
PreparedQuery results = datastore.prepare(query);
for (Entity entity : results.asIterable()) {
datastore.delete(entity.getKey());
}
}
/**
* This function returns a list of Book objects of length numToRetrieve from the stored Book
* objects in Datastore, starting at startIndex
*
* @param numToRetrieve number of Books to retrieve
* @param startIndex index to start retrieving results from
* @return ArrayList<Book>
*/
public static ArrayList<Book> getStoredBooksToDisplay(int numToRetrieve, int startIndex) {
Query query = new Query("Book").addSort("order", SortDirection.ASCENDING);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
PreparedQuery results = datastore.prepare(query);
ArrayList<Book> books = new ArrayList<>();
int added = 0;
for (Entity entity : results.asIterable()) {
if (getStoredBookIndex(entity) >= startIndex) {
if (added < numToRetrieve) {
books.add(getBookFromEntity(entity));
++added;
} else {
break;
}
}
}
return books;
}
/**
* This function returns the Book object stored in the Book Entity parameter in Datastore
*
* @param bookEntity Entity in Datastore
* @return Book object
*/
public static Book getBookFromEntity(Entity bookEntity) {
Blob bookBlob = (Blob) bookEntity.getProperty("book");
Book book = SerializationUtils.deserialize(bookBlob.getBytes());
return book;
}
/**
* This function returns the index of the the Book Entity parameter in Datastore
*
* @param bookEntity Entity in Datastore
* @return int index
*/
public static int getStoredBookIndex(Entity bookEntity) {
Long lngValue = (Long) bookEntity.getProperty("order");
return lngValue.intValue();
}
/**
* This function returns the BookQuery object stored in Datastore, storing the parameters for
* previous BookQuery
*
* @return BookQuery object
*/
public static BookQuery getStoredBookQuery() {
Query query = new Query("BookQuery");
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Entity entity = datastore.prepare(query).asSingleEntity();
Blob bookQueryBlob = (Blob) entity.getProperty("bookQuery");
return SerializationUtils.deserialize(bookQueryBlob.getBytes());
}
/**
* This function returns the previous index specified by indexName stored in Datastore Indices
* Entity
*
* @param indexName name of Indices: startIndex, resultsStored, totalResults, or displayNum
* @return int startIndex
*/
public static int getStoredIndices(String indexName) {
Query query = new Query("Indices");
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Entity entity = datastore.prepare(query).asSingleEntity();
Long lngValue = (Long) entity.getProperty(indexName);
return lngValue.intValue();
}
/**
* This function returns the stored Book object that matches the parameter orderNum from Datastore
* and throws an exception if the requested Book doesn't exist
*
* @param orderNum order number of book to retrieve
* @param startIndex index to start retrieving results from
* @return Book object
*/
public static Book getBookFromOrderNum(int orderNum, int startIndex)
throws IllegalArgumentException {
Query query = new Query("Book").addSort("order", SortDirection.ASCENDING);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
PreparedQuery results = datastore.prepare(query);
for (Entity entity : results.asIterable()) {
if (getStoredBookIndex(entity) == orderNum) {
return getBookFromEntity(entity);
}
}
throw new IllegalArgumentException();
}
}
|
package org.hackerrank.java.datastructure;
import java.util.Scanner;
public class Array1DPart2
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int[][] sequences = new int[scanner.nextInt()][];
int[] jumps = new int[sequences.length];
for(int i = 0; i < sequences.length; i++)
{
sequences[i] = new int[scanner.nextInt()];
jumps[i] = scanner.nextInt();
for(int j = 0; j < sequences[i].length; j++)
{
sequences[i][j] = scanner.nextInt();
}
}
scanner.close();
for(int i = 0; i < sequences.length; i++)
{
int currentIndex = 0;
int currentStart = 0;
boolean solveable = false;
while(!solveable)
{
if(sequences[i][currentIndex + jumps[i]] == 0)
{
currentIndex += jumps[i];
}
}
}
}
}
|
package com.nativelibs4java.opencl;
import static com.nativelibs4java.opencl.CLException.error;
import com.nativelibs4java.opencl.CLPlatform.DeviceFeature;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.logging.*;
import com.nativelibs4java.opencl.library.OpenCLLibrary;
import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_platform_id;
import org.bridj.*;
import org.bridj.util.ProcessUtils;
import org.ochafik.util.string.StringUtils;
import static org.bridj.Pointer.*;
/**
* Entry point class for the OpenCL4Java Object-oriented wrappers around the OpenCL API.<br/>
* @author Olivier Chafik
*/
public class JavaCL {
static final boolean debug = "true".equals(System.getProperty("javacl.debug")) || "1".equals(System.getenv("JAVACL_DEBUG"));
static final boolean verbose = debug || "true".equals(System.getProperty("javacl.verbose")) || "1".equals(System.getenv("JAVACL_VERBOSE"));
static final int minLogLevel = Level.WARNING.intValue();
static final String JAVACL_DEBUG_COMPILER_FLAGS_PROP = "JAVACL_DEBUG_COMPILER_FLAGS";
static List<String> DEBUG_COMPILER_FLAGS;
static boolean shouldLog(Level level) {
return verbose || level.intValue() >= minLogLevel;
}
static boolean log(Level level, String message, Throwable ex) {
if (!shouldLog(level))
return true;
Logger.getLogger(JavaCL.class.getSimpleName()).log(level, message, ex);
return true;
}
static boolean log(Level level, String message) {
log(level, message, null);
return true;
}
private static int getPlatformIDs(int count, Pointer<cl_platform_id> out, Pointer<Integer> pCount) {
try {
return CL.clIcdGetPlatformIDsKHR(count, out, pCount);
} catch (Throwable th) {
return CL.clGetPlatformIDs(count, out, pCount);
}
}
@org.bridj.ann.Library("OpenCLProbe")
@org.bridj.ann.Convention(org.bridj.ann.Convention.Style.StdCall)
public static class OpenCLProbeLibrary {
static {
BridJ.setNativeLibraryActualName("OpenCLProbe", "OpenCL");
BridJ.register();
}
@org.bridj.ann.Optional
public native static synchronized int clGetPlatformIDs(int cl_uint1, Pointer<OpenCLLibrary.cl_platform_id > cl_platform_idPtr1, Pointer<Integer > cl_uintPtr1);
@org.bridj.ann.Optional
public native static synchronized int clIcdGetPlatformIDsKHR(int cl_uint1, Pointer<OpenCLLibrary.cl_platform_id > cl_platform_idPtr1, Pointer<Integer > cl_uintPtr1);
public boolean isValid() {
Pointer<Integer> pCount = allocateInt();
int err;
try {
err = clIcdGetPlatformIDsKHR(0, null, pCount);
} catch (Throwable th) {
try {
err = clGetPlatformIDs(0, null, pCount);
} catch (Throwable th2) {
return false;
}
}
return err == OpenCLLibrary.CL_SUCCESS && pCount.get() > 0;
}
}
static final OpenCLLibrary CL;
static {
{
OpenCLProbeLibrary probe = new OpenCLProbeLibrary();
try {
if (!probe.isValid()) {
String alt;
if (Platform.is64Bits() && BridJ.getNativeLibraryFile(alt = "atiocl64") != null ||
BridJ.getNativeLibraryFile(alt = "atiocl32") != null ||
BridJ.getNativeLibraryFile(alt = "atiocl") != null)
{
log(Level.INFO, "Hacking around ATI's weird driver bugs (using atiocl library instead of OpenCL)", null);
BridJ.setNativeLibraryActualName("OpenCL", alt);
}
}
} finally {
probe = null;
BridJ.unregister(OpenCLProbeLibrary.class);
}
}
if (debug) {
String debugArgs = System.getenv(JAVACL_DEBUG_COMPILER_FLAGS_PROP);
if (debugArgs != null)
DEBUG_COMPILER_FLAGS = Arrays.asList(debugArgs.split(" "));
else if (Platform.isMacOSX())
DEBUG_COMPILER_FLAGS = Arrays.asList("-g");
else
DEBUG_COMPILER_FLAGS = Arrays.asList("-O0", "-g");
int pid = ProcessUtils.getCurrentProcessId();
log(Level.INFO, "Debug mode enabled with compiler flags \"" + StringUtils.implode(DEBUG_COMPILER_FLAGS, " ") + "\" (can be overridden with env. var. JAVACL_DEBUG_COMPILER_FLAGS_PROP)");
log(Level.INFO, "You can debug your kernels with GDB using one of the following commands :\n"
+ "\tsudo gdb --tui --pid=" + pid + "\n"
+ "\tsudo ddd --debugger \"gdb --pid=" + pid + "\"\n"
+ "More info here :\n"
+ "\thttp://code.google.com/p/javacl/wiki/DebuggingKernels");
}
CL = new OpenCLLibrary();
}
/**
* List the OpenCL implementations that contain at least one GPU device.
*/
public static CLPlatform[] listGPUPoweredPlatforms() {
CLPlatform[] platforms = listPlatforms();
List<CLPlatform> out = new ArrayList<CLPlatform>(platforms.length);
for (CLPlatform platform : platforms) {
if (platform.listGPUDevices(true).length > 0)
out.add(platform);
}
return out.toArray(new CLPlatform[out.size()]);
}
/**
* Lists all available OpenCL implementations.
*/
public static CLPlatform[] listPlatforms() {
Pointer<Integer> pCount = allocateInt();
error(getPlatformIDs(0, null, pCount));
int nPlats = pCount.get();
if (nPlats == 0)
return new CLPlatform[0];
Pointer<cl_platform_id> ids = allocateTypedPointers(cl_platform_id.class, nPlats);
error(getPlatformIDs(nPlats, ids, null));
CLPlatform[] platforms = new CLPlatform[nPlats];
for (int i = 0; i < nPlats; i++) {
platforms[i] = new CLPlatform(ids.get(i));
}
return platforms;
}
/**
* Creates an OpenCL context formed of the provided devices.<br/>
* It is generally not a good idea to create a context with more than one device,
* because much data is shared between all the devices in the same context.
* @param devices devices that are to form the new context
* @return new OpenCL context
*/
public static CLContext createContext(Map<CLPlatform.ContextProperties, Object> contextProperties, CLDevice... devices) {
return devices[0].getPlatform().createContext(contextProperties, devices);
}
/**
* Allows the implementation to release the resources allocated by the OpenCL compiler. <br/>
* This is a hint from the application and does not guarantee that the compiler will not be used in the future or that the compiler will actually be unloaded by the implementation. <br/>
* Calls to Program.build() after unloadCompiler() will reload the compiler, if necessary, to build the appropriate program executable.
*/
public static void unloadCompiler() {
error(CL.clUnloadCompiler());
}
/**
* Returns the "best" OpenCL device (currently, the one that has the largest amount of compute units).<br>
* For more control on what is to be considered a better device, please use the {@link JavaCL#getBestDevice(CLPlatform.DeviceFeature[]) } variant.<br>
* This is currently equivalent to <code>getBestDevice(MaxComputeUnits)</code>
*/
public static CLDevice getBestDevice() {
return getBestDevice(CLPlatform.DeviceFeature.MaxComputeUnits);
}
/**
* Returns the "best" OpenCL device based on the comparison of the provided prioritized device feature.<br>
* The returned device does not necessarily exhibit the features listed in preferredFeatures, but it has the best ordered composition of them.<br>
* For instance on a system with a GPU and a CPU device, <code>JavaCL.getBestDevice(CPU, MaxComputeUnits)</code> will return the CPU device, but on another system with two GPUs and no CPU device it will return the GPU that has the most compute units.
*/
public static CLDevice getBestDevice(CLPlatform.DeviceFeature... preferredFeatures) {
List<CLDevice> devices = new ArrayList<CLDevice>();
for (CLPlatform platform : listPlatforms())
devices.addAll(Arrays.asList(platform.listAllDevices(true)));
return CLPlatform.getBestDevice(Arrays.asList(preferredFeatures), devices);
}
/**
* Creates an OpenCL context with the "best" device (see {@link JavaCL#getBestDevice() })
*/
public static CLContext createBestContext() {
return createBestContext(DeviceFeature.MaxComputeUnits);
}
/**
* Creates an OpenCL context with the "best" device based on the comparison of the provided prioritized device feature (see {@link JavaCL#getBestDevice(CLPlatform.DeviceFeature) })
*/
public static CLContext createBestContext(CLPlatform.DeviceFeature... preferredFeatures) {
CLDevice device = getBestDevice(preferredFeatures);
return device.getPlatform().createContext(null, device);
}
/**
* Creates an OpenCL context able to share entities with the current OpenGL context.
* @throws RuntimeException if JavaCL is unable to create an OpenGL-shared OpenCL context.
*/
public static CLContext createContextFromCurrentGL() {
RuntimeException first = null;
for (CLPlatform platform : listPlatforms()) {
try {
CLContext ctx = platform.createContextFromCurrentGL();
if (ctx != null)
return ctx;
} catch (RuntimeException ex) {
if (first == null)
first = ex;
}
}
throw new RuntimeException("Failed to create an OpenCL context based on the current OpenGL context", first);
}
static File userJavaCLDir = new File(new File(System.getProperty("user.home")), ".javacl");
static File userCacheDir = new File(userJavaCLDir, "cache");
static synchronized File createTempFile(String prefix, String suffix, String category) {
File dir = new File(userJavaCLDir, category);
dir.mkdirs();
try {
return File.createTempFile(prefix, suffix, dir);
} catch (IOException ex) {
throw new RuntimeException("Failed to create a temporary directory for category '" + category + "' in " + userJavaCLDir + ": " + ex.getMessage(), ex);
}
}
static synchronized File createTempDirectory(String prefix, String suffix, String category) {
File file = createTempFile(prefix, suffix, category);
file.delete();
file.mkdir();
return file;
}
}
|
package com.psddev.dari.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.instrument.ClassDefinition;
import java.lang.instrument.Instrumentation;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.psddev.dari.util.sa.JvmAnalyzer;
import com.psddev.dari.util.sa.JvmLogger;
<url-pattern>/*</url-pattern>
</filter-mapping>
* }</pre></blockquote>
*
* <p>And the application must include a {@code build.properties} file
* that specifies the locations of the source code:
*
* <ul>
* <li>{@link CodeUtils#JAVA_SOURCE_DIRECTORY_PROPERTY}
* <li>{@link #WEBAPP_SOURCES_PROPERTY}
* </ul>
*
* <p>You can skip this step if the project uses Apache Maven to manage
* the build and inherits from {@code com.psddev:dari-parent}, because
* that parent POM automatically adds those properties during the
* {@code generate-resources} phase.
*/
public class SourceFilter extends AbstractFilter {
/**
* Build property that specifies the directory containing the
* web application sources, such as JSPs.
*/
public static final String WEBAPP_SOURCES_PROPERTY = "webappSourceDirectory";
public static final String DEFAULT_INTERCEPT_PATH = "/_sourceFilter";
public static final String INTERCEPT_PATH_SETTING = "dari/sourceFilterInterceptPath";
public static final String DEFAULT_RELOADER_PATH = "/reloader/";
public static final String RELOADER_PATH_SETTING = "dari/sourceFilterReloaderPath";
public static final String RELOADER_ACTION_PARAMETER = "action";
public static final String RELOADER_PING_ACTION = "ping";
public static final String RELOADER_RELOAD_ACTION = "reload";
public static final String RELOADER_CONTEXT_PATH_PARAMETER = "contextPath";
public static final String RELOADER_REQUEST_PATH_PARAMETER = "requestPath";
private static final Logger LOGGER = LoggerFactory.getLogger(SourceFilter.class);
private static final String CLASSES_PATH = "/WEB-INF/classes/";
private static final String BUILD_PROPERTIES_PATH = "build.properties";
private static final String ISOLATING_RESPONSE_ATTRIBUTE = SourceFilter.class.getName() + ".isolatingResponse";
private static final String IS_ISOLATION_DONE_ATTRIBUTE = SourceFilter.class.getName() + ".isIsolationDone";
private static final String COPIED_ATTRIBUTE = SourceFilter.class.getName() + ".copied";
private static final String CATALINA_BASE_PROPERTY = "catalina.base";
private static final String RELOADER_MAVEN_ARTIFACT_ID = "dari-reloader-tomcat6";
private static final String RELOADER_MAVEN_VERSION = "2.0-SNAPSHOT";
private static final String RELOADER_MAVEN_URL = "https://artifactory.psdops.com/public/com/psddev/" + RELOADER_MAVEN_ARTIFACT_ID + "/" + RELOADER_MAVEN_VERSION + "/";
private static final Pattern BUILD_NUMBER_PATTERN = Pattern.compile("<buildNumber>([^<]*)</buildNumber>");
private static final Pattern TIMESTAMP_PATTERN = Pattern.compile("<timestamp>([^<]*)</timestamp>");
private File classOutput;
private final Set<File> javaSourcesSet = new HashSet<File>();
private Map<JavaFileObject, Long> javaSourceFileModifieds;
private final Map<String, File> webappSourcesMap = new HashMap<String, File>();
private final Map<File, Long> webappSourceFileModifieds = new ConcurrentHashMap<File, Long>();
private final Map<String, Date> changedClassTimes = new TreeMap<String, Date>();
private final Map<Class<?>, List<AnalysisResult>> analysisResultsByClass = new TreeMap<Class<?>, List<AnalysisResult>>(new Comparator<Class<?>>() {
@Override
public int compare(Class<?> x, Class<?> y) {
return x.getName().compareTo(y.getName());
}
});
@Override
protected void doInit() {
if (ToolProvider.getSystemJavaCompiler() == null) {
LOGGER.info("Java compiler not available!");
return;
}
ServletContext context = getServletContext();
String classOutputString = context.getRealPath(CLASSES_PATH);
if (classOutputString == null) {
LOGGER.info("Can't get the real path to [{}]!", CLASSES_PATH);
return;
}
classOutput = new File(classOutputString);
if (classOutput.exists()) {
LOGGER.info("Saving recompiled Java classes to [{}]", classOutput);
} else {
LOGGER.info("[{}] doesn't exist!", classOutput);
classOutput = null;
return;
}
javaSourcesSet.addAll(CodeUtils.getSourceDirectories());
processWarBuildProperties(context, "");
for (String contextPath : JspUtils.getEmbeddedSettings(context).keySet()) {
processWarBuildProperties(context, contextPath);
}
}
/**
* Processes the build properties file associated with the given
* {@code context} and {@code contextPath} and adds its source
* directories.
*
* @param context Can't be {@code null}.
* @param contextPath Can't be {@code null}.
*/
private void processWarBuildProperties(ServletContext context, String contextPath) {
InputStream buildPropertiesInput = context.getResourceAsStream(contextPath + CLASSES_PATH + BUILD_PROPERTIES_PATH);
if (buildPropertiesInput == null) {
return;
}
try {
try {
Properties buildProperties = new Properties();
buildProperties.load(buildPropertiesInput);
String javaSourcesString = buildProperties.getProperty(CodeUtils.JAVA_SOURCE_DIRECTORY_PROPERTY);
if (javaSourcesString != null) {
File javaSources = new File(javaSourcesString);
if (javaSources.exists()) {
javaSourcesSet.add(javaSources);
LOGGER.info("Found Java sources in [{}]", javaSources);
}
}
String webappSourcesString = buildProperties.getProperty(WEBAPP_SOURCES_PROPERTY);
if (webappSourcesString != null) {
File webappSources = new File(webappSourcesString);
if (webappSources.exists()) {
LOGGER.info("Copying webapp sources from [{}] to [{}/]", webappSources, contextPath);
webappSourcesMap.put(contextPath, webappSources);
}
}
} finally {
buildPropertiesInput.close();
}
} catch (IOException error) {
LOGGER.debug("Can't read WAR build properties!", error);
}
}
@Override
protected void doDestroy() {
classOutput = null;
javaSourcesSet.clear();
javaSourceFileModifieds = null;
webappSourcesMap.clear();
webappSourceFileModifieds.clear();
changedClassTimes.clear();
}
@Override
protected void doDispatch(
HttpServletRequest request,
HttpServletResponse response,
FilterChain chain)
throws Exception {
if (Settings.isProduction()) {
chain.doFilter(request, response);
return;
}
if (request.getAttribute(IS_ISOLATION_DONE_ATTRIBUTE) != null) {
return;
}
IsolatingResponse isolatingResponse = (IsolatingResponse) request.getAttribute(ISOLATING_RESPONSE_ATTRIBUTE);
if (isolatingResponse != null) {
if (JspUtils.getCurrentServletPath(request).equals(isolatingResponse.jsp)) {
@SuppressWarnings("all")
HtmlWriter html = new HtmlWriter(isolatingResponse.getResponse().getWriter());
html.putAllStandardDefaults();
try {
StringWriter writer = new StringWriter();
JspUtils.include(request, response, writer, request.getParameter("_draft"));
html.writeStart("pre");
html.writeHtml(writer.toString().trim());
html.writeEnd();
} catch (RuntimeException ex) {
html.writeStart("pre", "class", "alert alert-error");
html.writeObject(ex);
html.writeEnd();
} finally {
request.setAttribute(IS_ISOLATION_DONE_ATTRIBUTE, Boolean.TRUE);
}
return;
}
}
copyWebappSource(request);
super.doDispatch(request, response, chain);
}
@Override
protected void doRequest(
final HttpServletRequest request,
HttpServletResponse response,
FilterChain chain)
throws IOException, ServletException {
copyResources.get();
// Intercept special actions.
if (!ObjectUtils.isBlank(request.getParameter("_reload"))
&& isReloaderAvailable(request)) {
compileJavaSourceFiles();
response.sendRedirect(StringUtils.addQueryParameters(
getReloaderPath(),
RELOADER_CONTEXT_PATH_PARAMETER, request.getContextPath(),
RELOADER_REQUEST_PATH_PARAMETER, JspUtils.getAbsolutePath(request, "", "_reload", null),
RELOADER_ACTION_PARAMETER, RELOADER_RELOAD_ACTION));
return;
}
String servletPath = request.getServletPath();
if (servletPath.startsWith(getInterceptPath())) {
String action = request.getParameter("action");
if ("ping".equals(action)) {
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("OK");
} else if ("install".equals(action)) {
if (isReloaderAvailable(request)) {
String requestPath = request.getParameter("requestPath");
response.sendRedirect(ObjectUtils.isBlank(requestPath) ? "/" : requestPath);
} else {
@SuppressWarnings("all")
ReloaderInstaller installer = new ReloaderInstaller(request, response);
installer.writeStart();
}
} else if ("clear".equals(action)) {
analysisResultsByClass.clear();
} else {
throw new IllegalArgumentException(String.format(
"[%s] isn't a valid intercept action!", action));
}
return;
}
String contentType = ObjectUtils.getContentType(servletPath);
if (contentType.startsWith("image/")
|| contentType.startsWith("video/")
|| contentType.equals("text/css")
|| contentType.equals("text/javascript")) {
chain.doFilter(request, response);
return;
}
List<Diagnostic<? extends JavaFileObject>> diagnostics = compileJavaSourceFiles();
boolean requiresReload;
boolean hasBackgroundTasks;
if (diagnostics == null
&& !changedClassTimes.isEmpty()
&& !JspUtils.isAjaxRequest(request)) {
requiresReload = true;
if (hasBackgroundTasks()) {
hasBackgroundTasks = true;
} else if (isReloaderAvailable(request)) {
changedClassTimes.clear();
response.sendRedirect(StringUtils.addQueryParameters(
getReloaderPath(),
RELOADER_CONTEXT_PATH_PARAMETER, request.getContextPath(),
RELOADER_REQUEST_PATH_PARAMETER, JspUtils.getAbsolutePath(request, ""),
RELOADER_ACTION_PARAMETER, RELOADER_RELOAD_ACTION));
return;
} else {
hasBackgroundTasks = false;
}
} else {
requiresReload = false;
hasBackgroundTasks = false;
}
IsolatingResponse isolatingResponse = null;
String jsp = request.getParameter("_jsp");
if (!ObjectUtils.isBlank(jsp)) {
response.setContentType("text/plain");
isolatingResponse = new IsolatingResponse(response, jsp);
response = isolatingResponse;
request.setAttribute(ISOLATING_RESPONSE_ATTRIBUTE, isolatingResponse);
}
chain.doFilter(request, response);
if (diagnostics == null
&& analysisResultsByClass.isEmpty()
&& (changedClassTimes.isEmpty()
|| JspUtils.isAjaxRequest(request)
|| isolatingResponse != null)) {
return;
}
// Can't reload automatically so at least let the user know
// if viewing an HTML page.
String responseContentType = response.getContentType();
if (responseContentType == null
|| !responseContentType.startsWith("text/html")) {
return;
}
HtmlWriter noteWriter = new HtmlWriter(response.getWriter());
noteWriter.putDefault(StackTraceElement.class, HtmlFormatter.STACK_TRACE_ELEMENT);
noteWriter.putDefault(Throwable.class, HtmlFormatter.THROWABLE);
noteWriter.writeStart("div",
"class", "dari-sourceFilter-notification",
"style", noteWriter.cssString(
"background", "#002b36",
"border-bottom-left-radius", "2px",
"box-sizing", "border-box",
"color", "#839496",
"font-family", "'Helvetica Neue', 'Arial', sans-serif",
"font-size", "13px",
"font-weight", "normal",
"line-height", "18px",
"margin", "0",
"max-height", "50%",
"max-width", "350px",
"overflow", "auto",
"padding", "0 35px 10px 10px",
"position", "fixed",
"right", "0",
"top", "0",
"word-break", "break-all",
"word-wrap", "break-word",
"z-index", "1000000"));
noteWriter.writeStart("span",
"onclick",
"var notifications = document.querySelectorAll('.dari-sourceFilter-notification');"
+ "var notificationsIndex = 0;"
+ "var notificationsLength = notifications.length;"
+ "for (; notificationsIndex < notificationsLength; ++ notificationsIndex) {"
+ "var notification = notifications[notificationsIndex];"
+ "notification.parentNode.removeChild(notification);"
+ "}"
+ "var xhr = new XMLHttpRequest();"
+ "xhr.open('get', '" + StringUtils.escapeJavaScript(JspUtils.getAbsolutePath(request, getInterceptPath(), "action", "clear")) + "', true);"
+ "xhr.send('');"
+ "return false;",
"style", noteWriter.cssString(
"cursor", "pointer",
"font-size", "20px",
"height", "20px",
"line-height", "20px",
"position", "absolute",
"right", "5px",
"text-align", "center",
"top", "5px",
"width", "20px"));
noteWriter.writeHtml("\u00d7");
noteWriter.writeEnd();
if (requiresReload) {
if (hasBackgroundTasks) {
noteWriter.writeHtml("The application wasn't reloaded automatically because there are background tasks running!");
} else {
noteWriter.writeHtml("The application must be reloaded before the changes to these classes become visible. ");
noteWriter.writeStart("a",
"href", JspUtils.getAbsolutePath(request, getInterceptPath(),
"action", "install",
"requestPath", JspUtils.getAbsolutePath(request, "")),
"style", "color: white; text-decoration: underline;");
noteWriter.writeHtml("Install the reloader");
noteWriter.writeEnd();
noteWriter.writeHtml(" to automate this process.");
noteWriter.writeElement("br");
noteWriter.writeElement("br");
for (Map.Entry<String, Date> entry : changedClassTimes.entrySet()) {
noteWriter.writeHtml(entry.getKey());
noteWriter.writeHtml(" - ");
noteWriter.writeObject(entry.getValue());
noteWriter.writeElement("br");
}
}
}
if (diagnostics != null) {
for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) {
JavaFileObject source = diagnostic.getSource();
writeDiagnostic(
noteWriter,
diagnostic.getKind(),
source != null ? source.getName() : "Unknown Source",
null,
diagnostic.getLineNumber(),
diagnostic.getColumnNumber(),
diagnostic.getMessage(null));
}
}
for (Map.Entry<Class<?>, List<AnalysisResult>> entry : analysisResultsByClass.entrySet()) {
File source = CodeUtils.getSource(entry.getKey().getName());
if (source != null) {
String sourceFileName = source.getPath();
for (AnalysisResult ar : entry.getValue()) {
writeDiagnostic(
noteWriter,
ar.getKind(),
sourceFileName,
ar.getMethod(),
ar.getLine(),
-1,
ar.getMessage());
}
}
}
noteWriter.writeEnd();
}
private void writeDiagnostic(
HtmlWriter writer,
Diagnostic.Kind kind,
String fileName,
Method method,
long lineNumber,
long columnNumber,
String message)
throws IOException {
String color;
switch (kind) {
case ERROR :
color = "#dc322f";
break;
case MANDATORY_WARNING :
case WARNING :
color = "#b58900";
break;
default :
color = "#839496";
break;
}
writer.writeStart("div", "style", writer.cssString(
"color", color,
"margin-top", "10px"));
writer.writeHtml('[');
writer.writeHtml(kind);
writer.writeHtml("] ");
writer.writeStart("a",
"target", "_blank",
"style", writer.cssString(
"color", color,
"text-decoration", "underline"),
"href", StringUtils.addQueryParameters(
"/_debug/code",
"action", "edit",
"file", fileName,
"line", lineNumber));
if (method != null) {
writer.writeHtml(method.getDeclaringClass().getName());
writer.writeHtml('.');
writer.writeHtml(method.getName());
} else {
int separatorAt = fileName.lastIndexOf(File.separatorChar);
writer.writeHtml(separatorAt > -1
? fileName.substring(separatorAt + 1)
: fileName);
}
if (lineNumber > 0) {
writer.writeHtml(':');
writer.writeHtml(lineNumber);
}
if (columnNumber > 0) {
writer.writeHtml(':');
writer.writeHtml(columnNumber);
}
writer.writeEnd();
writer.writeHtml(' ');
writer.writeHtml(message);
writer.writeEnd();
}
/**
* Returns the path that intercepts all special actions.
*
* @return Always starts and ends with a slash.
*/
private static String getInterceptPath() {
return StringUtils.ensureStart(Settings.getOrDefault(String.class, INTERCEPT_PATH_SETTING, DEFAULT_INTERCEPT_PATH), "/");
}
/**
* Returns the path to the application that can reload this one.
*
* @return Always starts and ends with a slash.
*/
private static String getReloaderPath() {
return StringUtils.ensureSurrounding(Settings.getOrDefault(String.class, RELOADER_PATH_SETTING, DEFAULT_RELOADER_PATH), "/");
}
/**
* Returns {@code true} if the reloader is available in the same
* server as this application.
*
* @param request Can't be {@code null}.
*/
private boolean isReloaderAvailable(HttpServletRequest request) {
String servletPath = request.getServletPath();
String reloaderPath = getReloaderPath();
if (!servletPath.startsWith(reloaderPath)) {
try {
URL pingUrl = new URL(StringUtils.addQueryParameters(
JspUtils.getHostUrl(request) + reloaderPath,
RELOADER_ACTION_PARAMETER, RELOADER_PING_ACTION));
// To avoid infinite redirects in case the ping hits this
// application.
URLConnection pingConnection = pingUrl.openConnection();
if (pingConnection instanceof HttpURLConnection) {
((HttpURLConnection) pingConnection).setInstanceFollowRedirects(false);
}
InputStream pingInput = pingConnection.getInputStream();
try {
return "OK".equals(IoUtils.toString(pingInput, StandardCharsets.UTF_8));
} finally {
pingInput.close();
}
} catch (IOException error) {
// If the ping fails for any reason, assume that the reloader
// isn't available.
}
}
return false;
}
/** Returns {@code true} if there are any background tasks running. */
private boolean hasBackgroundTasks() {
for (TaskExecutor executor : TaskExecutor.Static.getAll()) {
String executorName = executor.getName();
if (!("Periodic Caches".equals(executorName)
|| "Miscellaneous Tasks".equals(executorName))) {
for (Object task : executor.getTasks()) {
if (task instanceof Task && !((Task) task).isSafeToStop() && ((Task) task).isRunning()) {
return true;
}
}
}
}
return false;
}
// Copies all resources, throttled to run at most once per second.
private final Supplier<Void> copyResources = Suppliers.memoizeWithExpiration(new Supplier<Void>() {
@Override
public Void get() {
if (classOutput != null) {
for (File resourceDirectory : CodeUtils.getResourceDirectories()) {
Long jarModified = CodeUtils.getJarLastModified(resourceDirectory);
try {
copy(resourceDirectory, jarModified, resourceDirectory);
} catch (IOException error) {
throw new IllegalStateException(error);
}
}
}
ResourceBundle.clearCache();
return null;
}
private void copy(File resourceDirectory, Long jarModified, File resource) throws IOException {
if (resource.isDirectory()) {
for (File child : resource.listFiles()) {
copy(resourceDirectory, jarModified, child);
}
} else {
File output = new File(classOutput, resource.toString().substring(resourceDirectory.toString().length()).replace(File.separatorChar, '/'));
long resourceModified = resource.lastModified();
long outputModified = output.lastModified();
if ((jarModified == null
|| resourceModified > jarModified)
&& resourceModified > outputModified) {
IoUtils.copy(resource, output);
LOGGER.info("Copied [{}]", resource);
}
}
}
}, 1, TimeUnit.SECONDS);
// Compile any Java source files that's changed and redefine them
// in place if possible.
private synchronized List<Diagnostic<? extends JavaFileObject>> compileJavaSourceFiles() throws IOException {
if (javaSourcesSet.isEmpty()) {
return null;
}
boolean firstRun;
if (javaSourceFileModifieds == null) {
firstRun = true;
javaSourceFileModifieds = new HashMap<JavaFileObject, Long>();
} else {
firstRun = false;
}
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
Map<JavaFileObject, Long> newSourceFiles = new HashMap<JavaFileObject, Long>();
Map<String, Date> newChangedClassTimes = new HashMap<String, Date>();
List<ClassDefinition> toBeRedefined = new ArrayList<ClassDefinition>();
List<Diagnostic<? extends JavaFileObject>> diagnostics = null;
try {
fileManager.setLocation(StandardLocation.SOURCE_PATH, javaSourcesSet);
fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(classOutput));
// Find all source files that's changed.
for (JavaFileObject sourceFile : fileManager.list(
StandardLocation.SOURCE_PATH,
"",
Collections.singleton(JavaFileObject.Kind.SOURCE),
true)) {
// On first run, assume nothing has changed.
if (firstRun) {
javaSourceFileModifieds.put(sourceFile, sourceFile.getLastModified());
} else {
Long oldModified = javaSourceFileModifieds.get(sourceFile);
long newModified = sourceFile.getLastModified();
if (oldModified == null || oldModified != newModified) {
newSourceFiles.put(sourceFile, newModified);
}
}
}
if (!newSourceFiles.isEmpty()) {
LOGGER.info("Recompiling {}", newSourceFiles.keySet());
// Compiler can't use the current class loader so try to
// guess all of its class paths.
Set<File> classPaths = new LinkedHashSet<File>();
for (ClassLoader loader = ObjectUtils.getCurrentClassLoader();
loader != null;
loader = loader.getParent()) {
if (loader instanceof URLClassLoader) {
for (URL url : ((URLClassLoader) loader).getURLs()) {
File file = IoUtils.toFile(url, StandardCharsets.UTF_8);
if (file != null) {
classPaths.add(file);
}
}
}
}
fileManager.setLocation(StandardLocation.CLASS_PATH, classPaths);
// Remember the current class file modified times for later
// when we need to figure out what changed.
Map<JavaFileObject, Long> outputFileModifieds = new HashMap<JavaFileObject, Long>();
for (JavaFileObject outputFile : fileManager.list(
StandardLocation.CLASS_OUTPUT,
"",
Collections.singleton(JavaFileObject.Kind.CLASS),
true)) {
outputFileModifieds.put(outputFile, outputFile.getLastModified());
}
DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<JavaFileObject>();
if (!compiler.getTask(null, fileManager, diagnosticsCollector, Arrays.asList("-g"), null, newSourceFiles.keySet()).call()) {
diagnostics = diagnosticsCollector.getDiagnostics();
for (Diagnostic<? extends JavaFileObject> d : diagnostics) {
LOGGER.warn("Failed to compile: {}", d.getSource());
}
return diagnostics;
} else {
javaSourceFileModifieds.putAll(newSourceFiles);
Set<Class<? extends ClassEnhancer>> enhancerClasses = ClassFinder.findClasses(ClassEnhancer.class);
// Process any class files that's changed.
for (JavaFileObject outputFile : fileManager.list(
StandardLocation.CLASS_OUTPUT,
"",
Collections.singleton(JavaFileObject.Kind.CLASS),
true)) {
Long oldModified = outputFileModifieds.get(outputFile);
long newModified = outputFile.getLastModified();
if (oldModified != null && oldModified == newModified) {
continue;
}
// Enhance the bytecode.
InputStream input = outputFile.openInputStream();
byte[] bytecode;
try {
bytecode = IoUtils.toByteArray(input);
} finally {
input.close();
}
byte[] enhancedBytecode = ClassEnhancer.Static.enhance(bytecode, enhancerClasses);
if (enhancedBytecode != null) {
bytecode = enhancedBytecode;
}
OutputStream output = outputFile.openOutputStream();
try {
output.write(bytecode);
} finally {
output.close();
}
String outputClassName = fileManager.inferBinaryName(StandardLocation.CLASS_OUTPUT, outputFile);
Class<?> outputClass = ObjectUtils.getClassByName(outputClassName);
newChangedClassTimes.put(outputClassName, new Date(newModified));
if (outputClass != null) {
toBeRedefined.add(new ClassDefinition(outputClass, bytecode));
}
}
// Try to redefine the classes in place.
List<ClassDefinition> failures = CodeUtils.redefineClasses(toBeRedefined);
List<Class<?>> toBeAnalyzed = new ArrayList<Class<?>>();
toBeRedefined.removeAll(failures);
for (ClassDefinition success : toBeRedefined) {
Class<?> c = success.getDefinitionClass();
newChangedClassTimes.remove(c.getName());
toBeAnalyzed.add(c);
analysisResultsByClass.remove(c);
}
if (!toBeAnalyzed.isEmpty()) {
JvmAnalyzer.Static.analyze(toBeAnalyzed, new AnalysisResultLogger());
}
if (!failures.isEmpty() && LOGGER.isInfoEnabled()) {
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("Can't redefine [");
for (ClassDefinition failure : failures) {
messageBuilder.append(failure.getDefinitionClass().getName());
messageBuilder.append(", ");
}
messageBuilder.setLength(messageBuilder.length() - 2);
messageBuilder.append("]!");
}
}
}
} finally {
fileManager.close();
}
// Remember all classes that's changed but not yet redefined.
changedClassTimes.putAll(newChangedClassTimes);
return diagnostics != null && !diagnostics.isEmpty() ? diagnostics : null;
}
// Copies the webapp source associated with the given request.
private void copyWebappSource(HttpServletRequest request) throws IOException {
ServletContext context = getServletContext();
String path = JspUtils.getCurrentServletPath(request);
if (path.startsWith("/WEB-INF/_draft/")) {
return;
}
String contextPath = JspUtils.getEmbeddedContextPath(context, path);
File webappSources = webappSourcesMap.get(contextPath);
if (webappSources == null) {
return;
}
String outputFileString = context.getRealPath(path);
if (outputFileString == null) {
return;
}
@SuppressWarnings("unchecked")
Set<String> copied = (Set<String>) request.getAttribute(COPIED_ATTRIBUTE);
if (copied == null) {
copied = new HashSet<String>();
request.setAttribute(COPIED_ATTRIBUTE, copied);
}
if (copied.contains(outputFileString)) {
return;
} else {
copied.add(outputFileString);
}
File sourceFile = new File(webappSources, path.substring(contextPath.length()).replace('/', File.separatorChar));
File outputFile = new File(outputFileString);
if (sourceFile.isDirectory()
|| outputFile.isDirectory()) {
return;
}
if (sourceFile.exists()) {
if (!outputFile.exists()) {
IoUtils.createParentDirectories(outputFile);
} else {
Long oldModified = webappSourceFileModifieds.get(sourceFile);
long newModified = sourceFile.lastModified();
if (oldModified == null) {
webappSourceFileModifieds.put(sourceFile, newModified);
return;
} else if (oldModified != newModified) {
webappSourceFileModifieds.put(sourceFile, newModified);
} else if (newModified <= outputFile.lastModified()) {
return;
}
}
IoUtils.copy(sourceFile, outputFile);
LOGGER.info("Copied [{}]", sourceFile);
} else if (outputFile.exists()
&& !outputFile.isDirectory()) {
LOGGER.debug("[{}] disappeared!", sourceFile);
}
}
/** {@linkplain SourceFilter} utility methods. */
public static final class Static {
/**
* Returns the servlet path for pinging this web application to
* make sure that it's running.
*
* @return Never {@code null}.
*/
public static String getInterceptPingPath() {
return StringUtils.addQueryParameters(getInterceptPath(), "action", "ping");
}
/** @deprecated Use {@link CodeUtils#getInstrumentation} instead. */
@Deprecated
public static Instrumentation getInstrumentation() {
return CodeUtils.getInstrumentation();
}
}
/** Installs an web application that can reload other web applications. */
private class ReloaderInstaller extends HtmlWriter {
private final HttpServletRequest request;
private final HttpServletResponse response;
public ReloaderInstaller(
HttpServletRequest request,
HttpServletResponse response)
throws IOException {
super(response.getWriter());
this.request = request;
this.response = response;
}
public void writeStart() throws IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
writeTag("!doctype html");
writeStart("html");
writeStart("head");
writeStart("title").writeHtml("Installing Reloader").writeEnd();
writeStart("link",
"href", JspUtils.getAbsolutePath(request, "/_resource/bootstrap/css/bootstrap.css"),
"rel", "stylesheet",
"type", "text/css");
writeStart("style", "type", "text/css");
write(".hero-unit { background: transparent; left: 0; margin: -72px 0 0 60px; padding: 0; position: absolute; top: 50%; }");
write(".hero-unit h1 { line-height: 1.33; }");
writeEnd();
writeEnd();
writeStart("body");
writeStart("div", "class", "hero-unit");
writeStart("h1");
writeHtml("Installing Reloader");
writeEnd();
try {
writeStart("ul", "class", "muted");
try {
flush();
install();
writeStart("script", "type", "text/javascript");
write("location.href = '" + StringUtils.escapeJavaScript(
JspUtils.getAbsolutePath(request, "")) + "';");
writeEnd();
} finally {
writeEnd();
}
} catch (RuntimeException ex) {
writeObject(ex);
}
writeEnd();
writeEnd();
writeEnd();
}
private void addProgress(Object... messageParts) throws IOException {
writeStart("li");
for (int i = 0, length = messageParts.length; i < length; ++ i) {
Object part = messageParts[i];
if (i % 2 == 0) {
writeHtml(part);
} else {
writeStart("em");
writeHtml(part);
writeEnd();
}
}
writeEnd();
flush();
}
private void install() throws IOException {
String catalinaBase = System.getProperty(CATALINA_BASE_PROPERTY);
if (ObjectUtils.isBlank(catalinaBase)) {
throw new IllegalStateException(String.format(
"[%s] system property isn't set!", CATALINA_BASE_PROPERTY));
}
URL metadataUrl = new URL(RELOADER_MAVEN_URL + "maven-metadata.xml");
String metadata = IoUtils.toString(metadataUrl);
addProgress("Looking for it using ", metadataUrl);
Matcher timestampMatcher = TIMESTAMP_PATTERN.matcher(metadata);
if (!timestampMatcher.find()) {
throw new IllegalStateException("No timestamp in Maven metadata!");
}
Matcher buildNumberMatcher = BUILD_NUMBER_PATTERN.matcher(metadata);
if (!buildNumberMatcher.find()) {
throw new IllegalStateException("No build number in Maven metadata!");
}
File webappsDirectory = new File(catalinaBase, "webapps");
File war = File.createTempFile("dari-reloader-", null, webappsDirectory);
try {
URL warUrl = new URL(
RELOADER_MAVEN_URL
+ RELOADER_MAVEN_ARTIFACT_ID + "-"
+ RELOADER_MAVEN_VERSION.replace("-SNAPSHOT", "") + "-"
+ timestampMatcher.group(1) + "-"
+ buildNumberMatcher.group(1) + ".war");
addProgress("Downloading it from ", warUrl);
addProgress("Saving it to ", war);
InputStream warInput = warUrl.openStream();
try {
FileOutputStream warOutput = new FileOutputStream(war);
try {
IoUtils.copy(warInput, warOutput);
} finally {
warOutput.close();
}
} finally {
warInput.close();
}
String reloaderPath = getReloaderPath();
reloaderPath = reloaderPath.substring(1, reloaderPath.length() - 1);
File reloaderWar = new File(webappsDirectory, reloaderPath + ".war");
IoUtils.delete(reloaderWar);
IoUtils.delete(new File(catalinaBase,
"conf" + File.separator
+ "Catalina" + File.separator
+ "localhost" + File.separator
+ reloaderPath + ".xml"));
addProgress("Deploying it to ", "/" + reloaderPath);
IoUtils.rename(war, reloaderWar);
for (int i = 0; i < 20; ++ i) {
if (isReloaderAvailable(request)) {
addProgress("Finished!");
return;
}
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
break;
}
}
throw new IllegalStateException("Can't deploy!");
} finally {
IoUtils.delete(war);
}
}
}
private static class IsolatingResponse extends HttpServletResponseWrapper {
public final String jsp;
private final ServletOutputStream output = new IsolatingOutputStream();
private final PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8));
public IsolatingResponse(HttpServletResponse response, String jsp) {
super(response);
this.jsp = jsp;
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
return output;
}
@Override
public PrintWriter getWriter() throws IOException {
return writer;
}
}
private static final class IsolatingOutputStream extends ServletOutputStream {
@Override
public boolean isReady() {
throw new UnsupportedOperationException();
}
@Override
public void setWriteListener(WriteListener writeListener) {
throw new UnsupportedOperationException();
}
@Override
public void write(int b) {
}
}
private class AnalysisResultLogger extends JvmLogger {
private List<AnalysisResult> getOrCreateAnalysisResults(Method method) {
Class<?> c = method.getDeclaringClass();
List<AnalysisResult> analysisResults = analysisResultsByClass.get(c);
if (analysisResults == null) {
analysisResults = new ArrayList<AnalysisResult>();
analysisResultsByClass.put(c, analysisResults);
}
return analysisResults;
}
@Override
public void warn(Method method, int line, String message) {
LOGGER.warn(format(method, line, message));
getOrCreateAnalysisResults(method).add(new AnalysisResult(Diagnostic.Kind.WARNING, method, line, message));
}
@Override
public void error(Method method, int line, String message) {
LOGGER.error(format(method, line, message));
getOrCreateAnalysisResults(method).add(new AnalysisResult(Diagnostic.Kind.ERROR, method, line, message));
}
}
private static class AnalysisResult {
private final Diagnostic.Kind kind;
private final Method method;
private final int line;
private final String message;
public AnalysisResult(Diagnostic.Kind kind, Method method, int line, String message) {
this.kind = kind;
this.method = method;
this.line = line;
this.message = message;
}
public Diagnostic.Kind getKind() {
return kind;
}
public Method getMethod() {
return method;
}
public int getLine() {
return line;
}
public String getMessage() {
return message;
}
}
}
|
package ui;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;
import javafx.geometry.Orientation;
import javafx.scene.Node;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ScrollBar;
import javafx.scene.control.ScrollPane;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.controlsfx.control.action.Action;
import org.controlsfx.dialog.Dialog;
import org.controlsfx.dialog.Dialogs;
import service.ServiceManager;
import storage.DataManager;
import ui.issuecolumn.ColumnControl;
import ui.issuecolumn.IssueColumn;
import util.DialogMessage;
import util.events.IssueCreatedEvent;
import util.events.LabelCreatedEvent;
import util.events.MilestoneCreatedEvent;
import util.events.PanelSavedEvent;
import util.events.PanelSavedEventHandler;
public class MenuControl extends MenuBar {
private static final Logger logger = LogManager.getLogger(MenuControl.class.getName());
private final ColumnControl columns;
private final ScrollPane columnsScrollPane;
private final UI ui;
public MenuControl(UI ui, ColumnControl columns, ScrollPane columnsScrollPane) {
this.columns = columns;
this.columnsScrollPane = columnsScrollPane;
this.ui = ui;
createMenuItems();
}
private void createMenuItems() {
Menu newMenu = new Menu("New");
newMenu.getItems().addAll(createNewMenuItems());
Menu panels = createPanelsMenu();
Menu boards = new Menu("Boards");
boards.getItems().addAll(createBoardsMenu());
Menu view = new Menu("View");
view.getItems().addAll(createRefreshMenuItem(), createForceRefreshMenuItem(), createDocumentationMenuItem());
getMenus().addAll(newMenu, panels, boards, view);
}
private Menu createPanelsMenu() {
Menu cols = new Menu("Panels");
MenuItem createLeft = new MenuItem("Create (Left)");
createLeft.setOnAction(e -> {
logger.info("Menu: Panels > Create (Left)");
columns.createNewPanelAtStart();
columnsScrollPane.setHvalue(columnsScrollPane.getHmin());
});
createLeft.setAccelerator(new KeyCodeCombination(KeyCode.N, KeyCombination.CONTROL_DOWN,
KeyCombination.SHIFT_DOWN));
MenuItem createRight = new MenuItem("Create");
createRight.setOnAction(e -> {
logger.info("Menu: Panels > Create");
columns.createNewPanelAtEnd();
// listener is used as columnsScroll's Hmax property doesn't update
// synchronously
ChangeListener<Number> listener = new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> arg0, Number arg1, Number arg2) {
for (Node child : columnsScrollPane.getChildrenUnmodifiable()) {
if (child instanceof ScrollBar) {
ScrollBar scrollBar = (ScrollBar) child;
if (scrollBar.getOrientation() == Orientation.HORIZONTAL
&& scrollBar.visibleProperty().get()) {
columnsScrollPane.setHvalue(columnsScrollPane.getHmax());
break;
}
}
}
columns.widthProperty().removeListener(this);
}
};
columns.widthProperty().addListener(listener);
});
createRight.setAccelerator(new KeyCodeCombination(KeyCode.N, KeyCombination.CONTROL_DOWN));
MenuItem closeColumn = new MenuItem("Close");
closeColumn.setOnAction(e -> {
logger.info("Menu: Panels > Close");
columns.closeCurrentColumn();
});
closeColumn.setAccelerator(new KeyCodeCombination(KeyCode.W, KeyCombination.CONTROL_DOWN));
cols.getItems().addAll(createRight, createLeft, closeColumn);
return cols;
}
/**
* Called upon the Panels > Sets > Save being clicked
*/
private void onPanelSetSave() {
logger.info("Menu: Boards > Save");
List<String> filterStrings = getCurrentFilterExprs();
if (!filterStrings.isEmpty()) {
Optional<String> response = Dialogs.create()
.title("Board Name")
.lightweight()
.masthead("Please name this board")
.message("What should this board be called?").showTextInput();
if (response.isPresent()) {
DataManager.getInstance().addPanelSet(response.get(), filterStrings);
ui.triggerEvent(new PanelSavedEvent());
logger.info("New panel set " + response.get() + " saved, containing " + filterStrings);
return;
}
}
logger.info("Did not save new panel set");
}
/**
* Called upon the Panels > Sets > Open being clicked
*/
private void onPanelSetOpen(String panelSetName, List<String> filterSet) {
logger.info("Menu: Boards > Open > " + panelSetName);
columns.closeAllColumns();
columns.openColumnsWithFilters(filterSet);
}
/**
* Called upon the Panels > Sets > Delete being clicked
*/
private void onPanelSetDelete(String panelSetName) {
logger.info("Menu: Boards > Delete > " + panelSetName);
Action response = Dialogs.create().title("Confirmation")
.masthead("Delete board '" + panelSetName + "'?")
.message("Are you sure you want to delete this board?")
.actions(new Action[] { Dialog.Actions.YES, Dialog.Actions.NO }).showConfirm();
if (response == Dialog.Actions.YES) {
DataManager.getInstance().removePanelSet(panelSetName);
ui.triggerEvent(new PanelSavedEvent());
logger.info(panelSetName + " was deleted");
} else {
logger.info(panelSetName + " was not deleted");
}
}
private MenuItem[] createBoardsMenu() {
MenuItem save = new MenuItem("Save");
save.setOnAction(e -> onPanelSetSave());
Menu open = new Menu("Open");
Menu delete = new Menu("Delete");
ui.registerEvent(new PanelSavedEventHandler() {
@Override
public void handle(PanelSavedEvent e) {
open.getItems().clear();
delete.getItems().clear();
Map<String, List<String>> panelSets = DataManager.getInstance().getAllPanelSets();
for (final String panelSetName : panelSets.keySet()) {
final List<String> filterSet = panelSets.get(panelSetName);
MenuItem openItem = new MenuItem(panelSetName);
openItem.setOnAction(e1 -> onPanelSetOpen(panelSetName, filterSet));
open.getItems().add(openItem);
MenuItem deleteItem = new MenuItem(panelSetName);
deleteItem.setOnAction(e1 -> onPanelSetDelete(panelSetName));
delete.getItems().add(deleteItem);
}
}
});
return new MenuItem[] {save, open, delete};
}
/**
* Returns the list of filter strings currently showing the user interface
* @return
*/
private List<String> getCurrentFilterExprs() {
return columns.getChildren().stream().flatMap(c -> {
if (c instanceof IssueColumn) {
return Stream.of(((IssueColumn) c).getCurrentFilterString());
} else {
return Stream.of();
}
}).collect(Collectors.toList());
}
private MenuItem createDocumentationMenuItem() {
MenuItem documentationMenuItem = new MenuItem("Documentation");
documentationMenuItem.setOnAction((e) -> {
logger.info("Menu: View > Documentation");
ui.getBrowserComponent().showDocs();
});
documentationMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.F1));
return documentationMenuItem;
}
private MenuItem createRefreshMenuItem() {
MenuItem refreshMenuItem = new MenuItem("Refresh");
refreshMenuItem.setOnAction((e) -> {
logger.info("Menu: View > Refresh");
ServiceManager.getInstance().updateModelNowAndPeriodically();
columns.refresh();
});
refreshMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.F5));
return refreshMenuItem;
}
private MenuItem createForceRefreshMenuItem() {
MenuItem forceRefreshMenuItem = new MenuItem("Force Refresh");
forceRefreshMenuItem.setOnAction((e) -> {
triggerForceRefreshProgressDialog();
});
forceRefreshMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.F5, KeyCombination.CONTROL_DOWN));
return forceRefreshMenuItem;
}
private void triggerForceRefreshProgressDialog() {
Task<Boolean> task = new Task<Boolean>() {
@Override
protected Boolean call() throws IOException {
try {
logger.info("Menu: View > Force Refresh");
ServiceManager.getInstance().stopModelUpdate();
ServiceManager.getInstance().getModel().forceReloadComponents();
ServiceManager.getInstance().updateModelNowAndPeriodically();
} catch (SocketTimeoutException e) {
handleSocketTimeoutException(e);
return false;
} catch (UnknownHostException e) {
handleUnknownHostException(e);
return false;
} catch (Exception e) {
logger.error(e.getMessage(), e);
e.printStackTrace();
return false;
}
logger.info("Menu: View > Force Refresh completed");
return true;
}
private void handleSocketTimeoutException(Exception e) {
Platform.runLater(() -> {
logger.error(e.getMessage(), e);
DialogMessage.showWarningDialog("Internet Connection is down",
"Timeout while loading items from github. Please check your internet connection.");
});
}
private void handleUnknownHostException(Exception e) {
Platform.runLater(() -> {
logger.error(e.getMessage(), e);
DialogMessage.showWarningDialog("No Internet Connection",
"Please check your internet connection and try again");
});
}
};
DialogMessage.showProgressDialog(task,
"Reloading issues for current repo... This may take awhile, please wait.");
Thread thread = new Thread(task);
thread.setDaemon(true);
thread.start();
}
private MenuItem[] createNewMenuItems() {
MenuItem newIssueMenuItem = new MenuItem("Issue");
newIssueMenuItem.setOnAction(e -> {
logger.info("Menu: New > Issue");
ui.triggerEvent(new IssueCreatedEvent());
});
newIssueMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.I, KeyCombination.CONTROL_DOWN));
MenuItem newLabelMenuItem = new MenuItem("Label");
newLabelMenuItem.setOnAction(e -> {
logger.info("Menu: New > Label");
ui.triggerEvent(new LabelCreatedEvent());
});
newLabelMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.L, KeyCombination.CONTROL_DOWN));
MenuItem newMilestoneMenuItem = new MenuItem("Milestone");
newMilestoneMenuItem.setOnAction(e -> {
logger.info("Menu: New > Milestone");
ui.triggerEvent(new MilestoneCreatedEvent());
});
newMilestoneMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.M, KeyCombination.CONTROL_DOWN));
return new MenuItem[] { newIssueMenuItem, newLabelMenuItem, newMilestoneMenuItem };
}
}
|
package motocitizen.maps.google;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import motocitizen.app.mc.MCAccTypes;
import motocitizen.app.mc.MCAccidents;
import motocitizen.app.mc.MCLocation;
import motocitizen.app.mc.MCPoint;
import motocitizen.main.R;
import motocitizen.maps.general.MCMap;
import motocitizen.startup.Startup;
import motocitizen.utils.Inflate;
import motocitizen.utils.MCUtils;
@SuppressLint("UseSparseArrays")
public class MCGoogleMap extends MCMap {
private static GoogleMap map;
private static Marker user;
private static Map<String, Integer> accidents;
private static String selected;
public MCGoogleMap(Context context) {
setName(MCMap.GOOGLE);
selected = "";
Inflate.set(context, R.id.map_container, R.layout.google_maps_view);
map = ((MapFragment) ((Activity) context).getFragmentManager().findFragmentById(R.id.google_map)).getMap();
init();
map.setOnMarkerClickListener(new OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
String id = marker.getId();
if (selected.equals(id) && accidents.containsKey(id)) {
MCAccidents.toDetails(Startup.context, accidents.get(selected));
} else {
marker.showInfoWindow();
selected = id;
}
return true;
}
});
}
@SuppressWarnings("UnusedParameters")
public void placeUser(Context context) {
if (user != null) {
user.remove();
}
user = map.addMarker(new MarkerOptions().position(MCUtils.LocationToLatLng(MCLocation.current)).title("Вы")
.icon(MCAccTypes.getBitmapDescriptor("user")));
}
public void jumpToPoint(Location location) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(MCUtils.LocationToLatLng(location), 16));
}
@SuppressWarnings("UnusedParameters")
public void placeAcc(Context context) {
if (accidents == null) {
accidents = new HashMap<>();
}
init();
accidents.clear();
for (int id : MCAccidents.points.keySet()) {
MCPoint p = MCAccidents.points.getPoint(id);
String title = p.getTypeText();
if (!p.getMedText().equals("")) {
title += ", " + p.getMedText();
}
title += ", " + MCUtils.getIntervalFromNowInText(p.created) + " назад";
float alpha;
int age = (int) (((new Date()).getTime() - p.created.getTime()) / 3600000);
if (age < 2) {
alpha = 1.0f;
} else if (age < 6) {
alpha = 0.5f;
} else {
alpha = 0.2f;
}
Marker marker = map.addMarker(new MarkerOptions().position(MCUtils.LocationToLatLng(p.location)).title(title)
.icon(MCAccTypes.getBitmapDescriptor(p.type)).alpha(alpha));
accidents.put(marker.getId(), id);
}
}
private static void init() {
map.clear();
map.setMyLocationEnabled(true);
map.getUiSettings().setMyLocationButtonEnabled(true);
map.getUiSettings().setZoomControlsEnabled(true);
}
public void zoom(int zoom) {
map.animateCamera(CameraUpdateFactory.zoomTo(zoom));
}
}
|
package ch.hsr.ifs.pystructure.typeinference.evaluators.references;
import java.util.ArrayList;
import java.util.List;
import org.python.pydev.parser.jython.ast.Name;
import ch.hsr.ifs.pystructure.typeinference.basetype.CombinedType;
import ch.hsr.ifs.pystructure.typeinference.contexts.ModuleContext;
import ch.hsr.ifs.pystructure.typeinference.evaluators.base.AbstractEvaluator;
import ch.hsr.ifs.pystructure.typeinference.goals.base.GoalState;
import ch.hsr.ifs.pystructure.typeinference.goals.base.IGoal;
import ch.hsr.ifs.pystructure.typeinference.goals.types.DefinitionTypeGoal;
import ch.hsr.ifs.pystructure.typeinference.goals.types.ExpressionTypeGoal;
import ch.hsr.ifs.pystructure.typeinference.model.definitions.Definition;
import ch.hsr.ifs.pystructure.typeinference.model.definitions.Module;
import ch.hsr.ifs.pystructure.typeinference.model.definitions.NameUse;
import ch.hsr.ifs.pystructure.typeinference.model.definitions.Use;
/**
* Evaluator for the type of an unqualified name, like <code>var</code> or
* <code>func</code>.
*/
public class NameTypeEvaluator extends AbstractEvaluator {
private final Name nameNode;
private CombinedType resultType;
public NameTypeEvaluator(ExpressionTypeGoal goal, Name nameNode) {
super(goal);
this.nameNode = nameNode;
this.resultType = goal.resultType;
}
@Override
public List<IGoal> init() {
List<IGoal> subgoals = new ArrayList<IGoal>();
ModuleContext context = getGoal().getContext();
Module module = context.getModule();
for (Use use : module.getContainedUses()) {
if (use instanceof NameUse) {
NameUse nameUse = (NameUse) use;
if (nameNode.equals(nameUse.getExpression())) {
for (Definition definition : nameUse.getDefinitions()) {
subgoals.add(new DefinitionTypeGoal(getGoal().getContext(), definition));
}
}
}
}
return subgoals;
}
@Override
public List<IGoal> subgoalDone(IGoal subgoal, GoalState subgoalState) {
if (!(subgoal instanceof DefinitionTypeGoal)) { unexpectedSubgoal(subgoal); }
DefinitionTypeGoal g = (DefinitionTypeGoal) subgoal;
resultType.appendType(g.resultType);
return IGoal.NO_GOALS;
}
}
|
package com.googlecode.totallylazy.records;
import org.junit.Test;
import static com.googlecode.totallylazy.records.Keyword.keyword;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class KeywordTest {
@Test
public void nameReturnsLastPartOfKeyword() throws Exception {
assertThat(keyword("USER.foo").name(), is("foo"));
assertThat(keyword("USER.TABLE.foo").name(), is("foo"));
assertThat(keyword("foo").name(), is("foo"));
}
@Test
public void equalityIsBasedOnTheNameOnly() throws Exception {
assertThat(keyword("USER.foo"), is(equalTo(keyword("foo"))));
assertThat(keyword("USER.TABLE.foo"), is(equalTo(keyword("foo"))));
assertThat(keyword("USER.TABLE.foo"), is(equalTo(keyword("USER.foo"))));
assertThat(keyword("FOO"), is(equalTo(keyword("foo"))));
}
}
|
package dr.evomodel.treedatalikelihood.continuous;
import dr.evolution.tree.MultivariateTraitTree;
import dr.evomodel.tree.TreeModel;
import dr.evomodel.treedatalikelihood.continuous.cdi.PrecisionType;
import dr.evomodelxml.treelikelihood.TreeTraitParserUtilities;
import dr.inference.model.*;
import dr.xml.*;
import java.util.Arrays;
import java.util.List;
/**
* @author Marc A. Suchard
*/
public class IntegratedFactorAnalysisLikelihood extends AbstractModelLikelihood
implements ContinuousTraitPartialsProvider {
public IntegratedFactorAnalysisLikelihood(String name,
CompoundParameter traitParameter,
List<Integer> missingIndices,
MatrixParameterInterface loadings,
Parameter traitPrecision) {
super(name);
this.traitParameter = traitParameter;
this.loadings = loadings;
this.traitPrecision = traitPrecision;
this.missingIndices = missingIndices;
this.numTaxa = traitParameter.getParameterCount();
this.dimTrait = traitParameter.getParameter(0).getDimension();
this.dimPartial = dimTrait + PrecisionType.FULL.getMatrixLength(dimTrait);
this.numFactors = loadings.getRowDimension(); // TODO Confirm this is not column-dimension!
addVariable(traitParameter);
addVariable(loadings);
addVariable(traitPrecision);
this.observedIndicators = setupObservedIndicators(missingIndices, numTaxa, dimTrait);
this.observedDimensions = setupObservedDimensions(observedIndicators);
}
@Override
public boolean bufferTips() {
return true;
}
@Override
public int getTraitCount() {
return 1;
}
@Override
public int getTraitDimension() {
return numFactors;
} // Returns dimension of latent factors
@Override
public PrecisionType getPrecisionType() {
return PrecisionType.FULL;
}
@Override
public double[] getTipPartial(int taxonIndex, boolean fullyObserved) {
checkStatistics();
throw new RuntimeException("To implement");
}
@Override
public double[] getTipPartial(int taxonIndex) {
checkStatistics();
throw new RuntimeException("To implement");
}
@Override
public double[] getTipObservation(int taxonIndex, PrecisionType precisionType) {
checkStatistics();
throw new RuntimeException("To implement");
}
@Override
public List<Integer> getMissingIndices() {
return null; // TODO Fix use-case (all tree-tip values (factors) should be missing)
}
@Override
public CompoundParameter getParameter() {
return null; // TODO Fix use-case
}
@Override
public Model getModel() {
return this;
}
@Override
public double getLogLikelihood() {
if (!likelihoodKnown) {
logLikelihood = calculateLogLikelihood();
likelihoodKnown = true;
}
return logLikelihood;
}
@Override
public void makeDirty() {
likelihoodKnown = false;
}
@Override
protected void handleModelChangedEvent(Model model, Object object, int index) {
// No model dependencies
}
@Override
protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
if (variable == loadings || variable == traitPrecision) {
statisticsKnown = false;
likelihoodKnown = false;
fireModelChanged(this);
// fireModelChanged(this, getTaxonIndex(index));
} else if (variable == traitParameter) {
statisticsKnown = false;
likelihoodKnown = false;
fireModelChanged(this);
} else {
throw new RuntimeException("Unhandled parameter change type");
}
}
@Override
protected void storeState() {
storedLogLikelihood = logLikelihood;
storedLikelihoodKnow = likelihoodKnown;
storedStatisticsKnown = statisticsKnown;
System.arraycopy(partials, 0, storedPartials, 0, partials.length);
System.arraycopy(remainders, 0, storedRemainders, 0, remainders.length);
}
@Override
protected void restoreState() {
logLikelihood = storedLogLikelihood;
likelihoodKnown = storedLikelihoodKnow;
statisticsKnown = storedStatisticsKnown;
double[] tmp1 = partials;
partials = storedPartials;
storedPartials = tmp1;
double[] tmp2 = remainders;
remainders = storedRemainders;
storedRemainders = tmp2;
}
@Override
protected void acceptState() {
// Do nothing
}
private double calculateLogLikelihood() {
double logLikelihood = 0.0;
for (double r : remainders) {
logLikelihood += r;
}
return logLikelihood;
}
private void setupStatistics() {
if (partials == null) {
partials = new double[numTaxa * dimPartial];
}
if (remainders == null) {
remainders = new double[numTaxa];
}
computePartialsAndRemainders();
}
private void computePartialsAndRemainders() {
int partialsOffset = 0;
for (int taxon = 0; taxon < numTaxa; ++taxon) {
// TODO Fill in partial means, precisions, (maybe?) variances and normalization constants
partialsOffset += dimPartial;
}
}
private void checkStatistics() {
if (!statisticsKnown) {
setupStatistics();
statisticsKnown = true;
}
}
private static double[][] setupObservedIndicators(List<Integer> missingIndices, int nTaxa, int dimTrait) {
double[][] observed = new double[nTaxa][dimTrait];
for (double[] v : observed) {
Arrays.fill(v, 1.0);
}
for (Integer idx : missingIndices) {
int taxon = idx / dimTrait;
int trait = idx % dimTrait;
observed[taxon][trait] = 0.0;
}
return observed;
}
private static int[] setupObservedDimensions(double[][] observed) {
int length = observed.length;
int[] dimensions = new int[length];
for (int i = 0; i < length; ++i) {
double sum = 0;
for (double x : observed[i]) {
sum += x;
}
dimensions[i] = (int) sum;
}
return dimensions;
}
private boolean likelihoodKnown = false;
private boolean storedLikelihoodKnow;
private boolean statisticsKnown = false;
private boolean storedStatisticsKnown;
private double logLikelihood;
private double storedLogLikelihood;
private double[] partials;
private double[] storedPartials;
private double[] remainders;
private double[] storedRemainders;
private final int numTaxa;
private final int dimTrait;
private final int dimPartial;
private final int numFactors;
private final CompoundParameter traitParameter;
private final MatrixParameterInterface loadings;
private final Parameter traitPrecision;
private final List<Integer> missingIndices;
private final double[][] observedIndicators;
private final int[] observedDimensions;
// TODO Move remainder into separate class file
public static AbstractXMLObjectParser PARSER = new AbstractXMLObjectParser() {
@Override
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
MultivariateTraitTree treeModel = (MultivariateTraitTree) xo.getChild(TreeModel.class);
TreeTraitParserUtilities utilities = new TreeTraitParserUtilities();
TreeTraitParserUtilities.TraitsAndMissingIndices returnValue =
utilities.parseTraitsFromTaxonAttributes(xo, TreeTraitParserUtilities.DEFAULT_TRAIT_NAME,
treeModel, true);
CompoundParameter traitParameter = returnValue.traitParameter;
List<Integer> missingIndices = returnValue.missingIndices;
MatrixParameterInterface loadings = (MatrixParameterInterface) xo.getElementFirstChild(LOADINGS);
Parameter traitPrecision = (Parameter) xo.getElementFirstChild(PRECISION);
return new IntegratedFactorAnalysisLikelihood(xo.getId(), traitParameter, missingIndices,
loadings, traitPrecision);
}
@Override
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
@Override
public String getParserDescription() {
return null;
}
@Override
public Class getReturnType() {
return IntegratedFactorAnalysisLikelihood.class;
}
@Override
public String getParserName() {
return INTEGRATED_FACTOR_Model;
}
};
public static final String INTEGRATED_FACTOR_Model = "integratedFactorModel";
public static final String LOADINGS = "loadings";
public static final String PRECISION = "precision";
private final static XMLSyntaxRule[] rules = new XMLSyntaxRule[] {
new ElementRule(LOADINGS, new XMLSyntaxRule[] {
new ElementRule(MatrixParameterInterface.class),
}),
new ElementRule(PRECISION, new XMLSyntaxRule[] {
new ElementRule(Parameter.class),
}),
// Tree trait parser
new ElementRule(MultivariateTraitTree.class),
AttributeRule.newStringRule(TreeTraitParserUtilities.TRAIT_NAME),
new ElementRule(TreeTraitParserUtilities.TRAIT_PARAMETER, new XMLSyntaxRule[]{
new ElementRule(Parameter.class)
}),
new ElementRule(TreeTraitParserUtilities.MISSING, new XMLSyntaxRule[]{
new ElementRule(Parameter.class)
}, true),
};
}
|
package org.apache.lenya.cms.cocoon.acting;
import java.io.File;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.acting.AbstractComplementaryConfigurableAction;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.Session;
import org.apache.lenya.cms.task.*;
import org.apache.lenya.cms.workflow.WorkflowFactory;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.lenya.cms.publication.DefaultDocument;
import org.apache.lenya.cms.publication.Document;
import org.apache.lenya.cms.publication.PageEnvelope;
import org.apache.lenya.cms.publication.Publication;
import org.apache.lenya.cms.publication.PublicationFactory;
import org.apache.lenya.workflow.Event;
import org.apache.lenya.workflow.Situation;
import org.apache.lenya.workflow.WorkflowInstance;
/**
* An action that executes a task.
*
* @author <a href="mailto:ah@lenya.org">Andreas Hartmann</a>
*/
public class TaskAction extends AbstractComplementaryConfigurableAction {
private String taskId = null;
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public String getTaskId() {
return taskId;
}
/**
* DOCUMENT ME!
*
* @param configuration DOCUMENT ME!
*
* @throws ConfigurationException DOCUMENT ME!
*/
public void configure(Configuration configuration)
throws ConfigurationException {
super.configure(configuration);
try {
taskId = configuration.getChild("task").getAttribute(TaskManager.TASK_ID_ATTRIBUTE);
getLogger().debug("CONFIGURATION:\ntask id = " + taskId);
} catch (ConfigurationException e) {
getLogger().debug("CONFIGURATION:\nNo task id provided");
}
}
/**
* DOCUMENT ME!
*
* @param redirector DOCUMENT ME!
* @param sourceResolver DOCUMENT ME!
* @param objectModel DOCUMENT ME!
* @param str DOCUMENT ME!
* @param parameters DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws java.lang.Exception DOCUMENT ME!
*/
public java.util.Map act(Redirector redirector, SourceResolver sourceResolver,
Map objectModel, String str, Parameters parameters) throws java.lang.Exception {
Publication publication = PublicationFactory.getPublication(objectModel);
File publicationDirectory = publication.getDirectory();
// Get request object
Request request = ObjectModelHelper.getRequest(objectModel);
if (request == null) {
getLogger().error("No request object");
return null;
}
taskId = parameters.getParameter("task-id", taskId);
if (taskId == null) {
throw new IllegalStateException("No task id provided!");
}
// prepare default parameters
Parameters taskParameters = new Parameters();
taskParameters.setParameter(Task.PARAMETER_SERVLET_CONTEXT, publication.getServletContext().getCanonicalPath());
taskParameters.setParameter(Task.PARAMETER_CONTEXT_PREFIX, request.getContextPath() + "/");
taskParameters.setParameter(Task.PARAMETER_SERVER_PORT,
Integer.toString(request.getServerPort()));
taskParameters.setParameter(Task.PARAMETER_SERVER_URI, "http://" + request.getServerName());
taskParameters.setParameter(Task.PARAMETER_PUBLICATION_ID, publication.getId());
// set parameters using the request parameters
for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {
String name = (String) e.nextElement();
taskParameters.setParameter(name, request.getParameter(name));
}
// execute task
getLogger().debug("\n
getTaskId() + "'" + "\n
TaskManager manager = new TaskManager(publication.getDirectory().getCanonicalPath());
Task task = manager.getTask(getTaskId());
task.parameterize(taskParameters);
task.execute(publication.getServletContext().getCanonicalPath());
WorkflowFactory factory = WorkflowFactory.newInstance();
PageEnvelope envelope = new PageEnvelope(publication, request);
Document document = new DefaultDocument(publication, envelope.getDocumentId());
if (factory.hasWorkflow(document)) {
String eventName = request.getParameter("lenya.event");
WorkflowInstance instance = factory.buildInstance(document);
Situation situation = factory.buildSituation(objectModel);
Event event = null;
Event events[] = instance.getExecutableEvents(situation);
for (int i = 0; i < events.length; i++) {
if (events[i].getName().equals(eventName)) {
event = events[i];
}
}
assert event != null;
instance.invoke(situation, event);
}
// get session
Session session = request.getSession(true);
if (session == null) {
getLogger().error("No session object");
return null;
}
// Return referer
String parent_uri = (String) session.getAttribute(
"org.apache.lenya.cms.cocoon.acting.TaskAction.parent_uri");
HashMap actionMap = new HashMap();
actionMap.put("parent_uri", parent_uri);
session.removeAttribute("org.apache.lenya.cms.cocoon.acting.TaskAction.parent_uri");
return actionMap;
}
}
|
package org.traccar.protocol;
import org.junit.Test;
import org.traccar.ProtocolTest;
public class HuabaoProtocolDecoderTest extends ProtocolTest {
@Test
public void testDecode() throws Exception {
HuabaoProtocolDecoder decoder = new HuabaoProtocolDecoder(new HuabaoProtocol());
verifyNothing(decoder, binary(
"7e0100002d0141305678720024002c012f373031313142534a2d41362d424400000000000000000000003035363738373201d4c14238383838386d7e"));
verifyNothing(decoder, binary(
"7E0100002D013511221122000500000000373031303748422D52303347424400000000000000000000003233363631303402CBD5424136383630387E"));
verifyNothing(decoder, binary(
"7e0100002d007089994489002800000000000000000048422d523033474244000000000000000000000031393036373531024142433030303030d17e"));
verifyNothing(decoder, binary(
"7E0102000E013511221122000661757468656E7469636174696F6E3F7E"));
verifyPosition(decoder, binary(
"7E02000032013511221122000700000000000C000301578CC006CA3A5C00470000000014072317201501040000000030011631010BD07E"));
verifyNothing(decoder, binary(
"7E010200100940278494700084323031313131303831313333323139369F7E"));
verifyNothing(decoder, binary(
"7e010000190940278494700012000000000000000000000000000000000000094027849470000a7e"));
verifyPosition(decoder, binary(
"7e0200002e094027587492000a000000010000000a03083db7001329f3000000140000130412164952010400000012360a0002341502cb0c20085c107e"));
verifyPosition(decoder, binary(
"7e020000220014012499170007000000000000400e012af16f02cbd2ba000000000000150101194257010400000077a97e"));
}
}
|
package com.malhartech.stram.cli;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import jline.ArgumentCompletor;
import jline.Completor;
import jline.ConsoleReader;
import jline.FileNameCompletor;
import jline.History;
import jline.MultiCompletor;
import jline.SimpleCompletor;
import javax.ws.rs.core.MediaType;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.api.protocolrecords.GetAllApplicationsRequest;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ApplicationReport;
import org.apache.hadoop.yarn.api.records.FinalApplicationStatus;
import org.apache.hadoop.yarn.api.records.YarnApplicationState;
import org.apache.hadoop.yarn.exceptions.YarnRemoteException;
import org.apache.hadoop.yarn.util.Records;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.malhartech.stram.cli.StramAppLauncher.AppConfig;
import com.malhartech.stram.cli.StramClientUtils.ClientRMHelper;
import com.malhartech.stram.cli.StramClientUtils.YarnClientHelper;
import com.malhartech.stram.plan.logical.*;
import com.malhartech.stram.security.StramUserLogin;
import com.malhartech.stram.webapp.StramWebServices;
import com.malhartech.util.VersionInfo;
import com.malhartech.util.WebServicesClient;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import java.util.*;
import org.apache.commons.cli.*;
import org.codehaus.jackson.map.ObjectMapper;
/**
*
* Provides command line interface for a streaming application on hadoop (yarn)<p>
* <br>
* <table border=1 cellspacing=0>
* <caption>Currently supported Commands</caption>
* <thead>
* <tr align=center><th width=10%><b>Command</b></th><th width=20%><b>Parameters</b></th><th width=70%><b>Description</b></th></tr>
* </thead><tbody>
* <tr><td><b>help</b></td><td></td><td>prints help on all cli commands</td></tr>
* <tr><td><b>ls</b></td><td></td><td>list applications or operators</td></tr>
* <tr><td><b>cd</b></td><td>appId</td><td>connect to the given application</td></tr>
* <tr><td><b>launch</b></td><td>jarFile</td><td>Launch application packaged in jar file</td></tr>
* <tr><td><b>timeout</b></td><td>duration</td><td>Wait for completion of current application</td></tr>
* <tr><td><b>kill</b></td><td></td><td>Force termination for current application</td></tr>
* <tr><td><b>exit</b></td><td></td><td>Exit the app</td></tr>
* </tbody>
* </table>
* <br>
*/
@SuppressWarnings("UseOfSystemOutOrSystemErr")
public class StramCli
{
private static final Logger LOG = LoggerFactory.getLogger(StramCli.class);
private final Configuration conf = new Configuration();
private ClientRMHelper rmClient;
private ApplicationReport currentApp = null;
private String currentDir = "/";
private boolean consolePresent;
private String[] commandsToExecute;
protected ApplicationReport getApplication(int appSeq)
{
List<ApplicationReport> appList = getApplicationList();
for (ApplicationReport ar: appList) {
if (ar.getApplicationId().getId() == appSeq) {
return ar;
}
}
return null;
}
private class CliException extends RuntimeException
{
private static final long serialVersionUID = 1L;
CliException(String msg, Throwable cause)
{
super(msg, cause);
}
CliException(String msg)
{
super(msg);
}
}
public StramCli()
{
StramClientUtils.addStramResources(conf);
}
public void init(String[] args) throws IOException
{
consolePresent = (System.console() != null);
Options options = new Options();
options.addOption("e", true, "Commands are read from the argument");
CommandLineParser parser = new BasicParser();
try {
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("e")) {
commandsToExecute = cmd.getOptionValues("e");
consolePresent = false;
for (String command : commandsToExecute) {
LOG.debug("Command to be executed: {}", command);
}
}
}
catch (ParseException ex) {
System.err.println("Invalid argument: " + ex);
System.exit(1);
}
// Need to initialize security before starting RPC for the credentials to
// take effect
StramUserLogin.attemptAuthentication(conf);
YarnClientHelper yarnClient = new YarnClientHelper(conf);
rmClient = new ClientRMHelper(yarnClient);
}
/**
* Why reinvent the wheel?
* JLine 2.x supports search and more.. but it uses the same package as JLine 1.x
* Hadoop bundles and forces 1.x into our class path (when CLI is launched via hadoop command).
*/
private class ConsoleReaderExt extends ConsoleReader
{
private final char REVERSE_SEARCH_KEY = (char)31;
ConsoleReaderExt() throws IOException
{
// CTRL-/ since CTRL-R already mapped to redisplay
addTriggeredAction(REVERSE_SEARCH_KEY, new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try {
searchHistory();
}
catch (IOException ex) {
}
}
});
}
public int searchBackwards(CharSequence searchTerm, int startIndex)
{
@SuppressWarnings("unchecked")
List<String> history = getHistory().getHistoryList();
if (startIndex < 0) {
startIndex = history.size();
}
for (int i = startIndex; --i > 0;) {
String line = history.get(i);
if (line.contains(searchTerm)) {
return i;
}
}
return -1;
}
private void searchHistory() throws IOException
{
final String prompt = "reverse-search: ";
StringBuilder searchTerm = new StringBuilder();
String matchingCmd = null;
int historyIndex = -1;
while (true) {
while (backspace()) {
continue;
}
String line = prompt + searchTerm;
if (matchingCmd != null) {
line = line.concat(": ").concat(matchingCmd);
}
this.putString(line);
int c = this.readVirtualKey();
if (c == 8) {
if (searchTerm.length() > 0) {
searchTerm.deleteCharAt(searchTerm.length() - 1);
}
}
else if (c == REVERSE_SEARCH_KEY) {
int newIndex = searchBackwards(searchTerm, historyIndex);
if (newIndex >= 0) {
historyIndex = newIndex;
matchingCmd = (String)getHistory().getHistoryList().get(historyIndex);
}
}
else if (!Character.isISOControl(c)) {
searchTerm.append(Character.toChars(c));
int newIndex = searchBackwards(searchTerm, -1);
if (newIndex >= 0) {
historyIndex = newIndex;
matchingCmd = (String)getHistory().getHistoryList().get(historyIndex);
}
}
else {
while (backspace()) {
continue;
}
if (!StringUtils.isBlank(matchingCmd)) {
this.putString(matchingCmd);
this.flushConsole();
}
return;
}
}
}
}
public void run() throws IOException
{
ConsoleReader reader = new ConsoleReaderExt();
reader.setBellEnabled(false);
if (consolePresent) {
printWelcomeMessage();
String[] commandsList = new String[] {"help", "ls", "cd", "shutdown", "timeout", "kill", "container-kill",
"startrecording", "stoprecording", "syncrecording", "operator-property-set",
"begin-logical-plan-change",
"exit"};
List<Completor> completors = new LinkedList<Completor>();
completors.add(new SimpleCompletor(commandsList));
List<Completor> launchCompletors = new LinkedList<Completor>();
launchCompletors.add(new SimpleCompletor(new String[] {"launch", "launch-local"}));
launchCompletors.add(new FileNameCompletor()); // jarFile
launchCompletors.add(new FileNameCompletor()); // topology
completors.add(new ArgumentCompletor(launchCompletors));
reader.addCompletor(new MultiCompletor(completors));
File historyFile = new File(StramClientUtils.getSettingsRootDir(), ".history");
historyFile.getParentFile().mkdirs();
try {
History history = new History(historyFile);
reader.setHistory(history);
}
catch (IOException exp) {
System.err.printf("Unable to open %s for writing.", historyFile);
}
}
String line;
PrintWriter out = new PrintWriter(System.out);
int i = 0;
while (true) {
if (commandsToExecute != null) {
if (i >= commandsToExecute.length) {
break;
}
line = commandsToExecute[i++];
} else {
line = readLine(reader, "");
if (line == null) {
break;
}
}
try {
String[] commands = line.split("\\s*;\\s*");
for (String command : commands) {
if ("help".equals(command)) {
printHelp();
}
else if (command.startsWith("ls")) {
ls(command);
}
else if (command.startsWith("cd")) {
connect(command);
}
else if (command.startsWith("listoperators")) {
listOperators(null);
}
else if (command.startsWith("launch")) {
launchApp(command, reader);
}
else if (command.startsWith("shutdown")) {
shutdownApp(command);
}
else if (command.startsWith("timeout")) {
timeoutApp(command, reader);
}
else if (command.startsWith("kill")) {
killApp(command);
}
else if (command.startsWith("container-kill")) {
killContainer(command);
}
else if (command.startsWith("startrecording")) {
startRecording(command);
}
else if (command.startsWith("stoprecording")) {
stopRecording(command);
}
else if (command.startsWith("syncrecording")) {
syncRecording(command);
}
else if (command.startsWith("operator-property-set")) {
setOperatorProperty(command);
}
else if (command.startsWith("begin-logical-plan-change")) {
beginLogicalPlanChange(command, reader);
}
else if ("exit".equals(command)) {
System.out.println("Exiting application");
return;
}
else {
System.err.println("Invalid command, For assistance press TAB or type \"help\" then hit ENTER.");
}
}
}
catch (CliException e) {
System.err.println(e.getMessage());
LOG.info("Error processing line: " + line, e);
}
catch (Exception e) {
System.err.println("Unexpected error: " + e.getMessage());
}
out.flush();
}
System.out.println("exit");
}
private void printWelcomeMessage()
{
System.out.println("Stram CLI " + VersionInfo.getVersion() + " " + VersionInfo.getDate() + " " + VersionInfo.getRevision());
}
private void printHelp()
{
System.out.println("help - Show help");
System.out.println("ls - List applications or operators");
System.out.println("connect <appId> - Connect to running streaming application");
System.out.println("launch <jarFile> [<configuration>] - Launch application packaged in jar file.");
System.out.println("timeout <duration> - Wait for completion of current application.");
System.out.println("kill - Force termination for current application.");
System.out.println("startrecording <operId> [<portName>] - Start recording tuples for the given operator id");
System.out.println("stoprecording <operId> [<portName>] - Stop recording tuples for the given operator id");
System.out.println("syncrecording <operId> [<portName>] - Sync recording tuples for the given operator id");
System.out.println("operator-property-set <operId> <name> <value> - Set the property of the given operator id");
System.out.println("begin-logical-plan-change - Begin changing the logical plan for the current application");
System.out.println("exit - Exit the app");
}
private void printHelpLogicalPlanChange()
{
System.out.println("help - Show help");
System.out.println("create-operator <name> <class> - Create an operator with the given name and the given class");
System.out.println("remove-operator <name> - Remove an operator with the given name");
System.out.println("create-stream <name> <operator-source-name> <operator-source-port-name> <operator-sink-name> <operator-sink-port-name> - Create a stream");
System.out.println("remove-stream <name");
System.out.println("operator-property-set <name> <property-name> <property-value> - Set the property of the given operator name");
System.out.println("operator-attribute-set <name> <attribute-name> <attribute-value> - Set the attribute of the given operator name");
System.out.println("port-attribute-set <operator-name> <port-name> <attribute-name> <attribute-value> - Set the attribute of the given port of the given operator");
System.out.println("abort - Abort the logical plan change");
System.out.println("submit - Submit the logical plan change");
}
private String readLine(ConsoleReader reader, String promptMessage)
throws IOException
{
String line = reader.readLine(promptMessage + (consolePresent ? "\nstramcli> " : ""));
if (line == null) {
return null;
}
return line.trim();
}
private String[] assertArgs(String line, int num, String msg)
{
line = line.trim();
String[] args = StringUtils.splitByWholeSeparator(line, " ");
if (args.length < num) {
throw new CliException(msg);
}
return args;
}
private int getIntArg(String line, int argIndex, String msg)
{
String[] args = assertArgs(line, argIndex + 1, msg);
try {
int arg = Integer.parseInt(args[argIndex]);
return arg;
}
catch (Exception e) {
throw new CliException("Not a valid number: " + args[argIndex]);
}
}
private List<ApplicationReport> getApplicationList()
{
try {
GetAllApplicationsRequest appsReq = Records.newRecord(GetAllApplicationsRequest.class);
return rmClient.clientRM.getAllApplications(appsReq).getApplicationList();
}
catch (Exception e) {
throw new CliException("Error getting application list from resource manager: " + e.getMessage(), e);
}
}
private void ls(String line) throws JSONException
{
String[] args = StringUtils.splitByWholeSeparator(line, " ");
for (int i = args.length; i
args[i] = args[i].trim();
}
String context = (args.length > 1 ? args[1] : currentDir);
if (context.equals("/")) {
listApplications(args);
}
else if (context.startsWith("container")) {
listContainers(Arrays.copyOfRange(args, 2, args.length));
}
else {
listOperators(args);
}
}
private void listApplications(String[] args)
{
try {
List<ApplicationReport> appList = getApplicationList();
Collections.sort(appList, new Comparator<ApplicationReport>()
{
@Override
public int compare(ApplicationReport o1, ApplicationReport o2)
{
return o1.getApplicationId().getId() - o2.getApplicationId().getId();
}
});
System.out.println("Applications:");
int totalCnt = 0;
int runningCnt = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (ApplicationReport ar: appList) {
boolean show;
/*
* This is inefficient, but what the heck, if this can be passed through the command line, can anyone notice slowness.
*/
if (args.length == 1 || args.length == 2 && (args[1].equals("/") || args[1].equals(".."))) {
show = true;
}
else {
show = false;
String appid = String.valueOf(ar.getApplicationId().getId());
for (int i = args.length; i
if (appid.equals(args[i])) {
show = true;
break;
}
}
}
if (show) {
StringBuilder sb = new StringBuilder();
sb.append("startTime: ").append(sdf.format(new java.util.Date(ar.getStartTime()))).
append(", id: ").append(ar.getApplicationId().getId()).
append(", name: ").append(ar.getName()).
append(", state: ").append(ar.getYarnApplicationState().name()).
append(", trackingUrl: ").append(ar.getTrackingUrl()).
append(", finalStatus: ").append(ar.getFinalApplicationStatus());
System.out.println(sb);
totalCnt++;
if (ar.getYarnApplicationState() == YarnApplicationState.RUNNING) {
runningCnt++;
}
}
}
System.out.println(runningCnt + " active, total " + totalCnt + " applications.");
}
catch (Exception ex) {
throw new CliException("Failed to retrieve application list", ex);
}
}
private ApplicationReport assertRunningApp(ApplicationReport app)
{
ApplicationReport r;
try {
r = rmClient.getApplicationReport(app.getApplicationId());
if (r.getYarnApplicationState() != YarnApplicationState.RUNNING) {
String msg = String.format("Application %s not running (status %s)",
r.getApplicationId().getId(), r.getYarnApplicationState());
throw new CliException(msg);
}
}
catch (YarnRemoteException rmExc) {
throw new CliException("Unable to determine application status.", rmExc);
}
return r;
}
private ClientResponse getResource(String resourcePath)
{
if (currentApp == null) {
throw new CliException("No application selected");
}
if (StringUtils.isEmpty(currentApp.getTrackingUrl()) || currentApp.getFinalApplicationStatus() != FinalApplicationStatus.UNDEFINED) {
currentApp = null;
currentDir = "/";
throw new CliException("Application terminated.");
}
WebServicesClient wsClient = new WebServicesClient();
Client client = wsClient.getClient();
client.setFollowRedirects(true);
WebResource r = client.resource("http://" + currentApp.getTrackingUrl()).path(StramWebServices.PATH).path(resourcePath);
try {
return wsClient.process(r, ClientResponse.class, new WebServicesClient.WebServicesHandler<ClientResponse>() {
@Override
public ClientResponse process(WebResource webResource, Class<ClientResponse> clazz)
{
ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (!MediaType.APPLICATION_JSON_TYPE.equals(response.getType())) {
//throw new Exception("Unexpected response type " + response.getType());
}
return response;
}
});
}
catch (Exception e) {
// check the application status as above may have failed due application termination etc.
currentApp = assertRunningApp(currentApp);
throw new CliException("Failed to request " + r.getURI(), e);
}
}
private void connect(String line)
{
String[] args = StringUtils.splitByWholeSeparator(line, " ");
if (args.length != 2) {
System.err.println("Invalid arguments");
return;
}
if ("..".equals(args[1]) || "/".equals(args[1])) {
currentDir = "/";
return;
}
else {
currentDir = args[1];
}
currentApp = getApplication(Integer.parseInt(currentDir));
if (currentApp == null) {
throw new CliException("Invalid application id: " + args[1]);
}
boolean connected = false;
try {
LOG.info("Selected {} with tracking url: ", currentApp.getApplicationId(), currentApp.getTrackingUrl());
ClientResponse rsp = getResource(StramWebServices.PATH_INFO);
JSONObject json = rsp.getEntity(JSONObject.class);
System.out.println(json.toString(2));
connected = true; // set as current only upon successful connection
}
catch (CliException e) {
throw e; // pass on
}
catch (JSONException e) {
throw new CliException("Error connecting to app " + args[1], e);
}
finally {
if (!connected) {
//currentApp = null;
//currentDir = "/";
}
}
}
private void listOperators(String[] argv) throws JSONException
{
ClientResponse rsp = getResource(StramWebServices.PATH_OPERATORS);
JSONObject json = rsp.getEntity(JSONObject.class);
if (argv.length > 1) {
String singleKey = "" + json.keys().next();
JSONArray matches = new JSONArray();
// filter operators
JSONArray arr = json.getJSONArray(singleKey);
for (int i = 0; i < arr.length(); i++) {
Object val = arr.get(i);
if (val.toString().matches(argv[1])) {
matches.put(val);
}
}
json.put(singleKey, matches);
}
System.out.println(json.toString(2));
}
private void listContainers(String[] args) throws JSONException
{
ClientResponse rsp = getResource(StramWebServices.PATH_CONTAINERS);
JSONObject json = rsp.getEntity(JSONObject.class);
if (args == null || args.length == 0) {
System.out.println(json.toString(2));
}
else {
JSONArray containers = json.getJSONArray("containers");
if (containers == null) {
System.out.println("No containers found!");
}
else {
for (int o = containers.length(); o
JSONObject container = containers.getJSONObject(o);
String id = container.getString("id");
if (id != null && !id.isEmpty()) {
for (int argc = args.length; argc
String s1 = "0" + args[argc];
String s2 = "_" + args[argc];
if (id.endsWith(s1) || id.endsWith(s2)) {
System.out.println(container.toString(2));
}
}
}
}
}
}
}
private void launchApp(String line, ConsoleReader reader)
{
String[] args = assertArgs(line, 2, "No jar file specified.");
boolean localMode = "launch-local".equals(args[0]);
AppConfig appConfig = null;
if (args.length == 3) {
File file = new File(args[2]);
appConfig = new StramAppLauncher.PropertyFileAppConfig(file);
}
try {
StramAppLauncher submitApp = new StramAppLauncher(new File(args[1]));
if (appConfig == null) {
List<AppConfig> cfgList = submitApp.getBundledTopologies();
if (cfgList.isEmpty()) {
throw new CliException("No applications bundled in jar, please specify one");
}
else if (cfgList.size() == 1) {
appConfig = cfgList.get(0);
}
else {
for (int i = 0; i < cfgList.size(); i++) {
System.out.printf("%3d. %s\n", i + 1, cfgList.get(i).getName());
}
boolean useHistory = reader.getUseHistory();
reader.setUseHistory(false);
@SuppressWarnings("unchecked")
List<Completor> completors = new ArrayList<Completor>(reader.getCompletors());
for (Completor c: completors) {
reader.removeCompletor(c);
}
String optionLine = reader.readLine("Pick application? ");
reader.setUseHistory(useHistory);
for (Completor c: completors) {
reader.addCompletor(c);
}
try {
int option = Integer.parseInt(optionLine);
if (0 < option && option <= cfgList.size()) {
appConfig = cfgList.get(option - 1);
}
}
catch (Exception e) {
// ignore
}
}
}
if (appConfig != null) {
if (!localMode) {
ApplicationId appId = submitApp.launchApp(appConfig);
this.currentApp = rmClient.getApplicationReport(appId);
this.currentDir = "" + currentApp.getApplicationId().getId();
System.out.println(appId);
}
else {
submitApp.runLocal(appConfig);
}
}
else {
System.err.println("No application specified.");
}
}
catch (Exception e) {
throw new CliException("Failed to launch " + args[1] + ": " + e.getMessage(), e);
}
}
@SuppressWarnings({"null", "ConstantConditions"})
private void killApp(String line)
{
String[] args = StringUtils.splitByWholeSeparator(line, " ");
if (args.length == 1) {
if (currentApp == null) {
throw new CliException("No application selected");
}
else {
try {
rmClient.killApplication(currentApp.getApplicationId());
currentDir = "/";
currentApp = null;
}
catch (YarnRemoteException e) {
throw new CliException("Failed to kill " + currentApp.getApplicationId(), e);
}
}
return;
}
ApplicationReport app = null;
int i = 0;
try {
while (++i < args.length) {
app = getApplication(Integer.parseInt(args[i]));
rmClient.killApplication(app.getApplicationId());
if (app == currentApp) {
currentDir = "/";
currentApp = null;
}
}
}
catch (YarnRemoteException e) {
throw new CliException("Failed to kill " + (app.getApplicationId() == null? "unknown application": app.getApplicationId()) + ". Aborting killing of any additional applications.", e);
}
catch (NumberFormatException nfe) {
throw new CliException("Invalid application Id " + args[i], nfe);
}
catch (NullPointerException npe) {
throw new CliException("Application with Id " + args[i] + " does not seem to be alive!", npe);
}
}
private WebResource getPostResource(WebServicesClient webServicesClient)
{
if (currentApp == null) {
throw new CliException("No application selected");
}
// YARN-156 WebAppProxyServlet does not support POST - for now bypass it for this request
currentApp = assertRunningApp(currentApp); // or else "N/A" might be there..
String trackingUrl = currentApp.getOriginalTrackingUrl();
Client wsClient = webServicesClient.getClient();
wsClient.setFollowRedirects(true);
return wsClient.resource("http://" + trackingUrl).path(StramWebServices.PATH);
}
private void shutdownApp(String line)
{
WebServicesClient webServicesClient = new WebServicesClient();
WebResource r = getPostResource(webServicesClient).path(StramWebServices.PATH_SHUTDOWN);
try {
JSONObject response = webServicesClient.process(r, JSONObject.class, new WebServicesClient.WebServicesHandler<JSONObject>()
{
@Override
public JSONObject process(WebResource webResource, Class<JSONObject> clazz)
{
return webResource.accept(MediaType.APPLICATION_JSON).post(clazz);
}
});
System.out.println("shutdown requested: " + response);
currentDir = "/";
currentApp = null;
}
catch (Exception e) {
throw new CliException("Failed to request " + r.getURI(), e);
}
}
private void timeoutApp(String line, final ConsoleReader reader)
{
if (currentApp == null) {
throw new CliException("No application selected");
}
int timeout = getIntArg(line, 1, "Specify wait duration");
ClientRMHelper.AppStatusCallback cb = new ClientRMHelper.AppStatusCallback()
{
@Override
public boolean exitLoop(ApplicationReport report)
{
System.out.println("current status is: " + report.getYarnApplicationState());
try {
if (reader.getInput().available() > 0) {
return true;
}
}
catch (IOException e) {
LOG.error("Error checking for input.", e);
}
return false;
}
};
try {
boolean result = rmClient.waitForCompletion(currentApp.getApplicationId(), cb, timeout * 1000);
if (!result) {
System.err.println("Application terminated unsucessful.");
}
}
catch (YarnRemoteException e) {
throw new CliException("Failed to kill " + currentApp.getApplicationId(), e);
}
}
private void killContainer(String line)
{
if (currentApp == null) {
throw new CliException("No application selected");
}
String[] args = assertArgs(line, 2, "no container id specified.");
WebServicesClient webServicesClient = new WebServicesClient();
WebResource r = getPostResource(webServicesClient).path(StramWebServices.PATH_CONTAINERS).path(args[1]).path("kill");
try {
JSONObject response = webServicesClient.process(r, JSONObject.class, new WebServicesClient.WebServicesHandler<JSONObject>()
{
@Override
public JSONObject process(WebResource webResource, Class<JSONObject> clazz)
{
return webResource.accept(MediaType.APPLICATION_JSON).post(clazz, new JSONObject());
}
});
System.out.println("container stop requested: " + response);
}
catch (Exception e) {
throw new CliException("Failed to request " + r.getURI(), e);
}
}
private void startRecording(String line)
{
if (currentApp == null) {
throw new CliException("No application selected");
}
String[] args = StringUtils.splitByWholeSeparator(line, " ");
if (args.length != 2 && args.length != 3) {
System.err.println("Invalid arguments");
return;
}
WebServicesClient webServicesClient = new WebServicesClient();
WebResource r = getPostResource(webServicesClient).path(StramWebServices.PATH_STARTRECORDING);
final JSONObject request = new JSONObject();
try {
request.put("operId", args[1]);
if (args.length == 3) {
request.put("portName", args[2]);
}
JSONObject response = webServicesClient.process(r, JSONObject.class, new WebServicesClient.WebServicesHandler<JSONObject>()
{
@Override
public JSONObject process(WebResource webResource, Class<JSONObject> clazz)
{
return webResource.accept(MediaType.APPLICATION_JSON).post(clazz, request);
}
});
System.out.println("start recording requested: " + response);
}
catch (Exception e) {
throw new CliException("Failed to request " + r.getURI(), e);
}
}
private void stopRecording(String line)
{
if (currentApp == null) {
throw new CliException("No application selected");
}
String[] args = StringUtils.splitByWholeSeparator(line, " ");
if (args.length != 2 && args.length != 3) {
System.err.println("Invalid arguments");
return;
}
WebServicesClient webServicesClient = new WebServicesClient();
WebResource r = getPostResource(webServicesClient).path(StramWebServices.PATH_STOPRECORDING);
final JSONObject request = new JSONObject();
try {
request.put("operId", args[1]);
if (args.length == 3) {
request.put("portName", args[2]);
}
JSONObject response = webServicesClient.process(r, JSONObject.class, new WebServicesClient.WebServicesHandler<JSONObject>() {
@Override
public JSONObject process(WebResource webResource, Class<JSONObject> clazz)
{
return webResource.accept(MediaType.APPLICATION_JSON).post(clazz, request);
}
});
System.out.println("stop recording requested: " + response);
}
catch (Exception e) {
throw new CliException("Failed to request " + r.getURI(), e);
}
}
private void syncRecording(String line)
{
if (currentApp == null) {
throw new CliException("No application selected");
}
String[] args = StringUtils.splitByWholeSeparator(line, " ");
if (args.length != 2 && args.length != 3) {
System.err.println("Invalid arguments");
return;
}
WebServicesClient webServicesClient = new WebServicesClient();
WebResource r = getPostResource(webServicesClient).path(StramWebServices.PATH_SYNCRECORDING);
final JSONObject request = new JSONObject();
try {
request.put("operId", args[1]);
if (args.length == 3) {
request.put("portName", args[2]);
}
JSONObject response = webServicesClient.process(r, JSONObject.class, new WebServicesClient.WebServicesHandler<JSONObject>() {
@Override
public JSONObject process(WebResource webResource, Class<JSONObject> clazz)
{
return webResource.accept(MediaType.APPLICATION_JSON).post(clazz, request);
}
});
System.out.println("sync recording requested: " + response);
}
catch (Exception e) {
throw new CliException("Failed to request " + r.getURI(), e);
}
}
private void setOperatorProperty(String line)
{
if (currentApp == null) {
throw new CliException("No application selected");
}
String[] args = assertArgs(line, 4, "required arguments: <operatorName> <propertyName> <propertyValue>");
WebServicesClient webServicesClient = new WebServicesClient();
WebResource r = getPostResource(webServicesClient).path(StramWebServices.PATH_LOGICAL_PLAN_OPERATORS).path(args[1]).path("setProperty");
try {
final JSONObject request = new JSONObject();
request.put("propertyName", args[2]);
request.put("propertyValue", args[3]);
JSONObject response = webServicesClient.process(r, JSONObject.class, new WebServicesClient.WebServicesHandler<JSONObject>()
{
@Override
public JSONObject process(WebResource webResource, Class<JSONObject> clazz)
{
return webResource.accept(MediaType.APPLICATION_JSON).post(JSONObject.class, request);
}
});
System.out.println("request submitted: " + response);
}
catch (Exception e) {
throw new CliException("Failed to request " + r.getURI(), e);
}
}
private void beginLogicalPlanChange(String line, ConsoleReader reader)
{
if (currentApp == null) {
throw new CliException("No application selected");
}
try {
List<LogicalPlanRequest> requests = new ArrayList<LogicalPlanRequest>();
while (true) {
String line2 = reader.readLine("logical-plan-change> ");
LogicalPlanRequest request = null;
if ("help".equals(line2)) {
printHelpLogicalPlanChange();
}
else if ("submit".equals(line2)) {
// submit change
System.out.println("Logical plan change submitted.");
submitLogicalPlanChange(requests);
return;
}
else if ("abort".equals(line2)) {
System.out.println("Logical plan change aborted.");
return;
}
else if (line2.startsWith("create-operator")) {
request = logicalPlanCreateOperatorRequest(line2);
}
else if (line2.startsWith("remove-operator")) {
request = logicalPlanRemoveOperatorRequest(line2);
}
else if (line2.startsWith("create-stream")) {
request = logicalPlanCreateStreamRequest(line2);
}
else if (line2.startsWith("remove-stream")) {
request = logicalPlanRemoveStreamRequest(line2);
}
else if (line2.startsWith("operator-attribute-set")) {
request = logicalPlanOperatorAttributeSetRequest(line2);
}
else if (line2.startsWith("operator-property-set")) {
request = logicalPlanOperatorPropertySetRequest(line2);
}
else if (line2.startsWith("port-attribute-set")) {
request = logicalPlanPortAttributeSetRequest(line2);
}
else if (line2.startsWith("stream-attribute-set")) {
request = logicalPlanStreamAttributeSetRequest(line2);
}
else if (line2.startsWith("queue")) {
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.defaultPrettyPrintingWriter().writeValueAsString(requests));
System.out.println("Total operations in queue: " + requests.size());
}
else {
System.out.println("Invalid command. Ignored.");
}
if (request != null) {
requests.add(request);
}
}
} catch (Exception ex) {
throw new CliException("Failed to submit logical plan change", ex);
}
}
private LogicalPlanRequest logicalPlanCreateOperatorRequest(String line)
{
String[] args = assertArgs(line, 3, "required arguments: <operatorName> <className>");
String operatorName = args[1];
String className = args[2];
CreateOperatorRequest request = new CreateOperatorRequest();
request.setOperatorName(operatorName);
request.setOperatorFQCN(className);
return request;
}
private LogicalPlanRequest logicalPlanRemoveOperatorRequest(String line)
{
String[] args = assertArgs(line, 2, "required arguments: <operatorName>");
String operatorName = args[1];
RemoveOperatorRequest request = new RemoveOperatorRequest();
request.setOperatorName(operatorName);
return request;
}
private LogicalPlanRequest logicalPlanCreateStreamRequest(String line)
{
String[] args = assertArgs(line, 6, "required arguments: <streamName> <sourceOperatorName> <sourcePortName> <sinkOperatorName> <sinkPortName>");
String streamName = args[1];
String sourceOperatorName = args[2];
String sourcePortName = args[3];
String sinkOperatorName = args[4];
String sinkPortName = args[5];
CreateStreamRequest request = new CreateStreamRequest();
request.setStreamName(streamName);
request.setSourceOperatorName(sourceOperatorName);
request.setSinkOperatorName(sinkOperatorName);
request.setSourceOperatorPortName(sourcePortName);
request.setSinkOperatorPortName(sinkPortName);
return request;
}
private LogicalPlanRequest logicalPlanRemoveStreamRequest(String line)
{
String[] args = assertArgs(line, 2, "required arguments: <streamName>");
String streamName = args[1];
RemoveStreamRequest request = new RemoveStreamRequest();
request.setStreamName(streamName);
return request;
}
private LogicalPlanRequest logicalPlanOperatorAttributeSetRequest(String line)
{
String[] args = assertArgs(line, 4, "required arguments: <operatorName> <attributeName> <attributeValue>");
String operatorName = args[1];
String attributeName = args[2];
String attributeValue = args[3];
OperatorAttributeSetRequest request = new OperatorAttributeSetRequest();
request.setOperatorName(operatorName);
request.setAttributeName(attributeName);
request.setAttributeValue(attributeValue);
return request;
}
private LogicalPlanRequest logicalPlanOperatorPropertySetRequest(String line)
{
String[] args = assertArgs(line, 4, "required arguments: <operatorName> <propertyName> <propertyValue>");
String operatorName = args[1];
String propertyName = args[2];
String propertyValue = args[3];
OperatorPropertySetRequest request = new OperatorPropertySetRequest();
request.setOperatorName(operatorName);
request.setPropertyName(propertyName);
request.setPropertyValue(propertyValue);
return request;
}
private LogicalPlanRequest logicalPlanPortAttributeSetRequest(String line)
{
String[] args = assertArgs(line, 5, "required arguments: <operatorName> <portName> <attributeName> <attributeValue>");
String operatorName = args[1];
String attributeName = args[2];
String attributeValue = args[3];
PortAttributeSetRequest request = new PortAttributeSetRequest();
request.setOperatorName(operatorName);
request.setAttributeName(attributeName);
request.setAttributeValue(attributeValue);
return request;
}
private LogicalPlanRequest logicalPlanStreamAttributeSetRequest(String line)
{
String[] args = assertArgs(line, 4, "required arguments: <streamName> <attributeName> <attributeValue>");
String streamName = args[1];
String attributeName = args[2];
String attributeValue = args[3];
StreamAttributeSetRequest request = new StreamAttributeSetRequest();
request.setStreamName(streamName);
request.setAttributeName(attributeName);
request.setAttributeValue(attributeValue);
return request;
}
private void submitLogicalPlanChange(List<LogicalPlanRequest> requests)
{
if (currentApp == null) {
throw new CliException("No application selected");
}
if (requests.isEmpty()) {
throw new CliException("Nothing to submit");
}
WebServicesClient webServicesClient = new WebServicesClient();
WebResource r = getPostResource(webServicesClient).path(StramWebServices.PATH_LOGICAL_PLAN_MODIFICATION);
try {
final Map<String, Object> m = new HashMap<String, Object>();
ObjectMapper mapper = new ObjectMapper();
m.put("requests", requests);
final JSONObject jsonRequest = new JSONObject(mapper.writeValueAsString(m));
JSONObject response = webServicesClient.process(r, JSONObject.class, new WebServicesClient.WebServicesHandler<JSONObject>()
{
@Override
public JSONObject process(WebResource webResource, Class<JSONObject> clazz)
{
return webResource.accept(MediaType.APPLICATION_JSON).post(JSONObject.class, jsonRequest);
}
});
System.out.println("request submitted: " + response);
}
catch (Exception e) {
throw new CliException("Failed to request " + r.getURI(), e);
}
}
public static void main(String[] args) throws Exception
{
StramCli shell = new StramCli();
shell.init(args);
shell.run();
}
}
|
package org.cloudfoundry.samples.music.web.controllers;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class TestEmployeeDetails {
EmpBusinessLogic empBusinessLogic = new EmpBusinessLogic();
EmployeeDetails employee = new EmployeeDetails();
//test to check appraisal
@Test
public void testCalculateAppriasal() {
System.out.println("new gradle");
System.out.println("new lal's changes");
System.out.println("new lal's changes2");
System.out.println("new_gradle_change2");
employee.setName("Rajeev");
employee.setAge(25);
employee.setMonthlySalary(8000);
double appraisal = empBusinessLogic.calculateAppraisal(employee);
assertEquals(500, appraisal, 0.0);
System.out.println("assertEquals");
System.out.println("assertNOtEquals");
System.out.println("new_gradle_change2");
System.out.println("new_gradle_change3");
System.out.println("new_gradle_change");
}
// test to check yearly salary
@Test
public void testCalculateYearlySalary() {
System.out.println("new lal's changes");
employee.setName("Rajeev");
employee.setAge(25);
employee.setMonthlySalary(8000);
double salary = empBusinessLogic.calculateYearlySalary(employee);
assertEquals(96000, salary, 0.0);
System.out.println("Rajeev");
System.out.println("Rajeev1....");
}
}
|
package com.github.pedrovgs.nox.path;
/**
* Spiral Path implementation used to place NoxItem objects in a equiangular spiral starting from
* the center of the view. NoxItem instances in this path will have the same size. This path is
* based on the Archimedean Spiral.
*
* @author Pedro Vicente Gomez Sanchez.
*/
class SpiralPath extends Path {
//TODO: Change path implementation related to getMinMaxXY and follow this approach
//This is easier for Nox library clients.private int minX;
private int maxX;
private int minY;
private int maxY;
SpiralPath(PathConfig pathConfig) {
super(pathConfig);
}
@Override public void calculate() {
PathConfig pc = getPathConfig();
int numberOfItems = pc.getNumberOfElements();
float centerY =
(pc.getViewHeight() / 2) - (pc.getFirstItemSize() / 2) - (pc.getFirstItemMargin() / 2);
float centerX =
(pc.getViewWidth() / 2) - (pc.getFirstItemSize() / 2) - (pc.getFirstItemMargin() / 2);
float angle = pc.getFirstItemSize();
for (int i = 0; i < numberOfItems; i++) {
setX(centerX, angle, i);
setY(centerY, angle, i);
}
}
private void setX(float centerX, float angle, int i) {
double x = centerX + (angle * i * Math.cos(i));
setNoxItemLeftPosition(i, (float) x);
minX = (int) Math.min(x, minX);
maxX = (int) Math.max(x, maxX);
}
private void setY(float centerY, float angle, int i) {
double y = centerY + (angle * i * Math.sin(i));
setNoxItemTopPosition(i, (float) y);
minY = (int) Math.min(y, minY);
maxY = (int) Math.max(y, maxY);
}
@Override public int getMinX() {
return minX;
}
@Override public int getMaxX() {
return maxX;
}
@Override public int getMinY() {
return minY;
}
@Override public int getMaxY() {
return maxY;
}
}
|
package io.spacedog.test;
import java.util.Iterator;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import io.spacedog.client.LogEndpoint.LogSearchResults;
import io.spacedog.client.SpaceDog;
import io.spacedog.client.elastic.ESQueryBuilders;
import io.spacedog.client.elastic.ESSearchSourceBuilder;
import io.spacedog.client.elastic.ESSortBuilders;
import io.spacedog.client.elastic.ESSortOrder;
import io.spacedog.http.SpaceBackend;
import io.spacedog.http.SpaceRequest;
import io.spacedog.http.SpaceTest;
public class LogResourceTest extends SpaceTest {
@Test
public void purgeBackendLogs() throws InterruptedException {
// prepare
prepareTest();
SpaceDog test2 = resetTest2Backend();
SpaceDog test = resetTestBackend();
SpaceDog fred = createTempDog(test, "fred").login();
fred.data().getAll().get();
fred.data().getAll().get();
// superadmin gets test2 backend total log count to check
// later that they aren't affected by test backend log purge
long test2TotalLogs = test2.log().get(0, true).total;
// superadmin checks everything is in place
LogSearchResults log = test.log().get(6, true);
assertEquals(5, log.results.size());
assertEquals("/1/data", log.results.get(0).path);
assertEquals("/1/data", log.results.get(1).path);
assertEquals("/1/login", log.results.get(2).path);
assertEquals("/1/credentials", log.results.get(3).path);
assertEquals("/1/backend", log.results.get(4).path);
DateTime before = log.results.get(1).receivedAt;
// superadmin deletes all logs before GET /data requests
test.log().delete(before);
// superadmin checks all test backend logs are deleted but ...
log = test.log().get(10, true);
assertEquals(4, log.total);
assertEquals("DELETE", log.results.get(0).method);
assertEquals("/1/log", log.results.get(0).path);
assertEquals("GET", log.results.get(1).method);
assertEquals("/1/log", log.results.get(1).path);
assertEquals("GET", log.results.get(2).method);
assertEquals("/1/data", log.results.get(2).path);
assertEquals("GET", log.results.get(3).method);
assertEquals("/1/data", log.results.get(3).path);
before = log.results.get(1).receivedAt;
// superdog deletes all logs before GET /log requests
superdog(test).log().delete(before);
// superadmin checks all test backend logs are deleted but ...
log = superdog(test).log().get(10, true);
assertEquals(4, log.total);
assertEquals("DELETE", log.results.get(0).method);
assertEquals("/1/log", log.results.get(0).path);
assertEquals("GET", log.results.get(1).method);
assertEquals("/1/log", log.results.get(1).path);
assertEquals("DELETE", log.results.get(2).method);
assertEquals("/1/log", log.results.get(2).path);
assertEquals("GET", log.results.get(3).method);
assertEquals("/1/log", log.results.get(3).path);
// count = last time checked + 1, because of the first check.
// It demonstrates purge of specific backend doesn't affect other
// backends
log = test2.log().get(0, true);
assertEquals(test2TotalLogs + 1, log.total);
}
@Test
public void searchInLogs() {
// prepare
prepareTest();
// creates test backend and user
SpaceDog superadmin = resetTestBackend();
SpaceDog guest = SpaceDog.backend(superadmin);
guest.get("/1/data").go(200);
guest.get("/1/data/user").go(403);
SpaceDog vince = createTempDog(superadmin, "vince").login();
vince.credentials().get(vince.id());
// superadmin search for test backend logs with status 400 and higher
ESSearchSourceBuilder query = ESSearchSourceBuilder.searchSource()
.query(ESQueryBuilders.rangeQuery("status").gte(400))
.sort(ESSortBuilders.fieldSort("receivedAt").order(ESSortOrder.DESC));
LogSearchResults results = superadmin.log().search(query, true);
assertEquals(1, results.results.size());
assertEquals("/1/data/user", results.results.get(0).path);
assertEquals(403, results.results.get(0).status);
// superadmin search for test backend logs
// with credentials type equal to superadmin and lower
query = ESSearchSourceBuilder.searchSource()
.query(ESQueryBuilders.termsQuery("credentials.type", "superadmin", "user", "guest"))
.sort(ESSortBuilders.fieldSort("receivedAt").order(ESSortOrder.DESC));
results = superadmin.log().search(query, true);
assertEquals(7, results.results.size());
assertEquals("/1/log/search", results.results.get(0).path);
assertEquals("/1/credentials/" + vince.id(), results.results.get(1).path);
assertEquals("/1/login", results.results.get(2).path);
assertEquals("/1/credentials", results.results.get(3).path);
assertEquals("/1/data/user", results.results.get(4).path);
assertEquals("/1/data", results.results.get(5).path);
assertEquals("/1/backend", results.results.get(6).path);
// superadmin search for test backend log to only get user and lower logs
query = ESSearchSourceBuilder.searchSource()
.query(ESQueryBuilders.termsQuery("credentials.type", "user", "guest"))
.sort(ESSortBuilders.fieldSort("receivedAt").order(ESSortOrder.DESC));
results = superadmin.log().search(query, true);
assertEquals(5, results.results.size());
assertEquals("/1/credentials/" + vince.id(), results.results.get(0).path);
assertEquals("/1/login", results.results.get(1).path);
assertEquals("/1/data/user", results.results.get(2).path);
assertEquals("/1/data", results.results.get(3).path);
assertEquals("/1/backend", results.results.get(4).path);
// superadmin search for test backend log to only get guest logs
query = ESSearchSourceBuilder.searchSource()
.query(ESQueryBuilders.termQuery("credentials.type", "guest"))
.sort(ESSortBuilders.fieldSort("receivedAt").order(ESSortOrder.DESC));
results = superadmin.log().search(query, true);
assertEquals(3, results.results.size());
assertEquals("/1/data/user", results.results.get(0).path);
assertEquals("/1/data", results.results.get(1).path);
assertEquals("/1/backend", results.results.get(2).path);
// superdog gets all test backend logs
query = ESSearchSourceBuilder.searchSource()
.query(ESQueryBuilders.matchAllQuery())
.sort(ESSortBuilders.fieldSort("receivedAt").order(ESSortOrder.DESC));
results = superadmin.log().search(query, true);
assertEquals(10, results.results.size());
assertEquals("/1/log/search", results.results.get(0).path);
assertEquals("/1/log/search", results.results.get(1).path);
assertEquals("/1/log/search", results.results.get(2).path);
assertEquals("/1/log/search", results.results.get(3).path);
assertEquals("/1/credentials/" + vince.id(), results.results.get(4).path);
assertEquals("/1/login", results.results.get(5).path);
assertEquals("/1/credentials", results.results.get(6).path);
assertEquals("/1/data/user", results.results.get(7).path);
assertEquals("/1/data", results.results.get(8).path);
assertEquals("/1/backend", results.results.get(9).path);
}
@Test
public void pingRequestAreNotLogged() {
prepareTest();
// load balancer pings a SpaceDog instance
SpaceRequest.get("").go(200);
// this ping should not be present in logs
JsonNode results = superdog().get("/1/log")
.size(5).go(200).get("results");
Iterator<JsonNode> elements = results.elements();
while (elements.hasNext()) {
JsonNode element = elements.next();
if (element.get("path").asText().equals("/")
&& element.get("credentials").get("backendId").asText().equals(SpaceBackend.defaultBackendId()))
Assert.fail();
}
}
}
|
package step.localrunner;
import static org.junit.Assert.assertEquals;
import static step.planbuilder.BaseArtefacts.*;
import static step.planbuilder.FunctionArtefacts.keyword;
import static step.planbuilder.FunctionArtefacts.keywordWithDynamicInput;
import static step.planbuilder.FunctionArtefacts.keywordWithDynamicKeyValues;
import static step.planbuilder.FunctionArtefacts.keywordWithKeyValues;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import junit.framework.Assert;
import step.artefacts.Echo;
import step.artefacts.FunctionGroup;
import step.artefacts.Script;
import step.artefacts.Sequence;
import step.artefacts.reports.EchoReportNode;
import step.core.artefacts.reports.ReportNodeStatus;
import step.core.dynamicbeans.DynamicValue;
import step.core.plans.Plan;
import step.core.plans.builder.PlanBuilder;
public class LocalPlanRunnerTest {
protected LocalPlanRunner runner;
@Before
public void init() {
runner = new LocalPlanRunner(LocalRunnerTestLibrary.class);
}
@Test
public void testProperties() throws IOException {
Map<String, String> properties = new HashMap<>();
properties.put("prop1", "MyProp1");
Echo echo = new Echo();
echo.setText(new DynamicValue<>("prop1", ""));
Plan plan = PlanBuilder.create().startBlock(new Sequence()).add(echo).endBlock().build();
runner = new LocalPlanRunner(properties, LocalRunnerTestLibrary.class);
runner.run(plan).visitReportNodes(node->{
if(node instanceof EchoReportNode) {
Assert.assertEquals("MyProp1",((EchoReportNode) node).getEcho());
}
});
}
@Test
public void testSession() throws IOException {
Plan plan = PlanBuilder.create()
.startBlock(new Sequence())
.startBlock(new FunctionGroup())
.add(keyword("writeSessionValue", "{\"key\":\"myKey\", \"value\":\"myValue\"}"))
// Assert that the key is in the Session
.add(keyword("assertSessionValue", "{\"key\":\"myKey\", \"value\":\"myValue\"}"))
.endBlock()
.startBlock(new FunctionGroup())
// Assert that the key isn't in the Session anymore as we're not in the same FunctionGroup
.add(keyword("assertSessionValue", "{\"key\":\"myKey\", \"value\":\"\"}"))
.endBlock()
.endBlock()
.build();
StringWriter tree = new StringWriter();
runner.run(plan).visitReportNodes(node->{
assertEquals(ReportNodeStatus.PASSED, node.getStatus());
}).printTree(tree);
Assert.assertEquals("Sequence:PASSED:\n" +
" Session:PASSED:\n" +
" writeSessionValue:PASSED:\n" +
" assertSessionValue:PASSED:\n" +
" Session:PASSED:\n" +
" assertSessionValue:PASSED:\n", tree.toString());
}
@Test
public void testError() throws IOException {
Script script = new Script();
script.setScript("throw new Exception()");
Plan plan = PlanBuilder.create().startBlock(sequence()).add(script).endBlock().build();
StringWriter tree = new StringWriter();
runner.run(plan).printTree(tree);
Assert.assertEquals("Sequence:TECHNICAL_ERROR:\n" +
" Script:TECHNICAL_ERROR:Error while running groovy expression: 'throw new Exception()'\n", tree.toString());
}
@Test
public void testFor() throws IOException {
Plan plan = PlanBuilder.create().startBlock(for_(1, 10))
.add(keyword("keyword1"))
.add(keyword("keyword1"))
.endBlock().build();
String expectedTree =
"For:PASSED:\n" +
" Iteration1:PASSED:\n" +
" keyword1:PASSED:\n" +
" keyword1:PASSED:\n" +
" Iteration2:PASSED:\n" +
" keyword1:PASSED:\n" +
" keyword1:PASSED:\n" +
" Iteration3:PASSED:\n" +
" keyword1:PASSED:\n" +
" keyword1:PASSED:\n" +
" Iteration4:PASSED:\n" +
" keyword1:PASSED:\n" +
" keyword1:PASSED:\n" +
" Iteration5:PASSED:\n" +
" keyword1:PASSED:\n" +
" keyword1:PASSED:\n" +
" Iteration6:PASSED:\n" +
" keyword1:PASSED:\n" +
" keyword1:PASSED:\n" +
" Iteration7:PASSED:\n" +
" keyword1:PASSED:\n" +
" keyword1:PASSED:\n" +
" Iteration8:PASSED:\n" +
" keyword1:PASSED:\n" +
" keyword1:PASSED:\n" +
" Iteration9:PASSED:\n" +
" keyword1:PASSED:\n" +
" keyword1:PASSED:\n" +
" Iteration10:PASSED:\n" +
" keyword1:PASSED:\n" +
" keyword1:PASSED:\n";
StringWriter tree = new StringWriter();
runner.run(plan).visitReportNodes(node->{
assertEquals(ReportNodeStatus.PASSED, node.getStatus());
}).printTree(tree);
Assert.assertEquals(expectedTree, tree.toString());
}
@Test
public void testChain() {
Plan plan = PlanBuilder.create().startBlock(for_(1, 10))
.add(keyword("keyword1"))
.add(keywordWithDynamicInput("keyword2","/{\"Param1\":\"${previous.Result1}\"}/.toString()"))
.endBlock().build();
runner.run(plan).visitReportNodes(node->{
assertEquals(ReportNodeStatus.PASSED, node.getStatus());
});
}
@Test
public void testKeywordWithKeyValues() {
Plan plan = PlanBuilder.create().startBlock(for_(1, 10))
.add(keywordWithKeyValues("keyword2", "Param1","value1"))
.endBlock().build();
runner.run(plan).visitReportNodes(node->{
assertEquals(ReportNodeStatus.PASSED, node.getStatus());
});
}
// private void printReportNode(ReportNode node, int level) {
// StringBuilder builder = new StringBuilder();
// for(int i=0;i<level;i++) {
// builder.append(" ");
// builder.append(node.getName()+":"+node.getStatus()+":"+(node.getError()!=null?node.getError().getMsg():""));
// System.out.println(builder.toString());
// ReportNodeAccessor reportNodeAccessor = runner.context.getReportNodeAccessor();
// getChildren(reportNodeAccessor, node).forEach(n->printReportNode(n, level+1));
// protected List<ReportNode> getChildren(ReportNodeAccessor reportNodeAccessor, ReportNode node) {
// return StreamSupport.stream(Spliterators.spliteratorUnknownSize(reportNodeAccessor.getChildren(node.getId()), Spliterator.ORDERED), false).collect(Collectors.toList());
//TODO analyze why this test is failing when building in maven @Test
public void testKeywordWithDynamicKeyValues() {
Plan plan = PlanBuilder.create().startBlock(for_(1, 10))
.add(keywordWithDynamicKeyValues("keyword1", "Param1","'value1'"))
.add(keywordWithDynamicKeyValues("keyword2", "Param1","previous.Param1"))
.endBlock().build();
runner.run(plan).visitReportNodes(node->{
assertEquals(ReportNodeStatus.PASSED, node);
});;
}
// @Test
// public void testForEach() {
// Plan plan = PlanBuilder.create().startBlock(forEachRowInExcel())
// .add(keyword("keyword1"))
// .endBlock().build();
// runner.run(plan);
}
|
// $Id: ObserverList.java,v 1.3 2002/05/20 20:41:47 mdb Exp $
package com.samskivert.util;
import java.util.ArrayList;
import com.samskivert.Log;
/**
* Provides a simplified mechanism for maintaining a list of observers (or
* listeners or whatever you like to call them) and notifying those
* observers when desired. Notification takes place through a {@link
* ObserverOp} which allows the list maintainer to call an arbitrary
* method on its observers.
*
* <p> A couple of different usage patterns will help to illuminate. The
* first, where a new notify operation is created every time the observers
* are notified. This wins on brevity but loses on performance.
*
* <pre>
* ...
* // notify our observers
* final int foo = 19;
* final String bar = "yay!";
* _observers.apply(new ObserverList.ObserverOp() {
* public boolean apply (Object observer) {
* ((MyHappyObserver)observer).foozle(foo, bar);
* return true;
* }
* });
* ...
* </pre>
*
* The second where a singleton instance of the operation class is
* maintained and is configured each time notification is desired.
*
* <pre>
* ...
* protected static class FoozleOp implements ObserverOp
* {
* public void init (int foo, String bar)
* {
* _foo = foo;
* _bar = bar;
* }
*
* public boolean apply (Object observer)
* {
* ((MyHappyObserver)observer).foozle(_foo, _bar);
* return true;
* }
*
* protected int _foo;
* protected String _bar;
* }
* ...
* // notify our observers
* _foozleOp.init(19, "yay!");
* _observers.apply(_foozleOp);
* ...
* protected static FoozleOp _foozleOp = new FoozleOp();
* ...
* </pre>
*
* Bear in mind that this latter case is not thread safe.
*
* <p> Other usage patterns are most certainly conceivable, and hopefully
* these two will give you a useful starting point for determining what is
* the most appropriate usage for your needs.
*/
public class ObserverList extends ArrayList
{
/**
* Instances of this interface are used to apply methods to all
* observers in a list.
*/
public static interface ObserverOp
{
/**
* Called once for each observer in the list.
*
* @return true if the observer should remain in the list, false
* if it should be removed in response to this application.
*/
public boolean apply (Object observer);
}
/** A notification ordering policy indicating that the observers
* should be notified in the order they were added and that the
* notification should be done on a snapshot of the array. */
public static final int SAFE_IN_ORDER_NOTIFY = 1;
/** A notification ordering policy wherein the observers are notified
* last to first so that they can be removed during the notification
* process and new observers added will not inadvertently be notified
* as well, but no copy of the observer list need be made. This will
* not work if observers are added or removed from arbitrary positions
* in the list during a notification call. */
public static final int FAST_UNSAFE_NOTIFY = 2;
/**
* Creates an empty observer list with the supplied notification
* policy.
*
* @param notifyPolicy Either {@link #SAFE_IN_ORDER_NOTIFY} or {@link
* #FAST_UNSAFE_NOTIFY}.
*/
public ObserverList (int notifyPolicy)
{
// make sure the policy is valid
if (notifyPolicy != SAFE_IN_ORDER_NOTIFY &&
notifyPolicy != FAST_UNSAFE_NOTIFY) {
throw new RuntimeException("Invalid notification policy " +
"[policy=" + notifyPolicy + "]");
}
_policy = notifyPolicy ;
}
/**
* Applies the supplied observer operation to all observers in the
* list in a manner conforming to the notification ordering policy
* specified at construct time.
*/
public void apply (ObserverOp obop)
{
if (_policy == SAFE_IN_ORDER_NOTIFY) {
// if we have to notify our observers in order, we need to
// create a snapshot of the observer array at the time we
// start the notification to ensure that modifications to the
// array during notification don't hose us
Object[] obs = toArray();
int ocount = obs.length;
for (int ii = 0; ii < ocount; ii++) {
if (!checkedApply(obop, obs[ii])) {
remove(obs[ii]);
}
}
} else if (_policy == FAST_UNSAFE_NOTIFY) {
int ocount = size();
for (int ii = ocount-1; ii >= 0; ii
if (!checkedApply(obop, get(ii))) {
remove(ii);
}
}
}
}
/**
* Applies the operation to the observer, catching and logging any
* exceptions thrown in the process.
*/
protected static boolean checkedApply (ObserverOp obop, Object obs)
{
try {
return obop.apply(obs);
} catch (Throwable thrown) {
Log.warning("ObserverOp choked during notification " +
"[op=" + obop +
", obs=" + StringUtil.safeToString(obs) + "].");
Log.logStackTrace(thrown);
// if they booched it, definitely don't remove them
return true;
}
}
/** The notification policy. */
protected int _policy;
}
|
package org.orbeon.oxf.xforms.processor;
import org.apache.commons.pool.ObjectPool;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.orbeon.oxf.common.OXFException;
import org.orbeon.oxf.common.ValidationException;
import org.orbeon.oxf.pipeline.api.ExternalContext;
import org.orbeon.oxf.pipeline.api.PipelineContext;
import org.orbeon.oxf.processor.*;
import org.orbeon.oxf.processor.generator.URLGenerator;
import org.orbeon.oxf.util.UUIDUtils;
import org.orbeon.oxf.xforms.*;
import org.orbeon.oxf.xforms.processor.handlers.HandlerContext;
import org.orbeon.oxf.xforms.processor.handlers.XHTMLBodyHandler;
import org.orbeon.oxf.xforms.processor.handlers.XHTMLHeadHandler;
import org.orbeon.oxf.xml.*;
import org.orbeon.oxf.xml.dom4j.LocationDocumentResult;
import org.orbeon.oxf.xml.dom4j.ExtendedLocationData;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.Locator;
import javax.xml.transform.sax.TransformerHandler;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* This processor handles XForms initialization and produces an XHTML document which is a
* translation from the source XForms + XHTML.
*/
public class XFormsToXHTML extends ProcessorImpl {
private static final boolean TEST_BYPASS_INPUT = false;// TODO: for testing only
// private static final boolean IS_MIGRATE_TO_SESSION = false;// TODO: for testing only
public static Logger logger = XFormsServer.logger;
private static final String INPUT_ANNOTATED_DOCUMENT = "annotated-document";
private static final String OUTPUT_DOCUMENT = "document";
private static final String OUTPUT_CACHE_KEY = "dynamicState";
// private static final String NAMESPACE_CACHE_KEY = "containerNamespace";
// private static final Long CONSTANT_VALIDITY = new Long(0);
private static InputDependencies testCachingStaticStateInputDependencies;
// private static final KeyValidity CONSTANT_KEY_VALIDITY
// = new KeyValidity(new InternalCacheKey("sessionId", "NO_SESSION_DEPENDENCY"), new Long(0));
public XFormsToXHTML() {
addInputInfo(new ProcessorInputOutputInfo(INPUT_ANNOTATED_DOCUMENT));
addOutputInfo(new ProcessorInputOutputInfo(OUTPUT_DOCUMENT));
}
/**
* Case where an XML response must be generated.
*/
public ProcessorOutput createOutput(final String outputName) {
final ProcessorOutput output = new URIProcessorOutputImpl(XFormsToXHTML.this, outputName, INPUT_ANNOTATED_DOCUMENT) {
public void readImpl(final PipelineContext pipelineContext, ContentHandler contentHandler) {
doIt(pipelineContext, contentHandler, this, outputName);
}
// protected OutputCacheKey getKeyImpl(PipelineContext pipelineContext) {
// final OutputCacheKey outputCacheKey = super.getKeyImpl(pipelineContext);
// if (IS_MIGRATE_TO_SESSION && outputCacheKey != null) {
// final InputDependencies inputDependencies = (InputDependencies) getCachedInputAsObject(pipelineContext, getInputByName(INPUT_ANNOTATED_DOCUMENT));
// if (inputDependencies != null && inputDependencies.isDependsOnSession()) {
// final ExternalContext externalContext = (ExternalContext) pipelineContext.getAttribute(PipelineContext.EXTERNAL_CONTEXT);
// final ExternalContext.Session session = externalContext.getSession(true);
// // Find cached info
// final XFormsEngineStaticState staticState = inputDependencies.getXFormsEngineStaticState();
// final String staticStateUUID = staticState.getUUID();
// final String encodedStaticState = staticState.getEncodedStaticState();
// final String dynamicStateUUID = (String) getOutputObject(pipelineContext, this, OUTPUT_CACHE_KEY,
// new KeyValidity(outputCacheKey, getValidityImpl(pipelineContext)));
// // Migrate data to current session
// return outputCacheKey;
protected boolean supportsLocalKeyValidity() {
return true;
}
public KeyValidity getLocalKeyValidity(PipelineContext pipelineContext, URIReferences uriReferences) {
// TODO: For now we disable caching of the output, as migration from the application cache to the session cache has no be completed
return null;
// Use the container namespace as a dependency
// final ExternalContext externalContext = (ExternalContext) pipelineContext.getAttribute(PipelineContext.EXTERNAL_CONTEXT);
// final String containerNamespace = externalContext.getRequest().getContainerNamespace();
// return new KeyValidity(new InternalCacheKey(XFormsToXHTML.this, NAMESPACE_CACHE_KEY, containerNamespace), CONSTANT_VALIDITY);
}
};
addOutput(outputName, output);
return output;
}
public void reset(PipelineContext context) {
setState(context, new URIProcessorOutputImpl.URIReferencesState());
}
private void doIt(final PipelineContext pipelineContext, ContentHandler contentHandler, final URIProcessorOutputImpl processorOutput, String outputName) {
final ExternalContext externalContext = (ExternalContext) pipelineContext.getAttribute(PipelineContext.EXTERNAL_CONTEXT);
// ContainingDocument and XFormsState created below
final XFormsContainingDocument[] containingDocument = new XFormsContainingDocument[1];
final XFormsState[] xformsState = new XFormsState[1];
final boolean[] cachedInput = new boolean[] { TEST_BYPASS_INPUT } ;
// Read and try to cache the complete XForms+XHTML document with annotations
final InputDependencies inputDependencies;
if (testCachingStaticStateInputDependencies == null) {
inputDependencies = (InputDependencies) readCacheInputAsObject(pipelineContext, getInputByName(INPUT_ANNOTATED_DOCUMENT), new CacheableInputReader() {
public Object read(PipelineContext pipelineContext, ProcessorInput processorInput) {
// Create URIResolver
final XFormsURIResolver uriResolver = new XFormsURIResolver(XFormsToXHTML.this, processorOutput, pipelineContext, INPUT_ANNOTATED_DOCUMENT, URLGenerator.DEFAULT_HANDLE_XINCLUDE);
// Compute annotated XForms document + static state document
final SAXStore annotatedSAXStore;
final XFormsStaticState xformsStaticState;
{
final TransformerHandler identity = TransformerUtils.getIdentityTransformerHandler();
// TODO: Use TinyTree instead of dom4j Document
final LocationDocumentResult documentResult = new LocationDocumentResult();
identity.setResult(documentResult);
// TODO: Digest not used at this point
// final XMLUtils.DigestContentHandler digestContentHandler = new XMLUtils.DigestContentHandler("MD5");
annotatedSAXStore = new SAXStore(new TeeContentHandler(new ContentHandler[] {
new XFormsExtractorContentHandler(pipelineContext, identity, uriResolver)
// ,digestContentHandler
// ,new SAXLoggerProcessor.DebugContentHandler()
}));
// Read the input
readInputAsSAX(pipelineContext, processorInput, annotatedSAXStore);
// Get the results
final Document staticStateDocument = documentResult.getDocument();
// TODO: Digest not used at this point
// final String digest = Base64.encode(digestContentHandler.getResult());
// if (XFormsServer.logger.isDebugEnabled())
// XFormsServer.logger.debug("XForms - created digest for static state: " + digest);
// xformsEngineStaticState = new XFormsStaticState(pipelineContext, staticStateDocument, digest);
xformsStaticState = new XFormsStaticState(staticStateDocument);
}
// Create document here so we can do appropriate analysis of caching dependencies
createCacheContainingDocument(pipelineContext, uriResolver, xformsStaticState, containingDocument, xformsState);
// Set caching dependencies
final InputDependencies inputDependencies = new InputDependencies(annotatedSAXStore, xformsStaticState);
setCachingDependencies(containingDocument[0], inputDependencies);
return inputDependencies;
}
public void foundInCache() {
cachedInput[0] = true;
}
public void storedInCache() {
cachedInput[0] = true;
}
});
// For testing only
if (TEST_BYPASS_INPUT)
testCachingStaticStateInputDependencies = inputDependencies;
} else {
// For testing only
inputDependencies = testCachingStaticStateInputDependencies;
}
try {
// Create containing document if not done yet
final String staticStateUUID;
if (containingDocument[0] == null) {
// In this case, we found the static state and more in the cache, but we must now create a new XFormsContainingDocument from this information
logger.debug("XForms - annotated document and static state obtained from cache; creating containing document.");
// Create URIResolver and XFormsContainingDocument
final XFormsURIResolver uriResolver = new XFormsURIResolver(XFormsToXHTML.this, processorOutput, pipelineContext, INPUT_ANNOTATED_DOCUMENT, URLGenerator.DEFAULT_HANDLE_XINCLUDE);
createCacheContainingDocument(pipelineContext, uriResolver, inputDependencies.getXFormsEngineStaticState(), containingDocument, xformsState);
} else {
logger.debug("XForms - annotated document and static state not obtained from cache.");
}
// Get static state UUID
if (cachedInput[0]) {
staticStateUUID = inputDependencies.getXFormsEngineStaticState().getUUID();
logger.debug("XForms - found cached static state UUID.");
} else {
staticStateUUID = null;
logger.debug("XForms - did not find cached static state UUID.");
}
// Try to cache dynamic state UUID associated with the output
final String dynamicStateUUID = (String) getCacheOutputObject(pipelineContext, processorOutput, OUTPUT_CACHE_KEY, new OutputObjectCreator() {
public Object create(PipelineContext pipelineContext, ProcessorOutput processorOutput) {
logger.debug("XForms - caching dynamic state UUID for resulting document.");
return UUIDUtils.createPseudoUUID();
}
public void foundInCache() {
logger.debug("XForms - found cached dynamic state UUID for resulting document.");
}
public void unableToCache() {
logger.debug("XForms - cannot cache dynamic state UUID for resulting document.");
}
});
// Output resulting document
if (outputName.equals("document"))
outputResponseDocument(pipelineContext, externalContext, inputDependencies.getAnnotatedSAXStore(), containingDocument[0], contentHandler, xformsState[0], staticStateUUID, dynamicStateUUID);
else
testOutputResponseState(pipelineContext, externalContext, containingDocument[0], contentHandler, xformsState[0], staticStateUUID, dynamicStateUUID);
} catch (Throwable e) {
if (containingDocument[0] != null) {
// If an exception is caught, we need to discard the object as its state may be inconsistent
final ObjectPool sourceObjectPool = containingDocument[0].getSourceObjectPool();
if (sourceObjectPool != null) {
logger.debug("XForms - containing document cache: throwable caught, discarding document from pool.");
try {
sourceObjectPool.invalidateObject(containingDocument);
containingDocument[0].setSourceObjectPool(null);
} catch (Exception e1) {
throw new OXFException(e1);
}
}
}
throw new OXFException(e);
}
}
// What can be cached: URI dependencies + the annotated XForms document
private static class InputDependencies extends URIProcessorOutputImpl.URIReferences {
private SAXStore annotatedSAXStore;
private XFormsStaticState xformsStaticState;
private boolean dependsOnSession;
public InputDependencies(SAXStore annotatedSAXStore, XFormsStaticState xformsStaticState) {
this.annotatedSAXStore = annotatedSAXStore;
this.xformsStaticState = xformsStaticState;
}
public SAXStore getAnnotatedSAXStore() {
return annotatedSAXStore;
}
public XFormsStaticState getXFormsEngineStaticState() {
return xformsStaticState;
}
public boolean isDependsOnSession() {
return dependsOnSession;
}
public void setDependsOnSession(boolean dependsOnSession) {
this.dependsOnSession = dependsOnSession;
}
}
private void setCachingDependencies(XFormsContainingDocument containingDocument, InputDependencies inputDependencies) {
// If a submission took place during XForms initialization, we currently don't cache
// TODO: Some cases could be easily handled, like GET
if (containingDocument.isGotSubmission()) {
if (logger.isDebugEnabled())
logger.debug("XForms - submission occurred during XForms initialization, disabling caching of output.");
inputDependencies.setNoCache();
return;
}
// Set caching dependencies if the input was actually read
for (Iterator i = containingDocument.getModels().iterator(); i.hasNext();) {
final XFormsModel currentModel = (XFormsModel) i.next();
// Add schema dependencies
final String schemaURI = currentModel.getSchemaURI();
if (schemaURI != null) {
if (logger.isDebugEnabled())
logger.debug("XForms - adding document cache dependency for schema: " + schemaURI);
inputDependencies.addReference(null, schemaURI, null, null);// TODO: support username / password on schema refs
}
// Add instance source dependencies
if (currentModel.getInstances() != null) {
for (Iterator j = currentModel.getInstances().iterator(); j.hasNext();) {
final XFormsInstance currentInstance = (XFormsInstance) j.next();
final String instanceSourceURI = currentInstance.getSourceURI();
if (instanceSourceURI != null) {
if (!currentInstance.isApplicationShared()) {
// Add dependency only for instances that are not globally shared
if (logger.isDebugEnabled())
logger.debug("XForms - adding document cache dependency for instance: " + instanceSourceURI);
inputDependencies.addReference(null, instanceSourceURI, currentInstance.getUsername(), currentInstance.getPassword());
} else {
// Don't add the dependency as we don't want the instance URI to be hit
// For all practical purposes, globally shared instances must remain constant!
if (logger.isDebugEnabled())
logger.debug("XForms - not adding document cache dependency for application shared instance: " + instanceSourceURI);
}
}
}
}
// TODO: Add @src attributes from controls?
}
// Handle dependency on session id
if (containingDocument.isSessionStateHandling()) {
inputDependencies.setDependsOnSession(true);
}
}
private void createCacheContainingDocument(final PipelineContext pipelineContext, XFormsURIResolver uriResolver, XFormsStaticState xformsStaticState,
XFormsContainingDocument[] containingDocument, XFormsState[] xformsState) {
{
// Create containing document and initialize XForms engine
containingDocument[0] = new XFormsContainingDocument(pipelineContext, xformsStaticState, uriResolver);
// Make sure we have up to date controls before creating state below
final XFormsControls xformsControls = containingDocument[0].getXFormsControls();
xformsControls.rebuildCurrentControlsStateIfNeeded(pipelineContext);
// This is the state after XForms initialization
xformsState[0] = new XFormsState(xformsStaticState.getEncodedStaticState(pipelineContext),
containingDocument[0].createEncodedDynamicState(pipelineContext));
}
// Cache ContainingDocument if requested and possible
{
if (XFormsUtils.isCacheDocument()) {
XFormsServerDocumentCache.instance().add(pipelineContext, xformsState[0], containingDocument[0]);
}
}
}
private void outputResponseDocument(final PipelineContext pipelineContext, final ExternalContext externalContext,
final SAXStore annotatedDocument, final XFormsContainingDocument containingDocument,
final ContentHandler contentHandler, final XFormsState xformsState,
final String staticStateUUID, String dynamicStateUUID) throws SAXException {
final ElementHandlerController controller = new ElementHandlerController();
// Make sure we have up to date controls (should already be the case)
final XFormsControls xformsControls = containingDocument.getXFormsControls();
xformsControls.rebuildCurrentControlsStateIfNeeded(pipelineContext);
xformsControls.evaluateAllControlsIfNeeded(pipelineContext);
// Register handlers on controller (the other handlers are registered by the body handler)
controller.registerHandler(XHTMLHeadHandler.class.getName(), XMLConstants.XHTML_NAMESPACE_URI, "head");
controller.registerHandler(XHTMLBodyHandler.class.getName(), XMLConstants.XHTML_NAMESPACE_URI, "body");
// Set final output with output to filter remaining xforms:* elements if any
// TODO: Remove this filter once the "exception elements" below are filtered at the source.
controller.setOutput(new DeferredContentHandlerImpl(new XFormsElementFilterContentHandler(contentHandler)));
controller.setElementHandlerContext(new HandlerContext(controller, pipelineContext, containingDocument, xformsState, staticStateUUID, dynamicStateUUID, externalContext));
// Process everything
annotatedDocument.replay(new ElementFilterContentHandler(controller) {
protected boolean isFilterElement(String uri, String localname, String qName, Attributes attributes) {
// We filter everything that is not a control
// TODO: There are some temporary exceptions, but those should actually be handled by the ControlInfo in the first place
return (XFormsConstants.XXFORMS_NAMESPACE_URI.equals(uri) && !(localname.equals("img") || localname.equals("dialog")))
|| (XFormsConstants.XFORMS_NAMESPACE_URI.equals(uri)
&& !(XFormsControls.isActualControl(localname) || exceptionXFormsElements.get(localname) != null));
}
// Below we wrap all the exceptions to try to add location information
private Locator locator;
public void setDocumentLocator(Locator locator) {
super.setDocumentLocator(locator);
this.locator = locator;
}
public void startElement(String uri, String localname, String qName, Attributes attributes) throws SAXException {
try {
super.startElement(uri, localname, qName, attributes);
} catch (RuntimeException e) {
wrapException(e);
}
}
public void endElement(String uri, String localname, String qName) throws SAXException {
try {
super.endElement(uri, localname, qName);
} catch (RuntimeException e) {
wrapException(e);
}
}
public void characters(char[] chars, int start, int length) throws SAXException {
try {
super.characters(chars, start, length);
} catch (RuntimeException e) {
wrapException(e);
}
}
public void startPrefixMapping(String s, String s1) throws SAXException {
try {
super.startPrefixMapping(s, s1);
} catch (RuntimeException e) {
wrapException(e);
}
}
public void endPrefixMapping(String s) throws SAXException {
try {
super.endPrefixMapping(s);
} catch (RuntimeException e) {
wrapException(e);
}
}
public void ignorableWhitespace(char[] chars, int start, int length) throws SAXException {
try {
super.ignorableWhitespace(chars, start, length);
} catch (RuntimeException e) {
wrapException(e);
}
}
public void skippedEntity(String s) throws SAXException {
try {
super.skippedEntity(s);
} catch (RuntimeException e) {
wrapException(e);
}
}
public void processingInstruction(String s, String s1) throws SAXException {
try {
super.processingInstruction(s, s1);
} catch (RuntimeException e) {
wrapException(e);
}
}
public void endDocument() throws SAXException {
try {
super.endDocument();
} catch (RuntimeException e) {
wrapException(e);
}
}
public void startDocument() throws SAXException {
try {
super.startDocument();
} catch (RuntimeException e) {
wrapException(e);
}
}
private void wrapException(Exception e) throws SAXException {
if (locator != null)
throw ValidationException.wrapException(e, new ExtendedLocationData(locator, "converting XHTML+XForms document to XHTML"));
else if (e instanceof SAXException)
throw (SAXException) e;
else if (e instanceof RuntimeException)
throw (RuntimeException) e;
else
throw new OXFException(e);// this should not happen
}
});
}
private static final Map exceptionXFormsElements = new HashMap();
static {
exceptionXFormsElements.put("item", "");
exceptionXFormsElements.put("itemset", "");
exceptionXFormsElements.put("choices", "");
exceptionXFormsElements.put("value", "");
exceptionXFormsElements.put("label", "");
exceptionXFormsElements.put("hint", "");
exceptionXFormsElements.put("help", "");
exceptionXFormsElements.put("alert", "");
}
private void testOutputResponseState(final PipelineContext pipelineContext, final ExternalContext externalContext,
final XFormsContainingDocument containingDocument,
final ContentHandler contentHandler, final XFormsState xformsState,
final String staticStateUUID, String dynamicStateUUID) throws SAXException {
// Make sure we have up to date controls
final XFormsControls xformsControls = containingDocument.getXFormsControls();
xformsControls.rebuildCurrentControlsStateIfNeeded(pipelineContext);
xformsControls.evaluateAllControlsIfNeeded(pipelineContext);
// Output XML response
XFormsServer.outputResponse(containingDocument, false, null, pipelineContext, contentHandler, staticStateUUID, dynamicStateUUID, externalContext, xformsState, false, true);
}
}
|
package org.propelgraph.util;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileInputStream;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.HashMap;
import java.util.HashSet;
import java.util.zip.GZIPInputStream;
import java.net.URL;
import java.net.URLConnection;
import java.io.InputStream;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonToken;
import org.propelgraph.LabeledVertexGraph;
import org.propelgraph.GraphExternalVertexIdSupport;
import com.tinkerpop.blueprints.KeyIndexableGraph;
import com.tinkerpop.blueprints.Graph;
import com.tinkerpop.blueprints.TransactionalGraph;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.Edge;
import static org.jasonnet.logln.Logln.logln;
public class LoadJSON2 {
HashSet<String> hsRecentEdgeExternalIds = new HashSet<String>();
HashMap<JsonParser.Feature,Boolean> htFeatures = new HashMap<JsonParser.Feature,Boolean>();
/**
* adjust the JSON parser used by this class. We have found
* that the following is often helpful:
*
* <pre>
* {@code
* lj.configure(com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);
* lj.configure(com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
* }
* </pre>
*
* @author ccjason (4/6/2015)
*
* @param feature
* @param val
*/
public void configure( JsonParser.Feature feature, boolean val ) {
htFeatures.put( feature, val );
}
/**
* add vertices and edges to the specified graph based on the content found
* in the provided InputStream
*
* This method skips adding vertices and edges that it's already
* seen. In the case of edges, it checks for only the edges
* added in the previous invocation of this method of this
* object.
*
* @author ccjason (03/16/2015)
*
* @param g the graph to update
* @param is is the input stream
* @param max maximum number of elements to process
*/
public void populateFromJSONStream(Graph g, InputStream is, long maxElements) throws IOException {
GraphExternalVertexIdSupport graph2 = g instanceof GraphExternalVertexIdSupport ? (GraphExternalVertexIdSupport)g : null;
boolean boolSupportsExIds = (! g.getFeatures().ignoresSuppliedIds) || (graph2 != null);
if (!boolSupportsExIds) {
System.out.println("Warning: This graph implementation does not support external ids so we will be using the _id property instead. We'll try to request indexing of that column here. That really should be done in the caller if the graph might already contain content.");
if (g instanceof KeyIndexableGraph) {
((KeyIndexableGraph)g).createKeyIndex("_id", Vertex.class);
System.out.println(" _id index created");
} else {
System.out.println("graph doesn't support the KeyIndexableGraph interface, so we can't index the _id column and must abort"); return;
}
}
LabeledVertexGraph lvgraph = null;
if (g instanceof LabeledVertexGraph) {
lvgraph = (LabeledVertexGraph)g;
}
final int dographops = 2;
final boolean boolUseExternalId = true;
long cntPartialVerts = 0;
long cntWholeVerts = 0;
long cntProps = 0;
long cntEdges = 0;
long cntWholeElements = 0;
long t0 = System.currentTimeMillis();
//VertexMapCache tm = new VertexMapCache(100);
HashSet<String> hsNewRecentEdgeExternalIds = new HashSet<String>();
JsonFactory jsonF = new JsonFactory();
JsonParser jp = jsonF.createParser(is);
for (JsonParser.Feature feat : htFeatures.keySet()) {
jp.configure( feat, htFeatures.get(feat).booleanValue());
}
if (jp.nextToken() != JsonToken.START_ARRAY) {
throw new IOException("Expected data to start with an Array");
}
HashMap<String,Object> hmRecord = new HashMap<String,Object>();
while (jp.nextToken() != JsonToken.END_ARRAY) {
//logln("s");
if (jp.getCurrentToken() == JsonToken.START_OBJECT) {
hmRecord.clear();
while (jp.nextToken() != JsonToken.END_OBJECT) {
String fieldName = jp.getCurrentName();
//logln("fieldName= "+fieldName);
// Let's move to value
JsonToken tok = jp.nextToken();
if (tok == JsonToken.VALUE_NUMBER_INT) {
hmRecord.put(fieldName, new Integer((int)jp.getLongValue()));
} else if (tok == JsonToken.VALUE_STRING) {
hmRecord.put(fieldName, jp.getText());
} else if (tok == JsonToken.VALUE_NUMBER_FLOAT) {
hmRecord.put(fieldName, new Double(jp.getDoubleValue()));
} else { // ignore, or signal error?
throw new IOException("Unrecognized Json type: "+tok);
}
}
if (hmRecord.containsKey("node_type")) {
String node_id = (String)hmRecord.get("node_id"); hmRecord.remove("node_id");
String node_type = (String)hmRecord.get("node_type"); hmRecord.remove("node_type");
//logln("getting vertex");
Vertex v;
if (boolSupportsExIds) {
if (graph2!=null) {
v = graph2.getVertexByExternalId(node_id);
} else {
v = g.getVertex(node_id);
}
} else {
Iterable<Vertex> viter = g.getVertices("_id", node_id);
v = null;
for (Vertex vv : viter) { v = vv; break; }
}
//logln("got vertex?");
if (v==null) {
if ((lvgraph==null) || (node_type==null)) {
v = g.addVertex(node_id);
} else {
v = lvgraph.addLabeledVertex(node_id,node_type);
}
if (!boolSupportsExIds) {
v.setProperty("_id", node_id);
}
} else {
cntPartialVerts
}
//logln("got vertex 2?");
for (Object kobj : hmRecord.keySet()) {
String key = (String)kobj;
//logln("set prop "+key);
Object val = hmRecord.get(key);
v.setProperty(key,val);
cntProps++;
}
//logln("set props");
cntWholeVerts++;
} else if (hmRecord.containsKey("edge_type")) {
String edge_id = (String)hmRecord.get("edge_id"); hmRecord.remove("edge_id");
if (hsRecentEdgeExternalIds.contains(edge_id)) {
// redundant. 'skip.
//logln("skipping edge with exid of "+edge_id);
} else {
//logln("not skipping edge with exid of "+edge_id);
hsNewRecentEdgeExternalIds.add(edge_id);
String edge_type = (String)hmRecord.get("edge_type"); hmRecord.remove("edge_type");
String end_node_type = (String)hmRecord.get("end_node_type"); hmRecord.remove("end_node_type");
String end_node = (String)hmRecord.get("end_node"); hmRecord.remove("end_node");
String source_node = (String)hmRecord.get("source_node"); hmRecord.remove("source_node");
Vertex vEnd, vSource; // = g.getVertex(end_node);
if (boolSupportsExIds) {
if (graph2!=null) {
vEnd = graph2.getVertexByExternalId(end_node);
vSource = graph2.getVertexByExternalId(source_node);
} else {
vEnd = g.getVertex(end_node);
vSource = g.getVertex(source_node);
}
} else {
Iterable<Vertex> viter = g.getVertices("_id", end_node);
vEnd = null;
for (Vertex vv : viter) { vEnd = vv; break; }
viter = g.getVertices("_id", source_node);
vSource = null;
for (Vertex vv : viter) { vSource = vv; break; }
}
if (vEnd==null) {
if ((lvgraph==null) || (end_node_type==null)) {
vEnd = g.addVertex(end_node);
} else {
vEnd = lvgraph.addLabeledVertex(end_node,end_node_type);
}
// todo: set vertex class/label
cntPartialVerts++;
}
//Vertex vSource = g.getVertex(source_node); // required to be already defined earlier in the file
if (vSource==null) {
System.out.println("missing source vertex, skipping edge creation"); // we let it continue to run for the sake of debugging parsing
} else {
Edge edge = g.addEdge(edge_id, vSource, vEnd, edge_type);
hsNewRecentEdgeExternalIds.add(edge_id);
for (Object kobj : hmRecord.keySet()) {
String key = (String)kobj;
Object val = hmRecord.get(key);
edge.setProperty(key,val);
cntProps++;
}
}
cntEdges++;
}
} else {
throw new RuntimeException("not an edge or vertex?");
}
} else {
throw new RuntimeException("expected to start a json object");
}
cntWholeElements++;
if ((cntWholeElements%10000)==0){
long cntVerts = cntPartialVerts+cntWholeVerts;
long t1 = System.currentTimeMillis(); System.out.printf("loadtime=%8d ms edges=%8d verts=%8d(%7d/sec) props=%8d \n", (t1-t0), cntEdges, cntVerts, cntVerts*1000L/(1+t1-t0), cntProps );
}
if (cntWholeElements>=maxElements) break;
}
jp.close(); // closes parser and underlying stream
{
long cntVerts = cntPartialVerts+cntWholeVerts;
long t1 = System.currentTimeMillis(); System.out.printf("loadtime=%8d ms edges=%8d verts=%8d(%7d/sec) props=%8d \n", (t1-t0), cntEdges, cntVerts, cntVerts*1000L/(1+t1-t0), cntProps );
}
hsRecentEdgeExternalIds = hsNewRecentEdgeExternalIds;
}
/**
* populate graph from the JSON data at the specified url.
*
* @see populateFromJSONStream(Graph, InputStream, long )
*
* @author ccjason (03/16/2015)
*
* @param g the graph
* @param strURL
* @param graphshortname short name for this load that will be
* listed in logs
* @param max maximum number of triples to process
*/
public void populateFromURL(Graph g, String strURL, String graphshortname, long max) throws FileNotFoundException, IOException {
long t0 = System.currentTimeMillis();
URL url;
{
url = new URL(strURL);
}
/*
if (true && (g instanceof RDFHTTPLoadingGraph)) {
System.out.println("fetching url: "+url + " with C++ RDF URL loader");
//((com.ibm.research.systemg.nativestore.tinkerpop.NSGraph)g).add_turtle_rdf_data_from_http_url(url.toString(), max);
((RDFHTTPLoadingGraph)g).add_turtle_rdf_data_from_http_url(url.toString(), max);
if (null!=new Object()) return; //
} else {
}
*/
System.out.println("fetching url: "+url + " with Java JSON2 URL loader");
InputStream isWeb;
if (false) {
isWeb = url.openStream();
} else { //JNIGen.println("ln 362");
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Encoding", "gzip");
//OutputStream osW = connection.getOutputStream();
InputStream isR1 = connection.getInputStream();
String sContEncoding = connection.getHeaderField("Content-Encoding");
if ((null!=sContEncoding) && sContEncoding.equals("gzip")) {
isWeb = new GZIPInputStream(isR1);
} else { //System.out.println("bbb");
isWeb = isR1;
}
}
populateFromJSONStream(g,isWeb,max);
if (g instanceof TransactionalGraph) {
TransactionalGraph tg = (TransactionalGraph)g;
tg.commit();
}
}
/**
* populate graph from the JSON data at the specified file.
*
* @see populateFromJSONStream(Graph, InputStream, long )
*
* @author ccjason (03/16/2015)
*
* @param g the graph
* @param strFN filename
* @param graphshortname short name for this load that will be
* listed in logs
* @param max maximum number of triples to process
*/
public void populateFromFile(Graph g, String strFN, String graphshortname, long max) throws FileNotFoundException, IOException {
long t0 = System.currentTimeMillis();
System.out.println("fetching file: "+strFN + " with Java JSON2 file loader");
InputStream is = new FileInputStream(strFN);
populateFromJSONStream(g,is,max);
if (g instanceof TransactionalGraph) {
TransactionalGraph tg = (TransactionalGraph)g;
tg.commit();
}
}
}
|
/*
* $Id: TestBlockingStreamComm.java,v 1.4 2005-05-26 16:08:19 tlipkis Exp $
*/
package org.lockss.protocol;
import java.util.*;
import java.io.*;
import java.net.*;
import org.lockss.config.Configuration;
import org.lockss.daemon.*;
import org.lockss.plugin.*;
import org.lockss.util.*;
import org.lockss.util.Queue;
import org.lockss.test.*;
/**
* This is the test class for org.lockss.protocol.BlockingStreamComm
*/
public class TestBlockingStreamComm extends LockssTestCase {
public static Class testedClasses[] = {
BlockingStreamComm.class,
BlockingPeerChannel.class,
};
static Logger log = Logger.getLogger("TestBlockingStreamComm");
// testMultipleChannels
static final int MAX_COMMS = 5;
static final int HEADER_LEN = PeerChannel.HEADER_LEN;
static final int HEADER_CHECK = PeerChannel.HEADER_CHECK;
static final int HEADER_OFF_CHECK = PeerChannel.HEADER_OFF_CHECK;
static final int HEADER_OFF_OP = PeerChannel.HEADER_OFF_OP;
static final int HEADER_OFF_LEN = PeerChannel.HEADER_OFF_LEN;
static final int HEADER_OFF_PROTO = PeerChannel.HEADER_OFF_PROTO;
static final byte OP_PEERID = PeerChannel.OP_PEERID;
static final byte OP_DATA = PeerChannel.OP_DATA;
// Arrays store multiple instances of test objects (ports, PeerIds,
// queues, etc). Usually used in parallel (comms[n] has local id
// pids[n], on port testports[n]
int[] testports = new int[MAX_COMMS];
PeerIdentity[] pids = new PeerIdentity[MAX_COMMS];
PeerAddress.Tcp[] pads = new PeerAddress.Tcp[MAX_COMMS];
MyBlockingStreamComm[] comms = new MyBlockingStreamComm[MAX_COMMS];
SimpleQueue[] rcvdMsgss = new SimpleQueue[MAX_COMMS];
// Convenience equivalents to [1] and [2] entries in arrays
int testport1, testport2;
PeerIdentity pid1, pid2;
PeerAddress.Tcp pad1, pad2;
MyBlockingStreamComm comm1, comm2;
SimpleQueue rcvdMsgs1, rcvdMsgs2;
String testStr1 = "This is test data 1";
String testStr2 = "This message contains a null \000 character";
String testStr3 =
"They that can give up essential liberty to obtain " +
"a little temporary safety deserve neither liberty nor safety.";
PeerMessage msg1, msg2, msg3;
// buffers for manually sending to or receiving from an scomm under test
private byte[] rcvHeader = new byte[HEADER_LEN];
private byte[] sndHeader = new byte[HEADER_LEN];
private byte[] peerbuf = new byte[BlockingPeerChannel.MAX_PEERID_LEN];
private MockLockssDaemon daemon;
private IdentityManager idmgr;
Properties cprops = new Properties(); // some tests add more to this and
// reconfigure
SimpleBinarySemaphore sem;
SimpleQueue assocQ;
boolean useInternalSockets = false;
public void setUp() throws Exception {
super.setUp();
sem = new SimpleBinarySemaphore();
assocQ = new SimpleQueue.Fifo();
daemon = getMockLockssDaemon();
String tempDirPath = null;
try {
tempDirPath = getTempDir().getAbsolutePath() + File.separator;
}
catch (IOException ex) {
fail("unable to create a temporary directory");
}
cprops.setProperty(IdentityManager.PARAM_IDDB_DIR, tempDirPath + "iddb");
cprops.setProperty(IdentityManager.PARAM_LOCAL_IP, "127.0.0.1");
ConfigurationUtil.setCurrentConfigFromProps(cprops);
idmgr = new MyIdentityManager();
daemon.setIdentityManager(idmgr);
idmgr.initService(daemon);
daemon.setDaemonInited(true);
// idmgr.startService();
setupMessages();
useInternalSockets(false);
}
public void tearDown() throws Exception {
for (int comm = 0; comm < MAX_COMMS; comm++) {
stopComm(comm);
}
if (idmgr != null) {
idmgr.stopService();
idmgr = null;
}
super.tearDown();
TimeBase.setReal();
}
void stopComm(int ix) {
if (comms[ix] != null) {
comms[ix].stopService();
comms[ix] = null;
}
}
void useInternalSockets(boolean flg) {
useInternalSockets = flg;
}
void setupPid(int ix) throws IOException {
if (useInternalSockets) {
setupInternalPid(ix);
} else {
setupRealPid(ix);
}
}
/** Create a PeerIdentity for a port on localhost
*/
void setupRealPid(int ix) throws IOException {
if (pids[ix] == null) {
testports[ix] = findUnboundTcpPort();
pids[ix] = findPeerId("127.0.0.1", testports[ix]);
pads[ix] = (PeerAddress.Tcp)pids[ix].getPeerAddress();
peerhack(ix);
}
}
PeerIdentity findPeerId(String addr, int port) {
String id = IdentityManager.ipAddrToKey(addr, port);
return idmgr.findPeerIdentity(id);
}
/** Create a PeerIdentity for an InternalSocket
*/
void setupInternalPid(int ix) throws IOException {
if (pids[ix] == null) {
InetAddress ip = InternalSocket.internalInetAddr;
String addr = ip.getHostAddress();
testports[ix] = InternalServerSocket.findUnboundPort(2000);
pids[ix] = findPeerId(addr, testports[ix]);
pads[ix] = (PeerAddress.Tcp)pids[ix].getPeerAddress();
peerhack(ix);
}
}
void peerhack(int ix) {
switch (ix) {
case 1:
testport1 = testports[ix];
pid1 = pids[ix];
pad1 = pads[ix];
break;
case 2:
testport2 = testports[ix];
pid2 = pids[ix];
pad2 = pads[ix];
break;
default:
}
}
/** Create and start BlockingStreamComm instance ix, register message
* handlers for it
*/
void setupComm(int ix) throws IOException {
if (pids[ix] == null) setupPid(ix);
comms[ix] = new MyBlockingStreamComm(pids[ix]);
comms[ix].initService(daemon);
comms[ix].startService();
rcvdMsgss[ix] = new SimpleQueue.Fifo();
for (int proto = 1; proto <= 3; proto++) {
comms[ix].registerMessageHandler(proto,
new MessageHandler(rcvdMsgss[ix]));
}
commhack(ix);
}
void commhack(int ix) {
switch (ix) {
case 1:
comm1 = comms[ix];
rcvdMsgs1 = rcvdMsgss[ix];
break;
case 2:
comm2 = comms[ix];
rcvdMsgs2 = rcvdMsgss[ix];
break;
default:
}
}
void setupComm1() throws IOException {
setupComm(1);
}
void setupComm2() throws IOException {
setupComm(2);
}
int nextPort = 2000;
int findUnboundTcpPort() {
for (int p = nextPort; p < 65535; p++) {
try {
ServerSocket sock = new ServerSocket(p);
sock.close();
nextPort = p + 1;
return p;
} catch (IOException e) {
}
}
log.error("Couldn't find unused TCP port");
return -1;
}
void setupMessages() throws IOException {
msg1 = makePeerMessage(1, testStr1);
msg2 = makePeerMessage(2, testStr2);
msg3 = makePeerMessage(3, testStr3);
}
PeerMessage makePeerMessage(int proto) throws IOException {
PeerMessage pm = new MyMemoryPeerMessage();
pm.setProtocol(proto);
return pm;
}
PeerMessage makePeerMessage(int proto, String data) throws IOException {
return makePeerMessage(proto, data.getBytes());
}
PeerMessage makePeerMessage(int proto, byte[] data) throws IOException {
PeerMessage pm = makePeerMessage(proto);
OutputStream os = pm.getOutputStream();
os.write(data);
os.close();
return pm;
}
PeerMessage makePeerMessage(int proto, String data, int rpt)
throws IOException {
PeerMessage pm = makePeerMessage(proto);
byte[] bdata = data.getBytes();
OutputStream os = pm.getOutputStream();
for (int ix = rpt; ix > 0; ix
os.write(bdata);
}
os.close();
return pm;
}
/** Write a peerid message to an output stream */
void writePeerId(OutputStream outs, PeerIdentity pid) throws IOException {
writePeerId(outs, pid.getIdString());
}
/** Write a peerid message to an output stream */
void writePeerId(OutputStream outs, String idstr) throws IOException {
writeHeader(outs, OP_PEERID, idstr.length(), 0);
outs.write(idstr.getBytes());
outs.flush();
}
/** Write a message header to an output stream */
void writeHeader(OutputStream outs, int op, int len, int proto)
throws IOException {
byte[] sndHeader = new byte[HEADER_LEN];
sndHeader[HEADER_OFF_CHECK] = HEADER_CHECK;
sndHeader[HEADER_OFF_OP] = (byte)op;
ByteArray.encodeInt(len, sndHeader, HEADER_OFF_LEN);
ByteArray.encodeInt(proto, sndHeader, HEADER_OFF_PROTO);
outs.write(sndHeader);
}
/** Read header from input stream, check that it's a message header */
public void assertRcvHeader(InputStream ins, int op) throws IOException {
StreamUtil.readBytes(ins, rcvHeader, HEADER_LEN);
assertHeaderOp(rcvHeader, op);
}
/** Read message data from input stream, return as String */
String rcvMsgData(InputStream ins) throws IOException {
int len = ByteArray.decodeInt(rcvHeader, 2);
StreamUtil.readBytes(ins, peerbuf, len);
return new String(peerbuf, 0, len);
}
/** Assert that buf contains a valid header */
public void assertHeader(byte[] buf) {
assertEquals(HEADER_CHECK, buf[HEADER_OFF_CHECK]);
}
/** Assert that buf contains a valid header with expected op */
public void assertHeaderOp(byte[] buf, int op) {
assertHeader(buf);
assertEquals(op, buf[HEADER_OFF_OP]);
}
/** Assert that messages are the same except for sender id */
public static void assertEqualsButSender(PeerMessage expected,
PeerMessage actual) {
if (expected == actual ||
(expected != null && expected.equalsButSender(actual))) {
return;
}
failNotEquals(null, expected, actual);
}
/** Assert that message is same as expected, with expected sender */
public void assertEqualsMessageFrom(PeerMessage expectedMsg,
PeerIdentity expectedPid,
PeerMessage actualMsg) {
assertNotNull("Null message", actualMsg);
assertEquals(expectedPid, actualMsg.getSender());
assertEqualsButSender(expectedMsg, actualMsg);
}
public void testStateTrans() throws IOException {
setupComm1();
BlockingPeerChannel chan =
new BlockingPeerChannel(comm1, pid1, null, null);
chan.state = 0;
assertFalse(chan.stateTrans(1, 2));
assertEquals(0, chan.state);
assertTrue(chan.stateTrans(0, 3));
assertEquals(3, chan.state);
assertTrue(chan.stateTrans(3, 4, "shouldn't"));
assertEquals(4, chan.state);
try {
chan.stateTrans(3, 4, "should error");
fail("stateTrans should have thrown");
} catch (IllegalStateException e) {
}
// array version of stateTrans() nyi
// int[] lst = {2, 4, 6};
// assertTrue(chan.stateTrans(lst, 6, "shouldn't"));
// assertTrue(chan.stateTrans(lst, 8, "shouldn't"));
// assertFalse(chan.stateTrans(lst, 8));
// assertEquals(8, chan.state);
}
public void testNotStateTrans() throws IOException {
setupComm1();
BlockingPeerChannel chan =
new BlockingPeerChannel(comm1, pid1, null, null);
chan.state = 0;
assertFalse(chan.notStateTrans(0, 2));
assertEquals(0, chan.state);
assertTrue(chan.notStateTrans(1, 3));
assertEquals(3, chan.state);
assertTrue(chan.notStateTrans(2, 5, "shouldn't"));
assertEquals(5, chan.state);
try {
chan.notStateTrans(5, 4, "should error");
fail("notStateTrans should have thrown");
} catch (IllegalStateException e) {
}
assertEquals(5, chan.state);
int[] lst = {2, 4, 6};
assertTrue(chan.notStateTrans(lst, 3, "shouldn't"));
assertTrue(chan.notStateTrans(lst, 4, "shouldn't"));
assertFalse(chan.notStateTrans(lst, 8));
assertEquals(4, chan.state);
}
public void testReadHeader() throws IOException {
setupComm1();
byte[] hdr = {(byte)0xff, 1, 1, 2, 3, 4, 2, 3, 4, 5};
assertEquals(HEADER_LEN, hdr.length);
byte[] buf = new byte[HEADER_LEN];
InputStream ins = new ByteArrayInputStream(hdr);
BlockingPeerChannel chan = new BlockingPeerChannel(comm1, pid1, ins, null);
assertTrue(chan.readHeader());
hdr[0] = 42;
ins = new ByteArrayInputStream(hdr);
chan = new BlockingPeerChannel(comm1, pid1, ins, null);
try {
chan.readHeader();
fail("readHeader() of illegal header should throw");
} catch (ProtocolException e) {
}
ins = new StringInputStream("");
chan = new BlockingPeerChannel(comm1, pid1, ins, null);
assertFalse(chan.readHeader());
ins = new StringInputStream("\177");
chan = new BlockingPeerChannel(comm1, pid1, ins, null);
try {
chan.readHeader();
fail("readHeader() of partial header should throw");
} catch (ProtocolException e) {
}
}
public void testWriteHeader() throws IOException {
setupComm1();
ByteArrayOutputStream outs = new ByteArrayOutputStream();
BlockingPeerChannel chan = new BlockingPeerChannel(comm1, pid1,
null, outs);
chan.writeHeader(5, 16, 34);
byte[] hdr = outs.toByteArray();
assertEquals(HEADER_LEN, hdr.length);
assertEquals(0xff, ByteArray.decodeByte(hdr, 0));
assertEquals(5, hdr[1]);
assertEquals(16, ByteArray.decodeInt(hdr, 2));
assertEquals(34, ByteArray.decodeInt(hdr, 6));
}
public void testIllSend() throws IOException {
setupComm1();
try {
comm1.sendTo(null, pid2, null);
fail("Null message should throw");
} catch (NullPointerException e) {
}
try {
comm1.sendTo(msg1, null, null);
fail("Null peer should throw");
} catch (NullPointerException e) {
}
}
public void testRefused() throws IOException {
List event;
setupComm1();
setupPid(2);
comm1.setAssocQueue(assocQ);
comm1.sendTo(msg1, pid2, null);
assertNotNull("Connecting channel didn't dissociate",
(event = (List)assocQ.get(TIMEOUT_SHOULDNT)));
assertEquals("Connecting channel didn't dissociate",
"dissoc", event.get(0));
assertEmpty(comm1.channels);
assertEmpty(comm1.rcvChannels);
}
public void testIncoming() throws IOException {
setupComm1();
Interrupter intr1 = interruptMeIn(TIMEOUT_SHOULDNT);
Socket sock = new Socket(pad1.getIPAddr().getInetAddr(), pad1.getPort());
SockAbort intr2 = abortIn(TIMEOUT_SHOULDNT, sock);
InputStream ins = sock.getInputStream();
StreamUtil.readBytes(ins, rcvHeader, HEADER_LEN);
assertHeaderOp(rcvHeader, OP_PEERID);
assertEquals(pid1.getIdString(), rcvMsgData(ins));
intr1.cancel();
intr2.cancel();
}
public void testIncomingRcvPeerId(String peerid, boolean isGoodId)
throws IOException {
log.debug("Incoming rcv pid " + peerid);
setupComm1();
Interrupter intr1 = interruptMeIn(TIMEOUT_SHOULDNT);
Socket sock = new Socket(pad1.getIPAddr().getInetAddr(), pad1.getPort());
SockAbort intr2 = abortIn(TIMEOUT_SHOULDNT, sock);
InputStream ins = sock.getInputStream();
OutputStream outs = sock.getOutputStream();
StreamUtil.readBytes(ins, rcvHeader, HEADER_LEN);
assertHeaderOp(rcvHeader, OP_PEERID);
assertEquals(pid1.getIdString(), rcvMsgData(ins));
comm1.setAssocQueue(assocQ);
writePeerId(outs, peerid);
List event;
if (isGoodId) {
assertNotNull("Connecting channel didn't associate",
(event = (List)assocQ.get(TIMEOUT_SHOULDNT)));
assertEquals("Connecting channel didn't associate",
"assoc", event.get(0));
assertEquals(1, comm1.channels.size());
assertEquals(0, comm1.rcvChannels.size());
} else {
assertNotNull("Connecting channel didn't dissociate",
(event = (List)assocQ.get(TIMEOUT_SHOULDNT)));
assertEquals("Connecting channel didn't dissociate",
"dissoc", event.get(0));
assertEquals(0, comm1.channels.size());
assertEquals(0, comm1.rcvChannels.size());
}
intr1.cancel();
intr2.cancel();
}
public void testIncomingRcvGoodPeerId1() throws IOException {
setupPid(2);
testIncomingRcvPeerId(pid2.getIdString(), true);
}
public void testIncomingRcvBadPeerId1() throws IOException {
int bogusport = 0x10005;
String bogus1 = findPeerId("127.0.0.1", bogusport).getIdString();
testIncomingRcvPeerId(bogus1, false);
}
public void testIncomingRcvBadPeerId2() throws IOException {
// V1 (non-stream) id
testIncomingRcvPeerId("127.0.0.1", false);
}
public void testOriginate() throws IOException {
setupComm1();
setupPid(2);
ServerSocket server = new ServerSocket(pad2.getPort());
SockAbort intr = abortIn(TIMEOUT_SHOULDNT, server);
comm1.findOrMakeChannel(pid2);
Socket sock = server.accept();
InputStream ins = sock.getInputStream();
SockAbort intr2 = abortIn(TIMEOUT_SHOULDNT, sock);
assertRcvHeader(ins, OP_PEERID);
assertEquals(pid1.getIdString(), rcvMsgData(ins));
IOUtil.safeClose(server);
IOUtil.safeClose(sock);
intr.cancel();
intr2.cancel();
}
public void testOriginateToBadPeerId() throws IOException {
setupComm1();
PeerIdentity bad1 = findPeerId("127.0.0.1", 100000);
try {
comm1.sendTo(msg1, bad1, null);
fail("sendTo(..., " + bad1 + ") should throw");
} catch (IdentityManager.MalformedIdentityKeyException e) {
}
}
public void testOriginateRcvPeerId(String peerid, boolean isGoodId)
throws IOException {
log.debug("Orig, send pid " + peerid);
setupComm1();
comm1.setAssocQueue(assocQ);
setupPid(2);
log.debug2("Listening on " + pad2.getPort());
ServerSocket server = new ServerSocket(pad2.getPort());
SockAbort intr = abortIn(TIMEOUT_SHOULDNT, server);
comm1.findOrMakeChannel(pid2);
Socket sock = server.accept();
InputStream ins = sock.getInputStream();
OutputStream outs = sock.getOutputStream();
assertRcvHeader(ins, OP_PEERID);
assertEquals(pid1.getIdString(), rcvMsgData(ins));
writePeerId(outs, peerid);
List event;
if (isGoodId) {
assertNull("Connecting channel shouldn't call associate",
assocQ.get(TIMEOUT_SHOULD));
assertEquals(1, comm1.channels.size());
assertEquals(0, comm1.rcvChannels.size());
} else {
assertNotNull("Connecting channel didn't dissociate",
(event = (List)assocQ.get(TIMEOUT_SHOULDNT)));
assertEquals("Connecting channel didn't dissociate",
"dissoc", event.get(0));
assertEquals(0, comm1.channels.size());
assertEquals(0, comm1.rcvChannels.size());
}
IOUtil.safeClose(server);
IOUtil.safeClose(sock);
intr.cancel();
}
public void testOriginateRcvGoodPeerId1() throws IOException {
setupPid(2);
testOriginateRcvPeerId(pid2.getIdString(), true);
}
public void testOriginateRcvBadPeerId1() throws IOException {
int bogusport = 0x10005;
String bogus1 = findPeerId("127.0.0.1", bogusport).getIdString();
testOriginateRcvPeerId(bogus1, false);
}
// equivalent to the previous test
public void testOriginateRcvBadPeerId2() throws IOException {
// V1 (non-stream) id
testOriginateRcvPeerId("127.0.0.1", false);
}
// Don't know how to test this without actually waiting for socket to timeout
public void XXXtestHangingClose() throws IOException {
TimeBase.setSimulated(1000);
cprops.setProperty(BlockingStreamComm.PARAM_CHANNEL_IDLE_TIME, "5000");
ConfigurationUtil.setCurrentConfigFromProps(cprops);
setupComm1();
setupPid(2);
Interrupter intr1 = interruptMeIn(TIMEOUT_SHOULDNT);
Socket sock = new Socket(pad1.getIPAddr().getInetAddr(), pad1.getPort());
SockAbort intr2 = abortIn(TIMEOUT_SHOULDNT, sock);
InputStream ins = sock.getInputStream();
OutputStream outs = sock.getOutputStream();
StreamUtil.readBytes(ins, rcvHeader, HEADER_LEN);
assertHeaderOp(rcvHeader, OP_PEERID);
assertEquals(pid1.getIdString(), rcvMsgData(ins));
comm1.setAssocQueue(assocQ);
writePeerId(outs, pid2);
// wait for it to get peerid before sending to it
List event;
assertNotNull("Channel didn't assoc",
(event = (List)assocQ.get(TIMEOUT_SHOULDNT)));
assertEquals("Channel didn't assoc",
"assoc", event.get(0));
assertEquals(1, comm1.channels.size());
msg1 = makePeerMessage(1, "1234567890123456789012345678901234567890", 100);
int msgsize = msg1.getDataSize();
int tobuffer = 20 * (sock.getReceiveBufferSize() +
sock.getSendBufferSize());
for (int bytes = 0; bytes < tobuffer; bytes += msgsize) {
// comm1.sendTo(msg1, pid2, null);
}
assertEquals(1, comm1.channels.size());
BlockingPeerChannel chan = (BlockingPeerChannel)comm1.channels.get(pid2);
assertNotNull("Didn't find expected channel", chan);
// assertFalse("Send queue shouldn't be empty", chan.isSendIdle());
assertEquals(0, comm1.rcvChannels.size());
TimeBase.step(6000);
assertEquals(0, ins.available());
assertNotNull("Channel didn't close automatically after timeout",
(event = (List)assocQ.get(TIMEOUT_SHOULDNT)));
assertEquals("Channel didn't close automatically after timeout",
"dissoc", event.get(0));
assertFalse(intr1.did());
assertFalse(intr2.did());
intr1.cancel();
intr2.cancel();
}
public void testHangingSend() throws IOException {
TimeBase.setSimulated(1000);
cprops.setProperty(BlockingStreamComm.PARAM_CHANNEL_IDLE_TIME, "5000");
ConfigurationUtil.setCurrentConfigFromProps(cprops);
setupComm1();
setupPid(2);
Interrupter intr1 = interruptMeIn(TIMEOUT_SHOULDNT);
Socket sock = new Socket(pad1.getIPAddr().getInetAddr(), pad1.getPort());
SockAbort intr2 = abortIn(TIMEOUT_SHOULDNT * 2, sock);
InputStream ins = sock.getInputStream();
OutputStream outs = sock.getOutputStream();
StreamUtil.readBytes(ins, rcvHeader, HEADER_LEN);
assertHeaderOp(rcvHeader, OP_PEERID);
assertEquals(pid1.getIdString(), rcvMsgData(ins));
comm1.setAssocQueue(assocQ);
writePeerId(outs, pid2);
// wait for it to get peerid before sending to it
List event;
assertNotNull("Channel didn't assoc",
(event = (List)assocQ.get(TIMEOUT_SHOULDNT)));
assertEquals("Channel didn't assoc",
"assoc", event.get(0));
assertEquals(1, comm1.channels.size());
// a 30KB message
msg1 = makePeerMessage(1, "123456789012345678901234567890", 1000);
int msgsize = msg1.getDataSize();
int tobuffer = 200 * (sock.getReceiveBufferSize() +
sock.getSendBufferSize());
// Send lots of data to ensure send thread blocks waiting for socket to
// have buffer space
for (int bytes = 0; bytes < tobuffer; bytes += msgsize) {
comm1.sendTo(msg1, pid2, null);
}
assertEquals(1, comm1.channels.size());
BlockingPeerChannel chan = (BlockingPeerChannel)comm1.channels.get(pid2);
assertNotNull("Didn't find expected channel", chan);
assertFalse("Send queue shouldn't be empty", chan.isSendIdle());
assertEquals(0, comm1.rcvChannels.size());
// give hung checker a chance to run. If fails, interrupter will stop us
while (null == (event = (List)assocQ.get(10))) {
TimeBase.step(6000);
}
assertNotNull("Channel didn't close automatically after timeout", event);
assertEquals("Channel didn't close automatically after timeout",
"dissoc", event.get(0));
assertFalse(intr1.did());
assertFalse(intr2.did());
intr1.cancel();
intr2.cancel();
}
public void testSingleConnect() throws IOException {
PeerMessage msgIn;
setupComm1();
setupComm2();
comm1.sendTo(msg1, pid2, null);
msgIn = (PeerMessage)rcvdMsgs2.get(TIMEOUT_SHOULDNT);
assertEqualsMessageFrom(msg1, pid1, msgIn);
// redundant checks
assertEquals(1, msgIn.getProtocol());
assertEquals(testStr1.length(), msgIn.getDataSize());
assertEquals(testStr1.length(), msg1.getDataSize());
// each comm should have only one channel
assertEquals(1, comm1.channels.size());
assertEquals(1, comm2.channels.size());
assertEquals(0, comm1.rcvChannels.size());
assertEquals(0, comm2.rcvChannels.size());
assertTrue(rcvdMsgs1.isEmpty());
assertTrue(rcvdMsgs2.isEmpty());
comm1.sendTo(msg2, pid2, null);
msgIn = (PeerMessage)rcvdMsgs2.get(TIMEOUT_SHOULDNT);
assertEqualsMessageFrom(msg2, pid1, msgIn);
comm2.sendTo(msg2, pid1, null);
msgIn = (PeerMessage)rcvdMsgs1.get(TIMEOUT_SHOULDNT);
assertNotNull(msgIn);
assertEqualsMessageFrom(msg2, pid2, msgIn);
comm2.sendTo(msg3, pid1, null);
comm2.sendTo(msg1, pid1, null);
comm1.sendTo(msg3, pid2, null);
comm1.sendTo(msg2, pid2, null);
// each comm should still have only one channel
assertEquals(1, comm1.channels.size());
assertEmpty(comm1.rcvChannels);
assertEquals(1, comm2.channels.size());
assertEmpty(comm2.rcvChannels);
msgIn = (PeerMessage)rcvdMsgs1.get(TIMEOUT_SHOULDNT);
assertEqualsMessageFrom(msg3, pid2, msgIn);
msgIn = (PeerMessage)rcvdMsgs1.get(TIMEOUT_SHOULDNT);
assertEqualsMessageFrom(msg1, pid2, msgIn);
msgIn = (PeerMessage)rcvdMsgs2.get(TIMEOUT_SHOULDNT);
assertEqualsMessageFrom(msg3, pid1, msgIn);
msgIn = (PeerMessage)rcvdMsgs2.get(TIMEOUT_SHOULDNT);
assertEqualsMessageFrom(msg2, pid1, msgIn);
}
public void testFileMessage() throws IOException {
cprops.setProperty(BlockingStreamComm.PARAM_MIN_FILE_MESSAGE_SIZE, "1000");
ConfigurationUtil.setCurrentConfigFromProps(cprops);
PeerMessage msgIn;
setupComm1();
setupComm2();
msg2 = makePeerMessage(1, "1234567890123456789012345678901234567890", 100);
comm1.sendTo(msg1, pid2, null);
comm1.sendTo(msg2, pid2, null);
msgIn = (PeerMessage)rcvdMsgs2.get(TIMEOUT_SHOULDNT);
assertEqualsMessageFrom(msg1, pid1, msgIn);
assertTrue(msgIn.toString(), msgIn instanceof MemoryPeerMessage);
msgIn = (PeerMessage)rcvdMsgs2.get(TIMEOUT_SHOULDNT);
assertEqualsMessageFrom(msg2, pid1, msgIn);
assertTrue(msgIn.toString(), msgIn instanceof FilePeerMessage);
}
public void testMaxMsg() throws IOException {
cprops.setProperty(BlockingStreamComm.PARAM_MAX_MESSAGE_SIZE, "2000");
ConfigurationUtil.setCurrentConfigFromProps(cprops);
PeerMessage msgIn;
setupComm1();
setupComm2();
List event;
comm2.setAssocQueue(assocQ);
comm1.sendTo(msg1, pid2, null);
msg2 = makePeerMessage(1, "1234567890123456789012345678901234567890", 100);
msgIn = (PeerMessage)rcvdMsgs2.get(TIMEOUT_SHOULDNT);
assertEqualsMessageFrom(msg1, pid1, msgIn);
assertNotNull("Channel didn't associate",
(event = (List)assocQ.get(TIMEOUT_SHOULDNT)));
assertEquals("Channel didn't associate",
"assoc", event.get(0));
comm1.sendTo(msg2, pid2, null);
assertNotNull("Channel didn't close on too-large message",
(event = (List)assocQ.get(TIMEOUT_SHOULDNT)));
assertEquals("Channel didn't close automatically after timeout",
"dissoc", event.get(0));
}
// force delayed connect in one direction
public void testSimultaneousConnect1() throws IOException {
PeerMessage msgIn;
SimpleBinarySemaphore sem2 = new SimpleBinarySemaphore();
setupComm1();
setupComm2();
// delay comm2's accept()
comm2.setAcceptSem(sem2);
comm1.sendTo(msg1, pid2, null);
comm2.sendTo(msg2, pid1, null);
// both should have one connecting channel
assertEquals(1, comm1.channels.size());
assertEquals(1, comm2.channels.size());
// comm1 should receive message
msgIn = (PeerMessage)rcvdMsgs1.get(TIMEOUT_SHOULDNT);
assertEqualsMessageFrom(msg2, pid2, msgIn);
assertEquals(1, comm1.rcvChannels.size());
// comm2 shouldn't
assertTrue(rcvdMsgs2.isEmpty());
sem2.give();
// now comm2 should receive
msgIn = (PeerMessage)rcvdMsgs2.get(TIMEOUT_SHOULDNT);
assertEqualsMessageFrom(msg1, pid1, msgIn);
}
// force delayed connect in both directions
public void testSimultaneousConnect2() throws IOException {
PeerMessage msgIn;
SimpleBinarySemaphore sem1 = new SimpleBinarySemaphore();
SimpleBinarySemaphore sem2 = new SimpleBinarySemaphore();
setupComm1();
setupComm2();
// delay accept() in both channels
comm1.setAcceptSem(sem1);
comm2.setAcceptSem(sem2);
comm1.sendTo(msg1, pid2, null);
comm2.sendTo(msg2, pid1, null);
// both should have one connecting channel
assertEquals(1, comm1.channels.size());
assertEquals(1, comm2.channels.size());
assertEquals(0, comm1.rcvChannels.size());
assertEquals(0, comm2.rcvChannels.size());
assertTrue(rcvdMsgs1.isEmpty());
assertTrue(rcvdMsgs2.isEmpty());
// allow comm1 accept to proceed, it should receive message
sem1.give();
msgIn = (PeerMessage)rcvdMsgs1.get(TIMEOUT_SHOULDNT);
// comm1 only should have secondary channel
assertEqualsMessageFrom(msg2, pid2, msgIn);
assertEquals(1, comm1.channels.size());
assertEquals(1, comm2.channels.size());
assertEquals(1, comm1.rcvChannels.size());
assertEquals(0, comm2.rcvChannels.size());
// allow comm2 to proceed
sem2.give();
msgIn = (PeerMessage)rcvdMsgs2.get(TIMEOUT_SHOULDNT);
assertEqualsMessageFrom(msg1, pid1, msgIn);
assertEquals(1, comm1.channels.size());
assertEquals(1, comm2.channels.size());
assertEquals(1, comm1.rcvChannels.size());
assertEquals(1, comm2.rcvChannels.size());
}
// allow channel to timeout and close after use
public void testChannelCloseAfterTimeout() throws IOException {
TimeBase.setSimulated(1000);
PeerMessage msgIn;
cprops.setProperty(BlockingStreamComm.PARAM_CHANNEL_IDLE_TIME, "5000");
ConfigurationUtil.setCurrentConfigFromProps(cprops);
setupComm1();
setupComm2();
comm1.setAssocQueue(assocQ);
comm1.sendTo(msg1, pid2, null);
msgIn = (PeerMessage)rcvdMsgs2.get(TIMEOUT_SHOULDNT);
comm2.sendTo(msg2, pid1, null);
msgIn = (PeerMessage)rcvdMsgs1.get(TIMEOUT_SHOULDNT);
TimeBase.step(4000);
assertEquals(1, comm1.channels.size());
TimeBase.step(2000);
List event;
assertNotNull("Channel didn't close automatically after timeout",
(event = (List)assocQ.get(TIMEOUT_SHOULDNT)));
assertEquals("Channel didn't close automatically after timeout",
"dissoc", event.get(0));
assertEquals(0, comm1.channels.size());
assertEquals(0, comm1.rcvChannels.size());
}
// read (so) timeout should abort channel
public void testReadTimeout() throws IOException {
TimeBase.setSimulated(1000);
PeerMessage msgIn;
cprops.setProperty(BlockingStreamComm.PARAM_CHANNEL_IDLE_TIME, "10h");
cprops.setProperty(BlockingStreamComm.PARAM_DATA_TIMEOUT, "100");
ConfigurationUtil.setCurrentConfigFromProps(cprops);
setupComm1();
setupComm2();
comm1.setAssocQueue(assocQ);
comm1.sendTo(msg1, pid2, null);
msgIn = (PeerMessage)rcvdMsgs2.get(TIMEOUT_SHOULDNT);
assertEqualsMessageFrom(msg1, pid1, msgIn);
List event;
assertNotNull("Channel didn't close automatically after timeout",
(event = (List)assocQ.get(TIMEOUT_SHOULDNT)));
assertEquals("Channel didn't close automatically after timeout",
"dissoc", event.get(0));
assertEquals(0, comm1.channels.size());
assertEquals(0, comm1.rcvChannels.size());
}
// create MAX_COMMS comm instances, have each of them sent messages to
// each
public void testMultipleChannels() throws IOException {
for (int comm = 0; comm < MAX_COMMS; comm++) {
setupComm(comm);
}
for (int comm = 0; comm < MAX_COMMS; comm++) {
for (int peer = 0; peer < MAX_COMMS; peer++) {
String data =
pids[comm].getIdString() + ">" + pids[peer].getIdString();
PeerMessage pm = makePeerMessage(1, data);
comms[comm].sendTo(pm, pids[peer], null);
}
}
for (int comm = 0; comm < MAX_COMMS; comm++) {
Set peers = allPeers();
while (!peers.isEmpty()) {
PeerMessage msgIn = (PeerMessage)rcvdMsgss[comm].get(TIMEOUT_SHOULDNT);
assertNotNull("Comm" + comm + " didn't receive messages from " + peers,
msgIn);
peers.remove(msgIn.getSender());
}
}
}
Set allPeers() {
return SetUtil.fromArray(pids);
}
class MyBlockingStreamComm extends BlockingStreamComm {
SocketFactory sockFact;
PeerIdentity localId;
SimpleQueue assocEvents;
SimpleBinarySemaphore acceptSem;
MyBlockingStreamComm(PeerIdentity localId) {
this.localId = localId;
sockFact = new MySocketFactory();
}
SocketFactory getSocketFactory() {
return sockFact;
}
protected PeerIdentity getLocalPeerIdentity() {
return localId;
}
void associateChannelWithPeer(BlockingPeerChannel chan,
PeerIdentity peer) {
super.associateChannelWithPeer(chan, peer);
if (assocEvents != null) {
assocEvents.put(ListUtil.list("assoc", this));
}
}
void dissociateChannelFromPeer(BlockingPeerChannel chan,
PeerIdentity peer) {
super.dissociateChannelFromPeer(chan, peer);
if (assocEvents != null) {
assocEvents.put(ListUtil.list("dissoc", this));
}
}
void processIncomingConnection(Socket sock) throws IOException {
if (acceptSem != null) {
acceptSem.take();
}
super.processIncomingConnection(sock);
}
void setAssocQueue(SimpleQueue sem) {
assocEvents = sem;
}
void setAcceptSem(SimpleBinarySemaphore sem) {
acceptSem = sem;
}
/** Socket factory creates either real or internal sockets, and
* MyBlockingPeerChannels.
*/
class MySocketFactory implements BlockingStreamComm.SocketFactory {
public ServerSocket newServerSocket(int port, int backlog)
throws IOException {
return (useInternalSockets ? new InternalServerSocket(port, backlog)
: new ServerSocket(port, backlog));
}
public Socket newSocket(IPAddr addr, int port) throws IOException {
return (useInternalSockets ? new InternalSocket(addr.getInetAddr(), port)
: new Socket(addr.getInetAddr(), port));
}
public BlockingPeerChannel newPeerChannel(BlockingStreamComm comm,
Socket sock)
throws IOException {
return new MyBlockingPeerChannel(comm, sock);
}
public BlockingPeerChannel newPeerChannel(BlockingStreamComm comm,
PeerIdentity peer)
throws IOException {
return new MyBlockingPeerChannel(comm, peer);
}
}
}
static class MyBlockingPeerChannel extends BlockingPeerChannel {
SimpleBinarySemaphore stopSem;
MyBlockingPeerChannel(BlockingStreamComm scomm, PeerIdentity peer) {
super(scomm, peer);
}
MyBlockingPeerChannel(BlockingStreamComm scomm, Socket sock) {
super(scomm, sock);
}
void stopChannel() {
super.stopChannel();
if (stopSem != null) {
stopSem.give();
}
}
void setStopSem(SimpleBinarySemaphore sem) {
stopSem = sem;
}
}
class MessageHandler implements BlockingStreamComm.MessageHandler {
SimpleQueue queue;
public MessageHandler(SimpleQueue queue) {
this.queue = queue;
}
public void handleMessage(PeerMessage msg) {
log.debug("handleMessage(" + msg + ")");
queue.put(msg);
}
}
static class MyIdentityManager extends IdentityManager {
public void storeIdentities() throws ProtocolException {
}
}
// Suppress delete() because it prevents comparison with messages that
// have been sent
static class MyMemoryPeerMessage extends MemoryPeerMessage {
boolean isDeleted = false;
public void delete() {
isDeleted = true;
}
}
SockAbort abortIn(long inMs, Socket sock) {
SockAbort sa = new SockAbort(inMs, sock);
if (Boolean.getBoolean("org.lockss.test.threadDump")) {
sa.setThreadDump();
}
sa.start();
return sa;
}
SockAbort abortIn(long inMs, ServerSocket sock) {
SockAbort sa = new SockAbort(inMs, sock);
if (Boolean.getBoolean("org.lockss.test.threadDump")) {
sa.setThreadDump();
}
sa.start();
return sa;
}
/** SockAbort aborts a socket by closing it
*/
class SockAbort extends DoLater {
Socket sock;
ServerSocket servsock;
SockAbort(long waitMs, Socket sock) {
super(waitMs);
this.sock = sock;
}
SockAbort(long waitMs, ServerSocket servsock) {
super(waitMs);
this.servsock = servsock;
}
protected void doit() {
try {
if (sock != null) {
log.debug("Closing sock");
sock.close();
}
} catch (IOException e) {
log.warning("sock", e);
}
try {
if (servsock != null) {
log.debug("Closing servsock");
servsock.close();
}
} catch (IOException e) {
log.warning("servsock", e);
}
}
}
}
|
package info.puzz.a10000sentences.importer;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.FileUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import info.puzz.a10000sentences.apimodels.InfoVO;
import info.puzz.a10000sentences.apimodels.LanguageVO;
import info.puzz.a10000sentences.apimodels.SentenceCollectionVO;
import info.puzz.a10000sentences.apimodels.SentenceVO;
import info.puzz.a10000sentences.language.Languages;
public class TatoebaImporter {
private static final float MAX_SENTENCE_LENGTH = 100;
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
public static final int MAX_SENTENCES_NO = 12_000;
private static final char ALTERNATIVE_DELIMITER = '|';
public static void main(String[] args) throws Exception {
String bucketFiles = "bucket_files";
new File(bucketFiles).mkdirs();
String[] languages = new String[]{
"ces",
"bul",
"srp",
"dan",
"swe",
"ukr",
"nld",
"fin",
"mkd",
"hun",
"pol",
"ita",
"epo",
"lat",
"tur",
"ell",
"ron",
"ara",
"heb",
"deu",
"fra",
"rus",
"por",
"spa",
};
System.out.println("Caching links");
Map<Integer, int[]> links = loadLinks();
System.out.println("Loading sentences");
Map<String, Map<Integer, TatoebaSentence>> sentencesPerLang = loadSentencesPerLanguage(languages);
InfoVO info = new InfoVO()
.setLanguages(Languages.getLanguages());
for (String language : languages) {
info.addSentencesCollection(importSentencesBothWays(links, sentencesPerLang, bucketFiles, "eng", language));
}
String infoFilename = Paths.get(bucketFiles, "info.json").toString();
FileUtils.writeByteArrayToFile(new File(infoFilename), OBJECT_MAPPER.writeValueAsBytes(info));
for (SentenceCollectionVO col : info.getSentenceCollections()) {
LanguageVO knownLang = Languages.getLanguageByAbbrev(col.getKnownLanguage());
LanguageVO targetLang = Languages.getLanguageByAbbrev(col.getTargetLanguage());
System.out.println(String.format("%s (for %s speakers): %d sentences", targetLang.getName(), knownLang.getName(), col.getCount()));
}
}
private static Map<String, Map<Integer, TatoebaSentence>> loadSentencesPerLanguage(String[] languages) throws Exception {
HashMap<String, Map<Integer, TatoebaSentence>> res = new HashMap<>();
Set<String> langs = new HashSet<>();
langs.add("eng");
for (String language : languages) {
langs.add(language);
}
FileInputStream fstream = new FileInputStream("tmp_files/sentences_detailed.csv");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split("\t");
int sentenceId = Integer.parseInt(parts[0]);
String lang = parts[1];
String text = parts[2];
if (langs.contains(lang)) {
if (!res.containsKey(lang)) {
res.put(lang, new HashMap<Integer, TatoebaSentence>());
}
TatoebaSentence sentence = new TatoebaSentence()
.setId(sentenceId)
.setText(prepareSentenceText(text, lang));
res.get(lang).put(sentenceId, sentence);
}
}
return res;
}
private static String prepareSentenceText(String text, String lang) {
if ("ar".equals(lang) || "ara".equals(lang)) {
return WordUtils.removeNonspacingChars(text).replace(ALTERNATIVE_DELIMITER, ' ');
}
return text.replace(ALTERNATIVE_DELIMITER, ' ');
}
private static Map<Integer, int[]> loadLinks() throws Exception {
HashMap<Integer, int[]> res = new HashMap<>();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("tmp_files/links.csv")));
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split("\t");
int sentence1 = Integer.parseInt(parts[0]);
int sentence2 = Integer.parseInt(parts[1]);
int[] related = res.get(sentence1);
if (related == null) {
res.put(sentence1, new int[] {sentence2});
} else {
int[] newRelated = new int[related.length + 1];
for (int i = 0; i < related.length; i++) {
newRelated[i] = related[i];
}
newRelated[newRelated.length - 1] = sentence2;
res.put(sentence1, newRelated);
}
}
return res;
}
private static List<SentenceCollectionVO> importSentencesBothWays(
Map<Integer, int[]> links,
Map<String,
Map<Integer, TatoebaSentence>> sentencesPerLang, String outputDir,
String lang1, String lang2) throws IOException {
ArrayList<SentenceCollectionVO> res = new ArrayList<>();
res.add(importSentences(links, sentencesPerLang, outputDir, lang1, lang2));
res.add(importSentences(links, sentencesPerLang, outputDir, lang2, lang1));
System.out.println(res);
return res;
}
private static SentenceCollectionVO importSentences(
Map<Integer, int[]> links,
Map<String, Map<Integer, TatoebaSentence>> sentencesPerLang,
String outputDir,
String knownLanguageAbbrev3, String targetLanguageAbbrev3) throws IOException {
long started = System.currentTimeMillis();
System.out.println(String.format("Processing %s->%s", knownLanguageAbbrev3, targetLanguageAbbrev3));
LanguageVO knownLanguage = Languages.getLanguageByAbbrev(knownLanguageAbbrev3);
LanguageVO targetLanguage = Languages.getLanguageByAbbrev(targetLanguageAbbrev3);
WordCounter wordCounter = new WordCounter();
Map<Integer, TatoebaSentence> targetLanguageSentences = sentencesPerLang.get(targetLanguageAbbrev3);
Map<Integer, TatoebaSentence> knownLanguageSentences = sentencesPerLang.get(knownLanguageAbbrev3);
for (TatoebaSentence sentence : targetLanguageSentences.values()) {
wordCounter.countWordsInSentence(sentence.getText());
}
System.out.println(String.format("Found %d known language sentences", knownLanguageSentences.size()));
System.out.println(String.format("Found %d target language sentences", targetLanguageSentences.size()));
System.out.println(String.format("%d distinct words, %d words", wordCounter.size(), wordCounter.count.intValue()));
String outFilename = String.format("%s-%s.csv", knownLanguage.getAbbrev(), targetLanguage.getAbbrev());
List<SentenceVO> sentences = new ArrayList<>();
for (TatoebaSentence targetSentence : targetLanguageSentences.values()) {
if (targetSentence == null) {
continue;
}
int[] knownSentenceIds = links.get(targetSentence.getId());
if (knownSentenceIds == null) {
continue;
}
StringBuilder knownSentenceAlternatives = new StringBuilder();
int alternatives = 0;
for (int knownSentenceId : knownSentenceIds) {
TatoebaSentence knownSentence = knownLanguageSentences.get(knownSentenceId);
if (knownSentence != null) {
if (knownSentenceAlternatives.length() > 0) {
knownSentenceAlternatives.append(ALTERNATIVE_DELIMITER);
}
knownSentenceAlternatives.append(knownSentence.getText());
++ alternatives;
}
}
if (alternatives > 0) {
String id = String.format("%s-%s-%d", knownLanguage.getAbbrev(), targetLanguage.getAbbrev(), targetSentence.id);
sentences.add(new SentenceVO()
.setSentenceId(id)
.setTargetSentenceId(targetSentence.id)
.setKnownSentence(knownSentenceAlternatives.toString())
.setTargetSentence(targetSentence.getText()));
}
}
// Order by id, so that older ids are deployed in the database (they are more likely to be
// without errors:
Collections.sort(sentences, new Comparator<SentenceVO>() {
@Override
public int compare(SentenceVO s1, SentenceVO s2) {
return s1.getTargetSentenceId() - s2.getTargetSentenceId();
}
});
sentences = sentences.subList(0, Math.min(MAX_SENTENCES_NO, sentences.size()));
for (SentenceVO sentence : sentences) {
calculateSentenceComplexity(sentence, wordCounter);
}
Collections.sort(sentences, new Comparator<SentenceVO>() {
@Override
public int compare(SentenceVO s1, SentenceVO s2) {
return Float.compare(s1.getComplexity(), s2.getComplexity());
}
});
FileOutputStream out = new FileOutputStream(Paths.get(outputDir, outFilename).toString());
for (SentenceVO sentence : sentences) {
out.write((sentence.getSentenceId() + "\t" + sentence.getKnownSentence() + "\t" + sentence.getTargetSentence() + "\n").getBytes("utf-8"));
}
out.close();
System.out.println(String.format("Found %d entences in %ds", sentences.size(), TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - started)));
System.out.println("Results written to: " + outFilename);
return new SentenceCollectionVO()
.setKnownLanguage(knownLanguage.getAbbrev())
.setTargetLanguage(targetLanguage.getAbbrev())
.setCount(sentences.size())
.setFilename(outFilename);
}
private static void calculateSentenceComplexity(SentenceVO sentence, WordCounter wordCounter) {
List<String> sentenceWords = WordUtils.getWords(sentence.getTargetSentence());
int[] counters = new int[sentenceWords.size()];
for (int i = 0; i < sentenceWords.size(); i++) {
counters[i] = wordCounter.getWordCount(sentenceWords.get(i));
}
Arrays.sort(counters);
if (counters.length > 3) {
// First are the less frequent words, ignore the 30% more frequent:
counters = Arrays.copyOfRange(counters, 0, (int) (counters.length * 0.70));
}
int sum = 0;
for (int counter : counters) {
sum += counter;
}
float avg = sum / ((float) counters.length);
sentence.setComplexity(- (float) (avg * Math.pow(0.95, sentenceWords.size())));
}
}
|
package net.md_5.bungee.connection;
import com.google.common.base.Preconditions;
import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.ServerConnection;
import net.md_5.bungee.UserConnection;
import net.md_5.bungee.Util;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.ChatEvent;
import net.md_5.bungee.api.event.PlayerDisconnectEvent;
import net.md_5.bungee.api.event.PluginMessageEvent;
import net.md_5.bungee.api.event.TabCompleteEvent;
import net.md_5.bungee.netty.ChannelWrapper;
import net.md_5.bungee.netty.PacketHandler;
import net.md_5.bungee.protocol.PacketWrapper;
import net.md_5.bungee.protocol.ProtocolConstants;
import net.md_5.bungee.protocol.packet.KeepAlive;
import net.md_5.bungee.protocol.packet.Chat;
import net.md_5.bungee.protocol.packet.PlayerListItem;
import net.md_5.bungee.protocol.packet.TabCompleteRequest;
import net.md_5.bungee.protocol.packet.ClientSettings;
import net.md_5.bungee.protocol.packet.PluginMessage;
import java.util.ArrayList;
import java.util.List;
import net.md_5.bungee.forge.ForgeConstants;
import net.md_5.bungee.protocol.packet.TabCompleteResponse;
public class UpstreamBridge extends PacketHandler
{
private final ProxyServer bungee;
private final UserConnection con;
private long lastTabCompletion = -1;
public UpstreamBridge(ProxyServer bungee, UserConnection con)
{
this.bungee = bungee;
this.con = con;
BungeeCord.getInstance().addConnection( con );
con.getTabListHandler().onConnect();
con.unsafe().sendPacket( BungeeCord.getInstance().registerChannels() );
}
@Override
public void exception(Throwable t) throws Exception
{
con.disconnect( Util.exception( t ) );
}
@Override
public void disconnected(ChannelWrapper channel) throws Exception
{
// We lost connection to the client
PlayerDisconnectEvent event = new PlayerDisconnectEvent( con );
bungee.getPluginManager().callEvent( event );
con.getTabListHandler().onDisconnect();
BungeeCord.getInstance().removeConnection( con );
if ( con.getServer() != null )
{
// Manually remove from everyone's tab list
// since the packet from the server arrives
// too late
// TODO: This should only done with server_unique
// tab list (which is the only one supported
// currently)
PlayerListItem packet = new PlayerListItem();
packet.setAction( PlayerListItem.Action.REMOVE_PLAYER );
PlayerListItem.Item item = new PlayerListItem.Item();
item.setUuid( con.getUniqueId() );
packet.setItems( new PlayerListItem.Item[]
{
item
} );
for ( ProxiedPlayer player : con.getServer().getInfo().getPlayers() )
{
player.unsafe().sendPacket( packet );
}
con.getServer().disconnect( "Quitting" );
}
}
@Override
public void handle(PacketWrapper packet) throws Exception
{
con.getEntityRewrite().rewriteServerbound( packet.buf, con.getClientEntityId(), con.getServerEntityId() );
if ( con.getServer() != null )
{
con.getServer().getCh().write( packet );
}
}
@Override
public void handle(KeepAlive alive) throws Exception
{
if ( alive.getRandomId() == con.getSentPingId() )
{
int newPing = (int) ( System.currentTimeMillis() - con.getSentPingTime() );
con.getTabListHandler().onPingChange( newPing );
con.setPing( newPing );
}
}
@Override
public void handle(Chat chat) throws Exception
{
Preconditions.checkArgument( chat.getMessage().length() <= 100, "Chat message too long" ); // Mojang limit, check on updates
ServerConnection server = con.getServer();
// if we're still connecting just ignore this packet
if ( server == null )
{
throw CancelSendSignal.INSTANCE;
}
ChatEvent chatEvent = new ChatEvent( con, server, chat.getMessage() );
if ( !bungee.getPluginManager().callEvent( chatEvent ).isCancelled() )
{
chat.setMessage( chatEvent.getMessage() );
if ( !chatEvent.isCommand() || !bungee.getPluginManager().dispatchCommand( con, chat.getMessage().substring( 1 ) ) )
{
server.unsafe().sendPacket( chat );
}
}
throw CancelSendSignal.INSTANCE;
}
@Override
public void handle(TabCompleteRequest tabComplete) throws Exception
{
if ( bungee.getConfig().getTabThrottle() > 0 )
{
long now = System.currentTimeMillis();
if ( lastTabCompletion > 0 && (now - lastTabCompletion) <= bungee.getConfig().getTabThrottle() )
{
throw CancelSendSignal.INSTANCE;
}
lastTabCompletion = now;
}
List<String> suggestions = new ArrayList<>();
if ( tabComplete.getCursor().startsWith( "/" ) )
{
bungee.getPluginManager().dispatchCommand( con, tabComplete.getCursor().substring( 1 ), suggestions );
}
TabCompleteEvent tabCompleteEvent = new TabCompleteEvent( con, con.getServer(), tabComplete.getCursor(), suggestions );
bungee.getPluginManager().callEvent( tabCompleteEvent );
if ( tabCompleteEvent.isCancelled() )
{
throw CancelSendSignal.INSTANCE;
}
List<String> results = tabCompleteEvent.getSuggestions();
if ( !results.isEmpty() )
{
con.unsafe().sendPacket( new TabCompleteResponse( results ) );
throw CancelSendSignal.INSTANCE;
}
}
@Override
public void handle(ClientSettings settings) throws Exception
{
con.setSettings( settings );
}
@Override
public void handle(PluginMessage pluginMessage) throws Exception
{
if ( pluginMessage.getTag().equals( "BungeeCord" ) )
{
throw CancelSendSignal.INSTANCE;
}
// Hack around Forge race conditions
if ( pluginMessage.getTag().equals( "FML" ) && pluginMessage.getStream().readUnsignedByte() == 1 )
{
throw CancelSendSignal.INSTANCE;
}
// We handle forge handshake messages if forge support is enabled.
if ( pluginMessage.getTag().equals( ForgeConstants.FML_HANDSHAKE_TAG ) )
{
// Let our forge client handler deal with this packet.
con.getForgeClientHandler().handle( pluginMessage );
throw CancelSendSignal.INSTANCE;
}
if ( con.getServer() != null && !con.getServer().isForgeServer() && pluginMessage.getData().length > Short.MAX_VALUE )
{
// Drop the packet if the server is not a Forge server and the message was > 32kiB (as suggested by @jk-5)
// Do this AFTER the mod list, so we get that even if the intial server isn't modded.
throw CancelSendSignal.INSTANCE;
}
PluginMessageEvent event = new PluginMessageEvent( con, con.getServer(), pluginMessage.getTag(), pluginMessage.getData().clone() );
if ( bungee.getPluginManager().callEvent( event ).isCancelled() )
{
throw CancelSendSignal.INSTANCE;
}
// TODO: Unregister as well?
if ( pluginMessage.getTag().equals( "REGISTER" ) )
{
con.getPendingConnection().getRegisterMessages().add( pluginMessage );
}
}
@Override
public String toString()
{
return "[" + con.getName() + "] -> UpstreamBridge";
}
}
|
package com.diamondq.common.utils.logback;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.checkerframework.checker.nullness.qual.Nullable;
import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.util.OptionHelper;
public class DQMDC extends ClassicConverter {
protected Map<String, @Nullable String> mKeep;
protected Set<String> mOmit;
@SuppressWarnings("null")
public DQMDC() {
}
@Override
public void start() {
processOptionList(getOptionList());
}
protected void processOptionList(@Nullable List<String> pOptionList) {
Set<String> omits = new HashSet<>();
Map<String, @Nullable String> keeps = new LinkedHashMap<>();
if (pOptionList != null)
for (String option : pOptionList) {
String[] optionInfo = OptionHelper.extractDefaultReplacement(option);
String key = optionInfo[0];
if (key != null) {
if (key.startsWith("!"))
omits.add(key.substring(1));
else
keeps.put(key, optionInfo[1]);
}
}
mKeep = Collections.unmodifiableMap(keeps);
mOmit = Collections.unmodifiableSet(omits);
super.start();
}
/**
* @see ch.qos.logback.core.pattern.Converter#convert(java.lang.Object)
*/
@Override
public String convert(ILoggingEvent pEvent) {
Map<String, @Nullable String> mdcPropertyMap = pEvent.getMDCPropertyMap();
StringBuilder sb = new StringBuilder();
TreeSet<String> keys = new TreeSet<>();
if (mKeep.isEmpty() == true)
keys.addAll(mdcPropertyMap.keySet());
else
keys.addAll(mKeep.keySet());
mOmit.forEach((k) -> keys.remove(k));
boolean onlyOne = mKeep.size() == 1;
boolean first = true;
for (String key : keys) {
if (first)
first = false;
else
sb.append(", ");
// format: key0=value0, key1=value1
String r = mdcPropertyMap.get(key);
if ((r != null) && ("DQIndent".equals(key))) {
String mdcThreadName = mdcPropertyMap.get("DQT");
String threadName = Thread.currentThread().getName();
if (threadName.equals(mdcThreadName) == false)
r = null;
}
if (r == null)
r = mKeep.get(key);
if (r == null)
r = "";
if (onlyOne == false)
sb.append(key).append('=');
sb.append(r);
}
return sb.toString();
}
}
|
package com.tuenti.voice.core.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import com.tuenti.voice.core.VoiceClient;
import com.tuenti.voice.core.manager.BuddyManagerImpl;
import com.tuenti.voice.core.manager.CallManagerImpl;
import com.tuenti.voice.core.manager.ConnectionManagerImpl;
public class VoiceClientService
extends Service
{
private BuddyManagerImpl mBuddyManager;
private CallManagerImpl mCallManager;
private VoiceClient mClient;
private ConnectionManagerImpl mConnectionManager;
@Override
public IBinder onBind( Intent intent )
{
if ( IConnectionService.class.getName().equals( intent.getAction() ) )
{
return mConnectionManager.onBind();
}
if ( IBuddyService.class.getName().equals( intent.getAction() ) )
{
return mBuddyManager.onBind();
}
if ( ICallService.class.getName().equals( intent.getAction() ) )
{
return mCallManager.onBind();
}
return null;
}
@Override
public void onCreate()
{
super.onCreate();
// VoiceClient should only be created here
// probably init here too.
mClient = new VoiceClient();
// init managers
mConnectionManager = new ConnectionManagerImpl( mClient );
mBuddyManager = new BuddyManagerImpl( mClient );
mCallManager = new CallManagerImpl( mClient, getBaseContext() );
mClient.init();
}
@Override
public void onDestroy()
{
super.onDestroy();
// destroy the client
mClient.release();
mClient = null;
}
@Override
public int onStartCommand( Intent intent, int flags, int startId )
{
return START_STICKY;
}
}
|
package at.ac.tuwien.kr.alpha.solver;
import at.ac.tuwien.kr.alpha.common.AnswerSet;
import at.ac.tuwien.kr.alpha.common.NoGood;
import at.ac.tuwien.kr.alpha.grounder.BooleanAssignmentReader;
import at.ac.tuwien.kr.alpha.grounder.Grounder;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.function.Consumer;
import static at.ac.tuwien.kr.alpha.common.Literals.atomOf;
import static at.ac.tuwien.kr.alpha.common.Literals.isNegated;
import static at.ac.tuwien.kr.alpha.common.Literals.isPositive;
import static at.ac.tuwien.kr.alpha.solver.ThriceTruth.FALSE;
import static at.ac.tuwien.kr.alpha.solver.ThriceTruth.TRUE;
import static java.lang.Math.abs;
public class NaiveSolver extends AbstractSolver {
private static final Logger LOGGER = LoggerFactory.getLogger(NaiveSolver.class);
private final ChoiceStack choiceStack;
private HashMap<Integer, Boolean> truthAssignments = new HashMap<>();
private ArrayList<Integer> newTruthAssignments = new ArrayList<>();
private ArrayList<ArrayList<Integer>> decisionLevels = new ArrayList<>();
private HashMap<Integer, NoGood> knownNoGoods = new HashMap<>();
private boolean doInit = true;
private boolean didChange;
private int decisionLevel;
private Map<Integer, Integer> choiceOn = new HashMap<>();
private Map<Integer, Integer> choiceOff = new HashMap<>();
private Integer nextChoice;
private HashSet<Integer> mbtAssigned = new HashSet<>();
private ArrayList<ArrayList<Integer>> mbtAssignedFromUnassigned = new ArrayList<>();
private ArrayList<ArrayList<Integer>> trueAssignedFromMbt = new ArrayList<>();
private List<Integer> unassignedAtoms;
NaiveSolver(Grounder grounder) {
super(grounder);
this.choiceStack = new ChoiceStack(grounder, false);
decisionLevels.add(0, new ArrayList<>());
mbtAssignedFromUnassigned.add(0, new ArrayList<>());
trueAssignedFromMbt.add(0, new ArrayList<>());
}
@Override
protected boolean tryAdvance(Consumer<? super AnswerSet> action) {
// Get basic rules and facts from grounder
if (doInit) {
obtainNoGoodsFromGrounder();
doInit = false;
} else {
// We already found one Answer-Set and are requested to find another one
doBacktrack();
if (isSearchSpaceExhausted()) {
return false;
}
}
// Try all assignments until grounder reports no more NoGoods and all of them are satisfied
while (true) {
if (!propagationFixpointReached()) {
LOGGER.trace("Propagating.");
updateGrounderAssignments(); // After a choice, it would be more efficient to propagate first and only then ask the grounder.
obtainNoGoodsFromGrounder();
doUnitPropagation();
doMBTPropagation();
LOGGER.trace("Assignment after propagation is: {}", truthAssignments);
} else if (assignmentViolatesNoGoods()) {
LOGGER.trace("Backtracking from wrong choices:");
LOGGER.trace("Choice stack: {}", choiceStack);
doBacktrack();
if (isSearchSpaceExhausted()) {
return false;
}
} else if (choicesLeft()) {
doChoice();
} else if (!allAtomsAssigned()) {
LOGGER.trace("Closing unassigned known atoms (assigning FALSE).");
assignUnassignedToFalse();
didChange = true;
} else if (noMBTValuesReamining()) {
AnswerSet as = getAnswerSetFromAssignment();
LOGGER.debug("Answer-Set found: {}", as);
LOGGER.trace("Choice stack: {}", choiceStack);
action.accept(as);
return true;
} else {
LOGGER.debug("Backtracking from wrong choices (MBT remaining):");
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Currently MBT:");
for (Integer integer : mbtAssigned) {
LOGGER.trace(grounder.atomToString(integer));
}
LOGGER.trace("Choice stack: {}", choiceStack);
}
doBacktrack();
if (isSearchSpaceExhausted()) {
return false;
}
}
}
}
private void assignUnassignedToFalse() {
for (Integer atom : unassignedAtoms) {
truthAssignments.put(atom, false);
newTruthAssignments.add(atom);
decisionLevels.get(decisionLevel).add(atom);
}
}
private boolean allAtomsAssigned() {
unassignedAtoms = new ArrayList<>();
HashSet<Integer> knownAtoms = new HashSet<>();
for (Map.Entry<Integer, NoGood> entry : knownNoGoods.entrySet()) {
for (Integer integer : entry.getValue()) {
knownAtoms.add(abs(integer));
}
}
for (Integer atom : knownAtoms) {
if (!truthAssignments.containsKey(atom)) {
unassignedAtoms.add(atom);
}
}
return unassignedAtoms.isEmpty();
}
private boolean noMBTValuesReamining() {
return mbtAssigned.size() == 0;
}
private void doMBTPropagation() {
boolean didPropagate = true;
while (didPropagate) {
didPropagate = false;
for (Map.Entry<Integer, NoGood> noGoodEntry : knownNoGoods.entrySet()) {
if (propagateMBT(noGoodEntry.getValue())) {
didPropagate = true;
didChange = true;
}
}
}
}
private String reportTruthAssignments() {
String report = "Current Truth assignments: ";
for (Integer atomId : truthAssignments.keySet()) {
report += (truthAssignments.get(atomId) ? "+" : "-") + atomId + " ";
}
return report;
}
private boolean propagationFixpointReached() {
// Check if anything changed.
// didChange is updated in places of change.
boolean changeCopy = didChange;
didChange = false;
return !changeCopy;
}
private AnswerSet getAnswerSetFromAssignment() {
ArrayList<Integer> trueAtoms = new ArrayList<>();
for (Map.Entry<Integer, Boolean> atomAssignment : truthAssignments.entrySet()) {
if (atomAssignment.getValue()) {
trueAtoms.add(atomAssignment.getKey());
}
}
return translate(trueAtoms);
}
private void doChoice() {
decisionLevel++;
ArrayList<Integer> list = new ArrayList<>();
list.add(nextChoice);
decisionLevels.add(decisionLevel, list);
trueAssignedFromMbt.add(decisionLevel, new ArrayList<>());
mbtAssignedFromUnassigned.add(decisionLevel, new ArrayList<>());
// We guess true for any unassigned choice atom (backtrack tries false)
truthAssignments.put(nextChoice, true);
newTruthAssignments.add(nextChoice);
choiceStack.push(nextChoice, true);
// Record change to compute propagation fixpoint again.
didChange = true;
}
private boolean choicesLeft() {
// Check if there is an enabled choice that is not also disabled
for (Map.Entry<Integer, Integer> e : choiceOn.entrySet()) {
final int atom = e.getKey();
// Only consider unassigned choices that are enabled.
if (truthAssignments.containsKey(atom) || !truthAssignments.getOrDefault(e.getValue(), false)) {
continue;
}
// Check that candidate is not disabled already
if (!truthAssignments.getOrDefault(choiceOff.getOrDefault(atom, 0), false)) {
nextChoice = atom;
return true;
}
}
return false;
}
private void doBacktrack() {
if (decisionLevel <= 0) {
return;
}
int lastGuessedAtom = choiceStack.peekAtom();
boolean lastGuessedTruthValue = choiceStack.peekValue();
choiceStack.remove();
// Remove truth assignments of current decision level
for (Integer atomId : decisionLevels.get(decisionLevel)) {
truthAssignments.remove(atomId);
}
// Handle MBT assigned values:
// First, restore mbt when it got assigned true in this decision level
for (Integer atomId : trueAssignedFromMbt.get(decisionLevel)) {
mbtAssigned.add(atomId);
}
// Second, remove mbt indicator for values that were unassigned
for (Integer atomId : mbtAssignedFromUnassigned.get(decisionLevel)) {
mbtAssigned.remove(atomId);
}
// Clear atomIds in current decision level
decisionLevels.set(decisionLevel, new ArrayList<>());
mbtAssignedFromUnassigned.set(decisionLevel, new ArrayList<>());
trueAssignedFromMbt.set(decisionLevel, new ArrayList<>());
if (lastGuessedTruthValue) {
// Guess false now
truthAssignments.put(lastGuessedAtom, false);
choiceStack.pushBacktrack(lastGuessedAtom, false);
newTruthAssignments.add(lastGuessedAtom);
decisionLevels.get(decisionLevel).add(lastGuessedAtom);
didChange = true;
} else {
decisionLevel
doBacktrack();
}
}
private void updateGrounderAssignments() {
grounder.updateAssignment(newTruthAssignments.stream().map(atom -> {
return (Assignment.Entry)new Entry(atom, truthAssignments.get(atom) ? TRUE : FALSE);
}).iterator());
newTruthAssignments.clear();
}
private static final class Entry implements Assignment.Entry {
private final ThriceTruth value;
private final int atom;
Entry(int atom, ThriceTruth value) {
this.value = value;
this.atom = atom;
}
@Override
public ThriceTruth getTruth() {
return value;
}
@Override
public int getDecisionLevel() {
throw new UnsupportedOperationException();
}
@Override
public NoGood getImpliedBy() {
throw new UnsupportedOperationException();
}
@Override
public Entry getPrevious() {
throw new UnsupportedOperationException();
}
@Override
public int getAtom() {
return atom;
}
@Override
public int getPropagationLevel() {
throw new UnsupportedOperationException();
}
@Override
public boolean isReassignAtLowerDecisionLevel() {
throw new UnsupportedOperationException();
}
@Override
public void setReassignFalse() {
throw new UnsupportedOperationException();
}
@Override
public String toString() {
throw new UnsupportedOperationException();
}
}
private class NaiveBooleanAssignmentReader extends BooleanAssignmentReader {
public NaiveBooleanAssignmentReader() {
super(null);
}
@Override
public boolean isTrue(int atomId) {
Boolean assigned = truthAssignments.get(atomId);
return assigned != null && assigned;
}
}
private void obtainNoGoodsFromGrounder() {
final int oldSize = knownNoGoods.size();
knownNoGoods.putAll(grounder.getNoGoods(new NaiveBooleanAssignmentReader()));
if (oldSize != knownNoGoods.size()) {
// Record to detect propagation fixpoint, checking if new NoGoods were reported would be better here.
didChange = true;
}
// Record choice atoms
final Pair<Map<Integer, Integer>, Map<Integer, Integer>> choiceAtoms = grounder.getChoiceAtoms();
choiceOn.putAll(choiceAtoms.getKey());
choiceOff.putAll(choiceAtoms.getValue());
}
private boolean isSearchSpaceExhausted() {
return decisionLevel == 0;
}
private void doUnitPropagation() {
// Check each NoGood if it is unit (naive algorithm)
for (NoGood noGood : knownNoGoods.values()) {
int implied = unitPropagate(noGood);
if (implied == -1) { // NoGood is not unit, skip.
continue;
}
int impliedLiteral = noGood.getLiteral(implied);
int impliedAtomId = atomOf(impliedLiteral);
boolean impliedTruthValue = isNegated(impliedLiteral);
if (truthAssignments.get(impliedAtomId) != null) { // Skip if value already was assigned.
continue;
}
truthAssignments.put(impliedAtomId, impliedTruthValue);
newTruthAssignments.add(impliedAtomId);
didChange = true; // Record to detect propagation fixpoint
decisionLevels.get(decisionLevel).add(impliedAtomId);
if (impliedTruthValue) { // Record MBT value in case true is assigned
mbtAssigned.add(impliedAtomId);
mbtAssignedFromUnassigned.get(decisionLevel).add(impliedAtomId);
}
}
}
private boolean isLiteralAssigned(int literal) {
return truthAssignments.get(atomOf(literal)) != null;
}
private boolean isLiteralViolated(int literal) {
final int atom = atomOf(literal);
final Boolean assignment = truthAssignments.get(atom);
// For unassigned atoms, any literal is not violated.
return assignment != null && isNegated(literal) != assignment;
}
/**
* Returns position of implied literal if input NoGood is unit.
* @param noGood
* @return -1 if NoGood is not unit.
*/
private int unitPropagate(NoGood noGood) {
int lastUnassignedPosition = -1;
for (int i = 0; i < noGood.size(); i++) {
int literal = noGood.getLiteral(i);
if (isLiteralAssigned(literal)) {
if (!isLiteralViolated(literal)) {
// The NoGood is satisfied, hence it cannot be unit.
return -1;
}
} else if (lastUnassignedPosition != -1) {
// NoGood is not unit, if there is not exactly one unassigned literal
return -1;
} else {
lastUnassignedPosition = i;
}
}
return lastUnassignedPosition;
}
private boolean propagateMBT(NoGood noGood) {
// The MBT propagation checks whether the head-indicated literal is MBT
// and the remaining literals are violated
// and none of them are MBT,
// then the head literal is set from MBT to true.
if (!noGood.hasHead()) {
return false;
}
int headAtom = noGood.getAtom(noGood.getHead());
// Check whether head is assigned MBT.
if (!mbtAssigned.contains(headAtom)) {
return false;
}
// Check that NoGood is violated except for the head (i.e., without the head set it would be unit)
// and that none of the true values is MBT.
for (int i = 0; i < noGood.size(); i++) {
if (noGood.getHead() == i) {
continue;
}
int literal = noGood.getLiteral(i);
if (!(isLiteralAssigned(literal) && isLiteralViolated(literal))) {
return false;
}
// Skip if positive literal is assigned MBT.
if (isPositive(literal) && mbtAssigned.contains(atomOf(literal))) {
return false;
}
}
// Set truth value from MBT to true.
mbtAssigned.remove(headAtom);
trueAssignedFromMbt.get(decisionLevel).add(headAtom);
return true;
}
private boolean assignmentViolatesNoGoods() {
// Check each NoGood, if it is violated
for (NoGood noGood : knownNoGoods.values()) {
boolean isSatisfied = false;
for (Integer noGoodLiteral : noGood) {
if (!isLiteralAssigned(noGoodLiteral) || !isLiteralViolated(noGoodLiteral)) {
isSatisfied = true;
break;
}
}
if (!isSatisfied) {
LOGGER.trace("Violated NoGood: {}", noGood);
return true;
}
}
return false;
}
}
|
package bm.game.tile.service;
import java.util.Collection;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import bm.game.tile.DAO.GamePlayDataDAO;
import bm.game.tile.DAO.IGameplayDataDAO;
import bm.game.tile.model.GameplayData;
/**
* Class for essential business logic of achievements and other statistics.
*
* @author collion
*
*/
public class GameplayDataService {
/**
* Logger.
*/
private static Logger logger = LoggerFactory.getLogger("GameplayDataService.class");
/**
* Data access object for the class.
*/
private IGameplayDataDAO gameplayDataDAO = new GamePlayDataDAO();
/**
*
* @param gameplayDataDAO
* - data access object of gameplay data
*/
public void setGameplayDataDAO(IGameplayDataDAO gameplayDataDAO) {
this.gameplayDataDAO = gameplayDataDAO;
}
/**
* Gets all the previously stored gameplay data of a certain player.
*
* @param playerNameToGet
* - the name of player
* @return - the list of the player's previous gameplay data
*/
public Collection<GameplayData> getGamePlayDataForPlayer(String playerNameToGet) {
logger.info("Player data loaded.");
return gameplayDataDAO.getAllGamePlayData().stream()
.filter(gameplayDataObject -> gameplayDataObject.getPlayerName().equals(playerNameToGet))
.collect(Collectors.toList());
}
/**
* Gets the highest scoring game's gameplay data.
*
* @param listOfGames
* - list of a player's game
* @return - gameplay data of highest score's game
*/
public GameplayData highestScoringGame(Collection<GameplayData> listOfGames) {
logger.info("Highest scoring game of player is loaded.");
GameplayData gameplayData = new GameplayData();
gameplayData.setFinalScore(0);
return listOfGames.stream().max((gameData1, gameData2) -> gameData1.getFinalScore() - gameData2.getFinalScore())
.orElse(gameplayData);
}
/**
* Decides whether the player deserves the 'Unlucky' achievement.
*
* @param listOfGames
* - collection of gameplay datas
* @return - whether the given list of gameplay data is eligible for
* unlocking the 'Unlucky' achievement
*/
public boolean isUnlucky(Collection<GameplayData> listOfGames) {
logger.info("Achievement Unlucky is checked.");
return listOfGames.stream().mapToInt(GameplayData::getFinalScore).min().orElse(5) <= 1;
}
/**
* Decides whether the player deserves the 'Hundred Percent' achievement.
*
* @param listOfGames
* - collection of gameplay datas
* @return - whether the given list of gameplay data is eligible for
* unlocking the 'Hundred Percent' achievement
*/
public boolean isOneHundredApproved(Collection<GameplayData> listOfGames) {
logger.info("Achievement One Hundred is checked.");
return listOfGames.stream().mapToInt(GameplayData::getFinalScore).max().orElse(5) >= 100;
}
/**
* Decides whether the player deserves the 'Are you iNsANe ?' achievement.
*
* @param listOfGames
* - collection of gameplay datas
* @return - whether the given list of gameplay data is eligible for
* unlocking the 'Are you iNsANe ?' achievement
*/
public boolean isInsane(Collection<GameplayData> listOfGames) {
logger.info("Achievement Are You Insane is checked.");
return listOfGames.stream().filter(gameplayData -> gameplayData.getDifficulty().equals("insane"))
.anyMatch(gameplayData -> gameplayData.getFinalScore() >= 10);
}
/**
* Decides whether the player deserves the 'Fast Fingers' achievement.
*
* @param listOfGames
* - collection of gameplay datas
* @return - whether the given list of gameplay data is eligible for
* unlocking the 'Fast Fingers' achievement
*/
public boolean hasFastFingers(Collection<GameplayData> listOfGames) {
logger.info("Achievement Fast Fingers is checked.");
return listOfGames.stream().filter(gameplayData -> gameplayData.getFinalScore() >= 10)
.mapToDouble(GameplayData::getAverageOfClickSpeed).min().orElse(1.0) <= 0.3;
}
/**
* Decides whether the player deserves the 'Rock Solid' achievement.
*
* @param listOfGames
* - collection of gameplay datas
* @return - whether the given list of gameplay data is eligible for
* unlocking the 'Rock Solid' achievement
*/
public boolean isRockSolid(Collection<GameplayData> listOfGames) {
logger.info("Achievement Rock Solid is checked.");
return listOfGames.stream()
.filter(gameplayData -> gameplayData.getDifficulty().equals("hard")
|| gameplayData.getDifficulty().equals("insane"))
.anyMatch(gameplayData -> gameplayData.getFinalScore() >= 100);
}
/**
* Decides whether the player deserves the 'Loyal Gamer' achievement.
*
* @param listOfGames
* - collection of gameplay datas
* @return - whether the given list of gameplay data is eligible for
* unlocking the 'Loyal Gamer' achievement
*/
public boolean isLoyal(Collection<GameplayData> listOfGames) {
logger.info("Achievement Loyal Gamer is checked.");
return listOfGames.stream().mapToInt(GameplayData::getFinalScore).max().orElse(5) >= 1000;
}
}
|
package arduinoMeasurement.model;
import arduinoMeasurement.mockup.SettingsMockup;
import arduinoMeasurement.transmission.BaudRate;
import arduinoMeasurement.transmission.DataBits;
import arduinoMeasurement.transmission.StopBits;
public class ConnectionSettings
{
private boolean wireless;
private BaudRate baudRate;
private DataBits dataBits;
private StopBits stopBits;
private boolean parity;
public ConnectionSettings()
{
wireless = false;
baudRate = BaudRate.b9600;
dataBits = DataBits.b8;
stopBits = StopBits.s0;
parity = false;
}
void setWireless(final boolean wireless)
{
this.wireless = wireless;
}
void setBaudRate(final BaudRate baudRate)
{
this.baudRate = baudRate;
}
void setDataBits(final DataBits dataBits)
{
this.dataBits = dataBits;
}
void setStopBits(final StopBits stopBits)
{
this.stopBits = stopBits;
}
void setParity(final boolean parity)
{
this.parity = parity;
}
public BaudRate getBaudRate()
{
return baudRate;
}
public DataBits getDataBits()
{
return dataBits;
}
public StopBits getStopBits()
{
return stopBits;
}
public boolean isWireless()
{
return wireless;
}
public boolean isParity()
{
return parity;
}
public SettingsMockup buildMockup()
{
return new SettingsMockup(wireless, baudRate, dataBits, stopBits, parity);
}
public void setSettings(final SettingsMockup settingsMockup)
{
wireless = settingsMockup.isWireless();
baudRate = settingsMockup.getBaudRate();
dataBits = settingsMockup.getDataBits();
stopBits = settingsMockup.getStopBits();
parity = settingsMockup.isParity();
}
}
|
package org.openlca.app.tools.mapping.model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.HashMap;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.openlca.app.db.Database;
import org.openlca.app.tools.mapping.model.FlowMapEntry.SyncState;
import org.openlca.core.database.FlowDao;
import org.openlca.core.database.IDatabase;
import org.openlca.core.matrix.cache.ConversionTable;
import org.openlca.core.model.Flow;
import org.openlca.core.model.FlowProperty;
import org.openlca.core.model.FlowPropertyFactor;
import org.openlca.core.model.Uncertainty;
import org.openlca.core.model.UncertaintyType;
import org.openlca.core.model.Unit;
import org.openlca.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Replacer implements Runnable {
private final ReplacerConfig conf;
private final IDatabase db;
private final Logger log = LoggerFactory.getLogger(getClass());
// the valid entries that could be applied: source flow ID -> mapping.
private final HashMap<Long, FlowMapEntry> entries = new HashMap<>();
// the source and target flows in the database: flow ID -> flow.
private final HashMap<Long, Flow> flows = new HashMap<>();
private ConversionTable conversions;
public Replacer(ReplacerConfig conf) {
this.conf = conf;
this.db = Database.get();
}
@Override
public void run() {
if (conf == null || (!conf.processes && !conf.methods)) {
log.info("no configuration; nothing to replace");
return;
}
buildIndices();
if (entries.isEmpty()) {
log.info("found no flows that can be mapped");
return;
}
log.info("found {} flows that can be mapped", entries.size());
try {
log.info("start updatable cursors");
Cursor exchangeCursor = null;
Cursor impactCursor = null;
ExecutorService pool = Executors.newFixedThreadPool(4);
if (conf.processes) {
exchangeCursor = new Cursor(Cursor.EXCHANGES);
pool.execute(exchangeCursor);
}
if (conf.methods) {
impactCursor = new Cursor(Cursor.IMPACTS);
pool.execute(impactCursor);
}
pool.shutdown();
int i = 0;
while (!pool.awaitTermination(10, TimeUnit.SECONDS)) {
i++;
log.info("waiting for cursors to finish; {} seconds", i * 10);
}
log.info("cursors finished");
// TODO: replace possible
if (conf.processes && conf.methods && conf.deleteMapped) {
// TODO: delete the flows with no failures
}
// TODO: log the mapping statistics
} catch (Exception e) {
log.error("Flow replacement failed", e);
}
}
private void buildIndices() {
FlowDao dao = new FlowDao(db);
for (FlowMapEntry entry : conf.mapping.entries) {
// only do the replacement for matched mapping entries
if (entry.syncState != SyncState.MATCHED)
continue;
// sync the source flow
Flow source = dao.getForRefId(entry.sourceFlow.flow.refId);
if (source == null) {
entry.syncState = SyncState.UNFOUND_SOURCE;
continue;
}
if (!entry.sourceFlow.syncWith(source)) {
entry.syncState = SyncState.INVALID_SOURCE;
continue;
}
// sync the target flow
Optional<Flow> tOpt = conf.provider.persist(entry.targetFlow, db);
if (!tOpt.isPresent()) {
entry.syncState = SyncState.UNFOUND_TARGET;
continue;
}
Flow target = tOpt.get();
if (!entry.targetFlow.syncWith(target)) {
entry.syncState = SyncState.INVALID_TARGET;
continue;
}
entries.put(source.id, entry);
flows.put(source.id, source);
flows.put(target.id, target);
}
conversions = ConversionTable.create(db);
}
class Stats {
private static final byte REPLACEMENT = 0;
private static final byte FAILURE = 1;
int failures;
int replacements;
final HashMap<Long, Integer> flowFailures = new HashMap<>();
final HashMap<Long, Integer> flowReplacements = new HashMap<>();
private void inc(long flowID, byte type) {
HashMap<Long, Integer> flowStats;
if (type == REPLACEMENT) {
replacements++;
flowStats = flowReplacements;
} else {
failures++;
flowStats = flowFailures;
}
Integer count = flowStats.get(flowID);
if (count == null) {
flowStats.put(flowID, 1);
} else {
flowStats.put(flowID, count + 1);
}
}
}
private class Cursor implements Runnable {
static final byte EXCHANGES = 0;
static final byte IMPACTS = 1;
final byte type;
final Stats stats = new Stats();
Cursor(byte type) {
this.type = type;
}
public void run() {
try {
Connection con = db.createConnection();
con.setAutoCommit(false);
Statement query = con.createStatement();
query.setCursorName(cursorName());
ResultSet cursor = query.executeQuery(querySQL());
PreparedStatement update = con.prepareStatement(updateSQL());
int total = 0;
int changed = 0;
while (cursor.next()) {
total++;
long flowID = cursor.getLong(1);
FlowMapEntry entry = entries.get(flowID);
if (entry == null)
continue;
Flow source = flows.get(entry.sourceFlow.flow.id);
Flow target = flows.get(entry.targetFlow.flow.id);
if (source == null || target == null)
continue;
// check flow property and unit of the source flow
FlowPropertyFactor propFactor = propFactor(
source, cursor.getLong("f_flow_property_factor"));
if (propFactor == null) {
stats.inc(source.id, Stats.FAILURE);
continue;
}
Unit unit = unit(propFactor.flowProperty, cursor.getLong("f_unit"));
if (unit == null) {
stats.inc(source.id, Stats.FAILURE);
continue;
}
// calculate the conversion factor; not that the factor
// has the inverse meaning for exchanges than for LCIA factors
double factor = type == EXCHANGES
? entry.factor
: 1 / entry.factor;
if (propFactor.flowProperty.id != entry.sourceFlow.flowProperty.id
|| unit.id != entry.sourceFlow.unit.id) {
double pi = conversions.getPropertyFactor(propFactor.id);
double ui = conversions.getUnitFactor(unit.id);
double ps = conversions.getPropertyFactor(
propFactor(source, entry.sourceFlow).id);
double us = conversions.getUnitFactor(entry.sourceFlow.unit.id);
double y = (ui * ps) / (pi * us);
factor *= type == EXCHANGES ? y : 1 / y;
}
// check the target flow property
FlowPropertyFactor targetPropertyFactor = propFactor(
target, entry.targetFlow);
if (targetPropertyFactor == null) {
stats.inc(source.id, Stats.FAILURE);
continue;
}
// amount and formula have type specific names
double amount = cursor.getDouble(4);
String formula = cursor.getString(5);
Uncertainty uncertainty = readUncertainty(cursor);
update.setLong(1, target.id); // f_flow
update.setLong(2, entry.targetFlow.unit.id); // f_unit
update.setLong(3, targetPropertyFactor.id); // f_flow_property_factor
update.setDouble(4, factor * amount); // resulting_amount_value
// resulting_amount_formula
if (Strings.nullOrEmpty(formula)) {
update.setString(5, null);
} else {
update.setString(5,
Double.toString(factor) + "* (" + formula + ")");
}
// uncertainty
updateUncertainty(update, factor, uncertainty);
update.executeUpdate();
changed++;
stats.inc(source.id, Stats.REPLACEMENT);
}
cursor.close();
query.close();
update.close();
con.commit();
con.close();
log.info("{} replaced flows in {} of {} rows",
cursorName(), changed, total);
} catch (Exception e) {
log.error("Flow replacement in " + cursorName() + " failed", e);
}
}
private String cursorName() {
return type == EXCHANGES
? "EXCHANGE_CURSOR"
: "IMPACT_CURSOR";
}
private String querySQL() {
String table;
String value;
String formula;
if (type == EXCHANGES) {
table = "tbl_exchanges";
value = "resulting_amount_value";
formula = "resulting_amount_formula";
} else {
table = "tbl_impact_factors";
value = "value";
formula = "formula";
}
return "SELECT "
+ "f_flow, "
+ "f_unit, "
+ "f_flow_property_factor, "
+ value + " , "
+ formula + ", "
+ "distribution_type, "
+ "parameter1_value, "
+ "parameter2_value, "
+ "parameter3_value "
+ "FROM " + table + " "
+ "FOR UPDATE OF "
+ "f_flow, "
+ "f_unit, "
+ "f_flow_property_factor, "
+ "resulting_amount_value, "
+ "resulting_amount_formula, "
+ "distribution_type, "
+ "parameter1_value, "
+ "parameter2_value, "
+ "parameter3_value";
}
private String updateSQL() {
String table;
String value;
String formula;
if (type == EXCHANGES) {
table = "tbl_exchanges";
value = "resulting_amount_value";
formula = "resulting_amount_formula";
} else {
table = "tbl_impact_factors";
value = "value";
formula = "formula";
}
return "UPDATE " + table + " "
+ "SET f_flow = ? , "
+ "f_unit = ? , "
+ "f_flow_property_factor = ? , "
+ value + " = ? , "
+ formula + " = ? , "
+ "distribution_type = ? , "
+ "parameter1_value = ? , "
+ "parameter2_value = ? , "
+ "parameter3_value = ? "
+ "WHERE CURRENT OF " + cursorName();
}
private Uncertainty readUncertainty(ResultSet cursor) throws Exception {
int idx = cursor.getInt("distribution_type");
if (cursor.wasNull())
return null;
switch (UncertaintyType.values()[idx]) {
case LOG_NORMAL:
return Uncertainty.logNormal(
cursor.getDouble("parameter1_value"),
cursor.getDouble("parameter2_value"));
case NORMAL:
return Uncertainty.normal(
cursor.getDouble("parameter1_value"),
cursor.getDouble("parameter2_value"));
case TRIANGLE:
return Uncertainty.triangle(
cursor.getDouble("parameter1_value"),
cursor.getDouble("parameter2_value"),
cursor.getDouble("parameter3_value"));
case UNIFORM:
return Uncertainty.uniform(
cursor.getDouble("parameter1_value"),
cursor.getDouble("parameter2_value"));
default:
return null;
}
}
private void updateUncertainty(PreparedStatement update,
double factor, Uncertainty uncertainty) throws SQLException {
if (uncertainty == null) {
update.setNull(6, Types.INTEGER);
update.setNull(7, Types.DOUBLE);
update.setNull(8, Types.DOUBLE);
update.setNull(9, Types.DOUBLE);
} else {
uncertainty.scale(factor);
update.setInt(6, uncertainty.distributionType.ordinal());
update.setDouble(7, uncertainty.parameter1);
update.setDouble(8, uncertainty.parameter2);
if (uncertainty.parameter3 != null) {
update.setDouble(9, uncertainty.parameter3);
}
}
}
private FlowPropertyFactor propFactor(Flow flow, long factorID) {
if (flow == null)
return null;
for (FlowPropertyFactor f : flow.flowPropertyFactors) {
if (f.id == factorID)
return f;
}
return null;
}
private FlowPropertyFactor propFactor(Flow flow, FlowRef ref) {
if (flow == null)
return null;
for (FlowPropertyFactor f : flow.flowPropertyFactors) {
if (f.flowProperty == null)
continue;
if (f.flowProperty.id == ref.flowProperty.id)
return f;
}
return null;
}
private Unit unit(FlowProperty property, long unitID) {
if (property == null || property.unitGroup == null)
return null;
for (Unit u : property.unitGroup.units) {
if (u.id == unitID)
return u;
}
return null;
}
}
}
|
package ch.deletescape.jterm.commandcontexts;
import java.io.IOException;
import ch.deletescape.jterm.CommandUtils;
import ch.deletescape.jterm.JTerm;
import ch.deletescape.jterm.Util;
import ch.deletescape.jterm.config.Resources;
import ch.deletescape.jterm.config.UserProperties;
import ch.deletescape.jterm.io.Printer;
public class Env extends CommandContext {
@Override
public void init() {
CommandUtils.addListener("getEnv", this::getEnv);
CommandUtils.addListener("exec", this::exec);
CommandUtils.addListener("exit", o -> exit());
CommandUtils.addListener("bye", o -> exit());
CommandUtils.addListener("os", this::os);
CommandUtils.addListener("alias", this::alias);
CommandUtils.addListener("mute", o -> mute());
CommandUtils.addListener("setProp", this::setProp);
CommandUtils.addListener("getProp", this::getProp);
}
private String getEnv(String cmd) {
String command = CommandUtils.parseInlineCommands(cmd);
StringBuilder output = new StringBuilder();
if (!command.isEmpty()) {
output.append(System.getenv(command) + "\n");
} else {
System.getenv().forEach((s1, s2) -> output.append(s1 + "=" + s2 + "\n"));
}
return Printer.out.println(output);
}
private String exec(String cmd) throws IOException {
String command = CommandUtils.parseInlineCommands(cmd);
Process proc = Runtime.getRuntime().exec(command);
return Util.copyStream(proc.getInputStream(), Printer.out.getPrintStream());
}
private Object exit() {
JTerm.exit();
return null;
}
private String os(String arg) {
String argument = CommandUtils.parseInlineCommands(arg);
String name = System.getProperty("os.name");
String arch = System.getProperty("os.arch");
String version = System.getProperty("os.version");
StringBuilder sb = new StringBuilder();
switch (argument) {
case "":
sb.append(String.format(Resources.getString("Env.DefaultFormat"), name, arch, version));
break;
case "-n":
case "--name":
sb.append(name);
break;
case "-v":
case "--version":
sb.append(version);
break;
case "-a":
case "--arch":
sb.append(arch);
break;
default:
Printer.err.println(Resources.getString("Env.UnknownOption"), argument);
case "-h":
case "--help":
sb.append(Resources.getString("Env.UsageInfo"));
break;
}
return Printer.out.println(sb);
}
String alias(String cmd) {
String command = CommandUtils.parseInlineCommands(cmd);
String alias = command.split("=")[0].trim().replaceAll(" ", "_");
String original = command.split("=")[1].trim();
if (CommandUtils.COMMAND_LISTENERS.containsKey(alias)) {
return Printer.err.println(Resources.getString("Env.CantSetAlias"), alias);
}
CommandUtils.addListener(alias, o -> CommandUtils.evaluateCommand((original + " " + o).trim()));
return Printer.out.println(Resources.getString("Env.SettingAlias"), alias, original);
}
private String setProp(String cmd) {
String command = CommandUtils.parseInlineCommands(cmd);
String key = command.split("=")[0].trim();
String value = command.split("=")[1].trim();
UserProperties.setProperty(key, value);
return Printer.out.println(Resources.getString("Env.SettingProp"), key, value);
}
private String getProp(String cmd) {
String key = CommandUtils.parseInlineCommands(cmd);
return Printer.out.println(UserProperties.getProperty(key));
}
private boolean mute() {
return Printer.out.toggleMute();
}
}
|
package cx2x.translator.transformer;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import cx2x.translator.common.GroupConfiguration;
import cx2x.translator.transformation.openacc.OpenAccContinuation;
import cx2x.xcodeml.transformation.*;
import cx2x.xcodeml.xnode.Xnode;
import org.w3c.dom.Element;
/**
* ClawTransformer stores all transformation groups applied during the
* translation.
*
* @author clementval
*/
public class ClawTransformer implements Transformer {
private int _transformationCounter = 0;
// Hold all transformation groups
private final Map<Class, TransformationGroup> _tGroups;
// Hold cross-transformation elements
private final Map<Element, Object> _crossTransformationTable;
// Hold the module file cache
private final ModuleCache _modCache;
private int _maxColumns;
/**
* ClawTransformer ctor. Creates the transformation groups needed for the CLAW
* transformation and order the accordingly to their interpretation order.
*
* @param groups List of transformation groups that define the transformation
* order.
* @param max Maximum number of columns.
*/
public ClawTransformer(List<GroupConfiguration> groups, int max) {
/*
* Use LinkedHashMap to be able to iterate through the map
* entries with the insertion order.
*/
_tGroups = new LinkedHashMap<>();
for(GroupConfiguration g : groups) {
switch(g.getType()) {
case DEPENDENT:
_tGroups.put(g.getTransformationClass(),
new DependentTransformationGroup(g.getName()));
break;
case INDEPENDENT:
_tGroups.put(g.getTransformationClass(),
new IndependentTransformationGroup(g.getName()));
break;
}
}
// Internal transformations not specified by default configuration or user
_tGroups.put(OpenAccContinuation.class,
new IndependentTransformationGroup("internal-open-acc-continuation"));
_crossTransformationTable = new HashMap<>();
_modCache = new ModuleCache();
_maxColumns = max;
}
/**
* @see Transformer#addTransformation(Transformation)
*/
public void addTransformation(Transformation t) {
if(_tGroups.containsKey(t.getClass())) {
_tGroups.get(t.getClass()).add(t);
}
}
/**
* @see Transformer#getGroups()
*/
public Map<Class, TransformationGroup> getGroups() {
return _tGroups;
}
/**
* Get the next extraction counter value.
*
* @return Transformation counter value.
*/
public int getNextTransformationCounter() {
return _transformationCounter++;
}
/**
* @see Transformer#getModCache()
*/
@Override
public ModuleCache getModCache() {
return _modCache;
}
/**
* @see Transformer#getMaxColumns()
*/
@Override
public int getMaxColumns() {
return _maxColumns;
}
/**
* @param max Max number of columns.
* @see Transformer#setMaxColumns(int)
*/
@Override
public void setMaxColumns(int max) {
_maxColumns = max;
}
/**
* Get a stored element from a previous transformation.
*
* @param key Key to use to retrieve the element.
* @return The stored element if present. Null otherwise.
*/
public Object hasElement(Xnode key) {
if(_crossTransformationTable.containsKey(key.getElement())) {
return _crossTransformationTable.get(key.getElement());
}
return null;
}
/**
* Store a Xnode from a transformation for a possible usage in another
* transformation. If a key is already present, the element is overwritten.
*
* @param key The element acting as a key.
* @param value The element to be stored.
*/
public void storeElement(Xnode key, Object value) {
if(_crossTransformationTable.containsKey(key.getElement())) {
_crossTransformationTable.remove(key.getElement());
}
_crossTransformationTable.put(key.getElement(), value);
}
}
|
package com.antsoft.yecai.model;
import com.antsoft.yecai.type.Gender;
import org.hibernate.validator.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class UserRegisterInfo {
@NotBlank
@Size(min = 3, max = 16)
private String loginName;
@NotBlank
@Size(min = 3, max = 20)
private String password;
private String relatedUserId;
private String userId;
private Gender gender = Gender.Unknown;
@NotNull
@Size(min = 0, max = 32)
private String qq;
@NotNull
@Size(min = 0, max = 64)
private String email;
@NotNull
@Size(min = 0, max = 256)
private String introduction;
private String sign;
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRelatedUserId() {
return relatedUserId;
}
public void setRelatedUserId(String relatedUserId) {
this.relatedUserId = relatedUserId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getIntroduction() {
return introduction;
}
public void setIntroduction(String introduction) {
this.introduction = introduction;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
}
|
package com.bebehp.mc.eewreciever.ping;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
public class QuakeNode {
public long uptime;
public String type;
public String time;
public int strong;
public boolean tsunami;
public String quaketype;
public String where;
public String deep;
public float magnitude;
public boolean modified;
public String[] point;
@Override
public boolean equals(Object o)
{
if (o instanceof QuakeNode)
return ((QuakeNode)o).uptime == this.uptime;
else
return false;
}
@Override
public String toString()
{
return "[" + this.quaketype + "]" +
this.time + "" +
this.where + "" +
"" + this.strong + "" +
"" + this.magnitude + "" +
"" +
"" + this.deep + "" +
(this.tsunami ?
"" :
"") +
"[" + this.point[0] + ":" + this.point[1] + "]";
}
public static List<QuakeNode> getUpdate(List<QuakeNode> older, List<QuakeNode> newer)
{
ArrayList<QuakeNode> list = new ArrayList<QuakeNode>(newer);
for (Iterator<QuakeNode> it = older.iterator(); it.hasNext();) {
list.remove(it.next());
}
return list;
}
public static <E> Collection<E> subtract(final Collection<E> a, final Collection<E> b) {
ArrayList<E> list = new ArrayList<E>( a );
for (Iterator<E> it = b.iterator(); it.hasNext();) {
list.remove(it.next());
}
return list;
}
}
|
package com.cjburkey.plugin.shop.cmd;
import java.io.FileWriter;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import com.cjburkey.plugin.shop.IO;
import com.cjburkey.plugin.shop.ShopHandler;
import com.cjburkey.plugin.shop.ShopPlugin;
import com.cjburkey.plugin.shop.Util;
import com.cjburkey.plugin.shop.guis.GuiShop;
public class ShopCommand implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command cmd, String lb, String[] args) {
if(args.length == 0) {
if(sender instanceof Player && sender.hasPermission("burkeyshop.use")) {
Player player = (Player) sender;
ShopPlugin.getGuiHandler().open(new GuiShop(player, 0));
Util.chat(player, ShopPlugin.getPlugin().getConfig().getString("langShopOpen"));
} else if(!sender.hasPermission("burkeyshop.use")) {
Util.chat(sender, ShopPlugin.getPlugin().getConfig().getString("langNoPerm"));
} else {
Util.log("&4&lOnly in-game players may use &6/shop&r");
}
} else if(args.length == 1) {
if(args[0].equalsIgnoreCase("reload")) {
if(sender.hasPermission("burkshop.admin")) {
ShopHandler.loadShop();
Util.chat(sender, ShopPlugin.getPlugin().getConfig().getString("langReloaded"));
} else {
Util.chat(sender, ShopPlugin.getPlugin().getConfig().getString("langNoPerm"));
}
} else {
sender.sendMessage(Util.color("&4&lUsage:"));
sender.sendMessage(Util.color("&4&l /shop"));
sender.sendMessage(Util.color("&4&l /shop reload"));
sender.sendMessage(Util.color("&4&l /shop add <buyPrice> <sellPrice>"));
}
} else if(args.length == 3) {
if(args[0].equalsIgnoreCase("add")) {
if(sender instanceof Player) {
if(sender.hasPermission("burkshop.admin")) {
Player ply = (Player) sender;
ItemStack hand = ply.getInventory().getItemInMainHand();
if(hand != null) {
double buy = Double.parseDouble(args[1]);
double sell = Double.parseDouble(args[2]);
try {
FileWriter writer = new FileWriter(IO.getShopFile(), true);
writer.write("\n" + hand.getType() + ((hand.getDurability() != 0) ? (":" + hand.getDurability()) : "") + ";" + buy + ";" + sell + "\n");
writer.close();
} catch(Exception e) {
Util.error(e, "An error occurred while adding that item.");
}
Util.chat(sender, ShopPlugin.getPlugin().getConfig().getString("langAddedItem"));
ShopHandler.loadShop();
} else {
Util.chat(sender, ShopPlugin.getPlugin().getConfig().getString("langNoHand"));
}
} else {
Util.chat(sender, ShopPlugin.getPlugin().getConfig().getString("langNoPerm"));
}
} else {
Util.log("&4&lOnly in-game players may add items to the shop.");
}
}
} else {
sender.sendMessage(Util.color("&4&lUsage:"));
sender.sendMessage(Util.color("&4&l /shop"));
sender.sendMessage(Util.color("&4&l /shop reload"));
sender.sendMessage(Util.color("&4&l /shop add <buyPrice> <sellPrice>"));
}
return true;
}
}
|
package com.concurrent.task;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableFutureResult {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
Task task = new Task();
Future<Integer> future = executorService.submit(task);
executorService.shutdown();
System.out.println("");
try {
Integer result = future.get();
System.out.println("task execute result is : " + result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
|
package com.erp.lib.server.exception;
import java.sql.BatchUpdateException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.postgresql.util.PSQLException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PGException {
private final Map<String, String> errors = new HashMap();
private final Set<ConstraintError> constraintErrors = new HashSet();
private final Set<FieldError> fieldErrors = new HashSet();
private final Logger logger = LoggerFactory.getLogger(PGException.class);
public PGException() {
initialize();
}
protected void initialize() {
}
protected void addError(String context, String message) {
errors.put(context, message);
}
protected void addConstraintError(String constraint, String field, String message) {
constraintErrors.add(new ConstraintError(constraint, field, message));
}
protected void addFieldError(String error, String field, String message) {
fieldErrors.add(new FieldError(error, field, message));
}
public void throwJsonException(Exception exception, String context) {
JsonException jsonException = new JsonException();
if (exception instanceof BatchUpdateException) {
exception = ((BatchUpdateException) exception).getNextException();
}
if (exception instanceof PSQLException) {
PSQLException psqlException = (PSQLException) exception;
if (psqlException.getSQLState().startsWith("23") || psqlException.getSQLState().startsWith("P0")) {
constraintErrors.forEach((constraintError) -> {
if (psqlException.getMessage().contains(constraintError.constraint)) {
jsonException.addField(constraintError.field, constraintError.message);
}
});
}
fieldErrors.forEach((fieldError) -> {
if (psqlException.getMessage().contains(fieldError.error)) {
jsonException.addField(fieldError.field, fieldError.message);
}
});
}
if (errors.containsKey(context)) {
jsonException.setMessage(errors.get(context));
}
logger.error(exception.getMessage());
throw jsonException;
}
private class ConstraintError {
private String constraint;
private String field;
private String message;
ConstraintError(String constraint, String field, String message) {
this.constraint = constraint;
this.field = field;
this.message = message;
}
}
private class FieldError {
private String error;
private String field;
private String message;
FieldError(String error, String field, String message) {
this.error = error;
this.field = field;
this.message = message;
}
}
}
|
package com.facebook.litho;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.annotation.AttrRes;
import android.support.annotation.ColorInt;
import android.support.annotation.DimenRes;
import android.support.annotation.Dimension;
import android.support.annotation.DrawableRes;
import android.support.annotation.Px;
import android.support.annotation.StringRes;
import android.util.SparseArray;
import com.facebook.yoga.YogaAlign;
import com.facebook.yoga.YogaBaselineFunction;
import com.facebook.yoga.YogaFlexDirection;
import com.facebook.yoga.YogaJustify;
import com.facebook.yoga.YogaDirection;
import com.facebook.yoga.YogaPositionType;
import com.facebook.yoga.YogaWrap;
import com.facebook.yoga.YogaEdge;
import com.facebook.litho.reference.Reference;
import com.facebook.yoga.YogaNodeAPI;
import static android.support.annotation.Dimension.DP;
/**
* Class representing an empty InternalNode with a null ComponentLayout. All methods
* have been overridden so no actions are performed, and no exceptions are thrown.
*/
class NoOpInternalNode extends InternalNode {
@Override
void init(YogaNodeAPI cssNode, ComponentContext componentContext, Resources resources) {}
@Override
void setComponent(Component component) {
}
@Px
@Override
public int getX() {
return 0;
}
@Px
@Override
public int getY() {
return 0;
}
@Px
@Override
public int getWidth() {
return 0;
}
@Px
@Override
public int getHeight() {
return 0;
}
@Px
@Override
public int getPaddingLeft() {
return 0;
}
@Px
@Override
public int getPaddingTop() {
return 0;
}
@Px
@Override
public int getPaddingRight() {
return 0;
}
@Px
@Override
public int getPaddingBottom() {
return 0;
}
@Override
public void setCachedMeasuresValid(boolean valid) {}
@Override
public int getLastWidthSpec() {
return 0;
}
@Override
public void setLastWidthSpec(int widthSpec) {}
@Override
public int getLastHeightSpec() {
return 0;
}
@Override
public void setLastHeightSpec(int heightSpec) {}
@Override
void setLastMeasuredWidth(float lastMeasuredWidth) {}
@Override
void setLastMeasuredHeight(float lastMeasuredHeight) {}
@Override
void setDiffNode(DiffNode diffNode) {}
@Override
public InternalNode layoutDirection(YogaDirection direction) {
return this;
}
@Override
public InternalNode flexDirection(YogaFlexDirection direction) {
return this;
}
@Override
public InternalNode wrap(YogaWrap wrap) {
return this;
}
@Override
public InternalNode justifyContent(YogaJustify justifyContent) {
return this;
}
@Override
public InternalNode alignItems(YogaAlign alignItems) {
return this;
}
@Override
public InternalNode alignContent(YogaAlign alignContent) {
return this;
}
@Override
public InternalNode alignSelf(YogaAlign alignSelf) {
return this;
}
@Override
public InternalNode positionType(YogaPositionType positionType) {
return this;
}
@Override
public InternalNode flex(float flex) {
return this;
}
@Override
public InternalNode flexGrow(float flexGrow) {
return this;
}
@Override
public InternalNode flexShrink(float flexShrink) {
return this;
}
@Override
public InternalNode flexBasisPx(@Px int flexBasis) {
return this;
}
@Override
public InternalNode flexBasisAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return this;
}
@Override
public InternalNode flexBasisAttr(@AttrRes int resId) {
return this;
}
@Override
public InternalNode flexBasisRes(@DimenRes int resId) {
return this;
}
@Override
public InternalNode flexBasisDip(@Dimension(unit = DP) int flexBasis) {
return this;
}
@Override
public InternalNode flexBasisPercent(float percent) {
return this;
}
@Override
public InternalNode importantForAccessibility(int importantForAccessibility) {
return this;
}
@Override
public InternalNode duplicateParentState(boolean duplicateParentState) {
return this;
}
@Override
public InternalNode marginPx(YogaEdge edge, @Px int margin) {
return this;
}
@Override
public InternalNode marginAttr(
YogaEdge edge,
@AttrRes int resId,
@DimenRes int defaultResId) {
return this;
}
@Override
public InternalNode marginAttr(YogaEdge edge, @AttrRes int resId) {
return this;
}
@Override
public InternalNode marginRes(YogaEdge edge, @DimenRes int resId) {
return this;
}
@Override
public InternalNode marginDip(YogaEdge edge, @Dimension(unit = DP) int margin) {
return this;
}
@Override
public InternalNode marginPercent(YogaEdge edge, float percent) {
return this;
}
@Override
public InternalNode marginAuto(YogaEdge edge) {
return this;
}
@Override
public InternalNode paddingPx(YogaEdge edge, @Px int padding) {
return this;
}
@Override
public InternalNode paddingAttr(
YogaEdge edge,
@AttrRes int resId,
@DimenRes int defaultResId) {
return this;
}
@Override
public InternalNode paddingAttr(YogaEdge edge, @AttrRes int resId) {
return this;
}
@Override
public InternalNode paddingRes(YogaEdge edge,@DimenRes int resId) {
return this;
}
@Override
public InternalNode paddingDip(YogaEdge edge, @Dimension(unit = DP) int padding) {
return this;
}
@Override
public InternalNode paddingPercent(YogaEdge edge, float percent) {
return this;
}
@Override
public InternalNode borderWidthPx(YogaEdge edge, @Px int borderWidth) {
return this;
}
@Override
public InternalNode borderWidthAttr(
YogaEdge edge,
@AttrRes int resId,
@DimenRes int defaultResId) {
return this;
}
@Override
public InternalNode borderWidthAttr(YogaEdge edge, @AttrRes int resId) {
return this;
}
@Override
public InternalNode borderWidthRes(YogaEdge edge,@DimenRes int resId) {
return this;
}
@Override
public InternalNode borderWidthDip(
YogaEdge edge,
@Dimension(unit = DP) int borderWidth) {
return this;
}
@Override
public InternalNode positionPx(YogaEdge edge, @Px int position) {
return this;
}
@Override
public InternalNode positionAttr(
YogaEdge edge,
@AttrRes int resId,
@DimenRes int defaultResId) {
return this;
}
@Override
public InternalNode positionRes(YogaEdge edge, @DimenRes int resId) {
return this;
}
@Override
public InternalNode positionDip(
YogaEdge edge,
@Dimension(unit = DP) int position) {
return this;
}
@Override
public InternalNode positionPercent(YogaEdge edge, float percent) {
return this;
}
@Override
public InternalNode widthPx(@Px int width) {
return this;
}
@Override
public InternalNode widthRes(@DimenRes int resId) {
return this;
}
@Override
public InternalNode widthAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return this;
}
@Override
public InternalNode widthAttr(@AttrRes int resId) {
return this;
}
@Override
public InternalNode widthDip(@Dimension(unit = DP) int width) {
return this;
}
@Override
public InternalNode widthPercent(float percent) {
return this;
}
@Override
public InternalNode minWidthPx(@Px int minWidth) {
return this;
}
@Override
public InternalNode minWidthAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return this;
}
@Override
public InternalNode minWidthAttr(@AttrRes int resId) {
return this;
}
@Override
public InternalNode minWidthRes(@DimenRes int resId) {
return this;
}
@Override
public InternalNode minWidthDip(@Dimension(unit = DP) int minWidth) {
return this;
}
@Override
public InternalNode minWidthPercent(float percent) {
return this;
}
@Override
public InternalNode maxWidthPx(@Px int maxWidth) {
return this;
}
@Override
public InternalNode maxWidthAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return this;
}
@Override
public InternalNode maxWidthAttr(@AttrRes int resId) {
return this;
}
@Override
public InternalNode maxWidthRes(@DimenRes int resId) {
return this;
}
@Override
public InternalNode maxWidthDip(@Dimension(unit = DP) int maxWidth) {
return this;
}
@Override
public InternalNode maxWidthPercent(float percent) {
return this;
}
@Override
public InternalNode heightPx(@Px int height) {
return this;
}
@Override
public InternalNode heightRes(@DimenRes int resId) {
return this;
}
@Override
public InternalNode heightAttr(@DimenRes int resId, @DimenRes int defaultResId) {
return this;
}
@Override
public InternalNode heightAttr(@AttrRes int resId) {
return this;
}
@Override
public InternalNode heightDip(@Dimension(unit = DP) int height) {
return this;
}
@Override
|
package com.facebook.litho;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.annotation.AttrRes;
import android.support.annotation.ColorInt;
import android.support.annotation.DimenRes;
import android.support.annotation.Dimension;
import android.support.annotation.DrawableRes;
import android.support.annotation.Px;
import android.support.annotation.StringRes;
import android.util.SparseArray;
import com.facebook.yoga.YogaAlign;
import com.facebook.yoga.YogaBaselineFunction;
import com.facebook.yoga.YogaFlexDirection;
import com.facebook.yoga.YogaJustify;
import com.facebook.yoga.YogaDirection;
import com.facebook.yoga.YogaPositionType;
import com.facebook.yoga.YogaWrap;
import com.facebook.yoga.YogaEdge;
import com.facebook.litho.reference.Reference;
import com.facebook.yoga.YogaNodeAPI;
import static android.support.annotation.Dimension.DP;
/**
* Class representing an empty InternalNode with a null ComponentLayout. All methods
* have been overridden so no actions are performed, and no exceptions are thrown.
*/
class NoOpInternalNode extends InternalNode {
@Override
void init(YogaNodeAPI cssNode, ComponentContext componentContext, Resources resources) {}
@Override
void setComponent(Component component) {
}
@Px
@Override
public int getX() {
return 0;
}
@Px
@Override
public int getY() {
return 0;
}
@Px
@Override
public int getWidth() {
return 0;
}
@Px
@Override
public int getHeight() {
return 0;
}
@Px
@Override
public int getPaddingLeft() {
return 0;
}
@Px
@Override
public int getPaddingTop() {
return 0;
}
@Px
@Override
public int getPaddingRight() {
return 0;
}
@Px
@Override
public int getPaddingBottom() {
return 0;
}
@Override
public void setCachedMeasuresValid(boolean valid) {}
@Override
public int getLastWidthSpec() {
return 0;
}
@Override
public void setLastWidthSpec(int widthSpec) {}
@Override
public int getLastHeightSpec() {
return 0;
}
@Override
public void setLastHeightSpec(int heightSpec) {}
@Override
void setLastMeasuredWidth(float lastMeasuredWidth) {}
@Override
void setLastMeasuredHeight(float lastMeasuredHeight) {}
@Override
void setDiffNode(DiffNode diffNode) {}
@Override
public InternalNode layoutDirection(YogaDirection direction) {
return this;
}
@Override
public InternalNode flexDirection(YogaFlexDirection direction) {
return this;
}
@Override
public InternalNode wrap(YogaWrap wrap) {
return this;
}
@Override
public InternalNode justifyContent(YogaJustify justifyContent) {
return this;
}
@Override
public InternalNode alignItems(YogaAlign alignItems) {
return this;
}
@Override
public InternalNode alignContent(YogaAlign alignContent) {
return this;
}
@Override
public InternalNode alignSelf(YogaAlign alignSelf) {
return this;
}
@Override
public InternalNode positionType(YogaPositionType positionType) {
return this;
}
@Override
public InternalNode flex(float flex) {
return this;
}
@Override
public InternalNode flexGrow(float flexGrow) {
return this;
}
@Override
public InternalNode flexShrink(float flexShrink) {
return this;
}
@Override
public InternalNode flexBasisPx(@Px int flexBasis) {
return this;
}
@Override
public InternalNode flexBasisAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return this;
}
@Override
public InternalNode flexBasisAttr(@AttrRes int resId) {
return this;
}
@Override
public InternalNode flexBasisRes(@DimenRes int resId) {
return this;
}
@Override
public InternalNode flexBasisDip(@Dimension(unit = DP) int flexBasis) {
return this;
}
@Override
public InternalNode flexBasisPercent(float percent) {
return this;
}
@Override
public InternalNode importantForAccessibility(int importantForAccessibility) {
return this;
}
@Override
public InternalNode duplicateParentState(boolean duplicateParentState) {
return this;
}
@Override
public InternalNode marginPx(YogaEdge edge, @Px int margin) {
return this;
}
@Override
public InternalNode marginAttr(
YogaEdge edge,
@AttrRes int resId,
@DimenRes int defaultResId) {
return this;
}
@Override
public InternalNode marginAttr(YogaEdge edge, @AttrRes int resId) {
return this;
}
@Override
public InternalNode marginRes(YogaEdge edge, @DimenRes int resId) {
return this;
}
@Override
public InternalNode marginDip(YogaEdge edge, @Dimension(unit = DP) int margin) {
return this;
}
@Override
public InternalNode marginPercent(YogaEdge edge, float percent) {
return this;
}
@Override
public InternalNode marginAuto(YogaEdge edge) {
return this;
}
@Override
public InternalNode paddingPx(YogaEdge edge, @Px int padding) {
return this;
}
@Override
public InternalNode paddingAttr(
YogaEdge edge,
@AttrRes int resId,
@DimenRes int defaultResId) {
return this;
}
@Override
public InternalNode paddingAttr(YogaEdge edge, @AttrRes int resId) {
return this;
}
@Override
public InternalNode paddingRes(YogaEdge edge,@DimenRes int resId) {
return this;
}
@Override
public InternalNode paddingDip(YogaEdge edge, @Dimension(unit = DP) int padding) {
return this;
}
@Override
public InternalNode paddingPercent(YogaEdge edge, float percent) {
return this;
}
@Override
public InternalNode borderWidthPx(YogaEdge edge, @Px int borderWidth) {
return this;
}
@Override
public InternalNode borderWidthAttr(
YogaEdge edge,
@AttrRes int resId,
@DimenRes int defaultResId) {
return this;
}
@Override
public InternalNode borderWidthAttr(YogaEdge edge, @AttrRes int resId) {
return this;
}
@Override
public InternalNode borderWidthRes(YogaEdge edge,@DimenRes int resId) {
return this;
}
@Override
public InternalNode borderWidthDip(
YogaEdge edge,
@Dimension(unit = DP) int borderWidth) {
return this;
}
@Override
public InternalNode positionPx(YogaEdge edge, @Px int position) {
return this;
}
@Override
public InternalNode positionAttr(
YogaEdge edge,
@AttrRes int resId,
@DimenRes int defaultResId) {
return this;
}
@Override
public InternalNode positionRes(YogaEdge edge, @DimenRes int resId) {
return this;
}
@Override
public InternalNode positionDip(
YogaEdge edge,
@Dimension(unit = DP) int position) {
return this;
}
@Override
public InternalNode positionPercent(YogaEdge edge, float percent) {
return this;
}
@Override
public InternalNode widthPx(@Px int width) {
return this;
}
@Override
public InternalNode widthRes(@DimenRes int resId) {
return this;
}
@Override
public InternalNode widthAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return this;
}
@Override
public InternalNode widthAttr(@AttrRes int resId) {
return this;
}
@Override
public InternalNode widthDip(@Dimension(unit = DP) int width) {
|
package kodkod.examples.pardinus.decomp;
import java.util.ArrayList;
import java.util.List;
import kodkod.ast.Expression;
import kodkod.ast.Formula;
import kodkod.ast.IntConstant;
import kodkod.ast.IntExpression;
import kodkod.ast.Relation;
import kodkod.ast.Variable;
import kodkod.engine.decomp.DModel;
import kodkod.instance.Bounds;
import kodkod.instance.RelativeBounds;
import kodkod.instance.TupleFactory;
import kodkod.instance.TupleSet;
import kodkod.instance.Universe;
public class RedBlackTreeP implements DModel {
final private Relation Node, Root, left, right, parent, key, color, Black, Red, Num, Color;
final int n;
final private Universe u;
final private Variant1 v1;
final private Variant2 v2;
public enum Variant1 {
COUNTER,
THEOREM;
}
public enum Variant2 {
V1,
V2;
}
public RedBlackTreeP(String[] args) {
Node = Relation.unary("Node");
Black = Relation.unary("Black");
Red = Relation.unary("Red");
Root = Relation.unary("Root");
left = Relation.binary("left");
right = Relation.binary("right");
parent = Relation.binary("parent");
key = Relation.binary("key");
color = Relation.binary("color");
Num = Relation.unary("Num");
Color = Relation.unary("Color");
n = Integer.valueOf(args[0]);
v1 = RedBlackTreeP.Variant1.valueOf(args[1]);
v2 = RedBlackTreeP.Variant2.valueOf(args[2]);
final List<Object> atoms = new ArrayList<Object>(2*n+2);
for (int i = 0; i < n; i++)
atoms.add("Node" + i);
atoms.add("Red");
atoms.add("Black");
for (int i = 0; i < n; i++)
atoms.add(Integer.valueOf(i));
u = new Universe(atoms);
}
private Formula decls1() {
Formula f1 = Root.in(Node);
Formula f2 = Root.one();
Formula f3 = left.partialFunction(Node, Node);
Formula f4 = right.partialFunction(Node, Node);
Formula f5 = key.function(Node, Num);
Variable i = Variable.unary("i");
Formula f6 = key.join(i).lone().forAll(i.oneOf(Num));
Formula res = Formula.and(f1,f2,f3,f4);
if (v2 != Variant2.V2)
res = Formula.and(res,f5,f6,ordered());
return res;
}
private Formula ordered() {
Expression children = (left.union(right)).closure().union(Expression.IDEN);
Variable n = Variable.unary("n"),l = Variable.unary("l"),r = Variable.unary("r");
Expression le = n.join(left).join(children);
Expression re = n.join(right).join(children);
Formula f1 = n.join(key).sum().gt(l.join(key).sum()).forAll(l.oneOf(le));
Formula f2 = n.join(key).sum().lt(r.join(key).sum()).forAll(r.oneOf(re));
return f1.and(f2).forAll(n.oneOf(Node));
}
@Override
public Formula partition1() {
Expression children = (left.union(right)).closure().union(Expression.IDEN);
Variable n = Variable.unary("n");
Formula acyclic3 = (left.union(right)).join(n).one().forAll(n.oneOf(Node.difference(Root)));
Formula root3 = (left.union(right)).join(Root).no();
Formula root4 = Root.in(Root.join((left.union(right)).closure())).not();
Formula root6 = Root.join(children).eq(Node);
Formula root5 = left.intersection(right).no();
return Formula.and(decls1(),root3,root4,root5,root6,acyclic3);
}
private Formula decls2() {
Formula f1 = color.function(Node, Black.union(Red));
Formula f2 = parent.partialFunction(Node, Node);
Formula f5 = key.function(Node, Num);
Variable i = Variable.unary("i");
Formula f6 = key.join(i).lone().forAll(i.oneOf(Num));
if (v2 == Variant2.V2)
return Formula.and(f1,f2,f5,f6,ordered());
else
return Formula.and(f1,f2);
}
private Formula color() {
Expression children = (left.union(right)).closure().union(Expression.IDEN);
Formula f1 = Root.join(color).eq(Black);
Variable n = Variable.unary("n");
Formula a1 = (n.join(color).eq(Red)).implies(n.join(left.union(right)).join(color).in(Black));
Expression e21 = (n.join(left).join(children)).difference(color.join(Red));
Expression e22 = (n.join(right).join(children)).difference(color.join(Red));
Formula a2 = e21.count().eq(e22.count());
Formula f2 = (a1.and(a2)).forAll(n.oneOf(Node));
if (v1 == Variant1.THEOREM)
return f1.and(f2).and(theorem().not());
else return f1.and(f2);
}
private Formula parent() {
Variable n = Variable.unary("n");
Formula f1 = n.join(parent).eq((left.union(right)).join(n)).forAll(n.oneOf(Node));
return f1;
}
@Override
public Formula partition2() {
return decls2().and(color());
}
private Formula theorem() {
Variable n1 = Variable.unary("n1");
Variable n2 = Variable.unary("n2");
Variable x = Variable.unary("x");
Expression set = (x.join(left).no().or(x.join(right).no())).comprehension(x.oneOf(Node));
IntExpression h1 = n1.join((left.union(right)).transpose().closure()).count();
IntExpression h2 = n2.join((left.union(right)).transpose().closure()).count();
Expression e1 = h1.minus(h2).toExpression();
Formula f1 = e1.in(IntConstant.constant(0).toExpression().union(IntConstant.constant(-1).toExpression()).union(IntConstant.constant(1).toExpression()));
return f1.forAll(n1.oneOf(set).and(n2.oneOf(set)));
}
@Override
public Bounds bounds1() {
final TupleFactory f = u.factory();
final Bounds b = new Bounds(u);
final TupleSet nb = f.range(f.tuple("Node0"), f.tuple("Node"+(n-1)));
final TupleSet kb = f.range(f.tuple(Integer.valueOf(0)), f.tuple(Integer.valueOf(n-1)));
b.boundExactly(Node, nb);
b.bound(Root, nb);
b.bound(left, nb.product(nb));
b.bound(right, nb.product(nb));
b.boundExactly(Num, kb);
if (v2 == Variant2.V1)
b.bound(key, nb.product(kb));
for (int i = 0; i < n; i++)
b.boundExactly(i, f.setOf(Integer.valueOf(i)));
return b;
}
@Override
public Bounds bounds2() {
final TupleFactory f = u.factory();
final Bounds b = new Bounds(u);
final TupleSet nb = f.range(f.tuple("Node0"), f.tuple("Node"+(n-1)));
final TupleSet cb = f.range(f.tuple("Red"), f.tuple("Black"));
final TupleSet kb = f.range(f.tuple(Integer.valueOf(0)), f.tuple(Integer.valueOf(n-1)));
if (v2 == Variant2.V2)
b.bound(key, nb.product(kb));
b.boundExactly(Black, f.setOf("Black"));
b.boundExactly(Red, f.setOf("Red"));
b.bound(color, nb.product(cb));
b.bound(parent, nb.product(nb));
return b;
}
// @Override
// public Bounds bounds2() {
// final TupleFactory f = u.factory();
// final RelativeBounds b = new RelativeBounds(u);
// final TupleSet nb = f.range(f.tuple("Node0"), f.tuple("Node"+(n-1)));
// final TupleSet cb = f.range(f.tuple("Red"), f.tuple("Black"));
// final TupleSet kb = f.range(f.tuple(Integer.valueOf(0)), f.tuple(Integer.valueOf(n-1)));
// if (v2 == Variant2.V2)
// b.bound(key, nb.product(kb));
// b.boundExactly(Color, cb);
// b.boundExactly(Black, f.setOf("Black"));
// b.boundExactly(Red, f.setOf("Red"));
// b.bound(color, new Relation[]{Node,Color});
// b.bound(parent, new Relation[]{Node,Node});
// return b;
private int bits(int n) {
float x = (float) (Math.log(n*2) / Math.log(2));
int y = (int) (1 + Math.floor(x));
return Math.max(3, y);
}
private int maxInt() {
return n;
}
@Override
public int getBitwidth() {
return bits(maxInt())+1;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("RedBlackTree");
sb.append(n);
return sb.toString();
}
@Override
public String shortName() {
return "RedBlackTree "+n+" "+v1.name()+" "+v2.name();
}
}
|
package java.lang;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OverrideablePrintStream;
import java.io.PrintStream;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
public abstract class System {
private static class Static {
public static Properties properties = makeProperties();
}
private static Map<String, String> environment;
private static SecurityManager securityManager;
// static {
// loadLibrary("natives");
private static final OverrideablePrintStream _out = new OverrideablePrintStream
(new BufferedOutputStream(new FileOutputStream(FileDescriptor.out)), true);
public static final PrintStream out = _out;
private static final OverrideablePrintStream _err = new OverrideablePrintStream
(new BufferedOutputStream(new FileOutputStream(FileDescriptor.err)), true);
public static final PrintStream err = _err;
public static final InputStream in
= new BufferedInputStream(new FileInputStream(FileDescriptor.in));
public static void setErr(PrintStream err) {
SecurityManager sm = getSecurityManager();
if(sm != null) {
getSecurityManager().checkPermission(new RuntimePermission("setIO"));
}
_err.overrideStream(err);
}
public static void setOut(PrintStream out) {
SecurityManager sm = getSecurityManager();
if(sm != null) {
getSecurityManager().checkPermission(new RuntimePermission("setIO"));
}
_err.overrideStream(out);
}
public static native void arraycopy(Object src, int srcOffset, Object dst,
int dstOffset, int length);
public static String getProperty(String name) {
return (String) Static.properties.get(name);
}
public static String getProperty(String name, String defaultValue) {
String result = getProperty(name);
if (result==null) {
return defaultValue;
}
return result;
}
public static String setProperty(String name, String value) {
return (String) Static.properties.put(name, value);
}
public static Properties getProperties() {
return Static.properties;
}
private static Properties makeProperties() {
Properties properties = new Properties();
for (String p: getNativeProperties()) {
if (p == null) break;
int index = p.indexOf('=');
properties.put(p.substring(0, index), p.substring(index + 1));
}
for (String p: getVMProperties()) {
if (p == null) break;
int index = p.indexOf('=');
properties.put(p.substring(0, index), p.substring(index + 1));
}
return properties;
}
private static native String[] getNativeProperties();
private static native String[] getVMProperties();
public static native long currentTimeMillis();
public static native int identityHashCode(Object o);
private static native long getBaseNanoTime();
public static long nanoTime() {
return getBaseNanoTime();
}
public static String mapLibraryName(String name) {
if (name != null) {
return doMapLibraryName(name);
} else {
throw new NullPointerException();
}
}
private static native String doMapLibraryName(String name);
public static void load(String path) {
ClassLoader.load(path, ClassLoader.getCaller(), false);
}
public static void loadLibrary(String name) {
ClassLoader.load(name, ClassLoader.getCaller(), true);
}
public static void gc() {
Runtime.getRuntime().gc();
}
public static void exit(int code) {
Runtime.getRuntime().exit(code);
}
public static SecurityManager getSecurityManager() {
return securityManager;
}
public static void setSecurityManager(SecurityManager securityManager) {
System.securityManager = securityManager;
}
public static String getenv(String name) throws NullPointerException,
SecurityException {
if (getSecurityManager() != null) { // is this allowed?
getSecurityManager().
checkPermission(new RuntimePermission("getenv." + name));
}
return getenv().get(name);
}
public static Map<String, String> getenv() throws SecurityException {
if (getSecurityManager() != null) { // is this allowed?
getSecurityManager().checkPermission(new RuntimePermission("getenv.*"));
}
if (environment == null) { // build environment table
String[] vars = getEnvironment();
environment = new Hashtable<String, String>(vars.length);
for (String var : vars) { // parse name-value pairs
int equalsIndex = var.indexOf('=');
// null names and values are forbidden
if (equalsIndex != -1 && equalsIndex < var.length() - 1) {
environment.put(var.substring(0, equalsIndex),
var.substring(equalsIndex + 1));
}
}
}
return environment;
}
/** Returns the native process environment. */
private static native String[] getEnvironment();
}
|
package com.facebook.presto.operator;
import com.facebook.presto.Range;
import com.facebook.presto.Ranges;
import com.facebook.presto.SizeOf;
import com.facebook.presto.TupleInfo;
import com.facebook.presto.block.AbstractYieldingIterator;
import com.facebook.presto.block.BlockBuilder;
import com.facebook.presto.block.YieldingIterable;
import com.facebook.presto.block.YieldingIterator;
import com.facebook.presto.block.YieldingIterators;
import com.facebook.presto.block.Cursor;
import com.facebook.presto.block.Cursor.AdvanceResult;
import com.facebook.presto.block.Cursors;
import com.facebook.presto.block.QuerySession;
import com.facebook.presto.block.TupleStream;
import com.facebook.presto.block.position.UncompressedPositionBlock;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.primitives.Ints;
import java.util.List;
import java.util.PriorityQueue;
import static com.facebook.presto.block.Cursor.AdvanceResult.FINISHED;
import static com.facebook.presto.block.Cursor.AdvanceResult.MUST_YIELD;
import static com.facebook.presto.block.TupleStreams.getCursorFunction;
import static com.facebook.presto.block.TupleStreams.getRangeFunction;
public class AndOperator
implements TupleStream, YieldingIterable<UncompressedPositionBlock>
{
private static final int MAX_POSITIONS_PER_BLOCK = Ints.checkedCast(BlockBuilder.DEFAULT_MAX_BLOCK_SIZE.toBytes() / SizeOf.SIZE_OF_LONG);
private final List<TupleStream> sources;
private final Range range;
public AndOperator(List<TupleStream> sources)
{
Preconditions.checkNotNull(sources, "sources is null");
Preconditions.checkArgument(!sources.isEmpty(), "sources is empty");
this.sources = ImmutableList.copyOf(sources);
this.range = Ranges.intersect(Iterables.transform(this.sources, getRangeFunction()));
}
public AndOperator(TupleStream... sources)
{
this(ImmutableList.copyOf(sources));
}
@Override
public TupleInfo getTupleInfo()
{
return TupleInfo.EMPTY;
}
@Override
public Range getRange()
{
return range;
}
@Override
public Cursor cursor(QuerySession session)
{
Preconditions.checkNotNull(session, "session is null");
return new GenericCursor(session, TupleInfo.EMPTY, iterator(session));
}
@Override
public YieldingIterator<UncompressedPositionBlock> iterator(QuerySession session)
{
Preconditions.checkNotNull(session, "session is null");
final List<Cursor> cursors = ImmutableList.copyOf(Iterables.transform(sources, getCursorFunction(session)));
if (!Cursors.advanceNextPositionNoYield(cursors)) {
return YieldingIterators.emptyIterator();
}
return new AndOperatorIterator(cursors);
}
private static class AndOperatorIterator
extends AbstractYieldingIterator<UncompressedPositionBlock>
{
private final PriorityQueue<Cursor> queue;
private boolean done = false;
private long currentMax = -1;
public AndOperatorIterator(List<Cursor> cursors)
{
queue = new PriorityQueue<>(cursors.size(), Cursors.orderByPosition());
for (Cursor cursor : cursors) {
queue.add(cursor);
currentMax = Math.max(currentMax, cursor.getPosition());
}
}
@Override
protected UncompressedPositionBlock computeNext()
{
if (done) {
endOfData();
return null;
}
ImmutableList.Builder<Long> positions = ImmutableList.builder();
int count = 0;
AdvanceResult result = FINISHED;
while (count < MAX_POSITIONS_PER_BLOCK) {
Cursor head = queue.remove();
long initialPosition = head.getPosition();
if (initialPosition == currentMax) {
// all cursors have this position in common
positions.add(currentMax);
++count;
// skip past the current position
currentMax++;
}
result = head.advanceToPosition(currentMax);
if (result == FINISHED) {
done = true;
break;
}
long endPosition = head.getPosition();
currentMax = Math.max(currentMax, endPosition);
queue.add(head);
if (result == MUST_YIELD && initialPosition == endPosition) {
break;
}
}
if (count == 0) {
switch (result) {
case SUCCESS:
throw new IllegalStateException("No positions produced and input was not finished");
case MUST_YIELD:
return setMustYield();
case FINISHED:
return endOfData();
}
}
return new UncompressedPositionBlock(positions.build());
}
}
}
|
package org.mozartoz.truffle.runtime;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
import org.mozartoz.truffle.nodes.OzGuards;
import org.mozartoz.truffle.translator.Loader;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
public class PropertyRegistry {
public static final PropertyRegistry INSTANCE = new PropertyRegistry();
private static final long START_TIME = System.currentTimeMillis();
private final Map<String, Accessor> properties = new HashMap<>();
private PropertyRegistry() {
}
public void initialize() {
registerValue("oz.home", Loader.PROJECT_ROOT.intern());
registerConstant("oz.version", "3.0.0-alpha");
registerConstant("oz.date", "oz.date");
registerValue("oz.search.path", ".");
String libCache = "cache=" + Loader.LIB_DIR;
String libImages = Loader.LIB_DIR + "/x-oz/system/images";
registerValue("oz.search.load", (libCache + ":" + libImages).intern());
registerConstant("application.gui", false);
registerValue("errors.debug", true);
registerValue("errors.thread", 40L);
registerValue("errors.width", 20L);
registerValue("errors.depth", 10L);
registerValue("errors.handler", Unit.INSTANCE);
registerConstant("fd.variables", 0L);
registerConstant("fd.propagators", 0L);
registerConstant("fd.invoked", 0L);
registerValue("fd.threshold", 0L);
registerComputed("gc.active", () -> GarbageCollectionNotifier.getLastActiveSize());
registerValue("gc.codeCycles", 0L);
registerValue("gc.free", 75L);
registerValue("gc.on", true);
registerValue("gc.tolerance", 10L);
MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
registerValue("gc.min", memoryMXBean.getHeapMemoryUsage().getInit());
registerComputed("gc.size", () -> memoryMXBean.getHeapMemoryUsage().getUsed());
registerComputed("gc.threshold", () -> memoryMXBean.getHeapMemoryUsage().getCommitted());
registerValue("internal.debug", false);
registerConstant("limits.bytecode.xregisters", 65536L);
registerConstant("limits.int.max", Long.MAX_VALUE);
registerConstant("limits.int.min", Long.MIN_VALUE);
registerValue("messages.gc", false);
registerValue("messages.idle", false);
registerValue("oz.standalone", true);
registerConstant("platform.arch", System.getProperty("os.arch").intern());
registerConstant("platform.os", System.getProperty("os.name").intern());
registerConstant("platform.name", System.getProperty("os.name").intern());
registerValue("priorities.high", 10L);
registerValue("priorities.medium", 10L);
registerConstant("spaces.created", 0L);
registerConstant("spaces.cloned", 0L);
registerConstant("spaces.committed", 0L);
registerConstant("spaces.failed", 0L);
registerConstant("spaces.succeeded", 0L);
registerComputed("threads.created", () -> OzThread.getNumberOfThreadsCreated());
registerComputed("threads.runnable", () -> OzThread.getNumberOfThreadsRunnable());
registerConstant("threads.min", 1L);
registerValue("print.verbose", false);
registerValue("print.width", 20L);
registerValue("print.depth", 10L);
registerConstant("time.user", 0L);
registerConstant("time.system", 0L);
registerConstant("time.total", 0L);
registerComputed("time.run", () -> System.currentTimeMillis() - START_TIME);
registerConstant("time.idle", 0L);
registerConstant("time.copy", 0L);
registerConstant("time.propagate", 0L);
registerComputed("time.gc", () -> {
long total = 0L;
for (GarbageCollectorMXBean gcBean : ManagementFactory.getGarbageCollectorMXBeans()) {
total += gcBean.getCollectionTime();
}
return total;
});
registerValue("time.detailed", false);
GarbageCollectionNotifier.register();
}
@TruffleBoundary
public boolean containsKey(String property) {
return properties.containsKey(property);
}
@TruffleBoundary
public Object get(String property) {
Accessor accessor = properties.get(property);
if (accessor == null) {
return null;
}
return accessor.get();
}
@TruffleBoundary
public void put(String property, Object value) {
assert isOzValue(value) : value;
Accessor accessor = properties.get(property);
accessor.set(value);
}
@TruffleBoundary
public void registerConstant(String property, Object value) {
assert isOzValue(value) : value;
registerInternal(property, new ConstantAccessor(property, value));
}
@TruffleBoundary
public void registerValue(String property, Object value) {
assert isOzValue(value) : value;
registerInternal(property, new ValueAccessor(value));
}
public void registerComputed(String property, Supplier<Object> getter) {
registerInternal(property, new ComputedAccessor(property, getter));
}
private void registerInternal(String property, Accessor accessor) {
if (properties.containsKey(property)) {
throw new RuntimeException();
}
properties.put(property, accessor);
}
private static boolean isOzValue(Object value) {
return OzGuards.isFeature(value) || OzGuards.isFloat(value) ||
OzGuards.isCons(value) || OzGuards.isRecord(value) ||
OzGuards.isProc(value);
}
public void setApplicationURL(String appURL) {
registerConstant("application.url", appURL);
}
public void setApplicationArgs(String[] args) {
Object list = "nil";
for (int i = args.length - 1; i >= 0; i
list = new OzCons(args[i].intern(), list);
}
registerConstant("application.args", list);
}
public interface Accessor {
Object get();
void set(Object newValue);
}
protected class ConstantAccessor implements Accessor {
private final String property;
private final Object value;
public ConstantAccessor(String property, Object value) {
this.property = property;
this.value = value;
}
@Override
public Object get() {
return value;
}
@Override
public void set(Object newValue) {
throw new RuntimeException("Tried to set constant property " + property);
}
}
protected class ValueAccessor implements Accessor {
private Object value;
public ValueAccessor(Object value) {
this.value = value;
}
@Override
public Object get() {
return value;
}
@Override
public void set(Object newValue) {
this.value = newValue;
}
}
protected class ComputedAccessor implements Accessor {
private final String property;
private final Supplier<Object> getter;
public ComputedAccessor(String property, Supplier<Object> getter) {
this.property = property;
this.getter = getter;
}
@Override
public Object get() {
Object value = getter.get();
assert isOzValue(value);
return value;
}
@Override
public void set(Object newValue) {
throw new RuntimeException("Tried to set computed property " + property);
}
}
}
|
package com.gamingmesh.jobs.container;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import com.gamingmesh.jobs.Jobs;
import com.gamingmesh.jobs.Signs.SignTopType;
import com.gamingmesh.jobs.api.JobsLevelUpEvent;
import com.gamingmesh.jobs.container.blockOwnerShip.BlockTypes;
import com.gamingmesh.jobs.dao.JobsDAO;
import com.gamingmesh.jobs.economy.PaymentData;
import com.gamingmesh.jobs.stuff.TimeManage;
import net.Zrips.CMILib.ActionBar.CMIActionBar;
import net.Zrips.CMILib.Colors.CMIChatColor;
import net.Zrips.CMILib.Equations.Parser;
import net.Zrips.CMILib.Items.CMIMaterial;
import net.Zrips.CMILib.Logs.CMIDebug;
import net.Zrips.CMILib.Time.CMITimeManager;
public class JobsPlayer {
private final Jobs plugin = org.bukkit.plugin.java.JavaPlugin.getPlugin(Jobs.class);
private String userName = "Unknown";
public UUID playerUUID;
// progression of the player in each job
public final List<JobProgression> progression = new ArrayList<>();
public int maxJobsEquation = 0;
private ArchivedJobs archivedJobs = new ArchivedJobs();
private PaymentData paymentLimits;
private final Map<String, List<BoostCounter>> boostCounter = new HashMap<>();
// display honorific
private String honorific;
// player save status
private volatile boolean isSaved = true;
// player online status
private volatile boolean isOnline = false;
private final Map<CurrencyType, Integer> limits = new HashMap<>();
private int userid = -1;
private final List<BossBarInfo> barMap = new ArrayList<>();
private final List<String> updateBossBarFor = new ArrayList<>();
// save lock
// public final Object saveLock = new Object();
private Map<String, Log> logList = new HashMap<>();
private Long seen = System.currentTimeMillis();
private Map<String, Boolean> permissionsCache;
private Long lastPermissionUpdate = -1L;
private final Map<String, Map<String, QuestProgression>> qProgression = new HashMap<>();
private int doneQuests = 0;
private int skippedQuests = 0;
private final Map<UUID, Map<Job, Long>> leftTimes = new HashMap<>();
private PlayerPoints pointsData = new PlayerPoints();
private Set<String> blockOwnerShipInform = null;
public JobsPlayer(OfflinePlayer player) {
this.userName = player.getName() == null ? "Unknown" : player.getName();
this.playerUUID = player.getUniqueId();
}
public JobsPlayer(Player player) {
this.userName = player.getName() == null ? "Unknown" : player.getName();
this.playerUUID = player.getUniqueId();
}
public JobsPlayer(String userName) {
this.userName = userName == null ? "Unknown" : userName;
}
/**
* @return the cached or new instance of {@link PlayerPoints}
*/
public PlayerPoints getPointsData() {
return pointsData;
}
/**
* Adds points to this player.
*
* @param points the amount of points
*/
public void addPoints(double points) {
pointsData.addPoints(points);
this.setSaved(false);
}
/**
* Takes points from this player.
*
* @param points the amount of points
*/
public void takePoints(double points) {
pointsData.takePoints(points);
this.setSaved(false);
}
/**
* Sets points for this player.
*
* @param points the amount of points
*/
public void setPoints(double points) {
pointsData.setPoints(points);
this.setSaved(false);
}
/**
* Sets points for this player from the given {@link PlayerPoints}
*
* @param points {@link PlayerPoints}
*/
public void setPoints(PlayerPoints points) {
pointsData.setPoints(points.getCurrentPoints());
pointsData.setTotalPoints(points.getTotalPoints());
pointsData.setDbId(points.getDbId());
}
/**
* Checks whenever have enough points for the given one.
*
* @param points amount of points
* @return true if yes
*/
public boolean havePoints(double points) {
return pointsData.getCurrentPoints() >= points;
}
/**
* @return the cached instance of {@link ArchivedJobs}
*/
public ArchivedJobs getArchivedJobs() {
return archivedJobs;
}
/**
* Returns the given archived job progression.
*
* @param job {@link Job}
* @return the given archived job progression
*/
public JobProgression getArchivedJobProgression(Job job) {
return archivedJobs.getArchivedJobProgression(job);
}
public void setArchivedJobs(ArchivedJobs archivedJob) {
this.archivedJobs = archivedJob;
}
/**
* @return the total level of all jobs for this player
*/
public int getTotalLevels() {
int i = 0;
for (JobProgression job : progression) {
i += job.getLevel();
}
return i;
}
public void setPaymentLimit(PaymentData paymentLimits) {
this.paymentLimits = paymentLimits;
}
/**
* @return the limit of {@link PaymentData}
*/
public PaymentData getPaymentLimit() {
if (paymentLimits == null)
paymentLimits = Jobs.getJobsDAO().getPlayersLimits(this);
if (paymentLimits == null)
paymentLimits = new PaymentData();
return paymentLimits;
}
/**
* Checks whenever this player is under limit for specific {@link CurrencyType}
*
* @param type {@link CurrencyType}
* @param amount amount of points
* @return true if it is under
*/
public boolean isUnderLimit(CurrencyType type, double amount) {
if (amount == 0)
return true;
Player player = getPlayer();
if (player == null)
return true;
CurrencyLimit limit = Jobs.getGCManager().getLimit(type);
if (!limit.isEnabled())
return true;
PaymentData data = getPaymentLimit();
if (data.isReachedLimit(type, getLimit(type))) {
String name = type.getName().toLowerCase();
if (!data.isInformed() && player.isOnline() && !data.isReseted(type)) {
if (Jobs.getGCManager().useMaxPaymentCurve) {
player.sendMessage(Jobs.getLanguage().getMessage("command.limit.output.reached" + name + "limit"));
player.sendMessage(Jobs.getLanguage().getMessage("command.limit.output.reached" + name + "limit2"));
player.sendMessage(Jobs.getLanguage().getMessage("command.limit.output.reached" + name + "limit3"));
} else {
player.sendMessage(Jobs.getLanguage().getMessage("command.limit.output.reached" + name + "limit"));
player.sendMessage(Jobs.getLanguage().getMessage("command.limit.output.reached" + name + "limit2"));
}
data.setInformed(true);
}
if (data.isAnnounceTime(limit.getAnnouncementDelay()) && player.isOnline())
CMIActionBar.send(player, Jobs.getLanguage().getMessage("command.limit.output." + name + "time", "%time%", CMITimeManager.to24hourShort(data.getLeftTime(type))));
if (data.isReseted(type))
data.setReseted(type, false);
return false;
}
data.addAmount(type, amount);
return true;
}
public double percentOverLimit(CurrencyType type) {
return getPaymentLimit().percentOverLimit(type, getLimit(type));
}
/**
* Attempt to load log for this player.
*
* @deprecated use {@link JobsDAO#loadLog(JobsPlayer)} instead
*/
@Deprecated
public void loadLogFromDao() {
Jobs.getJobsDAO().loadLog(this);
}
public List<String> getUpdateBossBarFor() {
return updateBossBarFor;
}
@Deprecated
public void clearUpdateBossBarFor() {
updateBossBarFor.clear();
}
public List<BossBarInfo> getBossBarInfo() {
return barMap;
}
public void hideBossBars() {
for (BossBarInfo one : barMap) {
one.getBar().setVisible(false);
}
}
public Map<String, Log> getLog() {
return logList;
}
public void setLog(Map<String, Log> logList) {
this.logList = logList;
}
public void setUserId(int userid) {
this.userid = userid;
}
public int getUserId() {
return userid;
}
/**
* @return {@link Player} or null if not exist
*/
public Player getPlayer() {
return playerUUID != null ? plugin.getServer().getPlayer(playerUUID) : null;
}
/**
* Attempts to get the boost from specific job and {@link CurrencyType}
*
* @param jobName
* @param type {@link CurrencyType}
* @see #getBoost(String, CurrencyType, boolean)
* @return amount of boost
*/
public double getBoost(String jobName, CurrencyType type) {
return getBoost(jobName, type, false);
}
/**
* Attempts to get the boost from specific job and {@link CurrencyType}
*
* @param jobName
* @param type {@link CurrencyType}
* @param force whenever to retrieve as soon as possible without time
* @return amount of boost
*/
public double getBoost(String jobName, CurrencyType type, boolean force) {
double boost = 0D;
if (type == null || !isOnline())
return boost;
long time = System.currentTimeMillis();
List<BoostCounter> counterList = boostCounter.get(jobName);
if (counterList != null) {
for (BoostCounter counter : counterList) {
if (counter.getType() != type)
continue;
if (force || time - counter.getTime() > 1000 * 60) {
boost = getPlayerBoostNew(jobName, type);
counter.setBoost(boost);
counter.setTime(time);
return boost;
}
return counter.getBoost();
}
boost = getPlayerBoostNew(jobName, type);
counterList.add(new BoostCounter(type, boost, time));
return boost;
}
boost = getPlayerBoostNew(jobName, type);
counterList = new ArrayList<>();
counterList.add(new BoostCounter(type, boost, time));
boostCounter.put(jobName, counterList);
return boost;
}
private Double getPlayerBoostNew(String jobName, CurrencyType type) {
Double v1 = Jobs.getPermissionManager().getMaxPermission(this, "jobs.boost." + jobName + "." + type.getName(), true, false);
Double boost = v1;
v1 = Jobs.getPermissionManager().getMaxPermission(this, "jobs.boost." + jobName + ".all", false, false);
if (v1 != 0d && (v1 > boost || v1 < boost))
boost = v1;
v1 = Jobs.getPermissionManager().getMaxPermission(this, "jobs.boost.all.all", false, false);
if (v1 != 0d && (v1 > boost || v1 < boost))
boost = v1;
v1 = Jobs.getPermissionManager().getMaxPermission(this, "jobs.boost.all." + type.getName(), false, false);
if (v1 != 0d && (v1 > boost || v1 < boost))
boost = v1;
return boost;
}
public int getPlayerMaxQuest(String jobName) {
int m1 = (int) Jobs.getPermissionManager().getMaxPermission(this, "jobs.maxquest.all", false, true);
int m2 = (int) Jobs.getPermissionManager().getMaxPermission(this, "jobs.maxquest." + jobName, false, true);
return m1 > m2 ? m1 : m2;
}
/**
* Reloads max experience for all jobs for this player.
*/
public void reloadMaxExperience() {
progression.forEach(JobProgression::reloadMaxExperience);
}
/**
* Reloads limit for this player.
*/
public void reload(CurrencyType type) {
Parser eq = Jobs.getGCManager().getLimit(type).getMaxEquation();
eq.setVariable("totallevel", getTotalLevels());
maxJobsEquation = Jobs.getPlayerManager().getMaxJobs(this);
limits.put(type, (int) eq.getValue());
setSaved(false);
}
public void reloadLimits() {
for (CurrencyType type : CurrencyType.values()) {
reload(type);
}
}
public int getLimit(CurrencyType type) {
return limits.getOrDefault(type, 0);
}
public void resetPaymentLimit() {
if (paymentLimits == null)
getPaymentLimit();
if (paymentLimits != null)
paymentLimits.resetLimits();
setSaved(false);
}
/**
* @return an unmodifiable list of job progressions
*/
public List<JobProgression> getJobProgression() {
return Collections.unmodifiableList(progression);
}
/**
* Get the job progression from the certain job
*
* @param job {@link Job}
* @return the job progression or null if job not exists
*/
public JobProgression getJobProgression(Job job) {
if (job != null) {
for (JobProgression prog : progression) {
if (prog.getJob().isSame(job))
return prog;
}
}
return null;
}
/**
* get the userName
* @return the userName
*/
@Deprecated
public String getUserName() {
return getName();
}
/**
* @return the name of this player
*/
public String getName() {
Player player = getPlayer();
if (player != null)
userName = player.getName();
return userName;
}
public String getDisplayName() {
if (!this.isOnline())
return getName();
Player p = this.getPlayer();
if (p == null)
return getName();
return p.getDisplayName() == null || p.getDisplayName().isEmpty() ? getName() : p.getDisplayName();
}
/**
* get the playerUUID
* @return the playerUUID
*/
@Deprecated
public UUID getPlayerUUID() {
return getUniqueId();
}
/**
* @return the {@link UUID} of this player
*/
public UUID getUniqueId() {
return playerUUID;
}
public void setPlayerUUID(UUID playerUUID) {
setUniqueId(playerUUID);
}
public void setUniqueId(UUID playerUUID) {
this.playerUUID = playerUUID;
}
public String getDisplayHonorific() {
if (honorific == null)
reloadHonorific();
return honorific;
}
/**
* Attempts to join this player to the given job.
*
* @param job where to join
*/
public boolean joinJob(Job job) {
// synchronized (saveLock) {
if (!isInJob(job)) {
int level = 1;
double exp = 0;
JobProgression archived = getArchivedJobProgression(job);
if (archived != null) {
level = getLevelAfterRejoin(archived);
exp = getExpAfterRejoin(archived, level);
Jobs.getJobsDAO().deleteArchive(this, job);
}
progression.add(new JobProgression(job, this, level, exp));
reloadMaxExperience();
reloadLimits();
reloadHonorific();
Jobs.getPermissionHandler().recalculatePermissions(this);
return true;
}
return false;
}
public int getLevelAfterRejoin(JobProgression jp) {
if (jp == null)
return 1;
int level = jp.getLevel();
level = (int) ((level - (level * (Jobs.getGCManager().levelLossPercentage / 100.0))));
if (level < 1)
level = 1;
if (jp.getLevel() == getMaxJobLevelAllowed(jp.getJob())) {
level = jp.getLevel();
if (!Jobs.getGCManager().fixAtMaxLevel) {
level = (int) (level - (level * (Jobs.getGCManager().levelLossPercentageFromMax / 100.0)));
if (level < 1)
level = 1;
}
}
return level;
}
public double getExpAfterRejoin(JobProgression jp, int level) {
if (jp == null)
return 1;
int max = jp.getMaxExperience(level);
double exp = jp.getExperience();
if (exp > max)
exp = max;
if (exp > 0) {
if (jp.getLevel() == getMaxJobLevelAllowed(jp.getJob())) {
if (!Jobs.getGCManager().fixAtMaxLevel)
exp = (exp - (exp * (Jobs.getGCManager().levelLossPercentageFromMax / 100.0)));
} else
exp = (exp - (exp * (Jobs.getGCManager().levelLossPercentage / 100.0)));
}
return exp;
}
/**
* Player leaves a job
* @param job - the job left
*/
public boolean leaveJob(Job job) {
// synchronized (saveLock) {
if (progression.remove(getJobProgression(job))) {
reloadMaxExperience();
reloadLimits();
reloadHonorific();
Jobs.getPermissionHandler().recalculatePermissions(this);
return true;
}
return false;
}
/**
* Attempts to leave all jobs from this player.
* @return true if success
*/
public boolean leaveAllJobs() {
// synchronized (saveLock) {
progression.clear();
reloadHonorific();
Jobs.getPermissionHandler().recalculatePermissions(this);
reloadLimits();
return true;
}
/**
* Promotes player in job
* @param job - the job being promoted
* @param levels - number of levels to promote
*/
public void promoteJob(Job job, int levels) {
if (levels <= 0)
return;
// synchronized (saveLock) {
JobProgression prog = getJobProgression(job);
if (prog == null)
return;
int oldLevel = prog.getLevel(),
newLevel = oldLevel + levels,
maxLevel = job.getMaxLevel(this);
if (maxLevel > 0 && newLevel > maxLevel)
newLevel = maxLevel;
setLevel(job, newLevel);
}
/**
* Demotes player in job
* @param job - the job being deomoted
* @param levels - number of levels to demote
*/
public void demoteJob(Job job, int levels) {
if (levels <= 0)
return;
// synchronized (saveLock) {
JobProgression prog = getJobProgression(job);
if (prog == null)
return;
int newLevel = prog.getLevel() - levels;
if (newLevel < 1)
newLevel = 1;
setLevel(job, newLevel);
}
/**
* Sets player to a specific level
* @param job - the job
* @param level - the level
*/
private void setLevel(Job job, int level) {
// synchronized (saveLock) {
JobProgression prog = getJobProgression(job);
if (prog == null)
return;
int oldLevel = prog.getLevel();
if (level != oldLevel) {
if (prog.setLevel(level)) {
JobsLevelUpEvent levelUpEvent = new JobsLevelUpEvent(this, job, prog.getLevel(),
Jobs.getTitleManager().getTitle(oldLevel, prog.getJob().getName()),
Jobs.getTitleManager().getTitle(prog.getLevel(), prog.getJob().getName()),
Jobs.getGCManager().SoundLevelupSound,
Jobs.getGCManager().SoundLevelupVolume,
Jobs.getGCManager().SoundLevelupPitch,
Jobs.getGCManager().SoundTitleChangeSound,
Jobs.getGCManager().SoundTitleChangeVolume,
Jobs.getGCManager().SoundTitleChangePitch);
plugin.getServer().getPluginManager().callEvent(levelUpEvent);
}
reloadHonorific();
reloadLimits();
Jobs.getPermissionHandler().recalculatePermissions(this);
}
}
/**
* Player leaves a job
* @param oldjob - the old job
* @param newjob - the new job
*/
public boolean transferJob(Job oldjob, Job newjob) {
// synchronized (saveLock) {
if (!isInJob(newjob)) {
for (JobProgression prog : progression) {
if (!prog.getJob().isSame(oldjob))
continue;
prog.setJob(newjob);
int maxLevel = getMaxJobLevelAllowed(newjob);
if (newjob.getMaxLevel() > 0 && prog.getLevel() > maxLevel)
prog.setLevel(maxLevel);
reloadMaxExperience();
reloadLimits();
reloadHonorific();
Jobs.getPermissionHandler().recalculatePermissions(this);
return true;
}
}
return false;
}
public int getMaxJobLevelAllowed(Job job) {
Player player = getPlayer();
int maxLevel = 0;
if (player != null && (player.hasPermission("jobs." + job.getName() + ".vipmaxlevel") || player.hasPermission("jobs.all.vipmaxlevel")))
maxLevel = job.getVipMaxLevel() > job.getMaxLevel() ? job.getVipMaxLevel() : job.getMaxLevel();
else
maxLevel = job.getMaxLevel();
int tMax = (int) Jobs.getPermissionManager().getMaxPermission(this, "jobs." + job.getName() + ".vipmaxlevel");
if (tMax > maxLevel)
maxLevel = tMax;
tMax = (int) Jobs.getPermissionManager().getMaxPermission(this, "jobs.all.vipmaxlevel");
if (tMax > maxLevel)
maxLevel = tMax;
return maxLevel;
}
/**
* Checks if the player is in the given job.
*
* @param job {@link Job}
* @return true if this player is in the given job, otherwise false
*/
public boolean isInJob(Job job) {
return getJobProgression(job) != null;
}
/**
* Function that reloads this player honorific
*/
public void reloadHonorific() {
StringBuilder builder = new StringBuilder();
if (progression.size() > 0) {
for (JobProgression prog : progression) {
DisplayMethod method = prog.getJob().getDisplayMethod();
if (method == DisplayMethod.NONE)
continue;
if (builder.length() > 0) {
builder.append(Jobs.getGCManager().modifyChatSeparator);
}
processesChat(method, builder, prog.getLevel(), Jobs.getTitleManager().getTitle(prog.getLevel(),
prog.getJob().getName()), prog.getJob());
}
} else {
Job nonejob = Jobs.getNoneJob();
if (nonejob != null) {
processesChat(nonejob.getDisplayMethod(), builder, -1, null, nonejob);
}
}
honorific = builder.toString().trim();
if (!honorific.isEmpty())
honorific = CMIChatColor.translate(Jobs.getGCManager().modifyChatPrefix + honorific + Jobs.getGCManager().modifyChatSuffix);
}
private static void processesChat(DisplayMethod method, StringBuilder builder, int level, Title title, Job job) {
String levelS = level < 0 ? "" : Integer.toString(level);
switch (method) {
case FULL:
processesTitle(builder, title, levelS);
processesJob(builder, job, levelS);
break;
case TITLE:
processesTitle(builder, title, levelS);
break;
case JOB:
processesJob(builder, job, levelS);
break;
case SHORT_FULL:
processesShortTitle(builder, title, levelS);
processesShortJob(builder, job, levelS);
break;
case SHORT_TITLE:
processesShortTitle(builder, title, levelS);
break;
case SHORT_JOB:
processesShortJob(builder, job, levelS);
break;
case SHORT_TITLE_JOB:
processesShortTitle(builder, title, levelS);
processesJob(builder, job, levelS);
break;
case TITLE_SHORT_JOB:
processesTitle(builder, title, levelS);
processesShortJob(builder, job, levelS);
break;
default:
break;
}
}
private static void processesShortTitle(StringBuilder builder, Title title, String levelS) {
if (title == null)
return;
builder.append(title.getChatColor());
builder.append(title.getShortName().replace("{level}", levelS));
builder.append(CMIChatColor.WHITE);
}
private static void processesTitle(StringBuilder builder, Title title, String levelS) {
if (title == null)
return;
builder.append(title.getChatColor());
builder.append(title.getName().replace("{level}", levelS));
builder.append(CMIChatColor.WHITE);
}
private static void processesShortJob(StringBuilder builder, Job job, String levelS) {
if (job == null)
return;
builder.append(job.getChatColor());
builder.append(job.getShortName().replace("{level}", levelS));
builder.append(CMIChatColor.WHITE);
}
private static void processesJob(StringBuilder builder, Job job, String levelS) {
if (job == null)
return;
builder.append(job.getChatColor());
builder.append(job.getName().replace("{level}", levelS));
builder.append(CMIChatColor.WHITE);
}
/**
* Performs player save into database
*/
public void save() {
// synchronized (saveLock) {
if (!isSaved) {
JobsDAO dao = Jobs.getJobsDAO();
dao.save(this);
dao.saveLog(this);
dao.savePoints(this);
dao.recordPlayersLimits(this);
dao.updateSeen(this);
setSaved(true);
Player player = getPlayer();
if (player == null || !player.isOnline()) {
Jobs.getPlayerManager().addPlayerToCache(this);
Jobs.getPlayerManager().removePlayer(player);
}
}
}
/**
* Perform connect
*/
public void onConnect() {
isOnline = true;
}
/**
* Perform disconnect for this player
*/
public void onDisconnect() {
clearBossMaps();
isOnline = false;
blockOwnerShipInform = null;
Jobs.getPlayerManager().addPlayerToCache(this);
}
public void clearBossMaps() {
for (BossBarInfo one : barMap) {
one.getBar().removeAll();
one.cancel();
}
barMap.clear();
}
/**
* Whether or not player is online
* @return true if online, otherwise false
*/
public boolean isOnline() {
Player player = getPlayer();
return player != null ? player.isOnline() : isOnline;
}
public boolean isSaved() {
return isSaved;
}
public void setSaved(boolean isSaved) {
this.isSaved = isSaved;
}
public Long getSeen() {
return seen;
}
public void setSeen(Long seen) {
this.seen = seen;
}
public Map<String, Boolean> getPermissionsCache() {
return permissionsCache;
}
public void setPermissionsCache(Map<String, Boolean> permissionsCache) {
this.permissionsCache = permissionsCache;
}
public void setPermissionsCache(String permission, Boolean state) {
permissionsCache.put(permission, state);
}
public Long getLastPermissionUpdate() {
return lastPermissionUpdate;
}
public void setLastPermissionUpdate(Long lastPermissionUpdate) {
this.lastPermissionUpdate = lastPermissionUpdate;
}
/**
* Checks whenever this player can get paid for the given action.
*
* @param info {@link ActionInfo}
* @return true if yes
*/
public boolean canGetPaid(ActionInfo info) {
int numjobs = progression.size();
if (numjobs == 0) {
if (Jobs.getNoneJob() == null)
return false;
JobInfo jobinfo = Jobs.getNoneJob().getJobInfo(info, 1);
if (jobinfo == null)
return false;
double income = jobinfo.getIncome(1, numjobs, maxJobsEquation);
double points = jobinfo.getPoints(1, numjobs, maxJobsEquation);
if (income == 0D && points == 0D)
return false;
}
for (JobProgression prog : progression) {
int level = prog.getLevel();
JobInfo jobinfo = prog.getJob().getJobInfo(info, level);
if (jobinfo == null)
continue;
double income = jobinfo.getIncome(level, numjobs, maxJobsEquation);
double pointAmount = jobinfo.getPoints(level, numjobs, maxJobsEquation);
double expAmount = jobinfo.getExperience(level, numjobs, maxJobsEquation);
if (income != 0D || pointAmount != 0D || expAmount != 0D)
return true;
}
return false;
}
public boolean inDailyQuest(Job job, String questName) {
Map<String, QuestProgression> qpl = qProgression.get(job.getName());
if (qpl == null)
return false;
for (QuestProgression one : qpl.values()) {
Quest quest = one.getQuest();
if (quest != null && quest.getConfigName().equalsIgnoreCase(questName))
return true;
}
return false;
}
private List<String> getQuestNameList(Job job, ActionType type) {
List<String> ls = new ArrayList<>();
if (!isInJob(job))
return ls;
Map<String, QuestProgression> qpl = qProgression.get(job.getName());
if (qpl == null)
return ls;
for (QuestProgression prog : qpl.values()) {
if (prog.isEnded())
continue;
Quest quest = prog.getQuest();
if (quest == null)
continue;
for (Map<String, QuestObjective> oneAction : quest.getObjectives().values()) {
for (QuestObjective oneObjective : oneAction.values()) {
if (type == null || type.name().equals(oneObjective.getAction().name())) {
ls.add(quest.getConfigName().toLowerCase());
break;
}
}
}
}
return ls;
}
public void resetQuests(Job job) {
resetQuests(getQuestProgressions(job));
}
public void resetQuests(List<QuestProgression> quests) {
for (QuestProgression oneQ : quests) {
oneQ.reset();
Quest quest = oneQ.getQuest();
if (quest != null) {
Map<String, QuestProgression> map = qProgression.get(quest.getJob().getName());
if (map != null) {
map.clear();
}
}
}
}
public void resetQuests() {
for (JobProgression prog : progression) {
resetQuests(prog.getJob());
}
}
public void getNewQuests() {
qProgression.clear();
}
public void getNewQuests(Job job) {
Map<String, QuestProgression> prog = qProgression.get(job.getName());
if (prog != null) {
prog.clear();
qProgression.put(job.getName(), prog);
}
}
public void replaceQuest(Quest quest) {
Job job = quest.getJob();
Map<String, QuestProgression> orProg = qProgression.get(job.getName());
Quest q = job.getNextQuest(getQuestNameList(job, null), getJobProgression(job).getLevel());
if (q == null) {
for (JobProgression one : progression) {
if (one.getJob().isSame(job))
continue;
q = one.getJob().getNextQuest(getQuestNameList(one.getJob(), null), getJobProgression(one.getJob()).getLevel());
if (q != null)
break;
}
}
if (q == null)
return;
Job qJob = q.getJob();
Map<String, QuestProgression> prog = qProgression.get(qJob.getName());
if (prog == null) {
prog = new HashMap<>();
qProgression.put(qJob.getName(), prog);
}
if (q.getConfigName().equals(quest.getConfigName()))
return;
String confName = q.getConfigName().toLowerCase();
if (prog.containsKey(confName))
return;
if (!qJob.isSame(job) && prog.size() >= qJob.getMaxDailyQuests())
return;
if (orProg != null) {
orProg.remove(quest.getConfigName().toLowerCase());
}
prog.put(confName, new QuestProgression(q));
skippedQuests++;
}
public List<QuestProgression> getQuestProgressions() {
List<QuestProgression> g = new ArrayList<>();
for (JobProgression one : progression) {
g.addAll(getQuestProgressions(one.getJob()));
}
return g;
}
public List<QuestProgression> getQuestProgressions(Job job) {
return getQuestProgressions(job, null);
}
public List<QuestProgression> getQuestProgressions(Job job, ActionType type) {
if (!isInJob(job))
return new ArrayList<>();
Map<String, QuestProgression> g = new HashMap<>();
Map<String, QuestProgression> qProg = qProgression.get(job.getName());
if (qProg != null)
g = new HashMap<>(qProg);
for (Entry<String, QuestProgression> one : new HashMap<>(g).entrySet()) {
QuestProgression qp = one.getValue();
if (qp.isEnded()) {
g.remove(one.getKey().toLowerCase());
skippedQuests = 0;
}
}
if (g.size() < job.getMaxDailyQuests()) {
int i = 0;
while (i <= job.getQuests().size()) {
++i;
Quest q = job.getNextQuest(new ArrayList<>(g.keySet()), getJobProgression(job).getLevel());
if (q == null)
continue;
QuestProgression qp = new QuestProgression(q);
Quest quest = qp.getQuest();
if (quest != null)
g.put(quest.getConfigName().toLowerCase(), qp);
if (g.size() >= job.getMaxDailyQuests())
break;
}
}
if (g.size() > job.getMaxDailyQuests()) {
int i = g.size();
while (i > 0) {
--i;
g.remove(g.keySet().iterator().next());
if (g.size() <= job.getMaxDailyQuests())
break;
}
}
qProgression.put(job.getName(), g);
Map<String, QuestProgression> tmp = new HashMap<>();
for (QuestProgression oneJ : g.values()) {
Quest q = oneJ.getQuest();
if (q == null) {
continue;
}
if (type == null) {
tmp.put(q.getConfigName().toLowerCase(), oneJ);
continue;
}
Map<String, QuestObjective> old = q.getObjectives().get(type);
if (old != null)
for (QuestObjective one : old.values()) {
if (type.name().equals(one.getAction().name())) {
tmp.put(q.getConfigName().toLowerCase(), oneJ);
break;
}
}
}
return new ArrayList<>(tmp.values());
}
public String getQuestProgressionString() {
String prog = "";
for (QuestProgression one : getQuestProgressions()) {
Quest q = one.getQuest();
if (q == null || q.getObjectives().isEmpty())
continue;
if (!prog.isEmpty())
prog += ";:;";
prog += q.getJob().getName() + ":" + q.getConfigName() + ":" + one.getValidUntil() + ":";
for (Map<String, QuestObjective> oneA : q.getObjectives().values()) {
for (Entry<String, QuestObjective> oneO : oneA.entrySet()) {
prog += oneO.getValue().getAction().toString() + ";" + oneO.getKey() + ";" + one.getAmountDone(oneO.getValue()) + ":;:";
}
}
if (prog.endsWith(":;:"))
prog = prog.substring(0, prog.length() - 3);
}
return prog.isEmpty() ? null : prog.endsWith(";:") ? prog.substring(0, prog.length() - 2) : prog;
}
public void setQuestProgressionFromString(String qprog) {
if (qprog == null || qprog.isEmpty())
return;
for (String one : qprog.split(";:;")) {
String jname = one.split(":", 2)[0];
Job job = Jobs.getJob(jname);
if (job == null)
continue;
one = one.substring(jname.length() + 1);
String qname = one.split(":", 2)[0];
Quest quest = job.getQuest(qname);
if (quest == null)
continue;
one = one.substring(qname.length() + 1);
String longS = one.split(":", 2)[0];
long validUntil = Long.parseLong(longS);
one = one.substring(longS.length() + 1);
Map<String, QuestProgression> currentProgression = qProgression.get(job.getName());
if (currentProgression == null) {
currentProgression = new HashMap<>();
qProgression.put(job.getName(), currentProgression);
}
String questName = qname.toLowerCase();
QuestProgression qp = currentProgression.get(questName);
if (qp == null) {
qp = new QuestProgression(quest);
qp.setValidUntil(validUntil);
currentProgression.put(questName, qp);
}
for (String oneA : one.split(":;:")) {
String prog = oneA.split(";", 2)[0];
ActionType action = ActionType.getByName(prog);
if (action == null || oneA.length() < prog.length() + 1)
continue;
Map<String, QuestObjective> old = quest.getObjectives().get(action);
if (old == null)
continue;
oneA = oneA.substring(prog.length() + 1);
String target = oneA.split(";", 2)[0];
QuestObjective obj = old.get(target);
if (obj == null)
continue;
oneA = oneA.substring(target.length() + 1);
qp.setAmountDone(obj, Integer.parseInt(oneA.split(";", 2)[0]));
}
if (qp.isCompleted())
qp.setGivenReward(true);
}
}
public int getDoneQuests() {
return doneQuests;
}
public void setDoneQuests(int doneQuests) {
this.doneQuests = doneQuests;
}
private Integer questSignUpdateShed;
public void addDoneQuest(final Job job) {
doneQuests++;
setSaved(false);
if (questSignUpdateShed == null) {
questSignUpdateShed = plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> {
Jobs.getSignUtil().signUpdate(job, SignTopType.questtoplist);
questSignUpdateShed = null;
}, Jobs.getGCManager().getSavePeriod() * 60 * 20L);
}
}
/**
* @deprecated {@link Jobs#getBlockOwnerShip(BlockTypes)}
* @return the furnace count
*/
@Deprecated
public int getFurnaceCount() {
return !plugin.getBlockOwnerShip(BlockTypes.FURNACE).isPresent() ? 0 : plugin.getBlockOwnerShip(BlockTypes.FURNACE).get().getTotal(getUniqueId());
}
/**
* @deprecated {@link Jobs#getBlockOwnerShip(BlockTypes)}
* @return the brewing stand count
*/
@Deprecated
public int getBrewingStandCount() {
return !plugin.getBlockOwnerShip(BlockTypes.BREWING_STAND).isPresent() ? 0 : plugin.getBlockOwnerShip(BlockTypes.BREWING_STAND).get().getTotal(getUniqueId());
}
/**
* @deprecated use {@link #getMaxOwnerShipAllowed(CMIMaterial)}
* @return max allowed brewing stands
*/
@Deprecated
public int getMaxBrewingStandsAllowed() {
Double maxV = Jobs.getPermissionManager().getMaxPermission(this, "jobs.maxbrewingstands");
if (maxV == 0)
maxV = (double) Jobs.getGCManager().getBrewingStandsMaxDefault();
return maxV.intValue();
}
/**
* @deprecated use {@link #getMaxOwnerShipAllowed(CMIMaterial)}
* @return the max allowed furnaces
*/
@Deprecated
public int getMaxFurnacesAllowed() {
return getMaxOwnerShipAllowed(BlockTypes.FURNACE);
}
/**
* Returns the max allowed owner ship for the given block type.
* @param type {@link BlockTypes}
* @return max allowed owner ship
*/
public int getMaxOwnerShipAllowed(BlockTypes type) {
double maxV = Jobs.getPermissionManager().getMaxPermission(this, "jobs.maxownership");
if (maxV > 0D) {
return (int) maxV;
}
if (type != BlockTypes.BREWING_STAND &&
(maxV = Jobs.getPermissionManager().getMaxPermission(this, "jobs.maxfurnaceownership")) > 0D) {
return (int) maxV;
}
String perm = "jobs.max" + (type == BlockTypes.FURNACE
? "furnaces" : type == BlockTypes.BLAST_FURNACE ? "blastfurnaces" : type == BlockTypes.SMOKER ? "smokers"
: type == BlockTypes.BREWING_STAND ? "brewingstands" : "");
maxV = Jobs.getPermissionManager().getMaxPermission(this, perm);
if (maxV == 0D && type == BlockTypes.FURNACE)
maxV = Jobs.getGCManager().getFurnacesMaxDefault();
if (maxV == 0D && type == BlockTypes.BLAST_FURNACE)
maxV = Jobs.getGCManager().BlastFurnacesMaxDefault;
if (maxV == 0D && type == BlockTypes.SMOKER)
maxV = Jobs.getGCManager().SmokersMaxDefault;
if (maxV == 0D && type == BlockTypes.BREWING_STAND)
maxV = Jobs.getGCManager().getBrewingStandsMaxDefault();
return (int) maxV;
}
public int getSkippedQuests() {
return skippedQuests;
}
public void setSkippedQuests(int skippedQuests) {
this.skippedQuests = skippedQuests;
}
public Map<UUID, Map<Job, Long>> getLeftTimes() {
return leftTimes;
}
public boolean isLeftTimeEnded(Job job) {
Map<Job, Long> map = leftTimes.get(getUniqueId());
Long time = map != null ? map.get(job) : null;
return time != null && time.longValue() < System.currentTimeMillis();
}
public void setLeftTime(Job job) {
UUID uuid = getUniqueId();
leftTimes.remove(uuid);
int hour = Jobs.getGCManager().jobExpiryTime;
if (hour == 0)
return;
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY) + hour);
Map<Job, Long> map = new HashMap<>();
map.put(job, cal.getTimeInMillis());
leftTimes.put(uuid, map);
}
public boolean hasBlockOwnerShipInform(String location) {
if (blockOwnerShipInform == null)
return false;
return blockOwnerShipInform.contains(location);
}
public void addBlockOwnerShipInform(String location) {
if (blockOwnerShipInform == null)
blockOwnerShipInform = new HashSet<String>();
this.blockOwnerShipInform.add(location);
}
}
|
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
* A simple HTTP Client application
*
* Computer Networks, KU Leuven.
*
* Arne De Brabandere
* Ward Schodts
*/
class HTTPClient {
/**
* Log file: log.txt
*/
public static LogFile logFile = new LogFile("log.txt");
public static void main(String[] args) throws Exception {
// if the arguments are invalid, then print the description of how to specify the program arguments
if (! validArguments(args)) {
printHelp();
} else {
// add command string to log file
logFile.addLine("\n" + "Command:" + "\n\n" + args[0] + " " + args[1] + " " + args[2] + " " + args[3]);
// get arguments
String command = args[0];
String uriString = args[1];
String portString = args[2];
String version = args[3];
// get URI object from uriString
URI uri = getURI(uriString);
// get port int
int port = Integer.parseInt(portString);
executeCommand(command, uri, port, version);
// add separator to log file
logFile.addLine("
}
}
/**
* Print the description of how to specify the program arguments.
*/
public static void printHelp() {
// TODO
System.out.println("The argument that you entered were wrong:");
System.out.println("HEAD url(starting with or without http) port(usuallly 80) httpversion(1.0 or 1.1)");
System.out.println("GET url port httpversion");
System.out.println("PUT url port httpversion");
System.out.println("POST url port httpversion");
}
/**
* Get URI object from given URI string
* @param uriString String value of the given URI
*/
private static URI getURI(String uriString) throws Exception {
if (! uriString.startsWith("http:
uriString = "http://" + uriString;
}
return new URI(uriString);
}
/**
* Execute the command.
* @param command command string
* @param uri URI object
* @param port port number
* @param version http version (1.0 or 1.1)
*/
private static void executeCommand(String command, URI uri, int port, String version) throws Exception {
String path = uri.getPath(); // path to file
String host = uri.getHost();
// Connect to the host.
Socket clientSocket = null;
try {
clientSocket = new Socket(host, port);
} catch (IOException e) {
System.out.println("Unable to connect to " + host + ":" + port);
}
// Create outputstream (convenient data writer) to this host.
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
// Create an inputstream (convenient data reader) to this host
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
ArrayList<String> uris;
// Parse command.
try {
switch (command) {
case "HEAD":
head(inFromServer, outToServer, path, host, version);
break;
case "GET":
// als get the returned array of embedded object URI's to request
uris = get(inFromServer, outToServer, path, host, version);
break;
/*case "PUT":
put(inFromServer, outToServer, path, host, version);
break;*/
case "POST":
post(inFromServer, outToServer, path, host, version);
break;
}
}
catch (Exception e) {
e.printStackTrace();
}
// Close the socket.
clientSocket.close();
// If command is GET and http version is 1.0, then get the embedded objects AFTER the socket was closed
// (if http version 1.1 was used, the embedded objects are requested inside the get() method)
if (command.equals("GET") && version.equals("1.0")) {
// get uris (get2)
// TODO
}
}
private static void head(BufferedReader inFromServer, DataOutputStream outToServer, String path, String host, String version) throws Exception {
// Send HTTP command to server.
if(version.equals("1.0")) {
outToServer.writeBytes("HEAD " + path + " HTTP/" + version + "\r\n\r\n");
} else {
outToServer.writeBytes("HEAD " + path + " HTTP/" + version + "\r\n" +
"HOST: " + host + "\r\n\r\n");
}
logFile.addLine("\n" + "Response:" + "\n");
// Read text from the server
String response = "";
while ((response = inFromServer.readLine()) != null) {
// print response to screen
System.out.println(response);
// write response to log file
logFile.addLine(response);
}
}
private static ArrayList<String> get(BufferedReader inFromServer, DataOutputStream outToServer, String path, String host, String version) throws Exception {
// Send HTTP command to server.
if(version.equals("1.0")) {
outToServer.writeBytes("GET " + path + " HTTP/" + version + "\r\n\r\n");
} else {
outToServer.writeBytes("GET " + path + " HTTP/" + version + "\r\n" +
"HOST: " + host + "\r\n\r\n");
}
logFile.addLine("\n" + "Response:" + "\n");
// Read text from the server
String response = "";
String outputString = "";
while ((response = inFromServer.readLine()) != null) {
// print response to screen
System.out.println(response);
// write response to log file
logFile.addLine(response);
// add line to output in outputString
outputString += response;
}
// Find URI's of embedded objects
ArrayList<String> uris = new ArrayList<>();
String pattern = "src=\"(.*?)\"";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(outputString);
while (m.find( )) {
// if http 1.0 was used, just add the src uri to uris
if (version.equals("1.0")) {
uris.add(m.group(1));
}
// if http 1.1 was used, then get the file save it
else {
// TODO
}
}
return uris;
}
public void get2(BufferedReader inFromServer, DataOutputStream outToServer, String path, String host, String version) throws Exception {
// Send HTTP command to server.
if(version.equals("1.0")) {
outToServer.writeBytes("GET " + path + " HTTP/" + version + "\r\n\r\n");
} else {
outToServer.writeBytes("GET " + path + " HTTP/" + version + "\r\n" +
"HOST: " + host + "\r\n\r\n");
}
// Read text from the server
String response = "";
String outputString = "";
while ((response = inFromServer.readLine()) != null) {
// add line to output in outputString
outputString += response;
}
File out = new File("out/" + host + path); // TODO
}
/**
* Check if the arguments are valid.
*/
public static boolean validArguments(String[] arguments) {
if (arguments.length != 4)
return false;
if (! arguments[0].equals("HEAD") && ! arguments[0].equals("GET") && ! arguments[0].equals("PUT") && ! arguments[0].equals("POST"))
return false;
if (! isInteger(arguments[2]))
return false;
if (! arguments[3].equals("1.0") && ! arguments[3].equals("1.1"))
return false;
return true;
}
/**
* Check if a string is an integer.
*/
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
return true;
}
///////////////////////////////////////////////////POST////////////////////////////////////////////////////////////
private static void post(BufferedReader inFromServer, DataOutputStream outToServer, String path, String host, String version) throws Exception {
// Send HTTP command to server.
if(version.equals(1.0)) {
outToServer.writeBytes("HEAD " + path + " HTTP/" + version + "\r\n\r\n");
} else {
outToServer.writeBytes("HEAD " + path + " HTTP/" + version + "\r\n" +
"HOST: " + host + "\r\n\r\n");
}
logFile.addLine("\n" + "Response:" + "\n");
// Read text from the server
String response = "";
while ((response = inFromServer.readLine()) != null) {
// print response to screen
System.out.println(response);
// write response to log file
logFile.addLine(response);
}
}
}
|
package com.github.cstroe.sqs.www;
import com.github.cstroe.sqs.dao.NoteDao;
import com.github.cstroe.sqs.dao.NotebookDao;
import com.github.cstroe.sqs.repository.RepositoryFactory;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import java.util.ArrayList;
import java.util.List;
class BaseActionBean implements ActionBean {
private ActionBeanContext context;
public void setContext(ActionBeanContext context) {
this.context = context;
}
public ActionBeanContext getContext() {
return context;
}
public List<NoteDao> getRecentNotes() {
return new ArrayList<>();
}
public void recordError() {
// do some sort of error logging here
throw new RuntimeException("Error was encountered");
}
public List<NotebookDao> getNotebooks() {
return RepositoryFactory.notebook().findAll();
}
}
|
package com.jamesloyd.foldergenutility;
import java.io.File;
import java.util.ArrayList;
public class FolderGen
{
private String location;
private String numberOfFiles;
private String startpoint;
private String folderName;
private char folderSeperator;
private FolderGen(folderGenBuilder builder)
{
this.folderName = builder.folderName;
this.numberOfFiles = builder.numberOfFiles;
this.startpoint = builder.startpoint;
this.location = builder.location;
this.folderSeperator = builder.folderSeperator;
}
public void generateFolders() throws Exception
{
StringBuffer buffer = new StringBuffer();
buffer.append(location);
buffer.append("\\");
buffer.append(folderName);
ArrayList<File> fileList = new ArrayList<>();
if(numberOfFiles == null && startpoint == null)
{
File file = new File(buffer.toString());
fileList.add(file);
}
else if (numberOfFiles !=null && startpoint == null)
{
//assume 1 is default number
for (int i = 0; i < Integer.parseInt(numberOfFiles) ; i++)
{
buffer.append(i);
File file = new File(buffer.toString());
fileList.add(file);
}
}
else if (numberOfFiles != null && startpoint == null && Character.isDefined(folderSeperator))
{
for (int i = 0; i < Integer.parseInt(numberOfFiles) ; i++)
{
buffer.append(folderSeperator);
buffer.append(i);
File file = new File((buffer.toString()));
fileList.add(file);
}
}
else if (numberOfFiles !=null && startpoint !=null && Character.isDefined(folderSeperator))
{
for (int i = Integer.parseInt(startpoint); i < Integer.parseInt(numberOfFiles) ; i++)
{
buffer.append(folderSeperator);
buffer.append(i);
File file = new File((buffer.toString()));
fileList.add(file);
}
}
else
{
for (int i = Integer.parseInt(startpoint); i < Integer.parseInt(numberOfFiles) ; i++)
{
buffer.append(folderSeperator);
buffer.append(i);
File file = new File(buffer.toString());
fileList.add(file);
}
}
generate(fileList);
}
private void generate(ArrayList<File> fileList) throws Exception
{
for (int i = 0; i < fileList.size() ; i++)
{
File file = null;
file = fileList.get(i);
try{
if(file.mkdir()) {
System.out.println("Directory Created");
} else {
System.out.println("Directory is not created");
}
} catch(Exception e){
e.printStackTrace();
}
}
}
//going for the builder pattern
public static class FolderGenBuilder{
private String location;
private String numberOfFiles;
private String startpoint;
private String folderName;
private char folderSeperator;
public folderGenBuilder(String location, String folderName)
{
this.location = location;
this.folderName = folderName;
}
public folderGenBuilder numberOfFiles(String numberOfFiles)
{
this.numberOfFiles = numberOfFiles;
return this;
}
public folderGenBuilder startpoint(String startpoint)
{
this.startpoint = startpoint;
return this;
}
public folderGenBuilder folderSeperator(char folderSeperator)
{
this.folderSeperator = folderSeperator;
return this;
}
public FolderGen build()
{
return new FolderGen(this);
}
}
}
|
package com.lazerycode.jmeter;
import com.lazerycode.jmeter.configuration.JMeterArgumentsArray;
import com.lazerycode.jmeter.configuration.ProxyConfiguration;
import com.lazerycode.jmeter.configuration.RemoteConfiguration;
import com.lazerycode.jmeter.properties.PropertyHandler;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Dependency;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
import org.joda.time.format.DateTimeFormat;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import static com.lazerycode.jmeter.UtilityFunctions.isSet;
import static org.apache.commons.io.FileUtils.copyFile;
import static org.apache.commons.io.FileUtils.copyInputStreamToFile;
/**
* JMeter Maven plugin.
* This is a base class for the JMeter mojos.
*
* @author Tim McCune
*/
@SuppressWarnings({"UnusedDeclaration", "FieldCanBeLocal", "JavaDoc"}) // Mojos get their fields set via reflection
public abstract class JMeterAbstractMojo extends AbstractMojo {
/**
* Sets the list of include patterns to use in directory scan for JMX files.
* Relative to testFilesDirectory.
*/
@Parameter
protected List<String> testFilesIncluded;
/**
* Sets the list of exclude patterns to use in directory scan for Test files.
* Relative to testFilesDirectory.
*/
@Parameter
protected List<String> testFilesExcluded;
/**
* Path under which JMX files are stored.
*/
@Parameter(defaultValue = "${basedir}/src/test/jmeter")
protected File testFilesDirectory;
/**
* Timestamp the test results.
*/
@Parameter(defaultValue = "true")
protected boolean testResultsTimestamp;
/**
* Append the results timestamp to the filename
* (It will be prepended by default if testResultsTimestamp is set to true)
*/
@Parameter(defaultValue = "false")
protected boolean appendResultsTimestamp;
@Parameter()
protected String resultsFileNameDateFormat;
/**
* Set the format of the results generated by JMeter
* Valid values are: xml, csv (XML set by default).
*/
@Parameter(defaultValue = "xml")
protected String resultsFileFormat;
/**
* Absolute path to JMeter custom (test dependent) properties file.
*/
@Parameter
protected Map<String, String> propertiesJMeter = new HashMap<String, String>();
/**
* JMeter Properties that are merged with precedence into default JMeter file in saveservice.properties
*/
@Parameter
protected Map<String, String> propertiesSaveService = new HashMap<String, String>();
/**
* JMeter Properties that are merged with precedence into default JMeter file in upgrade.properties
*/
@Parameter
protected Map<String, String> propertiesUpgrade = new HashMap<String, String>();
/**
* JMeter Properties that are merged with precedence into default JMeter file in user.properties
* user.properties takes precedence over jmeter.properties
*/
@Parameter
protected Map<String, String> propertiesUser = new HashMap<String, String>();
/**
* JMeter Global Properties that override those given in jmeterProps. <br>
* This sets local and remote properties (JMeter's definition of global properties is actually remote properties)
* and overrides any local/remote properties already set
*/
@Parameter
protected Map<String, String> propertiesGlobal = new HashMap<String, String>();
/**
* (Java) System properties set for the test run.
* Properties are merged with precedence into default JMeter file system.properties
*/
@Parameter
protected Map<String, String> propertiesSystem = new HashMap<String, String>();
/**
* Absolute path to JMeter custom (test dependent) properties file.
*/
@Parameter
protected File customPropertiesFile;
/**
* Replace the default JMeter properties with any custom properties files supplied.
* (If set to false any custom properties files will be merged with the default JMeter properties files, custom properties will overwrite default ones)
*/
@Parameter(defaultValue = "true")
protected boolean propertiesReplacedByCustomFiles;
/**
* Value class that wraps all proxy configurations.
*/
@Parameter
protected ProxyConfiguration proxyConfig;
/**
* Value class that wraps all remote configurations.
*/
@Parameter
protected RemoteConfiguration remoteConfig;
/**
* Set a root log level to override all log levels used by JMeter
* Valid log levels are: FATAL_ERROR, ERROR, WARN, INFO, DEBUG (They are not case sensitive);
* If you try to set an invalid log level it will be ignored
*/
@Parameter
protected String overrideRootLogLevel;
/**
* Sets whether FailureScanner should ignore failures in JMeter result file.
* Failures are for example failed requests
*/
@Parameter(defaultValue = "false")
protected boolean ignoreResultFailures;
/**
* Suppress JMeter output
*/
@Parameter(defaultValue = "true")
protected boolean suppressJMeterOutput;
/**
* Get a list of artifacts used by this plugin
*/
@Parameter(defaultValue = "${plugin.artifacts}", required = true, readonly = true)
protected List<Artifact> pluginArtifacts;
/**
* The information extracted from the plugin-section of the pom of the project where the plugin is used
*/
@Component
protected PluginDescriptor pluginDescriptor;
/**
* Skip the JMeter tests
*/
@Parameter(defaultValue = "false")
protected boolean skipTests;
/**
* Place where the JMeter files will be generated.
*/
@Parameter(defaultValue = "${project.build.directory}/jmeter")
protected transient File workDir;
protected File binDir;
protected File libDir;
protected File libExtDir;
protected File logsDir;
protected File resultsDir;
/**
* All property files are stored in this artifact, comes with JMeter library
*/
protected final String jmeterConfigArtifact = "ApacheJMeter_config";
protected JMeterArgumentsArray testArgs;
protected PropertyHandler pluginProperties;
protected boolean resultsOutputIsCSVFormat = false;
/**
* Generate the directory tree utilised by JMeter.
*/
@SuppressWarnings("ResultOfMethodCallIgnored")
protected void generateJMeterDirectoryTree() {
logsDir = new File(workDir, "logs");
logsDir.mkdirs();
binDir = new File(workDir, "bin");
binDir.mkdirs();
resultsDir = new File(workDir, "results");
resultsDir.mkdirs();
libDir = new File(workDir, "lib");
libExtDir = new File(libDir, "ext");
libExtDir.mkdirs();
//JMeter expects a <workdir>/lib/junit directory and complains if it can't find it.
new File(libDir, "junit").mkdirs();
}
protected void propertyConfiguration() throws MojoExecutionException {
pluginProperties = new PropertyHandler(testFilesDirectory, binDir, getArtifactNamed(jmeterConfigArtifact), propertiesReplacedByCustomFiles);
pluginProperties.setJMeterProperties(propertiesJMeter);
pluginProperties.setJMeterGlobalProperties(propertiesGlobal);
pluginProperties.setJMeterSaveServiceProperties(propertiesSaveService);
pluginProperties.setJMeterUpgradeProperties(propertiesUpgrade);
pluginProperties.setJmeterUserProperties(propertiesUser);
pluginProperties.setJMeterSystemProperties(propertiesSystem);
pluginProperties.configureJMeterPropertiesFiles();
pluginProperties.setDefaultPluginProperties(binDir.getAbsolutePath());
}
/**
* Create the JMeter directory tree and copy all compile time JMeter dependencies into it.
* Generic compile time artifacts are copied into the libDir
* ApacheJMeter_* artifacts are copied into the libExtDir
* Runtime dependencies set by the user are also copied into the libExtDir
*
* @throws MojoExecutionException
*/
protected void populateJMeterDirectoryTree() throws MojoExecutionException {
for (Artifact artifact : pluginArtifacts) {
try {
if (Artifact.SCOPE_COMPILE.equals(artifact.getScope()) || Artifact.SCOPE_RUNTIME.equals(artifact.getScope())) {
if (artifact.getArtifactId().equals(jmeterConfigArtifact)) {
extractConfigSettings(artifact);
} else if (artifact.getArtifactId().equals("ApacheJMeter")) {
copyFile(artifact.getFile(), new File(binDir + File.separator + artifact.getArtifactId() + ".jar"));
} else if (artifact.getArtifactId().startsWith("ApacheJMeter_")) {
copyFile(artifact.getFile(), new File(libExtDir + File.separator + artifact.getFile().getName()));
} else if (isArtifactAJMeterDependency(artifact)) {
copyFile(artifact.getFile(), new File(libDir + File.separator + artifact.getFile().getName()));
//TODO Work out if the artifact is a plugin that should be placed in the /lib/ext dir instead of the /lib dir
// } else if (isArtifactAnExplicitDependency(artifact) && <Some Condition to identify a plugin>) {
// copyFile(artifact.getFile(), new File(libExtDir + File.separator + artifact.getFile().getName()));
} else if (isArtifactAnExplicitDependency(artifact)) {
copyFile(artifact.getFile(), new File(libDir + File.separator + artifact.getFile().getName()));
}
}
} catch (IOException e) {
throw new MojoExecutionException("Unable to populate the JMeter directory tree: " + e);
}
}
}
/**
* Extract the configuration settings (not properties files) form the configuration artifact and load them into the /bin directory
*
* @param artifact Configuration artifact
* @throws IOException
*/
private void extractConfigSettings(Artifact artifact) throws IOException {
JarFile configSettings = new JarFile(artifact.getFile());
Enumeration<JarEntry> entries = configSettings.entries();
while (entries.hasMoreElements()) {
JarEntry jarFileEntry = entries.nextElement();
// Only interested in files in the /bin directory that are not properties files
if (!jarFileEntry.isDirectory() && jarFileEntry.getName().startsWith("bin") && !jarFileEntry.getName().endsWith(".properties")) {
copyInputStreamToFile(configSettings.getInputStream(jarFileEntry), new File(workDir.getCanonicalPath() + File.separator + jarFileEntry.getName()));
}
}
configSettings.close();
}
/**
* Check if the given artifact is needed by an explicit dependency (a dependency, that is explicitly defined in
* the pom of the project using the jmeter-maven-plugin).
* <p/>
* For example, consider the following pom:
*
* <code>
* <plugin>
* <groupId>com.lazerycode.jmeter</groupId>
* <artifactId>jmeter-maven-plugin</artifactId>
* <dependencies>
* <dependency>
* <groupId>kg.apc</groupId>
* <artifactId>jmeter-plugins</artifactId>
* </dependency>
* </dependencies>
* </plugin>
* </code>
* <p/>
*
* Now kg.apc:jmeter-plugins is an explicit dependency. And org.apache.jmeter:jorphan is a needed by this explicit dependency, so
* isArtifactAnExplicitDependency(org.apache.jmeter:jorphan) would return true.
*
* @param artifact Artifact to examine
* @return true if the given artifact is needed by a explicit dependency.
*/
protected boolean isArtifactAnExplicitDependency(Artifact artifact) {
List<Dependency> explizitDependencies = pluginDescriptor.getPlugin().getDependencies();
for (String parent : artifact.getDependencyTrail()) {
for (Dependency explicitDependency : explizitDependencies) {
if (parent.contains(explicitDependency.getGroupId() + ":" + explicitDependency.getArtifactId()))
return true;
}
}
return false;
}
/**
* Work out if an artifact is a JMeter dependency
*
* @param artifact Artifact to examine
* @return true if a Jmeter dependency, false if a plugin dependency.
*/
protected boolean isArtifactAJMeterDependency(Artifact artifact) {
for (String dependency : artifact.getDependencyTrail()) {
if (dependency.contains("org.apache.jmeter:ApacheJMeter")) {
return true;
}
}
return false;
}
/**
* Search the list of plugin artifacts for an artifact with a specific name
*
* @param artifactName
* @return
* @throws MojoExecutionException
*/
protected Artifact getArtifactNamed(String artifactName) throws MojoExecutionException {
for (Artifact artifact : pluginArtifacts) {
if (artifact.getArtifactId().equals(artifactName)) {
return artifact;
}
}
throw new MojoExecutionException("Unable to find artifact '" + artifactName + "'!");
}
/**
* Generate the initial JMeter Arguments array that is used to create the command line that we pass to JMeter.
*
* @throws MojoExecutionException
*/
protected void initialiseJMeterArgumentsArray(boolean disableGUI) throws MojoExecutionException {
testArgs = new JMeterArgumentsArray(disableGUI, workDir.getAbsolutePath());
testArgs.setResultsDirectory(resultsDir.getAbsolutePath());
testArgs.setResultFileOutputFormatIsCSV(resultsOutputIsCSVFormat);
if (testResultsTimestamp) {
testArgs.setResultsTimestamp(testResultsTimestamp);
testArgs.appendTimestamp(appendResultsTimestamp);
if (isSet(resultsFileNameDateFormat)) {
try {
testArgs.setResultsFileNameDateFormat(DateTimeFormat.forPattern(resultsFileNameDateFormat));
} catch (Exception ex) {
getLog().error("'" + resultsFileNameDateFormat + "' is an invalid DateTimeFormat. Defaulting to Standard ISO_8601.");
}
}
}
testArgs.setProxyConfig(proxyConfig);
testArgs.setACustomPropertiesFile(customPropertiesFile);
testArgs.setLogRootOverride(overrideRootLogLevel);
testArgs.setLogsDirectory(logsDir.getAbsolutePath());
}
protected void setJMeterResultFileFormat() {
if (resultsFileFormat.toLowerCase().equals("csv")) {
propertiesJMeter.put("jmeter.save.saveservice.output_format", "csv");
resultsOutputIsCSVFormat = true;
} else {
propertiesJMeter.put("jmeter.save.saveservice.output_format", "xml");
resultsOutputIsCSVFormat = false;
}
}
}
|
package com.lazerycode.jmeter;
import com.lazerycode.jmeter.configuration.JMeterArgumentsArray;
import com.lazerycode.jmeter.configuration.JMeterPlugins;
import com.lazerycode.jmeter.configuration.ProxyConfiguration;
import com.lazerycode.jmeter.configuration.RemoteConfiguration;
import com.lazerycode.jmeter.properties.PropertyHandler;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Dependency;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Parameter;
import org.joda.time.format.DateTimeFormat;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import static com.lazerycode.jmeter.UtilityFunctions.isSet;
import static org.apache.commons.io.FileUtils.copyFile;
import static org.apache.commons.io.FileUtils.copyInputStreamToFile;
/**
* JMeter Maven plugin.
* This is a base class for the JMeter mojos.
*
* @author Tim McCune
*/
@SuppressWarnings({"UnusedDeclaration", "FieldCanBeLocal", "JavaDoc"}) // Mojos get their fields set via reflection
public abstract class JMeterAbstractMojo extends AbstractMojo {
/**
* Sets the list of include patterns to use in directory scan for JMX files.
* Relative to testFilesDirectory.
*/
@Parameter
protected List<String> testFilesIncluded;
/**
* Sets the list of exclude patterns to use in directory scan for Test files.
* Relative to testFilesDirectory.
*/
@Parameter
protected List<String> testFilesExcluded;
/**
* Path under which JMX files are stored.
*/
@Parameter(defaultValue = "${basedir}/src/test/jmeter")
protected File testFilesDirectory;
/**
* Timestamp the test results.
*/
@Parameter(defaultValue = "true")
protected boolean testResultsTimestamp;
/**
* Append the results timestamp to the filename
* (It will be prepended by default if testResultsTimestamp is set to true)
*/
@Parameter(defaultValue = "false")
protected boolean appendResultsTimestamp;
@Parameter()
protected String resultsFileNameDateFormat;
/**
* Set the format of the results generated by JMeter
* Valid values are: xml, csv (XML set by default).
*/
@Parameter(defaultValue = "xml")
protected String resultsFileFormat;
/**
* Absolute path to JMeter custom (test dependent) properties file.
*/
@Parameter
protected Map<String, String> propertiesJMeter = new HashMap<String, String>();
/**
* JMeter Properties that are merged with precedence into default JMeter file in saveservice.properties
*/
@Parameter
protected Map<String, String> propertiesSaveService = new HashMap<String, String>();
/**
* JMeter Properties that are merged with precedence into default JMeter file in upgrade.properties
*/
@Parameter
protected Map<String, String> propertiesUpgrade = new HashMap<String, String>();
/**
* JMeter Properties that are merged with precedence into default JMeter file in user.properties
* user.properties takes precedence over jmeter.properties
*/
@Parameter
protected Map<String, String> propertiesUser = new HashMap<String, String>();
/**
* JMeter Global Properties that override those given in jmeterProps. <br>
* This sets local and remote properties (JMeter's definition of global properties is actually remote properties)
* and overrides any local/remote properties already set
*/
@Parameter
protected Map<String, String> propertiesGlobal = new HashMap<String, String>();
/**
* (Java) System properties set for the test run.
* Properties are merged with precedence into default JMeter file system.properties
*/
@Parameter
protected Map<String, String> propertiesSystem = new HashMap<String, String>();
/**
* Absolute path to JMeter custom (test dependent) properties file.
*/
@Parameter
protected File customPropertiesFile;
/**
* Replace the default JMeter properties with any custom properties files supplied.
* (If set to false any custom properties files will be merged with the default JMeter properties files, custom properties will overwrite default ones)
*/
@Parameter(defaultValue = "true")
protected boolean propertiesReplacedByCustomFiles;
/**
* Value class that wraps all proxy configurations.
*/
@Parameter
protected ProxyConfiguration proxyConfig;
/**
* Value class that wraps all remote configurations.
*/
@Parameter
protected RemoteConfiguration remoteConfig;
/**
* Value class that wraps all remote configurations.
*/
@Parameter
protected Set<JMeterPlugins> jmeterPlugins;
/**
* Set a root log level to override all log levels used by JMeter
* Valid log levels are: FATAL_ERROR, ERROR, WARN, INFO, DEBUG (They are not case sensitive);
* If you try to set an invalid log level it will be ignored
*/
@Parameter
protected String overrideRootLogLevel;
/**
* Sets whether FailureScanner should ignore failures in JMeter result file.
* Failures are for example failed requests
*/
@Parameter(defaultValue = "false")
protected boolean ignoreResultFailures;
/**
* Suppress JMeter output
*/
@Parameter(defaultValue = "true")
protected boolean suppressJMeterOutput;
/**
* Get a list of artifacts used by this plugin
*/
@Parameter(defaultValue = "${plugin.artifacts}", required = true, readonly = true)
protected List<Artifact> pluginArtifacts;
/**
* The information extracted from the plugin-section of the pom of the project where the plugin is used
*/
@Parameter(defaultValue = "${plugin.plugin.dependencies}", required = true, readonly = true)
protected List<Dependency> pluginDependencies;
/**
* Skip the JMeter tests
*/
@Parameter(defaultValue = "false")
protected boolean skipTests;
/**
* Place where the JMeter files will be generated.
*/
@Parameter(defaultValue = "${project.build.directory}/jmeter")
protected transient File workDir;
protected File binDir;
protected File libDir;
protected File libExtDir;
protected File logsDir;
protected File resultsDir;
/**
* All property files are stored in this artifact, comes with JMeter library
*/
protected final String jmeterConfigArtifact = "ApacheJMeter_config";
protected JMeterArgumentsArray testArgs;
protected PropertyHandler pluginProperties;
protected boolean resultsOutputIsCSVFormat = false;
/**
* Generate the directory tree utilised by JMeter.
*/
@SuppressWarnings("ResultOfMethodCallIgnored")
protected void generateJMeterDirectoryTree() {
logsDir = new File(workDir, "logs");
logsDir.mkdirs();
binDir = new File(workDir, "bin");
binDir.mkdirs();
resultsDir = new File(workDir, "results");
resultsDir.mkdirs();
libDir = new File(workDir, "lib");
libExtDir = new File(libDir, "ext");
libExtDir.mkdirs();
//JMeter expects a <workdir>/lib/junit directory and complains if it can't find it.
new File(libDir, "junit").mkdirs();
}
protected void propertyConfiguration() throws MojoExecutionException {
pluginProperties = new PropertyHandler(testFilesDirectory, binDir, getArtifactNamed(jmeterConfigArtifact), propertiesReplacedByCustomFiles);
pluginProperties.setJMeterProperties(propertiesJMeter);
pluginProperties.setJMeterGlobalProperties(propertiesGlobal);
pluginProperties.setJMeterSaveServiceProperties(propertiesSaveService);
pluginProperties.setJMeterUpgradeProperties(propertiesUpgrade);
pluginProperties.setJmeterUserProperties(propertiesUser);
pluginProperties.setJMeterSystemProperties(propertiesSystem);
pluginProperties.configureJMeterPropertiesFiles();
pluginProperties.setDefaultPluginProperties(binDir.getAbsolutePath());
}
/**
* Create the JMeter directory tree and copy all compile time JMeter dependencies into it.
* Generic compile time artifacts are copied into the libDir
* ApacheJMeter_* artifacts are copied into the libExtDir
* Runtime dependencies set by the user are also copied into the libExtDir
*
* @throws MojoExecutionException
*/
protected void populateJMeterDirectoryTree() throws MojoExecutionException {
for (Artifact artifact : pluginArtifacts) {
try {
if (Artifact.SCOPE_COMPILE.equals(artifact.getScope()) || Artifact.SCOPE_RUNTIME.equals(artifact.getScope())) {
if (artifact.getArtifactId().equals(jmeterConfigArtifact)) {
extractConfigSettings(artifact);
} else if (artifact.getArtifactId().equals("ApacheJMeter")) {
copyFile(artifact.getFile(), new File(binDir + File.separator + artifact.getArtifactId() + ".jar"));
} else if (artifact.getArtifactId().startsWith("ApacheJMeter_")) {
copyFile(artifact.getFile(), new File(libExtDir + File.separator + artifact.getFile().getName()));
} else if (isArtifactAJMeterDependency(artifact)) {
copyFile(artifact.getFile(), new File(libDir + File.separator + artifact.getFile().getName()));
} else if (isArtifactAnExplicitDependency(artifact)) {
if (isArtifactMarkedAsAJMeterPlugin(artifact)) {
copyFile(artifact.getFile(), new File(libExtDir + File.separator + artifact.getFile().getName()));
} else {
copyFile(artifact.getFile(), new File(libDir + File.separator + artifact.getFile().getName()));
}
}
}
} catch (IOException e) {
throw new MojoExecutionException("Unable to populate the JMeter directory tree: " + e);
}
}
}
/**
* Extract the configuration settings (not properties files) form the configuration artifact and load them into the /bin directory
*
* @param artifact Configuration artifact
* @throws IOException
*/
private void extractConfigSettings(Artifact artifact) throws IOException {
JarFile configSettings = new JarFile(artifact.getFile());
Enumeration<JarEntry> entries = configSettings.entries();
while (entries.hasMoreElements()) {
JarEntry jarFileEntry = entries.nextElement();
// Only interested in files in the /bin directory that are not properties files
if (!jarFileEntry.isDirectory() && jarFileEntry.getName().startsWith("bin") && !jarFileEntry.getName().endsWith(".properties")) {
copyInputStreamToFile(configSettings.getInputStream(jarFileEntry), new File(workDir.getCanonicalPath() + File.separator + jarFileEntry.getName()));
}
}
configSettings.close();
}
protected boolean isArtifactMarkedAsAJMeterPlugin(Artifact artifact) {
for (JMeterPlugins identifiedPlugin : jmeterPlugins) {
if (identifiedPlugin.toString().equals(artifact.getGroupId() + ":" + artifact.getArtifactId())) {
return true;
}
}
return false;
}
/**
* Check if the given artifact is needed by an explicit dependency (a dependency, that is explicitly defined in
* the pom of the project using the jmeter-maven-plugin).
* <p/>
* For example, consider the following pom:
* <p/>
* <code>
* <plugin>
* <groupId>com.lazerycode.jmeter</groupId>
* <artifactId>jmeter-maven-plugin</artifactId>
* <dependencies>
* <dependency>
* <groupId>kg.apc</groupId>
* <artifactId>jmeter-plugins</artifactId>
* </dependency>
* </dependencies>
* </plugin>
* </code>
* <p/>
* <p/>
* Now kg.apc:jmeter-plugins is an explicit dependency. And org.apache.jmeter:jorphan is a needed by this explicit dependency, so
* isArtifactAnExplicitDependency(org.apache.jmeter:jorphan) would return true.
*
* @param artifact Artifact to examine
* @return true if the given artifact is needed by a explicit dependency.
*/
protected boolean isArtifactAnExplicitDependency(Artifact artifact) {
for (int i = 0; i < pluginDependencies.size(); i++) {
Dependency dependency = pluginDependencies.get(i);
if (dependency.getGroupId().equals(artifact.getGroupId())
&& dependency.getArtifactId().equals(artifact.getArtifactId())
&& dependency.getVersion().equals(artifact.getVersion())) {
return true;
}
}
return false;
}
/**
* Work out if an artifact is a JMeter dependency
*
* @param artifact Artifact to examine
* @return true if a Jmeter dependency, false if a plugin dependency.
*/
protected boolean isArtifactAJMeterDependency(Artifact artifact) {
for (String dependency : artifact.getDependencyTrail()) {
if (dependency.contains("org.apache.jmeter:ApacheJMeter")) {
return true;
}
}
return false;
}
/**
* Search the list of plugin artifacts for an artifact with a specific name
*
* @param artifactName
* @return
* @throws MojoExecutionException
*/
protected Artifact getArtifactNamed(String artifactName) throws MojoExecutionException {
for (Artifact artifact : pluginArtifacts) {
if (artifact.getArtifactId().equals(artifactName)) {
return artifact;
}
}
throw new MojoExecutionException("Unable to find artifact '" + artifactName + "'!");
}
/**
* Generate the initial JMeter Arguments array that is used to create the command line that we pass to JMeter.
*
* @throws MojoExecutionException
*/
protected void initialiseJMeterArgumentsArray(boolean disableGUI) throws MojoExecutionException {
testArgs = new JMeterArgumentsArray(disableGUI, workDir.getAbsolutePath());
testArgs.setResultsDirectory(resultsDir.getAbsolutePath());
testArgs.setResultFileOutputFormatIsCSV(resultsOutputIsCSVFormat);
if (testResultsTimestamp) {
testArgs.setResultsTimestamp(testResultsTimestamp);
testArgs.appendTimestamp(appendResultsTimestamp);
if (isSet(resultsFileNameDateFormat)) {
try {
testArgs.setResultsFileNameDateFormat(DateTimeFormat.forPattern(resultsFileNameDateFormat));
} catch (Exception ex) {
getLog().error("'" + resultsFileNameDateFormat + "' is an invalid DateTimeFormat. Defaulting to Standard ISO_8601.");
}
}
}
testArgs.setProxyConfig(proxyConfig);
testArgs.setACustomPropertiesFile(customPropertiesFile);
testArgs.setLogRootOverride(overrideRootLogLevel);
testArgs.setLogsDirectory(logsDir.getAbsolutePath());
}
protected void setJMeterResultFileFormat() {
if (resultsFileFormat.toLowerCase().equals("csv")) {
propertiesJMeter.put("jmeter.save.saveservice.output_format", "csv");
resultsOutputIsCSVFormat = true;
} else {
propertiesJMeter.put("jmeter.save.saveservice.output_format", "xml");
resultsOutputIsCSVFormat = false;
}
}
}
|
package iluxonchik.github.io.markitdown;
import android.provider.BaseColumns;
public final class MarkItDownDbContract {
public static final String DB_NAME = "MarkItDown.db";
public static final int DB_VERSION = 1;
private static final String TEXT_TYPE = " TEXT";
private static final String INTEGER_TYPE = " INTEGER";
private static final String COMMA_SEP = ",";
// Prevent someone from accidentally instantiating the class
private MarkItDownDbContract() {}
public static abstract class Colors implements BaseColumns {
public static final String TABLE_NAME = "Colors";
public static final String COLUMN_NAME_COLOR_HEX = "ColorHex";
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " ("
+ _ID + INTEGER_TYPE + " PRIMARY KEY AUTOINCREMENT" + COMMA_SEP
+ COLUMN_NAME_COLOR_HEX + TEXT_TYPE
+ ");";
}
public static abstract class Tags implements BaseColumns {
public static final String TABLE_NAME = "Tags";
public static final String COLUMN_NAME_TITLE = "Title";
public static final String COLUMN_NAME_COLOR = "Color";
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " ("
+ _ID + INTEGER_TYPE + " PRIMARY KEY AUTOINCREMENT" + COMMA_SEP
+ COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP
+ COLUMN_NAME_COLOR + INTEGER_TYPE + " REFERENCES " + Colors.TABLE_NAME + "(_id)"
+ ");";
}
public static abstract class Notebooks implements BaseColumns {
public static final String TABLE_NAME = "Notebooks";
public static final String COLUMN_NAME_TITLE = "Title";
public static final String COLUMN_NAME_COLOR = "Color";
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " ("
+ _ID + INTEGER_TYPE + " PRIMARY KEY AUTOINCREMENT" + COMMA_SEP
+ COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP
+ COLUMN_NAME_COLOR + INTEGER_TYPE + " REFERENCES " + Colors.TABLE_NAME + "(_id)"
+ ");";
}
public static abstract class Notes implements BaseColumns {
public static final String TABLE_NAME = "Notes";
public static final String COLUMN_NAME_TITLE = "Title";
public static final String COLUMN_NAME_TEXT_MARKDOWN = "TextMD";
public static final String COLUMN_NAME_TEXT_HTML = "TextHTML";
public static final String COLUMN_NAME_NOTEBOOK = "Notebook";
public static final String COLUMN_NAME_TAGS = "Tags";
public static final String COLUMN_NAME_EDITED = "Edited";
public static final String COLUMN_NAME_DATE_SAVED = "DateSaved";
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " ("
+ _ID + INTEGER_TYPE + " PRIMARY KEY AUTOINCREMENT" + COMMA_SEP
+ COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP
+ COLUMN_NAME_TEXT_MARKDOWN + TEXT_TYPE + COMMA_SEP
+ COLUMN_NAME_TEXT_HTML + TEXT_TYPE + COMMA_SEP
+ COLUMN_NAME_NOTEBOOK + INTEGER_TYPE +" REFERENCES " + Notebooks.TABLE_NAME + "(_id)" + COMMA_SEP
+ COLUMN_NAME_TAGS + TEXT_TYPE + COMMA_SEP
+ COLUMN_NAME_DATE_SAVED + INTEGER_TYPE + COMMA_SEP
+ COLUMN_NAME_EDITED + INTEGER_TYPE
+ ");";
}
}
|
package com.orhanobut.wasp;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* @author Orhan Obut
*/
final class NetworkHandler implements InvocationHandler {
private static final String TAG = NetworkHandler.class.getSimpleName();
private final Map<String, MethodInfo> methodInfoCache = new LinkedHashMap<>();
private final Class<?> service;
private final NetworkStack networkStack;
private final Parser parser;
private final String endPoint;
private final ClassLoader classLoader;
private final RequestInterceptor requestInterceptor;
private NetworkHandler(Class<?> service, Wasp.Builder builder) {
this.service = service;
this.networkStack = builder.getNetworkStack();
this.parser = builder.getParser();
this.endPoint = builder.getEndPointUrl();
this.requestInterceptor = builder.getRequestInterceptor();
ClassLoader loader = service.getClassLoader();
this.classLoader = loader != null ? loader : ClassLoader.getSystemClassLoader();
}
public static NetworkHandler newInstance(Class<?> service, Wasp.Builder builder) {
return new NetworkHandler(service, builder);
}
Object getProxyClass() {
List<Method> methods = getMethods(service);
fillMethods(methods);
return Proxy.newProxyInstance(classLoader, new Class[]{service}, this);
}
private static List<Method> getMethods(Class<?> service) {
List<Method> result = new ArrayList<>();
// try {
// // result.add(Object.class.getMethod("equals", Object.class));
// // result.add(Object.class.getMethod("hashCode", Object.class));
// // result.add(Object.class.getMethod("toString", Object.class));
// } catch (NoSuchMethodException e) {
// throw new AssertionError();
getMethodsRecursive(service, result);
return result;
}
/**
* Fills {@code proxiedMethods} with the methods of {@code interfaces} and
* the interfaces they extend. May contain duplicates.
*/
private static void getMethodsRecursive(Class<?> service, List<Method> methods) {
Collections.addAll(methods, service.getDeclaredMethods());
}
private void fillMethods(List<Method> methods) {
for (Method method : methods) {
MethodInfo methodInfo = MethodInfo.newInstance(method);
methodInfoCache.put(method.getName(), methodInfo);
}
}
@Override
public Object invoke(Object proxy, final Method method, Object[] args) throws Throwable {
Logger.d("Proxy method invoked");
if (args.length == 0) {
throw new IllegalArgumentException("Callback must be sent as param");
}
Object lastArg = args[args.length - 1];
if (!(lastArg instanceof CallBack)) {
throw new IllegalArgumentException("Last param must be type of CallBack<T>");
}
final CallBack<?> callBack = (CallBack<?>) lastArg;
final MethodInfo methodInfo = methodInfoCache.get(method.getName());
WaspRequest waspRequest = new WaspRequest.Builder(methodInfo, args, endPoint, parser)
.setRequestInterceptor(requestInterceptor)
.build();
Logger.d(waspRequest.toString());
networkStack.invokeRequest(waspRequest, new CallBack<String>() {
@Override
public void onSuccess(String content) {
Logger.d("Response: " + content);
Object result = parser.fromJson(content, methodInfo.getResponseObjectType());
new ResponseWrapper(callBack, result).submitResponse();
}
@Override
public void onError(WaspError error) {
Logger.d(error.toString());
callBack.onError(error);
}
});
return null;
}
}
|
package com.example.spartahack.spartahack2016.Fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.spartahack.spartahack2016.Adapters.EventListAdapter;
import com.example.spartahack.spartahack2016.Adapters.SimpleSectionedRecyclerViewAdapter;
import com.example.spartahack.spartahack2016.Model.Event;
import com.example.spartahack.spartahack2016.R;
import com.example.spartahack.spartahack2016.Retrofit.GSONMock;
import com.example.spartahack.spartahack2016.Retrofit.ParseAPIService;
import org.joda.time.DateTime;
import org.joda.time.DateTimeComparator;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
/**
* A simple {@link Fragment} subclass.
*/
public class ScheduleFragment extends BaseFragment {
/** Recycler view that displays all objects */
@Bind(android.R.id.list) RecyclerView recyclerView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_schedule, container, false);
ButterKnife.bind(this, v);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
ParseAPIService.INSTANCE.getRestAdapter().getSchedule()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<GSONMock.Schedules>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
Log.e("ScheduleFragment", e.toString());
}
@Override
public void onNext(GSONMock.Schedules schedules) {
ArrayList<Event> events = schedules.events;
// TODO: 1/5/16 fix this being empty
if (events == null || events.isEmpty())
return;
Collections.sort(events, new Comparator<Event>() {
@Override
public int compare(Event lhs, Event rhs) {
return DateTimeComparator.getInstance().compare(lhs.getTime(), rhs.getTime());
}
});
EventListAdapter eventListAdapter = new EventListAdapter(getActivity(), events);
ArrayList<SimpleSectionedRecyclerViewAdapter.Section> sections = new ArrayList<>();
DateTime date = events.get(0).getTime();
SimpleDateFormat formatDate = new SimpleDateFormat("EEEE");
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(0, formatDate.format(events.get(0).getTime().toDate())));
// location the header should go at
int sectionLoc = 0;
for (Event e : events){
if (DateTimeComparator.getDateOnlyInstance().compare(e.getTime(), date) == 1){
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(sectionLoc, formatDate.format(e.getTime().toDate())));
date = e.getTime();
}
sectionLoc++;
}
SimpleSectionedRecyclerViewAdapter.Section[] dummy = new SimpleSectionedRecyclerViewAdapter.Section[sections.size()];
SimpleSectionedRecyclerViewAdapter adapter = new SimpleSectionedRecyclerViewAdapter(getActivity(), R.layout.date_section, R.id.section_text, eventListAdapter);
adapter.setSections(sections.toArray(dummy));
recyclerView.setAdapter(adapter);
}
});
return v;
}
}
|
package com.pump.showcase;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.net.URL;
import javax.swing.JCheckBox;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import com.pump.plaf.button.MixedCheckBoxState;
public class MixedCheckBoxStateDemo extends ShowcaseExampleDemo {
JCheckBox allCheckBox = new JCheckBox("All condiments");
JCheckBox lettuceCheckBox = new JCheckBox("Lettuce");
JCheckBox tomatoCheckBox = new JCheckBox("Tomato", true);
JCheckBox mustardCheckBox = new JCheckBox("Mustard", true);
ChangeListener allListener = new ChangeListener() {
boolean wasSelected = allCheckBox.isSelected();
@Override
public void stateChanged(ChangeEvent e) {
boolean isSelected = allCheckBox.isSelected();
if(wasSelected != isSelected) {
isSelected = wasSelected;
lettuceCheckBox.removeChangeListener(individualListener);
tomatoCheckBox.removeChangeListener(individualListener);
mustardCheckBox.removeChangeListener(individualListener);
try {
if (allCheckBox.isSelected()) {
lettuceCheckBox.setSelected(true);
tomatoCheckBox.setSelected(true);
mustardCheckBox.setSelected(true);
} else {
lettuceCheckBox.setSelected(false);
tomatoCheckBox.setSelected(false);
mustardCheckBox.setSelected(false);
MixedCheckBoxState.setMixed(allCheckBox, false);
}
} finally {
lettuceCheckBox.addChangeListener(individualListener);
tomatoCheckBox.addChangeListener(individualListener);
mustardCheckBox.addChangeListener(individualListener);
}
}
}
};
ChangeListener individualListener = new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
allCheckBox.removeChangeListener(allListener);
try {
int selected = 0;
if (lettuceCheckBox.isSelected())
selected++;
if (tomatoCheckBox.isSelected())
selected++;
if (mustardCheckBox.isSelected())
selected++;
if (selected == 3) {
allCheckBox.setSelected(true);
} else {
allCheckBox.setSelected(false);
MixedCheckBoxState.setMixed(allCheckBox, selected > 0);
}
} finally {
allCheckBox.addChangeListener(allListener);
}
}
};
public MixedCheckBoxStateDemo() {
lettuceCheckBox.setOpaque(false);
tomatoCheckBox.setOpaque(false);
mustardCheckBox.setOpaque(false);
allCheckBox.setOpaque(false);
configurationPanel.setVisible(false);
configurationLabel.setVisible(false);
examplePanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
c.weighty = 1;
c.insets = new Insets(2, 2, 2, 2);
c.fill = GridBagConstraints.HORIZONTAL;
examplePanel.add(allCheckBox, c);
c.insets = new Insets(2, 20, 2, 2);
c.gridy++;
examplePanel.add(lettuceCheckBox, c);
c.gridy++;
examplePanel.add(tomatoCheckBox, c);
c.gridy++;
examplePanel.add(mustardCheckBox, c);
lettuceCheckBox.addChangeListener(individualListener);
tomatoCheckBox.addChangeListener(individualListener);
mustardCheckBox.addChangeListener(individualListener);
individualListener.stateChanged(null);
}
@Override
public String getTitle() {
return "MixedCheckBoxState Demo";
}
@Override
public String getSummary() {
return "This demonstrates the MixedCheckBoxState's ability to render a JCheckBox in a mixed state.";
}
@Override
public URL getHelpURL() {
return getClass().getResource("mixedCheckBoxDemo.html");
}
@Override
public String[] getKeywords() {
return new String[] { "mixed state", "checkbox", "ui", "ux" };
}
@Override
public Class<?>[] getClasses() {
return new Class[] { MixedCheckBoxState.class };
}
}
|
package com.scwang.refreshlayout.activity.using;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SnapHelper;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.scwang.refreshlayout.R;
import com.scwang.refreshlayout.adapter.BaseRecyclerAdapter;
import com.scwang.refreshlayout.adapter.SmartViewHolder;
import java.util.Arrays;
import java.util.Collection;
public class SnapHelperUsingActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_using_snaphelper);
final Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
View view = findViewById(R.id.recyclerView);
if (view instanceof RecyclerView) {
RecyclerView recyclerView = (RecyclerView) view;
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(new BaseRecyclerAdapter<Integer>(loadModels(), R.layout.listitem_using_snaphelper) {
@Override
protected void onBindViewHolder(SmartViewHolder holder, Integer model, int position) {
holder.image(R.id.imageView, model);
}
});
SnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
}
}
private Collection<Integer> loadModels() {
return Arrays.asList(
R.mipmap.image_weibo_home_1,
R.mipmap.image_weibo_home_2,
R.mipmap.image_weibo_home_1,
R.mipmap.image_weibo_home_2,
R.mipmap.image_weibo_home_1,
R.mipmap.image_weibo_home_2);
}
}
|
package com.redhat.ceylon.compiler.js;
import static com.redhat.ceylon.compiler.typechecker.tree.TreeUtil.formatPath;
import static com.redhat.ceylon.compiler.typechecker.tree.TreeUtil.getNativeBackend;
import static com.redhat.ceylon.compiler.typechecker.tree.TreeUtil.isForBackend;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.redhat.ceylon.cmr.api.ArtifactContext;
import com.redhat.ceylon.cmr.api.ArtifactCreator;
import com.redhat.ceylon.cmr.api.RepositoryManager;
import com.redhat.ceylon.cmr.ceylon.CeylonUtils;
import com.redhat.ceylon.cmr.impl.ShaSigner;
import com.redhat.ceylon.common.Backend;
import com.redhat.ceylon.common.FileUtil;
import com.redhat.ceylon.common.log.Logger;
import com.redhat.ceylon.compiler.js.util.JsIdentifierNames;
import com.redhat.ceylon.compiler.js.util.JsLogger;
import com.redhat.ceylon.compiler.js.util.JsOutput;
import com.redhat.ceylon.compiler.js.util.Options;
import com.redhat.ceylon.compiler.typechecker.TypeChecker;
import com.redhat.ceylon.compiler.typechecker.analyzer.AnalysisError;
import com.redhat.ceylon.compiler.typechecker.analyzer.UsageWarning;
import com.redhat.ceylon.compiler.typechecker.analyzer.Warning;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.parser.RecognitionError;
import com.redhat.ceylon.compiler.typechecker.tree.AnalysisMessage;
import com.redhat.ceylon.compiler.typechecker.tree.Message;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.ImportModule;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.ModuleDescriptor;
import com.redhat.ceylon.compiler.typechecker.tree.TreeUtil;
import com.redhat.ceylon.compiler.typechecker.tree.UnexpectedError;
import com.redhat.ceylon.compiler.typechecker.tree.Visitor;
import com.redhat.ceylon.compiler.typechecker.util.WarningSuppressionVisitor;
import com.redhat.ceylon.model.typechecker.model.Declaration;
import com.redhat.ceylon.model.typechecker.model.Import;
import com.redhat.ceylon.model.typechecker.model.ImportableScope;
import com.redhat.ceylon.model.typechecker.model.ModelUtil;
import com.redhat.ceylon.model.typechecker.model.Module;
import com.redhat.ceylon.model.typechecker.model.ModuleImport;
import com.redhat.ceylon.model.typechecker.model.Package;
import com.redhat.ceylon.model.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.model.typechecker.model.Unit;
public class JsCompiler {
protected final TypeChecker tc;
protected final Options opts;
protected final RepositoryManager outRepo;
private boolean stopOnErrors = true;
private int errCount = 0;
protected Set<Message> errors = new HashSet<Message>();
protected Set<Message> unitErrors = new HashSet<Message>();
protected List<File> srcFiles;
protected List<File> resFiles;
private final Map<Module, JsOutput> output = new HashMap<Module, JsOutput>();
//You have to manually set this when compiling the language module
static boolean compilingLanguageModule;
private int exitCode = 0;
private Logger logger;
private JsIdentifierNames names;
public int getExitCode() {
return exitCode;
}
private final Visitor unitVisitor = new Visitor() {
private boolean hasErrors(Node that) {
boolean r=false;
for (Message m: that.getErrors()) {
unitErrors.add(m);
r |= m instanceof AnalysisError;
}
return r;
}
@Override
public void visitAny(Node that) {
super.visitAny(that);
hasErrors(that);
}
@Override
public void visit(Tree.Declaration that) {
if (isForBackend(that.getAnnotationList(), Backend.JavaScript, that.getUnit())) {
super.visit(that);
}
}
@Override
public void visit(Tree.Import that) {
if (hasErrors(that)) {
exitCode = 1;
return;
}
super.visit(that);
}
@Override
public void visit(Tree.ImportMemberOrType that) {
if (hasErrors(that)) return;
Import importModel = that.getImportModel();
if (that.getImportModel() == null) {
return;
}
Declaration importedDeclaration = nativeImplToJavascript(importModel.getDeclaration());
if (importedDeclaration == null) {
return;
}
Unit importedDeclarationUnit = importedDeclaration.getUnit();
if (importedDeclarationUnit != null && nonCeylonUnit(importedDeclarationUnit)) {
if (!providedByAJavaNativeModuleImport(that.getUnit(), importedDeclarationUnit)) {
that.addUnexpectedError("cannot import Java declarations in Javascript", Backend.JavaScript);
}
}
super.visit(that);
}
@Override
public void visit(Tree.ImportModule that) {
if (hasErrors(that)) {
exitCode = 1;
} else {
boolean isJavaModule = false;
String importNativeBackend = null;
String moduleNativeBackend = null;
if (that.getImportPath() != null && that.getImportPath().getModel() instanceof Module) {
Module importedModule = (Module) that.getImportPath().getModel();
if (importedModule.isJava()) {
isJavaModule = true;
moduleNativeBackend = importedModule.getNativeBackend();
}
}
if (that.getQuotedLiteral() != null) {
isJavaModule = true;
}
if (isJavaModule) {
importNativeBackend = TreeUtil.getNativeBackend(that.getAnnotationList(), that.getUnit());
if (!Backend.Java.nativeAnnotation.equals(importNativeBackend)
&& !Backend.Java.nativeAnnotation.equals(moduleNativeBackend)) {
that.getImportPath().addUnexpectedError("cannot import Java modules in Javascript", Backend.JavaScript);
}
} else {
super.visit(that);
}
}
}
private Declaration nativeImplToJavascript(Declaration declaration) {
if (declaration == null) {
return null;
}
if (declaration.isNative()) {
Declaration header = ModelUtil.getNativeHeader(declaration);
if (header != null) {
Declaration javaScriptDecl = ModelUtil.getNativeDeclaration(header, Backend.JavaScript);
if (javaScriptDecl != null) {
declaration = javaScriptDecl;
}
}
}
return declaration;
}
@Override
public void visit(Tree.BaseMemberOrTypeExpression that) {
if (hasErrors(that)) return;
Declaration declaration = nativeImplToJavascript(that.getDeclaration());
Unit declarationUnit = null;
if (declaration != null) {
declarationUnit = declaration.getUnit();
}
if (declarationUnit != null && nonCeylonUnit(declarationUnit)) {
if (!providedByAJavaNativeModuleImport(that.getUnit(), declarationUnit)) {
that.addUnexpectedError("cannot call Java declarations in Javascript", Backend.JavaScript);
}
}
super.visit(that);
}
@Override
public void visit(Tree.QualifiedMemberOrTypeExpression that) {
if (hasErrors(that)) return;
Declaration declaration = nativeImplToJavascript(that.getDeclaration());
Unit declarationUnit = null;
if (declaration != null) {
declarationUnit = declaration.getUnit();
}
if (declarationUnit != null && nonCeylonUnit(declarationUnit)) {
if (!providedByAJavaNativeModuleImport(that.getUnit(), declarationUnit)) {
that.addUnexpectedError("cannot call Java declarations in Javascript", Backend.JavaScript);
}
}
super.visit(that);
}
protected boolean providedByAJavaNativeModuleImport(
Unit currentUnit, Unit declarationUnit) {
boolean isFromAJavaNativeModuleImport;
Module declarationModule = declarationUnit.getPackage().getModule();
String moduleNativeBackend = declarationModule.getNativeBackend();
String importNativeBackend = null;
for(ModuleImport moduleImport : currentUnit.getPackage().getModule().getImports()) {
if (declarationModule.equals(moduleImport.getModule())) {
importNativeBackend = moduleImport.getNativeBackend();
break;
}
}
isFromAJavaNativeModuleImport = Backend.Java.nativeAnnotation.equals(importNativeBackend)
|| Backend.Java.nativeAnnotation.equals(moduleNativeBackend);
return isFromAJavaNativeModuleImport;
}
};
public JsCompiler(TypeChecker tc, Options options) {
this.tc = tc;
opts = options;
outRepo = CeylonUtils.repoManager()
.cwd(options.getCwd())
.outRepo(options.getOutRepo())
.user(options.getUser())
.password(options.getPass())
.buildOutputManager();
logger = opts.getLogger();
if(logger == null) {
logger = new JsLogger(opts);
}
}
private boolean isURL(String path) {
try {
new URL(path);
return true;
} catch (MalformedURLException e) {
return false;
}
}
/** Specifies whether the compiler should stop when errors are found in a compilation unit (default true). */
public JsCompiler stopOnErrors(boolean flag) {
stopOnErrors = flag;
return this;
}
/** Sets the names of the files to compile. By default this is null, which means all units from the typechecker
* will be compiled. */
public void setSourceFiles(List<File> files) {
this.srcFiles = files;
}
/** Sets the names of the resources to pack with the compiler output. */
public void setResourceFiles(List<File> files) {
this.resFiles = files;
}
public Set<Message> listErrors() {
return getErrors();
}
/** Compile one phased unit.
* @return The errors found for the unit. */
public void compileUnit(PhasedUnit pu, JsIdentifierNames names) throws IOException {
unitErrors.clear();
pu.getCompilationUnit().visit(unitVisitor);
if (exitCode != 0) {
errors.addAll(unitErrors);
return;
}
if (errCount == 0 || !stopOnErrors) {
if (opts.isVerbose()) {
logger.debug("Compiling "+pu.getUnitFile().getPath()+" to JS");
}
//Perform capture analysis
for (com.redhat.ceylon.model.typechecker.model.Declaration d : pu.getDeclarations()) {
if (d instanceof TypedDeclaration && d instanceof com.redhat.ceylon.model.typechecker.model.Setter == false) {
pu.getCompilationUnit().visit(new ValueVisitor((TypedDeclaration)d));
}
}
JsOutput jsout = getOutput(pu);
GenerateJsVisitor jsv = new GenerateJsVisitor(jsout, opts, names, pu.getTokens());
pu.getCompilationUnit().visit(jsv);
pu.getCompilationUnit().visit(unitVisitor);
if (jsv.getExitCode() != 0) {
exitCode = jsv.getExitCode();
}
}
}
/** Indicates if compilation should stop, based on whether there were errors
* in the last compilation unit and the stopOnErrors flag is set. */
protected boolean stopOnError() {
for (Message err : unitErrors) {
if (err instanceof AnalysisError ||
err instanceof UnexpectedError) {
errCount++;
}
errors.add(err);
}
return stopOnErrors && errCount > 0;
}
/** Compile all the phased units in the typechecker.
* @return true is compilation was successful (0 errors/warnings), false otherwise. */
public boolean generate() throws IOException {
errors.clear();
errCount = 0;
output.clear();
try {
if (opts.isVerbose()) {
logger.debug("Generating metamodel...");
}
List<PhasedUnit> typecheckerPhasedUnits = tc.getPhasedUnits().getPhasedUnits();
List<PhasedUnit> phasedUnits = new ArrayList<>(typecheckerPhasedUnits.size());
for (PhasedUnit pu : typecheckerPhasedUnits) {
if (srcFiles == null) {
phasedUnits.add(pu);
} else {
File path = getFullPath(pu);
if (FileUtil.containsFile(srcFiles, path)) {
phasedUnits.add(pu);
}
}
}
boolean generatedCode = false;
checkInvalidNativePUs(phasedUnits);
//First generate the metamodel
final Module defmod = tc.getContext().getModules().getDefaultModule();
for (PhasedUnit pu: phasedUnits) {
//#416 default module with packages
Module mod = pu.getPackage().getModule();
if (mod.getVersion() == null && !mod.isDefault()) {
//Switch with the default module
for (com.redhat.ceylon.model.typechecker.model.Package pkg : mod.getPackages()) {
defmod.getPackages().add(pkg);
pkg.setModule(defmod);
}
}
if (opts.getSuppressWarnings() != null) {
pu.getCompilationUnit().visit(
new WarningSuppressionVisitor<Warning>(Warning.class, opts.getSuppressWarnings()));
}
pu.getCompilationUnit().visit(getOutput(pu).mmg);
if (opts.hasVerboseFlag("ast")) {
if (opts.getOutWriter() == null) {
logger.debug(pu.getCompilationUnit().toString());
} else {
opts.getOutWriter().write(pu.getCompilationUnit().toString());
opts.getOutWriter().write('\n');
}
}
}
//Then write it out and output the reference in the module file
names = new JsIdentifierNames();
if (!compilingLanguageModule) {
for (Map.Entry<Module,JsOutput> e : output.entrySet()) {
e.getValue().encodeModel(names);
}
}
checkInvalidNativeImports(phasedUnits);
//Output all the require calls for any imports
final Visitor importVisitor = new Visitor() {
public void visit(Tree.Import that) {
ImportableScope scope =
that.getImportMemberOrTypeList().getImportList().getImportedScope();
Module _m = that.getUnit().getPackage().getModule();
if (scope instanceof Package && !((Package)scope).getModule().equals(_m)) {
output.get(_m).require(((Package) scope).getModule(), names);
}
}
};
for (PhasedUnit pu: phasedUnits) {
pu.getCompilationUnit().visit(importVisitor);
}
//Then generate the JS code
if (srcFiles == null && !phasedUnits.isEmpty()) {
for (PhasedUnit pu: phasedUnits) {
compileUnit(pu, names);
generatedCode = true;
if (exitCode != 0) {
return false;
}
if (stopOnError()) {
logger.error("Errors found. Compilation stopped.");
break;
}
getOutput(pu).addSource(getFullPath(pu));
}
} else if(srcFiles != null && !srcFiles.isEmpty()
// For the specific case of the Stitcher
&& !typecheckerPhasedUnits.isEmpty() ){
PhasedUnit lastUnit;
if (phasedUnits.isEmpty()) {
// For the specific case of the Stitcher
lastUnit = typecheckerPhasedUnits.get(0);
} else {
lastUnit = phasedUnits.get(0);
}
for (File path : srcFiles) {
if (path.getPath().endsWith(ArtifactContext.JS)) {
//Just output the file
final JsOutput lastOut = getOutput(lastUnit);
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
String line = null;
while ((line = reader.readLine()) != null) {
if (opts.isMinify()) {
line = line.trim();
if (!opts.isComment() && line.startsWith("//") && !line.contains("*/")) {
continue;
}
}
if (line.length()==0) {
continue;
}
lastOut.getWriter().write(line);
lastOut.getWriter().write('\n');
}
} finally {
lastOut.addSource(path);
}
generatedCode = true;
} else {
//Find the corresponding compilation unit
for (PhasedUnit pu : phasedUnits) {
File unitFile = getFullPath(pu);
if (FileUtil.sameFile(path, unitFile)) {
compileUnit(pu, names);
generatedCode = true;
if (exitCode != 0) {
return false;
}
if (stopOnError()) {
logger.error("Errors found. Compilation stopped.");
return false;
}
getOutput(pu).addSource(unitFile);
lastUnit = pu;
}
}
}
}
}
if(!generatedCode){
logger.error("No source units found to compile");
exitCode = 2;
}
} finally {
if (exitCode==0) {
finish();
}
}
return errCount == 0 && exitCode == 0;
}
public File getFullPath(PhasedUnit pu) {
return new File(pu.getUnit().getFullPath());
}
private void checkInvalidNativePUs(List<PhasedUnit> phasedUnits) {
for (PhasedUnit pu : phasedUnits) {
ModuleDescriptor md = pu.findModuleDescriptor();
if (md != null) {
String be = getNativeBackend(md.getAnnotationList(), md.getUnit());
if (be != null) {
if (be.isEmpty()) {
md.addError("missing backend argument for native annotation on module: " + formatPath(md.getImportPath().getIdentifiers()), Backend.JavaScript);
} else if (!isForBackend(be, Backend.JavaScript)) {
md.addError("module not meant for this backend: " + formatPath(md.getImportPath().getIdentifiers()), Backend.JavaScript);
}
}
}
}
}
private void checkInvalidNativeImports(List<PhasedUnit> phasedUnits) {
for (PhasedUnit pu : phasedUnits) {
ModuleDescriptor md = pu.findModuleDescriptor();
if (md != null) {
for (ImportModule im : md.getImportModuleList().getImportModules()) {
String be = getNativeBackend(im.getAnnotationList(), im.getUnit());
if (im.getImportPath() != null) {
Module m = (Module)im.getImportPath().getModel();
if (be != null && m.isNative() && !be.equals(m.getNativeBackend())) {
im.addError("native backend name conflicts with imported module: '\"" +
be + "\"' is not '\"" + m.getNativeBackend() + "\"'", Backend.JavaScript);
}
}
}
}
}
}
/** Creates a JsOutput if needed, for the PhasedUnit.
* Right now it's one file per module. */
private JsOutput getOutput(PhasedUnit pu) throws IOException {
Module mod = pu.getPackage().getModule();
JsOutput jsout = output.get(mod);
if (jsout==null) {
jsout = newJsOutput(mod);
output.put(mod, jsout);
if (opts.isModulify()) {
jsout.openWrapper();
}
}
return jsout;
}
/** This exists solely so that the web IDE can override it and use a different JsOutput */
protected JsOutput newJsOutput(Module m) throws IOException {
return new JsOutput(m, opts.getEncoding());
}
JsOutput getOutputForModule(Module m) {
return output.get(m);
}
JsIdentifierNames getNames() {
return names;
}
/** Closes all output writers and puts resulting artifacts in the output repo. */
protected void finish() throws IOException {
String outDir = opts.getOutRepo();
if(!isURL(outDir)){
File root = new File(outDir);
if (root.exists()) {
if (!(root.isDirectory() && root.canWrite())) {
logger.error("Cannot write to "+root+". Stop.");
exitCode = 1;
}
} else {
if (!root.mkdirs()) {
logger.error("Cannot create "+root+". Stop.");
exitCode = 1;
}
}
}
for (Map.Entry<Module,JsOutput> entry: output.entrySet()) {
JsOutput jsout = entry.getValue();
if (!compilingLanguageModule) {
jsout.publishUnsharedDeclarations(names);
}
if (opts.isModulify()) {
jsout.closeWrapper();
}
String moduleName = entry.getKey().getNameAsString();
String moduleVersion = entry.getKey().getVersion();
if(opts.getDiagnosticListener() != null)
opts.getDiagnosticListener().moduleCompiled(moduleName, moduleVersion);
//Create the JS file
final File jsart = jsout.close();
final File modart = jsout.getModelFile();
if (entry.getKey().isDefault()) {
logger.info("Created module "+moduleName);
} else if (!compilingLanguageModule) {
logger.info("Created module "+moduleName+"/"+moduleVersion);
}
if (compilingLanguageModule) {
ArtifactContext artifact = new ArtifactContext("delete", "me", ArtifactContext.JS);
artifact.setForceOperation(true);
outRepo.putArtifact(artifact, jsart);
} else {
final ArtifactContext artifact = new ArtifactContext(moduleName, moduleVersion, ArtifactContext.JS);
artifact.setForceOperation(true);
outRepo.putArtifact(artifact, jsart);
final ArtifactContext martifact = new ArtifactContext(moduleName, moduleVersion, ArtifactContext.JS_MODEL);
martifact.setForceOperation(true);
outRepo.putArtifact(martifact, modart);
//js file signature
ShaSigner.signArtifact(outRepo, artifact, jsart, logger);
ShaSigner.signArtifact(outRepo, martifact, modart, logger);
//Create the src archive
if (opts.isGenerateSourceArchive()) {
ArtifactCreator sac = CeylonUtils.makeSourceArtifactCreator(
outRepo,
opts.getSrcDirs(),
moduleName, moduleVersion,
opts.hasVerboseFlag("cmr"), logger);
sac.copy(FileUtil.filesToPathList(jsout.getSources()));
}
if (resFiles != null && !resFiles.isEmpty()) {
ArtifactCreator sac = CeylonUtils.makeResourceArtifactCreator(
outRepo,
opts.getSrcDirs(),
opts.getResourceDirs(),
opts.getResourceRootName(),
moduleName, moduleVersion,
opts.hasVerboseFlag("cmr"), logger);
sac.copy(FileUtil.filesToPathList(filterForModule(resFiles, opts.getResourceDirs(), moduleName)));
}
}
FileUtil.deleteQuietly(jsart);
if (modart!=null) FileUtil.deleteQuietly(modart);
}
}
private Collection<File> filterForModule(List<File> files, List<File> roots, String moduleName) {
ArrayList<File> result = new ArrayList<File>(files.size());
for (File f : files) {
String rel = FileUtil.relativeFile(roots, f.getPath());
if (rel.startsWith(moduleName + "/") || rel.startsWith(moduleName + "\\")
|| ("default".equals(moduleName) && !(rel.contains("/") || rel.contains("\\")))) {
result.add(f);
}
}
return result;
}
/** Print all the errors found during compilation to the specified stream.
* @throws IOException */
public int printErrors(Writer out) throws IOException {
int count = 0;
DiagnosticListener diagnosticListener = opts.getDiagnosticListener();
for (Message err: errors) {
final boolean suppress = err instanceof UsageWarning && ((UsageWarning)err).isSuppressed();
if (suppress) {
continue;
}
if (err instanceof UsageWarning) {
out.write("warning");
} else {
out.write("error");
}
out.write(String.format(" encountered [%s]", err.getMessage()));
if (err instanceof AnalysisMessage) {
Node n = ((AnalysisMessage)err).getTreeNode();
if(n != null)
n = TreeUtil.getIdentifyingNode(n);
out.write(String.format(" at %s of %s", n.getLocation(), n.getUnit().getFilename()));
} else if (err instanceof RecognitionError) {
RecognitionError rer = (RecognitionError)err;
out.write(String.format(" at %d:%d", rer.getLine(), rer.getCharacterInLine()));
}
out.write(System.lineSeparator());
count++;
if(diagnosticListener != null){
boolean warning = err instanceof UsageWarning;
int position = -1;
File file = null;
if(err instanceof AnalysisMessage){
Node node = ((AnalysisMessage) err).getTreeNode();
if(node != null)
node = TreeUtil.getIdentifyingNode(node);
if(node != null && node.getToken() != null)
position = node.getToken().getCharPositionInLine();
if(node.getUnit() != null && node.getUnit().getFullPath() != null)
file = new File(node.getUnit().getFullPath()).getAbsoluteFile();
}else if(err instanceof RecognitionError){
// FIXME: file??
position = ((RecognitionError) err).getCharacterInLine();
}
if(position != -1)
position++; // make it 1-based
if(warning)
diagnosticListener.warning(file, err.getLine(), position, err.getMessage());
else
diagnosticListener.error(file, err.getLine(), position, err.getMessage());
}
}
out.flush();
return count;
}
/** Returns the list of errors found during compilation. */
public Set<Message> getErrors() {
return Collections.unmodifiableSet(errors);
}
public void printErrorsAndCount(Writer out) throws IOException {
int count = printErrors(out);
out.write(String.format("%d %s.%n", count, count==1?"error":"errors"));
}
/** Writes the beginning of the wrapper function for a JS module. */
public static void beginWrapper(Writer writer) throws IOException {
writer.write("(function(define) { define(function(require, ex$, module) {\n");
}
/** Writes the ending of the wrapper function for a JS module. */
public static void endWrapper(Writer writer) throws IOException {
//Finish the wrapper
writer.write("});\n");
writer.write("}(typeof define==='function' && define.amd ? define : function (factory) {\n");
writer.write("if (typeof exports!=='undefined') { factory(require, exports, module);\n");
writer.write("} else { throw 'no module loader'; }\n");
writer.write("}));\n");
}
protected boolean nonCeylonUnit(Unit u) {
return (u.getFilename() != null && !(u.getFilename().isEmpty()||u.getFilename().endsWith(".ceylon")))
|| (u.getPackage() != null && u.getPackage().getModule() != null && u.getPackage().getModule().isJava());
}
/** Returns true if the compiler is currently compiling the language module. */
public static boolean isCompilingLanguageModule() {
return compilingLanguageModule;
}
/** Create a path for a require call to fetch the specified module. */
public static String scriptPath(Module mod) {
StringBuilder path = new StringBuilder(mod.getNameAsString().replace('.', '/')).append('/');
if (!mod.isDefault()) {
path.append(mod.getVersion()).append('/');
}
path.append(mod.getNameAsString());
if (!mod.isDefault()) {
path.append('-').append(mod.getVersion());
}
return path.toString();
}
}
|
package com.apptentive.android.sdk.conversation;
import com.apptentive.android.sdk.ApptentiveLog;
import com.apptentive.android.sdk.debug.Assert;
import com.apptentive.android.sdk.model.ApptentiveMessage;
import com.apptentive.android.sdk.module.messagecenter.model.MessageFactory;
import com.apptentive.android.sdk.serialization.SerializableObject;
import com.apptentive.android.sdk.storage.MessageStore;
import com.apptentive.android.sdk.util.StringUtils;
import com.apptentive.android.sdk.util.Util;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static com.apptentive.android.sdk.util.Util.readNullableBoolean;
import static com.apptentive.android.sdk.util.Util.readNullableDouble;
import static com.apptentive.android.sdk.util.Util.readNullableUTF;
import static com.apptentive.android.sdk.util.Util.writeNullableBoolean;
import static com.apptentive.android.sdk.util.Util.writeNullableDouble;
import static com.apptentive.android.sdk.util.Util.writeNullableUTF;
class FileMessageStore implements MessageStore {
/**
* Binary format version
*/
private static final byte VERSION = 1;
private final File file;
private final List<MessageEntry> messageEntries;
private boolean shouldFetchFromFile;
FileMessageStore(File file) {
this.file = file;
this.messageEntries = new ArrayList<>(); // we need a random access
this.shouldFetchFromFile = true; // we would lazily read it from a file later
}
//region MessageStore
@Override
public synchronized void addOrUpdateMessages(ApptentiveMessage... apptentiveMessages) {
fetchEntries();
for (ApptentiveMessage apptentiveMessage : apptentiveMessages) {
MessageEntry existing = findMessageEntry(apptentiveMessage);
if (existing != null) {
// Update
existing.id = apptentiveMessage.getId();
existing.state = apptentiveMessage.getState().name();
if (apptentiveMessage.isRead()) { // A apptentiveMessage can't be unread after being read.
existing.isRead = true;
}
existing.json = apptentiveMessage.toString();
} else {
// Insert
MessageEntry entry = new MessageEntry();
entry.id = apptentiveMessage.getId();
entry.clientCreatedAt = apptentiveMessage.getClientCreatedAt();
entry.nonce = apptentiveMessage.getNonce();
entry.state = apptentiveMessage.getState().name();
entry.isRead = apptentiveMessage.isRead();
entry.json = apptentiveMessage.toString();
messageEntries.add(entry);
}
}
writeToFile();
}
@Override
public synchronized void updateMessage(ApptentiveMessage apptentiveMessage) {
fetchEntries();
MessageEntry entry = findMessageEntry(apptentiveMessage);
if (entry != null) {
entry.id = apptentiveMessage.getId();
entry.clientCreatedAt = apptentiveMessage.getClientCreatedAt();
entry.nonce = apptentiveMessage.getNonce();
entry.state = apptentiveMessage.getState().name();
if (apptentiveMessage.isRead()) { // A apptentiveMessage can't be unread after being read.
entry.isRead = true;
}
entry.json = apptentiveMessage.getJsonObject().toString();
writeToFile();
}
}
@Override
public synchronized List<ApptentiveMessage> getAllMessages() throws Exception {
fetchEntries();
List<ApptentiveMessage> apptentiveMessages = new ArrayList<>();
for (MessageEntry entry : messageEntries) {
ApptentiveMessage apptentiveMessage = MessageFactory.fromJson(entry.json);
if (apptentiveMessage == null) {
ApptentiveLog.e("Error parsing Record json from database: %s", entry.json);
continue;
}
apptentiveMessage.setState(ApptentiveMessage.State.parse(entry.state));
apptentiveMessage.setRead(entry.isRead);
apptentiveMessages.add(apptentiveMessage);
}
return apptentiveMessages;
}
@Override
public synchronized String getLastReceivedMessageId() throws Exception {
fetchEntries();
final String savedState = ApptentiveMessage.State.saved.name();
for (int i = messageEntries.size() - 1; i >= 0; --i) {
final MessageEntry entry = messageEntries.get(i);
if (StringUtils.equal(entry.state, savedState) && entry.id != null) {
return entry.id;
}
}
return null;
}
@Override
public synchronized int getUnreadMessageCount() throws Exception {
fetchEntries();
int count = 0;
for (MessageEntry entry : messageEntries) {
if (!entry.isRead && entry.id != null) {
++count;
}
}
return count;
}
@Override
public synchronized void deleteAllMessages() {
messageEntries.clear();
writeToFile();
}
@Override
public synchronized void deleteMessage(String nonce) {
fetchEntries();
for (int i = 0; i < messageEntries.size(); ++i) {
if (StringUtils.equal(nonce, messageEntries.get(i).nonce)) {
messageEntries.remove(i);
writeToFile();
break;
}
}
}
@Override
public ApptentiveMessage findMessage(String nonce) {
fetchEntries();
for (int i = 0; i < messageEntries.size(); ++i) {
final MessageEntry messageEntry = messageEntries.get(i);
if (StringUtils.equal(nonce, messageEntry.nonce)) {
return MessageFactory.fromJson(messageEntry.json);
}
}
return null;
}
//endregion
//region File save/load
private synchronized void fetchEntries() {
if (shouldFetchFromFile) {
readFromFile();
shouldFetchFromFile = false;
}
}
private synchronized void readFromFile() {
messageEntries.clear();
try {
if (file.exists()) {
List<MessageEntry> entries = readFromFileGuarded();
messageEntries.addAll(entries);
}
} catch (Exception e) {
ApptentiveLog.e(e, "Exception while reading entries");
}
}
private List<MessageEntry> readFromFileGuarded() throws IOException {
DataInputStream dis = null;
try {
dis = new DataInputStream(new FileInputStream(file));
byte version = dis.readByte();
if (version != VERSION) {
throw new IOException("Unsupported binary version: " + version);
}
int entryCount = dis.readInt();
List<MessageEntry> entries = new ArrayList<>();
for (int i = 0; i < entryCount; ++i) {
entries.add(new MessageEntry(dis));
}
return entries;
} finally {
Util.ensureClosed(dis);
}
}
private synchronized void writeToFile() {
try {
writeToFileGuarded();
} catch (Exception e) {
ApptentiveLog.e(e, "Exception while saving messages");
}
shouldFetchFromFile = false; // mark it as not shouldFetchFromFile to keep a memory version
}
private void writeToFileGuarded() throws IOException {
DataOutputStream dos = null;
try {
dos = new DataOutputStream(new FileOutputStream(file));
dos.writeByte(VERSION);
dos.writeInt(messageEntries.size());
for (MessageEntry entry : messageEntries) {
entry.writeExternal(dos);
}
} finally {
Util.ensureClosed(dos);
}
}
//endregion
//region Filtering
private MessageEntry findMessageEntry(ApptentiveMessage message) {
Assert.assertNotNull(message);
return message != null ? findMessageEntry(message.getNonce()) : null;
}
private MessageEntry findMessageEntry(String nonce) {
for (MessageEntry entry : messageEntries) {
if (StringUtils.equal(entry.nonce, nonce)) {
return entry;
}
}
return null;
}
//endregion
//region Message Entry
private static class MessageEntry implements SerializableObject {
String id;
Double clientCreatedAt;
String nonce;
String state;
Boolean isRead;
String json;
MessageEntry() {
}
MessageEntry(DataInput in) throws IOException {
id = readNullableUTF(in);
clientCreatedAt = readNullableDouble(in);
nonce = readNullableUTF(in);
state = readNullableUTF(in);
isRead = readNullableBoolean(in);
json = readNullableUTF(in);
}
@Override
public void writeExternal(DataOutput out) throws IOException {
writeNullableUTF(out, id);
writeNullableDouble(out, clientCreatedAt);
writeNullableUTF(out, nonce);
writeNullableUTF(out, state);
writeNullableBoolean(out, isRead);
writeNullableUTF(out, json);
}
}
//endregion
}
|
package org.ovirt.engine.core.bll;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.naming.AuthenticationException;
import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.bll.context.CommandContext;
import org.ovirt.engine.core.bll.context.CompensationContext;
import org.ovirt.engine.core.bll.job.ExecutionContext;
import org.ovirt.engine.core.bll.job.ExecutionHandler;
import org.ovirt.engine.core.bll.utils.ClusterUtils;
import org.ovirt.engine.core.bll.utils.PermissionSubject;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.action.AddVdsActionParameters;
import org.ovirt.engine.core.common.action.InstallVdsParameters;
import org.ovirt.engine.core.common.action.RemoveVdsParameters;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VdcReturnValueBase;
import org.ovirt.engine.core.common.action.VdsActionParameters;
import org.ovirt.engine.core.common.businessentities.StorageType;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.VDSType;
import org.ovirt.engine.core.common.businessentities.VdsDynamic;
import org.ovirt.engine.core.common.businessentities.VdsStatistics;
import org.ovirt.engine.core.common.businessentities.storage_pool;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.errors.VdcBLLException;
import org.ovirt.engine.core.common.errors.VdcBllErrors;
import org.ovirt.engine.core.common.job.Step;
import org.ovirt.engine.core.common.job.StepEnum;
import org.ovirt.engine.core.common.utils.ValidationUtils;
import org.ovirt.engine.core.common.validation.group.CreateEntity;
import org.ovirt.engine.core.common.validation.group.PowerManagementCheck;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.common.vdscommands.VDSReturnValue;
import org.ovirt.engine.core.common.vdscommands.gluster.AddGlusterServerVDSParameters;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.VdcBllMessages;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dal.job.ExecutionMessageDirector;
import org.ovirt.engine.core.utils.FileUtil;
import org.ovirt.engine.core.utils.ssh.SSHClient;
import org.ovirt.engine.core.utils.threadpool.ThreadPoolUtil;
import org.ovirt.engine.core.utils.transaction.TransactionMethod;
import org.ovirt.engine.core.utils.transaction.TransactionSupport;
@NonTransactiveCommandAttribute(forceCompensation = true)
public class AddVdsCommand<T extends AddVdsActionParameters> extends VdsCommand<T> {
private static final String USER_NAME = "root";
private VDS upServer;
private AuditLogType errorType = AuditLogType.USER_FAILED_ADD_VDS;
/**
* Constructor for command creation when compensation is applied on startup
*
* @param commandId
*/
protected AddVdsCommand(Guid commandId) {
super(commandId);
}
public AddVdsCommand(T parametars) {
super(parametars);
setVdsGroupId(parametars.getvds().getvds_group_id());
}
@Override
protected void executeCommand() {
Guid oVirtId = getParameters().getVdsForUniqueId();
if (oVirtId != null) {
// if fails to remove deprecated entry, we might attempt to add new oVirt host with an existing unique-id.
if (!removeDeprecatedOvirtEntry(oVirtId)) {
log.errorFormat("Failed to remove duplicated oVirt entry with id {0}. Abort adding oVirt Host type",
oVirtId);
throw new VdcBLLException(VdcBllErrors.HOST_ALREADY_EXISTS);
}
}
TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() {
@Override
public Void runInTransaction() {
AddVdsStaticToDb();
AddVdsDynamicToDb();
AddVdsStatisticsToDb();
getCompensationContext().stateChanged();
return null;
}
});
// set vds spm id
if (getVdsGroup().getStoragePoolId() != null) {
VdsActionParameters tempVar = new VdsActionParameters(getVdsIdRef().getValue());
tempVar.setSessionId(getParameters().getSessionId());
tempVar.setCompensationEnabled(true);
CompensationContext compensationContext = getCompensationContext();
VdcReturnValueBase addVdsSpmIdReturn =
Backend.getInstance().runInternalAction(VdcActionType.AddVdsSpmId,
tempVar,
new CommandContext(compensationContext));
if (!addVdsSpmIdReturn.getSucceeded()) {
setSucceeded(false);
getReturnValue().setFault(addVdsSpmIdReturn.getFault());
return;
}
}
TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() {
@Override
public Void runInTransaction() {
InitializeVds();
AlertIfPowerManagementNotConfigured(getParameters().getVdsStaticData());
TestVdsPowerManagementStatus(getParameters().getVdsStaticData());
setSucceeded(true);
setActionReturnValue(getVdsIdRef());
// If the installation failed, we don't want to compensate for the failure since it will remove the
// host, but instead the host should be left in an "install failed" status.
getCompensationContext().resetCompensation();
return null;
}
});
// do not install vds's which added in pending mode (currently power
// clients). they are installed as part of the approve process
if (Config.<Boolean> GetValue(ConfigValues.InstallVds) && !getParameters().getAddPending()) {
final InstallVdsParameters installVdsParameters = new InstallVdsParameters(getVdsId(),
getParameters().getRootPassword());
installVdsParameters.setOverrideFirewall(getParameters().getOverrideFirewall());
installVdsParameters.setRebootAfterInstallation(getParameters().isRebootAfterInstallation());
Map<String, String> values = new HashMap<String, String>();
values.put(VdcObjectType.VDS.name().toLowerCase(), getParameters().getvds().getvds_name());
Step installStep = ExecutionHandler.addSubStep(getExecutionContext(),
getExecutionContext().getJob().getStep(StepEnum.EXECUTING),
StepEnum.INSTALLING_HOST,
ExecutionMessageDirector.resolveStepMessage(StepEnum.INSTALLING_HOST, values));
final ExecutionContext installCtx = new ExecutionContext();
installCtx.setJob(getExecutionContext().getJob());
installCtx.setStep(installStep);
installCtx.setMonitored(true);
installCtx.setShouldEndJob(true);
ThreadPoolUtil.execute(new Runnable() {
@Override
public void run() {
Backend.getInstance().runInternalAction(VdcActionType.InstallVds,
installVdsParameters,
new CommandContext(installCtx));
}
});
ExecutionHandler.setAsyncJob(getExecutionContext(), true);
} else {
// If cluster supports gluster service do gluster peer probe
// only on non vds installation mode.
// Also gluster peer probe is not needed when importing an existing gluster cluster
if (isGlusterSupportEnabled() && getAllVds(getVdsGroupId()).size() > 1) {
String hostName =
(getParameters().getvds().gethost_name().isEmpty()) ? getParameters().getvds().getManagmentIp()
: getParameters().getvds().gethost_name();
VDSReturnValue returnValue =
runVdsCommand(
VDSCommandType.AddGlusterServer,
new AddGlusterServerVDSParameters(upServer.getId(),
hostName));
setSucceeded(returnValue.getSucceeded());
if (!getSucceeded()) {
getReturnValue().getFault().setError(returnValue.getVdsError().getCode());
getReturnValue().getFault().setMessage(returnValue.getVdsError().getMessage());
errorType = AuditLogType.GLUSTER_SERVER_ADD_FAILED;
return;
}
}
}
}
private boolean isGlusterSupportEnabled() {
return getVdsGroup().supportsGlusterService() && getParameters().isGlusterPeerProbeNeeded();
}
/**
* The scenario in which a host is already exists when adding new host after the canDoAction is when the existed
* host type is oVirt and its status is 'Pending Approval'. In this case the old entry is removed from the DB, since
* the oVirt node was added again, where the new host properties might be updated (e.g. cluster adjustment, data
* center, host name, host address) and a new entry with updated properties is added.
*
* @param oVirtId
* the deprecated host entry to remove
*/
private boolean removeDeprecatedOvirtEntry(final Guid oVirtId) {
final VDS vds = DbFacade.getInstance().getVdsDao().get(oVirtId);
if (vds == null || !VdsHandler.isPendingOvirt(vds)) {
return false;
}
String vdsName = getParameters().getVdsStaticData().getvds_name();
log.infoFormat("Host {0}, id {1} of type {2} is being re-registered as Host {3}",
vds.getvds_name(),
vds.getId(),
vds.getvds_type().name(),
vdsName);
VdcReturnValueBase result =
TransactionSupport.executeInNewTransaction(new TransactionMethod<VdcReturnValueBase>() {
@Override
public VdcReturnValueBase runInTransaction() {
return Backend.getInstance().runInternalAction(VdcActionType.RemoveVds,
new RemoveVdsParameters(oVirtId));
}
});
if (!result.getSucceeded()) {
String errors =
result.getCanDoAction() ? result.getFault().getError().name()
: StringUtils.join(result.getCanDoActionMessages(), ",");
log.warnFormat("Failed to remove Host {0}, id {1}, re-registering it as Host {2} fails with errors {3}",
vds.getvds_name(),
vds.getId(),
vdsName,
errors);
} else {
log.infoFormat("Host {0} is now known as Host {2}",
vds.getvds_name(),
vdsName);
}
return result.getSucceeded();
}
@Override
public AuditLogType getAuditLogTypeValue() {
return getSucceeded() ? AuditLogType.USER_ADD_VDS : errorType;
}
private void AddVdsStaticToDb() {
getParameters().getVdsStaticData().setserver_SSL_enabled(
Config.<Boolean> GetValue(ConfigValues.UseSecureConnectionWithServers));
DbFacade.getInstance().getVdsStaticDao().save(getParameters().getVdsStaticData());
getCompensationContext().snapshotNewEntity(getParameters().getVdsStaticData());
setVdsIdRef(getParameters().getVdsStaticData().getId());
setVds(null);
}
private void AddVdsDynamicToDb() {
VdsDynamic vdsDynamic = new VdsDynamic();
vdsDynamic.setId(getParameters().getVdsStaticData().getId());
// TODO: oVirt type - here oVirt behaves like power client?
if (Config.<Boolean> GetValue(ConfigValues.InstallVds)
&& getParameters().getVdsStaticData().getvds_type() == VDSType.VDS) {
vdsDynamic.setstatus(VDSStatus.Installing);
} else if (getParameters().getAddPending()) {
vdsDynamic.setstatus(VDSStatus.PendingApproval);
}
DbFacade.getInstance().getVdsDynamicDao().save(vdsDynamic);
getCompensationContext().snapshotNewEntity(vdsDynamic);
}
private void AddVdsStatisticsToDb() {
VdsStatistics vdsStatistics = new VdsStatistics();
vdsStatistics.setId(getParameters().getVdsStaticData().getId());
DbFacade.getInstance().getVdsStatisticsDao().save(vdsStatistics);
getCompensationContext().snapshotNewEntity(vdsStatistics);
}
@Override
protected boolean canDoAction() {
boolean returnValue = true;
setVdsGroupId(getParameters().getVdsStaticData().getvds_group_id());
getParameters().setVdsForUniqueId(null);
// Check if this is a valid cluster
if (getVdsGroup() == null) {
addCanDoActionMessage(VdcBllMessages.VDS_CLUSTER_IS_NOT_VALID);
returnValue = false;
} else {
VDS vds = getParameters().getvds();
String vdsName = vds.getvds_name();
String hostName = vds.gethost_name();
int maxVdsNameLength = Config.<Integer> GetValue(ConfigValues.MaxVdsNameLength);
// check that vds name is not null or empty
if (vdsName == null || vdsName.isEmpty()) {
addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_NAME_MAY_NOT_BE_EMPTY);
returnValue = false;
// check that VDS name is not too long
} else if (vdsName.length() > maxVdsNameLength) {
addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_NAME_LENGTH_IS_TOO_LONG);
returnValue = false;
// check that VDS hostname does not contain special characters.
} else if (!ValidationUtils.validHostname(hostName)) {
addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_INVALID_VDS_HOSTNAME);
returnValue = false;
} else {
returnValue = returnValue && validateSingleHostAttachedToLocalStorage();
if (Config.<Boolean> GetValue(ConfigValues.UseSecureConnectionWithServers)
&& !FileUtil.fileExists(Config.resolveCertificatePath())) {
addCanDoActionMessage(VdcBllMessages.VDS_TRY_CREATE_SECURE_CERTIFICATE_NOT_FOUND);
returnValue = false;
} else if (!getParameters().getAddPending()
&& StringUtils.isEmpty(getParameters().getRootPassword())) {
// We block vds installations if it's not a RHEV-H and password is empty
// Note that this may override local host SSH policy. See BZ#688718.
addCanDoActionMessage(VdcBllMessages.VDS_CANNOT_INSTALL_EMPTY_PASSWORD);
returnValue = false;
} else if (!IsPowerManagementLegal(getParameters().getVdsStaticData(), getVdsGroup()
.getcompatibility_version().toString())) {
returnValue = false;
} else {
returnValue = returnValue && canConnect(vds);
}
}
}
if (isGlusterSupportEnabled()) {
if (clusterHasServers()) {
upServer = ClusterUtils.getInstance().getUpServer(getVdsGroupId());
if (upServer == null) {
addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_NO_GLUSTER_HOST_TO_PEER_PROBE);
returnValue = false;
}
}
}
if (!returnValue) {
addCanDoActionMessage(VdcBllMessages.VAR__ACTION__ADD);
addCanDoActionMessage(VdcBllMessages.VAR__TYPE__HOST);
}
return returnValue;
}
private boolean clusterHasServers() {
return ClusterUtils.getInstance().hasServers(getVdsGroupId());
}
public SSHClient getSSHClient() {
return new SSHClient();
}
private boolean canConnect(VDS vds) {
boolean returnValue = true;
// execute the connectivity and id uniqueness validation for VDS type hosts
if (vds.getvds_type() == VDSType.VDS && Config.<Boolean> GetValue(ConfigValues.InstallVds)) {
SSHClient sshclient = null;
try {
Long timeout =
TimeUnit.SECONDS.toMillis(Config.<Integer> GetValue(ConfigValues.ConnectToServerTimeoutInSeconds));
sshclient = getSSHClient();
sshclient.setHardTimeout(timeout);
sshclient.setSoftTimeout(timeout);
sshclient.setHost(vds.gethost_name());
sshclient.setUser(USER_NAME);
sshclient.setPassword(getParameters().getRootPassword());
sshclient.connect();
sshclient.authenticate();
}
catch (AuthenticationException e) {
log.errorFormat(
"Failed to authenticate session with host {0}",
vds.getvds_name(),
e
);
addCanDoActionMessage(VdcBllMessages.VDS_CANNOT_AUTHENTICATE_TO_SERVER);
returnValue = false;
}
catch (Exception e) {
log.errorFormat(
"Failed to establish session with host {0}",
vds.getvds_name(),
e
);
addCanDoActionMessage(VdcBllMessages.VDS_CANNOT_CONNECT_TO_SERVER);
returnValue = false;
}
finally {
if (sshclient != null) {
sshclient.disconnect();
}
}
}
return returnValue;
}
private boolean validateSingleHostAttachedToLocalStorage() {
boolean retrunValue = true;
storage_pool storagePool = DbFacade.getInstance().getStoragePoolDao().getForVdsGroup(
getParameters().getVdsStaticData().getvds_group_id());
if (storagePool != null && storagePool.getstorage_pool_type() == StorageType.LOCALFS) {
if (!DbFacade.getInstance()
.getVdsStaticDao()
.getAllForVdsGroup(getParameters().getVdsStaticData().getvds_group_id())
.isEmpty()) {
addCanDoActionMessage(VdcBllMessages.VDS_CANNOT_ADD_MORE_THEN_ONE_HOST_TO_LOCAL_STORAGE);
retrunValue = false;
}
}
return retrunValue;
}
@Override
public List<PermissionSubject> getPermissionCheckSubjects() {
return Collections.singletonList(new PermissionSubject(getVdsGroupId(), VdcObjectType.VdsGroups,
getActionType().getActionGroup()));
}
@Override
protected List<Class<?>> getValidationGroups() {
addValidationGroup(CreateEntity.class);
if (getParameters().getVdsStaticData().getpm_enabled()) {
addValidationGroup(PowerManagementCheck.class);
}
return super.getValidationGroups();
}
@Override
public Map<String, String> getJobMessageProperties() {
if (jobProperties == null) {
jobProperties = super.getJobMessageProperties();
VDS vds = getParameters().getvds();
String vdsName = (vds != null && vds.getvds_name() != null) ? vds.getvds_name() : "";
jobProperties.put(VdcObjectType.VDS.name().toLowerCase(), vdsName);
}
return jobProperties;
}
/**
* This method will return the list of all vds from the cluster
*
* @param clusterId
* @return List of Vds
*/
private List<VDS> getAllVds(Guid clusterId) {
return getVdsDAO().getAllForVdsGroup(clusterId);
}
}
|
package com.senseidb.clue.commands;
import java.io.PrintStream;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.search.Query;
import com.senseidb.clue.ClueContext;
public class DeleteCommand extends ClueCommand {
public DeleteCommand(ClueContext ctx) {
super(ctx);
}
@Override
public String getName() {
return "delete";
}
@Override
public String help() {
return "deletes a list of documents from searching via a query, input: query";
}
@Override
public void execute(String[] args, PrintStream out) throws Exception {
Query q = null;
StringBuilder buf = new StringBuilder();
for (String s : args){
buf.append(s).append(" ");
}
String qstring = buf.toString();
try{
q = ctx.getQueryBuilder().build(qstring);
}
catch(Exception e){
out.println("cannot parse query: "+e.getMessage());
return;
}
out.println("parsed query: "+q);
if (q != null){
IndexWriter writer = ctx.getIndexWriter();
if (writer != null) {
writer.deleteDocuments(q);
writer.commit();
ctx.refreshReader();
}
else {
out.println("unable to open writer, index is in readonly mode");
}
}
}
}
|
package com.simplify4me.casslist;
import java.util.Iterator;
import java.util.Set;
import java.util.UUID;
import javax.annotation.Nonnull;
import com.netflix.astyanax.model.Column;
/**
* A collection of entries in the CassList
*/
public class CassListEntries {
private final String referenceID;
private final String consumerName;
private final Set<Column<UUID>> entries;
public CassListEntries(@Nonnull String consumerName, @Nonnull String referenceID, @Nonnull Set<Column<UUID>> entries) {
this.consumerName = consumerName;
this.referenceID = referenceID;
this.entries = entries;
}
public String getReferenceID() {
return referenceID;
}
public String getConsumerName() {
return consumerName;
}
public Iterator<String> iterator() {
final Iterator<Column<UUID>> delegate = entries.iterator();
return new Iterator<String>() {
@Override
public boolean hasNext() {
return delegate.hasNext();
}
@Override
public String next() {
final Column<UUID> next = delegate.next();
return next.getStringValue();
}
};
}
Set<Column<UUID>> getEntries() {
return entries;
}
public int size() {
return entries.size();
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("CassListEntry{");
sb.append("referenceID='").append(referenceID).append('\'');
sb.append(", entries=").append(String.valueOf(entries));
sb.append('}');
return sb.toString();
}
}
|
package com.skyline.roadsys.geometry;
import javax.vecmath.*;
import com.skyline.roadsys.streetgraph.*;
import com.skyline.roadsys.util.*;
public class LineSegment extends Line {
public LineSegment(Point first, Point second) {
super(first, second);
}
public LineSegment(Point point, Vector3d vector) {
this(point, point.plus(vector));
}
/** < Own copy ructor is neccessary */
public LineSegment(LineSegment source) {
super(source);
}
public LineSegment() {
// TODO Auto-generated constructor stub
}
public double length() {
return first.distance(second);
}
/**
* Returns the "2D normal" of this LineSegment (normal of the projection
* onto the X/Y plane).
*
* @return
*/
public Vector3d normal() {
Vector3d dir = new Vector3d(second);
dir.sub(first);
dir.set(-dir.y, dir.x, 0);
return dir;
}
public boolean hasPoint2D(Point point)
{
double lineTest = (point.x - first.x) * (second.y - first.y) -
(point.y - first.y) * (second.x - first.x);
// debug(Math.abs(lineTest));
// debug(toString());
// debug(point.toString());
if (Math.abs(lineTest) < Units.COORDINATES_EPSILON)
/* Point is on the line */
{
double t = 0.0;
if (Math.abs(first.x - second.x) > Units.COORDINATES_EPSILON) // (first.x
// second.x)
{
t = (point.x - first.x) / (second.x - first.x);
// debug(t);
return t >= 0 && t <= 1;
}
else if (Math.abs(first.y - second.y) > Units.COORDINATES_EPSILON) // (first.y
// second.y)
{
t = (point.y - first.y) / (second.y - first.y);
// debug(t);
return t >= 0 && t <= 1;
}
else
{
return first.equals(point);
}
}
return false;
}
public IntersectionType intersection2D(Line another, Point intersection) {
double r, d; // r, s, d
double x1 = beginning().x, y1 = beginning().y, x2 = end().x, y2 = end().y, x3 = another.beginning().x, y3 = another.beginning().y, x4 = another.end().x, y4 = another.end().y;
// Make sure the lines aren't parallel
if (Math.abs((y2 - y1) / (x2 - x1) - (y4 - y3) / (x4 - x3)) > Units.EPSILON)
{
d = (((x2 - x1) * (y4 - y3)) - (y2 - y1) * (x4 - x3));
if (d != 0)
{
r = (((y1 - y3) * (x4 - x3)) - (x1 - x3) * (y4 - y3)) / d;
// s = (((y1 - y3) * (x2 - x1)) - (x1 - x3) * (y2 - y1)) / d;
if (r >= -Units.EPSILON && r <= (1 + Units.EPSILON))
{
intersection.set(x1 + r * (x2 - x1), y1 + r * (y2 - y1), 0);
return IntersectionType.INTERSECTING;
}
}
}
return IntersectionType.ORTHOGONAL;
}
public double distance(Point point) {
Point closestPoint = nearestPoint(point);
Vector3d v = new Vector3d(point);
v.sub(closestPoint);
return v.length();
}
public Point nearestPoint(Point point) {
double parameter;
Point orthogonalProjection = new Point();
parameter = (second.x - first.x) * (point.x - first.x) +
(second.y - first.y) * (point.y - first.y) +
(second.z - first.z) * (point.z - first.z);
parameter /= length() * length();
if (parameter >= 0 && parameter <= 1)
{
orthogonalProjection.x = ((1 - parameter) * first.x + second.x * parameter);
orthogonalProjection.y = ((1 - parameter) * first.y + second.y * parameter);
orthogonalProjection.z = ((1 - parameter) * first.z + second.z * parameter);
return orthogonalProjection;
}
else
{
Vector3d v = new Vector3d(first);
v.sub(point);
double distanceToFirst = v.length();
v.set(second);
v.sub(point);
double distanceToSecond = v.length();
if (distanceToFirst < distanceToSecond)
{
return first;
}
else
{
return second;
}
}
}
public String toString() {
return "LineSegment(" + first.toString() + ", " + second.toString() + ")";
}
public boolean equals(LineSegment another) {
return (begining().equals(another.begining()) && end().equals(another.end())) ||
(begining().equals(another.end()) && end().equals(another.begining()));
}
/**
* Test whether this Line Segment crosses the given Segment.
*
* @param another
* the segment to test against this segment.
* @param intersection
* If the segments cross, the intersection point will be returned
* in this output param.
* @return an {@link IntersectionType}, indicating the type of intersection,
* if any.
*/
// TODO: Refactor this. IntersectionType should be a class containing
// IntersectionType (OVERLAPPING, INTERSECTING, etc) and intersectionPoint.
// Then remove the BYREF / output param. Output params are an anti-pattern
// in Java.
public IntersectionType intersection2D(LineSegment another, Point intersection) {
// BYREF:
// intersection
// NOTE: intersection can be null. (See RoadLSystem.localConstraints)
double denominator = ((another.end().y - another.begining().y) * (end().x - begining().x)) -
((another.end().x - another.begining().x) * (end().y - begining().y)), firstNumerator = ((another.end().x - another.begining().x) * (begining().y - another.begining().y)) -
((another.end().y - another.begining().y) * (begining().x - another.begining().x)), secondNumerator = ((end().x - begining().x) * (begining().y - another.begining().y)) -
((end().y - begining().y) * (begining().x - another.begining().x));
if (Math.abs(denominator) < Units.COORDINATES_EPSILON)
/* If the denominator is 0, both lines have same direction vector */
{
if (Math.abs(firstNumerator) < Units.COORDINATES_EPSILON &&
Math.abs(secondNumerator) < Units.COORDINATES_EPSILON)
/* Lines are coincident. */
{
/*
* WARNING Order of following checks is important for the right
* functionality.
*/
if (this == another || this.equals(another))
/* Line segments are identical */
{
return IntersectionType.IDENTICAL;
}
if (hasPoint2D(another.begining()) && hasPoint2D(another.end()))
/* This line is containing another. */
{
return IntersectionType.CONTAINING;
}
if (another.hasPoint2D(begining()) && another.hasPoint2D(end()))
/* This line is contained in another. */
{
return IntersectionType.CONTAINED;
}
if (!this.hasPoint2D(another.begining()) &&
!this.hasPoint2D(another.end()))
/* Line segments are subsequent, and do not cross. */
{
return IntersectionType.ORTHOGONAL;
}
if (begining().equals(another.begining()) ||
begining().equals(another.end()) ||
end().equals(another.end()) ||
end().equals(another.begining()))
/* Line segments touch just in one point. */
{
intersection.set(end());
return IntersectionType.INTERSECTING;
}
/* Line segments overlap */
return IntersectionType.OVERLAPPING;
}
// Lines are parallel thus nonintersecting
return IntersectionType.ORTHOGONAL;
}
double ua = firstNumerator / denominator, ub = secondNumerator / denominator;
if (ua >= 0 && ua <= 1 &&
ub >= 0 && ub <= 1)
{
intersection.x = (begining().x + ua * (end().x - begining().x));
intersection.y = (begining().y + ua * (end().y - begining().y));
return IntersectionType.INTERSECTING;
}
return IntersectionType.ORTHOGONAL;
}
}
|
package com.threadsafestudio.hip;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import se.hip.sdk.api.Api;
import se.hip.sdk.api.GetAlertInformationBuilder;
import se.hip.sdk.api.core.DefaultSubjectOfCare;
import se.hip.sdk.api.core.Response;
import se.hip.sdk.api.operation.GetAlertInformation;
import se.hip.sdk.api.query.result.DataResultSet;
import se.hip.sdk.service.api.impl.AlertInformationImpl;
/*
@Controller
public class AlertController {
@Autowired
private Api api;
@Autowired
ConsentService consentService;
@RequestMapping("/alert")
@ResponseBody
public Response<DataResultSet<AlertInformation>> careDocumentation() {
boolean consentPosted = consentService.postConsent();
if (consentPosted) {
final GetAlertInformation request =
api.getOperationBuilder(GetAlertInformationBuilder.class)
.as(consentService.getCareActor())
.withSubjectOfCare(DefaultSubjectOfCare.create("191212121212"))
.build();
return request.execute();
} else {
return null;
}
}
}
*/
|
package com.tts.component.webservice;
import com.tts.component.annotation.ZeuService;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.lang.reflect.Method;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
public class ZeusInitial implements ApplicationContextAware , InitializingBean{
private static final Logger logger = LoggerFactory.getLogger(ZeusInitial.class);
private static Map<String, Object> zeusServices = new HashMap<>();
private String ip;
private String port;
private IRegister register;
private String group;
private String hostName;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
zeusServices.putAll(applicationContext.getBeansWithAnnotation(Controller.class));
zeusServices.putAll(applicationContext.getBeansWithAnnotation(RestController.class));
logger.info("zeus service initialing , find all zeus service {}", zeusServices);
}
@Override
public void afterPropertiesSet() throws Exception {
String localIp = this.getLocalHost()[0];
String localHostName = this.getLocalHost()[1];
String localPort = port;
for (Object service : zeusServices.values()) {
RequestMapping requestMapping =AnnotationUtils.findAnnotation(service.getClass(), RequestMapping.class);
String classPath = getPath(requestMapping);
Method[] methods = ReflectionUtils.getAllDeclaredMethods(service.getClass());
for (Method method: methods) {
RequestMapping methodRequestMapping = method.getAnnotation(RequestMapping.class);
if (null != methodRequestMapping) {
ZeuService zeuService = AnnotationUtils.findAnnotation(method,ZeuService.class);
String serviceName = getServiceName(zeuService,method.getName());
String serviceGroup = getServiceGroup(zeuService,group);
String methodPath = getPath(methodRequestMapping);
register.registerService(localHostName,localIp,localPort,classPath,methodPath,serviceName,serviceGroup);
}
}
}
}
private String[] getLocalHost() {
if (StringUtils.isNotEmpty(this.ip) && StringUtils.isNotEmpty(this.hostName)) {
return new String[]{ip,hostName};
}
String localIP = "127.0.0.1";
String localHostName = "local";
DatagramSocket sock = null;
try {
InetSocketAddress e = new InetSocketAddress(InetAddress.getByName("1.2.3.4"), 1);
sock = new DatagramSocket();
sock.connect(e);
localIP = sock.getLocalAddress().getHostAddress();
localHostName = sock.getLocalAddress().getHostName();
this.ip = localIP;
this.hostName = localHostName;
} catch (Exception e) {
logger.error("get local ip error",e);
} finally {
sock.disconnect();
sock.close();
sock = null;
}
return new String[]{localIP,localHostName};
}
private String getServiceName(ZeuService zeuService, String defaultName) {
if (null == zeuService) {
return defaultName;
}
if (StringUtils.isBlank(zeuService.value())) {
return defaultName;
}
return zeuService.value();
}
private String getServiceGroup(ZeuService zeuService, String defaultGroup) {
if (null == zeuService) {
return defaultGroup;
}
if (StringUtils.isBlank(zeuService.value())) {
return defaultGroup;
}
return zeuService.group();
}
private static final String getPath(RequestMapping requestMapping) {
if(requestMapping == null) {
return null;
} else {
String[] path = requestMapping.path();
if(ArrayUtils.isNotEmpty(path)) {
return path[0];
} else {
String[] value = requestMapping.value();
return ArrayUtils.isNotEmpty(value)?value[0]:null;
}
}
}
public void setPort(String port) {
this.port = port;
}
public void setRegister(IRegister register) {
this.register = register;
}
public void setGroup(String group) {
this.group = group;
}
}
|
package org.thingml.compilers.c.arduino;
import org.sintef.thingml.*;
import org.thingml.compilers.Context;
import org.thingml.compilers.c.CCompilerContext;
import org.thingml.compilers.thing.ThingCepCompiler;
import org.thingml.compilers.thing.ThingCepSourceDeclaration;
import org.thingml.compilers.thing.ThingCepViewCompiler;
import java.util.ArrayList;
import java.util.List;
public class ArduinoThingCepCompiler extends ThingCepCompiler {
public ArduinoThingCepCompiler(ThingCepViewCompiler cepViewCompiler, ThingCepSourceDeclaration sourceDeclaration) {
super(cepViewCompiler, sourceDeclaration);
}
public static void generateSubscription(Stream stream, StringBuilder builder, Context context, String paramName, Message outPut) {
}
/**
* We generate a buffer for Join and Merge operations or if the source has a
* Length or Window specified
*
* @param thing Thing implementing some stream.
* @return List of Stream needing a buffer in order to produce their result.
*/
public static List<Stream> getStreamWithBuffer(Thing thing) {
List<Stream> ret = new ArrayList<>();
for (Stream s : thing.getStreams()) {
Source source = s.getInput();
if (source instanceof SourceComposition) {
ret.add(s);
} else {
for (ViewSource vs : source.getOperators()) {
if (vs instanceof LengthWindow) {
ret.add(s);
} else if (vs instanceof TimeWindow) {
ret.add(s);
}
}
}
}
return ret;
}
public static List<Message> getMessageFromStream(Stream stream) {
List<Message> ret = new ArrayList<>();
Source source = stream.getInput();
if (source instanceof SimpleSource) {
ret.add(((SimpleSource) source).getMessage().getMessage());
} else if (source instanceof MergeSources) {
for (Source s : ((MergeSources) source).getSources()) {
if (s instanceof SimpleSource) {
ret.add(((SimpleSource) s).getMessage().getMessage());
}
}
} else if (source instanceof JoinSources) {
for (Source s : ((JoinSources) source).getSources()) {
if (s instanceof SimpleSource) {
ret.add(((SimpleSource) s).getMessage().getMessage());
}
}
}
return ret;
}
public static void generateCEPLib(Thing thing, StringBuilder builder, CCompilerContext ctx) {
generateCEPLibAPI(thing, builder, ctx);
generateCEPLibImpl(thing, builder, ctx);
}
public static String getStreamSize(Stream s, CCompilerContext ctx) {
List<ViewSource> vsList = s.getInput().getOperators();
String ret = "DEFAULT_NUMBER_MSG";
for (ViewSource vs : vsList) {
StringBuilder b = new StringBuilder();
if (vs instanceof LengthWindow) {
ctx.getCompiler().getThingActionCompiler().generate(((LengthWindow) vs).getSize(), b, ctx);
ret = b.toString();
} else if (vs instanceof TimeWindow) {
ctx.getCompiler().getThingActionCompiler().generate(((TimeWindow) vs).getDuration(), b, ctx);
ret = "(" + b.toString() + "/TTL)";
}
}
return ret;
}
public static String getSlidingStep(Stream s, CCompilerContext ctx) {
String slidingImpl = "";
for (ViewSource vs : s.getInput().getOperators()) {
if (vs instanceof LengthWindow) {
StringBuilder b = new StringBuilder();
ctx.getCompiler().getThingActionCompiler().generate(((LengthWindow) vs).getStep(), b, ctx);
String step = b.toString();
slidingImpl += "int step = " + step + " * /*MESSAGE_NAME_UPPER*/_ELEMENT_SIZE;\n";
slidingImpl += "if (/*MESSAGE_NAME*/_length() < step )\n\tstep = /*MESSAGE_NAME_UPPER*/_FIFO_SIZE;\n";
slidingImpl += "/*MESSAGE_NAME*/_fifo_head = (/*MESSAGE_NAME*/_fifo_head + step) % /*MESSAGE_NAME_UPPER*/_FIFO_SIZE;";
break; // we stop at first match, a stream can have only one window right?
}
if (vs instanceof TimeWindow) {
StringBuilder b = new StringBuilder();
ctx.getCompiler().getThingActionCompiler().generate(((TimeWindow) vs).getStep(), b, ctx);
b.toString();
}
}
/* If no window is specified */
if (slidingImpl.equals(""))
slidingImpl += "/*MESSAGE_NAME*/_fifo_head = (/*MESSAGE_NAME*/_fifo_head + /*MESSAGE_NAME_UPPER*/_ELEMENT_SIZE) % /*MESSAGE_NAME_UPPER*/_FIFO_SIZE;";
return slidingImpl;
}
public static void generateCEPLibAPI(Thing thing, StringBuilder builder, CCompilerContext ctx) {
for (Stream s : ArduinoThingCepCompiler.getStreamWithBuffer(thing)) {
String cepTemplate = ctx.getCEPLibTemplateClass();
String constants = "";
String methodsSignatures = "";
String attributesSignatures = "";
for (Message msg : ArduinoThingCepCompiler.getMessageFromStream(s)) {
String constantTemplate = ctx.getCEPLibTemplateConstants();
int messageSize = ctx.getMessageSerializationSize(msg) - 4; //substract the ports size
constantTemplate = constantTemplate.replace("/*MESSAGE_NAME_UPPER*/", msg.getName().toUpperCase());
constantTemplate = constantTemplate.replace("/*STRUCT_SIZE*/", Integer.toString(messageSize));
constantTemplate = constantTemplate.replace("/*STREAM_SIZE*/", getStreamSize(s, ctx));
constants += constantTemplate;
String methodsTemplate = ctx.getCEPLibTemplateMethodsSignatures();
methodsTemplate = methodsTemplate.replace("/*MESSAGE_NAME*/", msg.getName());
StringBuilder paramBuilder = new StringBuilder();
ctx.appendFormalParameters(thing, paramBuilder, msg);
methodsTemplate = methodsTemplate.replace("/*MESSAGE_PARAMETERS*/", paramBuilder);
methodsSignatures += methodsTemplate;
String attributesTemplate = ctx.getCEPLibTemplateAttributesSignatures();
attributesTemplate = attributesTemplate.replace("/*MESSAGE_NAME*/", msg.getName());
attributesTemplate = attributesTemplate.replace("/*MESSAGE_NAME_UPPER*/", msg.getName().toUpperCase());
attributesSignatures += attributesTemplate;
}
|
package data_science.ui.info;
import javafx.geometry.Insets;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
/**
* @author Jasper Wijnhoven
*/
public final class InformationViewPane extends GridPane {
/**
* Creates a new {@link InformationViewPane}.
*/
InformationViewPane() {
setStyle();
setContent();
}
/*
* Set the content for the Pane. Every second row is empty for a prettier result.
*/
private void setContent() {
add(new Text("Naam"),0,0);
add(new Text(""),0,1);
add(new Text("Ilyas Baas"),0,2);
add(new Text("Jasper Wijnhoven"),0,3);
add(new Text("Xin Hao Xia"),0,4);
add(new Text("Dino Becker"),0,5);
add(new Text("Johan Bastinck"),0,6);
add(new Text("Gedaan"),1,0);
add(new Text(""),1,1);
add(new Text("TODO"),1,2);
add(new Text("Checkboxes, Comboboxes, Linechart, Tabs"),1,3);
add(new Text("Samples"),1,4);
add(new Text("CSS"),1,5);
add(new Text("Samples"),1,6);
}
/*
* Set the style for the Pane.
*/
private void setStyle() {
setStyle("-fx-font: normal 15px 'Segoe UI'");
setPadding(new Insets(10, 10, 10, 10));
setVgap(7);
setHgap(20);
}
}
|
package se.vgregion.ldapservice;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
public class LdapServiceImpl implements LdapService {
private String _bindDN;
private String _bindPw;
private String _bindUrl;
private String[] _defaultReadAttrs;
private String[] _defaultAddAttrs;
private Object[] _objectClasses;
private DirContext _ctx;
protected String base;
protected Properties properties;
public Properties getProperties() {
return properties;
}
/**
* Default zero-arg constructor
*/
public LdapServiceImpl() {
}
public LdapServiceImpl(Properties p) {
this(p.getProperty("BIND_URL"), p.getProperty("BIND_DN"), p.getProperty("BIND_PW"), new String[] {},
new String[] {}, new Object[] {});
this.properties = p;
this.base = p.getProperty("BASE");
}
private LdapServiceImpl(String bindUrl, String bindDN, String bindPassword, String[] readAttrs,
String[] updateAttrs, Object[] objClasses) {
_bindDN = bindDN;
_bindUrl = bindUrl;
_bindPw = bindPassword;
_defaultReadAttrs = readAttrs;
_objectClasses = objClasses;
_defaultAddAttrs = new String[updateAttrs.length + 4];
_defaultAddAttrs[0] = "objectclass";
_defaultAddAttrs[1] = "cn";
_defaultAddAttrs[2] = "sn";
_defaultAddAttrs[3] = "mail";
}
private void bind() {
try {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, _bindUrl);
if (_bindDN != null) {
env.put(Context.SECURITY_PRINCIPAL, _bindDN);
env.put(Context.SECURITY_CREDENTIALS, _bindPw);
}
_ctx = new InitialDirContext(env);
}
catch (Exception e) {
throw new RuntimeException("Bind failed", e);
}
}
private DirContext getBaseContext() {
if (_ctx == null) {
bind();
}
return _ctx;
}
public LdapUser[] search(String base, String filter, String[] attributes) {
this._defaultReadAttrs = attributes;
return this.search(base, filter);
}
public LdapUser[] search(String base, String filter) {
if (base == null) {
base = this.base;
}
try {
SearchControls sc = new SearchControls();
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
if (_defaultReadAttrs.length > 0) {
sc.setReturningAttributes(_defaultReadAttrs);
}
NamingEnumeration results = getBaseContext().search(base, filter, sc);
List entries = new ArrayList();
while (results.hasMore()) {
SearchResult oneRes = (SearchResult) results.next();
entries.add(new LdapUserEntryImpl(base, oneRes));
}
LdapUser[] res = new LdapUser[entries.size()];
for (int i = 0; i < res.length; i++) {
res[i] = (LdapUser) entries.get(i);
}
return res;
}
catch (Exception e) {
throw new RuntimeException("Search failed: base=" + base + " filter=" + filter, e);
}
}
public LdapUser getLdapUser(String base, String filter, String[] attributes) {
this._defaultReadAttrs = attributes;
return this.getLdapUser(base, filter);
}
public LdapUser getLdapUser(String base, String filter) {
if (base == null) {
base = this.base;
}
try {
SearchControls sc = new SearchControls();
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
if (_defaultReadAttrs.length > 0) {
sc.setReturningAttributes(_defaultReadAttrs);
}
NamingEnumeration results = getBaseContext().search(base, filter, sc);
List entries = new ArrayList();
while (results.hasMore()) {
SearchResult oneRes = (SearchResult) results.next();
entries.add(new LdapUserEntryImpl(base, oneRes));
}
if (entries.size() > 1) {
throw new RuntimeException("Entry is not unique: " + filter);
}
else if (entries.size() == 0) {
return null;
}
return (LdapUser) entries.get(0);
}
catch (Exception e) {
throw new RuntimeException("Search failed: base=" + base + " filter=" + filter, e);
}
}
/*
* (non-Javadoc)
*
* @see se.vgregion.ldapservice.LdapService#addLdapUser(java.lang.String, java.util.HashMap)
*/
public boolean addLdapUser(String context, HashMap<String, String> attributes) {
try {
int x = 0;
LdapUser e = this.newUser(context);
String[] addAttrs = new String[attributes.size() + 1];
addAttrs[x++] = "objectclass";
for (Map.Entry<String, String> entry : attributes.entrySet()) {
String attName = entry.getKey();
addAttrs[x++] = attName;
String attValue = entry.getValue();
e.setAttributeValue(attName, attValue);
}
e.addAttributeValue("objectclass", "vgrUser");
e.addAttributeValue("objectclass", "inetOrgPerson");
Attributes attrs = ((LdapUserEntryImpl) e).getAttributes(addAttrs);
String dn = e.getDn();
getBaseContext().createSubcontext(dn, attrs);
return true;
}
catch (Exception ex) {
throw new RuntimeException("Add failed", ex);
}
}
/*
* (non-Javadoc)
*
* @see se.vgregion.ldapservice.LdapService#modifyLdapUser(se.vgregion.ldapservice.LdapUser, java.util.HashMap)
*/
public boolean modifyLdapUser(LdapUser e, HashMap<String, String> modifyAttributes) {
try {
int x = 0;
String[] modifyAttrs = new String[modifyAttributes.size() + 1];
for (Map.Entry<String, String> entry : modifyAttributes.entrySet()) {
String attName = entry.getKey();
modifyAttrs[x++] = attName;
e.setAttributeValue(attName, entry.getValue());
}
Attributes attrs = ((LdapUserEntryImpl) e).getAttributes(modifyAttrs);
getBaseContext().modifyAttributes(e.getDn(), InitialDirContext.REPLACE_ATTRIBUTE, attrs);
return true;
}
catch (Exception ex) {
throw new RuntimeException("Modify failed", ex);
}
}
/*
* (non-Javadoc)
*
* @see se.vgregion.ldapservice.LdapService#deleteLdapUser(se.vgregion.ldapservice.LdapUser)
*/
public boolean deleteLdapUser(LdapUser e) {
try {
getBaseContext().destroySubcontext(e.getDn());
return true;
}
catch (Exception ex) {
throw new RuntimeException("Delete failed", ex);
}
}
public static String dumpSearchRes(LdapUser[] res) {
StringBuffer buf = new StringBuffer(256);
for (int i = 0; i < res.length; i++) {
buf.append(res[i]);
}
return buf.toString();
}
private static boolean arrayContains(String[] a, String val) {
for (int i = 0; i < a.length; i++) {
if (a[i] == null) {
if (val == null) {
return true;
}
}
else {
if (a[i].equals(val)) {
return true;
}
}
}
return false;
}
public static String dumpAttrMap(Map m) {
StringBuffer buf = new StringBuffer(256);
Iterator it = m.keySet().iterator();
while (it.hasNext()) {
String key = (String) it.next();
List values = (List) m.get(key);
buf.append(" " + key + ": |");
Iterator it2 = values.iterator();
while (it2.hasNext()) {
String oneVal = (String) it2.next();
buf.append(oneVal + "|");
}
buf.append("\n");
}
return buf.toString();
}
private LdapUser newUser(String rdn) {
LdapUser e = new LdapUserEntryImpl(rdn);
e.setAttributeValue("objectclass", _objectClasses);
return e;
}
public LdapUser getLdapUserByUid(String uid) {
throw new UnsupportedOperationException("Not implemented in LdapServiceImpl, use simple ldap service");
}
}
|
package de.iani.cubequest.quests;
import de.iani.cubequest.CubeQuest;
import de.iani.cubequest.EventListener.GlobalChatMsgType;
import de.iani.cubequest.QuestManager;
import de.iani.cubequest.Reward;
import de.iani.cubequest.bubbles.QuestTargetBubbleTarget;
import de.iani.cubequest.commands.SetDoBubbleCommand;
import de.iani.cubequest.commands.SetInteractorQuestConfirmationMessageCommand;
import de.iani.cubequest.commands.SetOrRemoveQuestInteractorCommand;
import de.iani.cubequest.commands.SetOverwrittenNameForSthCommand;
import de.iani.cubequest.conditions.QuestCondition;
import de.iani.cubequest.interaction.Interactor;
import de.iani.cubequest.interaction.InteractorDamagedEvent;
import de.iani.cubequest.interaction.InteractorProtecting;
import de.iani.cubequest.interaction.PlayerInteractInteractorEvent;
import de.iani.cubequest.questStates.QuestState;
import de.iani.cubequest.util.ChatAndTextUtil;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ClickEvent.Action;
import net.md_5.bungee.api.chat.ComponentBuilder;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
public abstract class InteractorQuest extends ServerDependendQuest implements InteractorProtecting {
private static final String[] DEFAULT_CONFIRMATION_MESSAGE = new String[] {
ChatColor.translateAlternateColorCodes('&', "&6&LQuest \""), "\" abschließen."};
private Interactor interactor;
private String overwrittenInteractorName;
private String confirmationMessage;
private boolean doBubble;
public InteractorQuest(int id, String name, String displayMessage, String giveMessage,
String successMessage, String failMessage, Reward successReward, Reward failReward,
int serverId, Interactor interactor) {
super(id, name, displayMessage, giveMessage, successMessage, failMessage, successReward,
failReward, serverId);
this.interactor = interactor;
this.doBubble = true;
}
public InteractorQuest(int id, String name, String displayMessage, String giveMessage,
String successMessage, String failMessage, Reward successReward, Reward failReward,
Interactor interactor) {
super(id, name, displayMessage, giveMessage, successMessage, failMessage, successReward,
failReward);
this.interactor = interactor;
this.doBubble = true;
}
public InteractorQuest(int id, String name, String displayMessage, String giveMessage,
String successMessage, Reward successReward, int serverId, Interactor interactor) {
this(id, name, displayMessage, giveMessage, successMessage, null, successReward, null,
serverId, interactor);
}
public InteractorQuest(int id, String name, String displayMessage, String giveMessage,
String successMessage, Reward successReward, Interactor interactor) {
this(id, name, displayMessage, giveMessage, successMessage, null, successReward, null,
interactor);
}
@Override
public void deserialize(YamlConfiguration yc) throws InvalidConfigurationException {
possiblyRemoveProtecting();
if (isLegal() && isForThisServer() && isReady()) {
CubeQuest.getInstance().getBubbleMaker()
.unregisterBubbleTarget(new QuestTargetBubbleTarget(this));
}
super.deserialize(yc);
this.interactor = yc.contains("interactor") ? (Interactor) yc.get("interactor") : null;
this.overwrittenInteractorName =
yc.contains("overwrittenInteractorName") ? yc.getString("overwrittenInteractorName")
: null;
this.confirmationMessage =
yc.contains("confirmationMessage") ? yc.getString("confirmationMessage") : null;
this.doBubble = yc.getBoolean("doBubble", true);
possiblyAddProtecting();
Bukkit.getScheduler().scheduleSyncDelayedTask(CubeQuest.getInstance(), () -> {
if (isForThisServer() && this.doBubble && isReady()) {
CubeQuest.getInstance().getBubbleMaker()
.registerBubbleTarget(new QuestTargetBubbleTarget(this));
}
}, 1L);
}
@Override
protected String serializeToString(YamlConfiguration yc) {
yc.set("interactor", this.interactor);
yc.set("overwrittenInteractorName", this.overwrittenInteractorName);
yc.set("confirmationMessage", this.confirmationMessage);
yc.set("duBubble", this.doBubble);
return super.serializeToString(yc);
}
@Override
public void setReady(boolean val) {
if (isReady() == val) {
return;
}
if (!isLegal()) {
super.setReady(val);
return;
}
boolean before = isDelayDatabaseUpdate();
setDelayDatabaseUpdate(true);
prepareSetReady(val);
super.setReady(val);
hasBeenSetReady(val);
setDelayDatabaseUpdate(before);
}
private void prepareSetReady(boolean val) {
if (isForThisServer()) {
if (!val) {
this.interactor.resetAccessible();
CubeQuest.getInstance().getBubbleMaker()
.unregisterBubbleTarget(new QuestTargetBubbleTarget(this));
}
}
}
public void hasBeenSetReady(boolean val) {
if (isForThisServer()) {
if (val) {
this.interactor.makeAccessible();
if (this.doBubble) {
CubeQuest.getInstance().getBubbleMaker()
.registerBubbleTarget(new QuestTargetBubbleTarget(this));
}
}
} else {
ByteArrayOutputStream msgbytes = new ByteArrayOutputStream();
DataOutputStream msgout = new DataOutputStream(msgbytes);
try {
msgout.writeInt(GlobalChatMsgType.NPC_QUEST_SETREADY.ordinal());
msgout.writeInt(getId());
msgout.writeBoolean(val);
} catch (IOException e) {
CubeQuest.getInstance().getLogger().log(Level.SEVERE,
"IOException trying to send PluginMessage!", e);
return;
}
byte[] msgarry = msgbytes.toByteArray();
CubeQuest.getInstance().getGlobalChatAPI().sendDataToServers("CubeQuest", msgarry);
}
}
@Override
protected void changeServerToThis() {
if (this.interactor != null && !this.interactor.isForThisServer()) {
this.interactor = null;
}
super.changeServerToThis();
}
@Override
public boolean onPlayerInteractInteractorEvent(PlayerInteractInteractorEvent<?> event,
QuestState state) {
if (!isForThisServer()) {
return false;
}
if (!event.getInteractor().equals(this.interactor)) {
return false;
}
return true;
}
@Override
public boolean isLegal() {
return this.interactor != null && (!isForThisServer() || this.interactor.isLegal());
}
@Override
public List<BaseComponent[]> getQuestInfo() {
List<BaseComponent[]> result = super.getQuestInfo();
result.add(new ComponentBuilder(ChatColor.DARK_AQUA + "Target: "
+ ChatAndTextUtil.getInteractorInfoString(this.interactor))
.event(new ClickEvent(Action.SUGGEST_COMMAND,
"/" + SetOrRemoveQuestInteractorCommand.FULL_SET_COMMAND))
.event(SUGGEST_COMMAND_HOVER_EVENT).create());
result.add(new ComponentBuilder(ChatColor.DARK_AQUA + "Name: " + ChatColor.GREEN
+ getInteractorName() + " "
+ (this.overwrittenInteractorName == null ? ChatColor.GOLD + "(automatisch)"
: ChatColor.GREEN + "(gesetzt)")).event(new ClickEvent(
Action.SUGGEST_COMMAND,
"/" + SetOverwrittenNameForSthCommand.SpecificSth.INTERACTOR.fullSetCommand))
.event(SUGGEST_COMMAND_HOVER_EVENT).create());
result.add(new ComponentBuilder(ChatColor.DARK_AQUA + "Blubbert: "
+ (this.doBubble ? ChatColor.GREEN : ChatColor.GOLD) + this.doBubble)
.event(new ClickEvent(Action.SUGGEST_COMMAND,
"/" + SetDoBubbleCommand.FULL_COMMAND))
.event(SUGGEST_COMMAND_HOVER_EVENT).create());
result.add(new ComponentBuilder("").create());
result.add(new ComponentBuilder(ChatColor.DARK_AQUA + "Bestätigungstext: " + ChatColor.RESET
+ getConfirmationMessage())
.event(new ClickEvent(Action.SUGGEST_COMMAND,
"/" + SetInteractorQuestConfirmationMessageCommand.FULL_COMMAND))
.event(SUGGEST_COMMAND_HOVER_EVENT).create());
result.add(new ComponentBuilder("").create());
return result;
}
@Override
public Interactor getInteractor() {
return this.interactor;
}
public void setInteractor(Interactor interactor) {
possiblyRemoveProtecting();
if (isForThisServer() && interactor == null) {
if (isReady()) {
setReady(false);
CubeQuest.getInstance().getBubbleMaker()
.unregisterBubbleTarget(new QuestTargetBubbleTarget(this));
}
}
Location oldLocation =
this.interactor != null && isForThisServer() ? this.interactor.getLocation() : null;
if (interactor != null) {
if (!interactor.isForThisServer()) {
throw new IllegalArgumentException("Interactor must be from this server.");
}
changeServerToThis();
}
this.interactor = interactor;
updateIfReal();
possiblyAddProtecting();
if (isForThisServer() && isReady() && this.doBubble) {
CubeQuest.getInstance().getBubbleMaker()
.updateBubbleTarget(new QuestTargetBubbleTarget(this), oldLocation);
}
}
public String getInteractorName() {
return this.overwrittenInteractorName != null ? this.overwrittenInteractorName
: this.interactor != null ? this.interactor.getName() : null;
}
public void setInteractorName(String name) {
this.overwrittenInteractorName = name;
updateIfReal();
}
public String getConfirmationMessage() {
return this.confirmationMessage == null
? DEFAULT_CONFIRMATION_MESSAGE[0] + getName() + DEFAULT_CONFIRMATION_MESSAGE[1]
: this.confirmationMessage;
}
public void setConfirmationMessage(String msg) {
this.confirmationMessage = msg;
updateIfReal();
}
public boolean isDoBubble() {
return this.doBubble;
}
public void setDoBubble(boolean val) {
if (this.doBubble == val) {
return;
}
this.doBubble = val;
if (isForThisServer()) {
if (!val) {
CubeQuest.getInstance().getBubbleMaker()
.unregisterBubbleTarget(new QuestTargetBubbleTarget(this));
} else if (isReady()) {
CubeQuest.getInstance().getBubbleMaker()
.registerBubbleTarget(new QuestTargetBubbleTarget(this));
}
}
updateIfReal();
}
public boolean playerConfirmedInteraction(Player player, QuestState state) {
if (!this.fulfillsProgressConditions(player, state.getPlayerData())) {
List<BaseComponent[]> missingConds = new ArrayList<>();
missingConds.add(new ComponentBuilder(
"Du erfüllst nicht alle Voraussetzungen, um diese Quest abzuschließen:")
.color(ChatColor.GOLD).create());
for (QuestCondition cond : getQuestProgressConditions()) {
if (cond.isVisible() && !cond.fulfills(player, state.getPlayerData())) {
missingConds.add(cond.getConditionInfo());
}
}
if (missingConds.size() == 1) {
ChatAndTextUtil.sendWarningMessage(player,
"Du kannst diese Quest derzeit nicht abschließen.");
} else {
ChatAndTextUtil.sendBaseComponent(player, missingConds);
}
return false;
}
return true;
}
@Override
public boolean onInteractorDamagedEvent(InteractorDamagedEvent<?> event) {
if (event.getInteractor().equals(this.interactor)) {
event.setCancelled(true);
return true;
}
return false;
}
private void possiblyAddProtecting() {
if (isReal() && isLegal() && isForThisServer()
&& QuestManager.getInstance().getQuest(getId()) == this) {
CubeQuest.getInstance().addProtecting(this);
}
}
private void possiblyRemoveProtecting() {
if (isReal() && isLegal() && isForThisServer()
&& QuestManager.getInstance().getQuest(getId()) == this) {
CubeQuest.getInstance().removeProtecting(this);
}
}
}
|
package novoda.lib.sqliteprovider.util;
import static org.junit.Assert.*;
import android.net.Uri;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(RoboRunner.class)
public class UriToSqlAttributesInspectorTest {
private UriInspector uriInspector = new UriInspector();;
private UriToSqlAttributes attrs = null;
@Before
private void setup() {
uriInspector = new UriInspector();
}
@Test
public void testUriInspectorCreationBehaviour() {
attrs = uriInspector.parse(Uri.parse("content://test.com/item/1"));
assertEquals("content://test.com/item/1", attrs.getUri().toString());
}
@Test
public void testHasWhereClauseInQuery() {
attrs = uriInspector.parse(Uri.parse("content://test.com/item/1"));
assertFalse(attrs.hasWhereClauseInQuery());
attrs = uriInspector.parse(Uri.parse("content://test.com/tableName?groupBy=col&having=value"));
assertTrue(attrs.hasWhereClauseInQuery());
}
}
|
package edu.berkeley.sparrow.daemon.util;
import java.io.IOException;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import com.google.common.base.Joiner;
public class Logging {
public final static String AUDIT_LOGGER_NAME = "audit";
public final static String AUDIT_LOG_FILENAME_FORMAT = "sparrow_audit.%d.log";
public final static String AUDIT_LOG_FORMAT = "%c\t%m%n";
private static Joiner paramJoiner = Joiner.on(",");
private static Joiner auditParamJoiner = Joiner.on("\t");
private static Joiner auditEventParamJoiner = Joiner.on(":");
/**
* Sets up audit logging to log to a file named based on the current time (in ms).
*
* The logger is configured to effectively ignore the log level.
*
* @throws IOException if the audit log file could not be opened for writing.
*/
public static void configureAuditLogging() throws IOException {
PatternLayout layout = new PatternLayout(AUDIT_LOG_FORMAT);
// This assumes that no other daemon will be started within 1 millisecond.
String filename = String.format(AUDIT_LOG_FILENAME_FORMAT,
System.currentTimeMillis());
FileAppender fileAppender = new FileAppender(layout, filename);
Logger auditLogger = Logger.getLogger(Logging.AUDIT_LOGGER_NAME);
auditLogger.addAppender(fileAppender);
auditLogger.setLevel(Level.ALL);
/* We don't want audit messages to be appended to the main appender, which is
* intended for potentially user-facing messages. */
auditLogger.setAdditivity(false);
}
/**
* Returns a log string for the given event, starting with the epoch time.
*/
public static String auditEventString(Object ... params) {
return auditParamJoiner.join(System.currentTimeMillis(),
auditEventParamJoiner.join(params));
}
/**
* Returns a logger to be used for audit logging messages for the given class.
*/
@SuppressWarnings("rawtypes")
public static Logger getAuditLogger(Class clazz) {
return Logger.getLogger(String.format("%s.%s", AUDIT_LOGGER_NAME, clazz.getName()));
}
/**
* Return a function name (determined via reflection) and all its parameters (passed)
* in a consistent stringformat. Very helpful in logging function calls throughout
* our program.
*/
public static String functionCall(Object ... params) {
String name = Thread.currentThread().getStackTrace()[2].getMethodName();
return name + ": [" + paramJoiner.join(params) + "]";
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.odu.icat.graphicsinterface;
import edu.odu.icat.analytics.AnalyticsEngine;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.util.List;
public class WorkSpace extends JFrame implements Printable{
protected JPanel graphComponent;
private JPanel contentPane;
private JPanel attributePane;
private JSplitPane split;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WorkSpace frame = new WorkSpace();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public WorkSpace() {
setTitle("Workspace");
this.setIconImage(Toolkit.getDefaultToolkit().getImage("src/main/resources/logo.png"));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 850, 600);
setLayout(new BorderLayout());
attributePane = new JPanel();
attributePane.add(new JLabel("Nothing Selected"));
graphComponent = new GraphEditor();
split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, attributePane,
graphComponent);
split.setOneTouchExpandable(false);
split.setDividerLocation(300);
split.setDividerSize(6);
split.setBorder(null);
add(split, BorderLayout.CENTER);
updateAttributePane(entityAttributes());
MenuButtons();
}
private JPopupMenu m_popup = new JPopupMenu();
public void MenuButtons() {
JMenu reportsMenu = new JMenu("Reports");
List<String> list = AnalyticsEngine.getInstance().getAlgorithms(); //get list of loaded algorithms
for(String s: list)
{
final String name = s;
JMenuItem temp = new JMenuItem(s);
temp.setEnabled(true);
//temp.setAccelerator(KeyStroke.getKeyStroke("control I"));
reportsMenu.add(temp);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateAttributePane(AnalyticsEngine.getInstance().getAlgorithmDialog(name));
}
});
}
JMenuItem saveItem = new JMenuItem("Save");
saveItem.setMnemonic('S');
saveItem.setAccelerator(KeyStroke.getKeyStroke("control S"));
JMenuItem saveAsItem = new JMenuItem("Save As");
saveAsItem.setMnemonic('A');
saveAsItem.setAccelerator(KeyStroke.getKeyStroke("control A"));
JMenuItem loadItem = new JMenuItem("Load");
loadItem.setMnemonic('L');
loadItem.setAccelerator(KeyStroke.getKeyStroke("control L"));
JMenuItem exportItem = new JMenuItem("Export");
exportItem.setMnemonic('E');
exportItem.setAccelerator(KeyStroke.getKeyStroke("control E"));
JMenuItem printItem = new JMenuItem("Print");
printItem.setMnemonic('P');
printItem.setAccelerator(KeyStroke.getKeyStroke("control P"));
JMenuItem quitItem = new JMenuItem("Exit");
quitItem.setMnemonic('X');
quitItem.setAccelerator(KeyStroke.getKeyStroke("control X"));
//Build menubar, menus, and add menuitems.
JMenuBar menubar = new JMenuBar(); // Create new menu bar
JMenu fileMenu = new JMenu("File"); // Create new menu
fileMenu.setMnemonic('F');
menubar.add(fileMenu); // Add menu to the menubar
fileMenu.add(saveItem); // Add menu item to the menu
fileMenu.add(saveAsItem);
fileMenu.add(loadItem);
fileMenu.add(exportItem);
fileMenu.add(printItem);
fileMenu.addSeparator(); // Add separator line to menu
fileMenu.add(quitItem);
fileMenu.setMnemonic('R');
menubar.add(reportsMenu);
//Add listeners to menu items
loadItem.addActionListener(new LoadAction());
quitItem.addActionListener(new QuitAction());
printItem.addActionListener(new PrintAction());
exportItem.addActionListener(new ExportAction());
saveItem.addActionListener(new SaveAction());
saveAsItem.addActionListener(new SaveAsAction());
setJMenuBar(menubar);
setTitle("WorkSpace");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null); // Center window
}
public void updateAttributePane(JComponent newComponent)
{
split.setLeftComponent(newComponent);
}
public JPanel entityAttributes()
{
JPanel newPanel = new JPanel();
newPanel.setLayout(new BoxLayout(newPanel, BoxLayout.Y_AXIS));
final JTextPane titlePane = new JTextPane();
titlePane.setSize( titlePane.getPreferredSize() );
newPanel.add(titlePane, newPanel);
titlePane.setText("Title");
titlePane.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
titlePane.setText("");
}
});
newPanel.add(Box.createVerticalGlue());
JMenuBar bar = new JMenuBar();
JMenu entityTypeMenu = new JMenu("Type");
bar.add(entityTypeMenu);
for(String s: edu.odu.icat.controller.Control.getInstance().getEntityClassifications())
{
entityTypeMenu.add(new JMenuItem(s));
}
newPanel.add(bar);
newPanel.add(Box.createVerticalGlue());
JTextField metaDataTextArea = new JTextField("",20);
newPanel.add(metaDataTextArea);
newPanel.add(Box.createVerticalGlue());
JCheckBox noncontrolCheckBox = new JCheckBox("Non-Controllable");
JCheckBox nonvisibleCheckBox = new JCheckBox("Non-Visible");
newPanel.add(nonvisibleCheckBox);
newPanel.add(noncontrolCheckBox);
newPanel.add(new JSeparator());
JButton deleteButton = new JButton("Delete");
newPanel.add(deleteButton, newPanel);
setVisible(true);
return newPanel;
}
public int print(Graphics g, PageFormat pf, int page) throws
PrinterException {
if (page > 0) { /* We have only one page, and 'page' is zero-based */
return NO_SUCH_PAGE;
}
/* User (0,0) is typically outside the imageable area, so we must
* translate by the X and Y values in the PageFormat to avoid clipping
*/
Graphics2D g2d = (Graphics2D)g;
java.awt.geom.AffineTransform originalTransform = g2d.getTransform();
double scaleX = pf.getImageableWidth() / graphComponent.getComponent(0).getWidth();
double scaleY = pf.getImageableHeight() / graphComponent.getComponent(0).getHeight();
// Maintain aspect ratio
double scale = Math.min(scaleX, scaleY);
g2d.translate(pf.getImageableX(), pf.getImageableY());
g2d.scale(scale, scale);
/* Now print the window and its visible contents */
graphComponent.getComponent(0).printAll(g2d);
g2d.setTransform(originalTransform);
/* tell the caller that this page is part of the printed document */
return PAGE_EXISTS;
}
class LoadAction implements ActionListener {
JFileChooser fc = new JFileChooser();
public void actionPerformed(ActionEvent e)
{
//JOptionPane.showMessageDialog(WorkSpace.this, "No Files Found.");
if (fc.showOpenDialog(WorkSpace.this) == JFileChooser.APPROVE_OPTION)
{
File openFils = fc.getSelectedFile();
// load the file here
}
}
}
class QuitAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
WorkSpace.this.dispose();
}
}
class PrintAction implements ActionListener
{
public void actionPerformed(ActionEvent e) {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(WorkSpace.this);
if (job.printDialog()) {
try {
job.print();
} catch (PrinterException ex) {
/* The job did not successfully complete */
}
}
}
}
class ExportAction implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
}
}
class SaveAction implements ActionListener {
JFileChooser fc = new JFileChooser();
public void actionPerformed(ActionEvent e)
{
// JOptionPane.showMessageDialog(WorkSpace.this, "No Files Found.");
if (fc.showSaveDialog(WorkSpace.this) == JFileChooser.APPROVE_OPTION)
{
File saveFils = fc.getSelectedFile();
// save the file here
}
}
}
class SaveAsAction implements ActionListener {
JFileChooser fc = new JFileChooser();
public void actionPerformed(ActionEvent e)
{
//JOptionPane.showMessageDialog(WorkSpace.this, "No Files Found.");
if (fc.showSaveDialog(WorkSpace.this) == JFileChooser.APPROVE_OPTION)
{
File saveFils = fc.getSelectedFile();
// save the file here
}
}
}
}
|
package function.genotype.pedmap;
import java.io.OutputStreamWriter;
import com.itextpdf.awt.PdfGraphics2D;
import com.itextpdf.text.Document;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
import function.genotype.base.Sample;
import function.genotype.base.SampleManager;
import global.Index;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.SeriesRenderingOrder;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import utils.CommonCommand;
import utils.ErrorManager;
import utils.LogManager;
import utils.ThirdPartyToolManager;
/**
*
* @author macrina
*/
public class FlashPCAManager {
public static void runFlashPCA(String inputName, String outExt, String logName) {
LogManager.writeAndPrint("flashpca for eigenvalues, vectors, pcs and percent variance explained by each pc. #dimenions = " + PedMapCommand.numEvec);
try {
if (PedMapCommand.numEvec <= 0) {
throw new IllegalArgumentException("Number of eigenvectors as input to flashpca cant be 0");
}
} catch (IllegalArgumentException e) {
ErrorManager.send(e);
}
String cmd = ThirdPartyToolManager.FLASHPCA
+ " --bfile " + CommonCommand.outputPath + inputName
+ " --ndim " + PedMapCommand.numEvec
+ " --outpc " + CommonCommand.outputPath + "pcs" + outExt
+ " --outvec " + CommonCommand.outputPath + "eigenvectors" + outExt
+ " --outval " + CommonCommand.outputPath + "eigenvalues" + outExt
+ " --outpve " + CommonCommand.outputPath + "pve" + outExt
+ " 2>&1 >> " + CommonCommand.outputPath + logName;
ThirdPartyToolManager.systemCall(new String[]{"/bin/sh", "-c", cmd});
LogManager.writeAndPrint("Verify flashpca mean square errors");
cmd = ThirdPartyToolManager.FLASHPCA
+ " -v"
+ " --bfile " + CommonCommand.outputPath + inputName
+ " --check"
+ " --outvec " + CommonCommand.outputPath + "eigenvectors" + outExt
+ " --outval " + CommonCommand.outputPath + "eigenvalues" + outExt
+ " 2>&1 >> " + CommonCommand.outputPath + logName;
ThirdPartyToolManager.systemCall(new String[]{"/bin/sh", "-c", cmd});
//if condition on rms ; print a warning
try {
Charset charset = Charset.defaultCharset();
List<String> log_lines = Files.readAllLines(Paths.get(CommonCommand.outputPath + logName), charset);
String text = log_lines.get(log_lines.size() - 2);
String[] rmsStr;
if (text.contains("Root mean squared error")) {
rmsStr = text.split(":");
} else {
throw new NoSuchFieldException("root mean squared error could not be read from flashpca.log file");
}
double rmsVal = Double.parseDouble(rmsStr[rmsStr.length - 1].split("\\(")[0].trim());
if (rmsVal > 0.0001) {
ErrorManager.print("The root mean sq error of flashpca is very high " + Double.toString(rmsVal), 1);
}
} catch (IOException | NoSuchFieldException | NumberFormatException e) {
ErrorManager.send(e);
}
}
public static void findOutliers() {
String cmd = ThirdPartyToolManager.PLINK
+ " --bfile " + CommonCommand.outputPath + "plink"
+ " --neighbour 1 " + String.valueOf(PedMapCommand.numNeighbor)
+ " --out " + CommonCommand.outputPath + "plink_outlier"
+ " 2>&1 >> " + CommonCommand.outputPath + "flashpca.log";
ThirdPartyToolManager.systemCall(new String[]{"/bin/sh", "-c", cmd});
}
public static void plot2DData(Map<String, SamplePCAInfo> sampleMap, int nDim, boolean includeOutlier, String pdfName) {
int numCharts = 1;
if (nDim == 3) {
numCharts = 3;
}
List<JFreeChart> charts = new ArrayList<>(numCharts);
switch (nDim) {
case 1:
charts.add(buildChartPcs(sampleMap, includeOutlier, -1, 0,true));
break;
case 2:
charts.add(buildChartPcs(sampleMap, includeOutlier, 0, 1,true));
break;
default:
charts.add(buildChartPcs(sampleMap, includeOutlier, 0, 1, true));
charts.add(buildChartPcs(sampleMap, includeOutlier, 1, 2, false));
charts.add(buildChartPcs(sampleMap, includeOutlier, 0, 2, false));
break;
}
saveChartAsPDF(pdfName, charts, 630, 1100);
}
private static JFreeChart buildChartPcs(Map<String, SamplePCAInfo> sampleMap, boolean includeOutlier, int dim1, int dim2, boolean printInfo) {
XYSeries outlierSeries = new XYSeries("outlier");
XYSeries caseSeries = new XYSeries("case");
XYSeries ctrlSeries = new XYSeries("control");
String plotName, xLabel, yLabel;
int countCase, countCtrl, countOut;
countOut = countCtrl = countCase = 0;
if (dim1 == -1) {
plotName = "principal components (pc) 1D scatter plot";
xLabel = "sample number";
yLabel = "pc in 1D";
for (SamplePCAInfo samplePCAInfo : sampleMap.values()) {
if (includeOutlier && samplePCAInfo.isOutlier()) {
outlierSeries.add(countOut++, samplePCAInfo.getPCAInfoPcs(dim2));
} else {
if (samplePCAInfo.getPheno() == Index.CTRL) {
ctrlSeries.add(countCtrl++, samplePCAInfo.getPCAInfoPcs(dim2));
} else {
caseSeries.add(countCase++, samplePCAInfo.getPCAInfoPcs(dim2));
}
}
}
} else {
plotName = "principal components (pc) 2D scatter plot";
xLabel = "pc dim " + Integer.toString(dim1 + 1);
yLabel = "pc dim " + Integer.toString(dim2 + 1);
for (SamplePCAInfo samplePCAInfo : sampleMap.values()) {
double[] pcsData = samplePCAInfo.getPCAInfoPcs(dim1, dim2);
if (includeOutlier && samplePCAInfo.isOutlier()) {
outlierSeries.add(pcsData[0], pcsData[1]);
countOut++;
} else {
if (samplePCAInfo.getPheno() == Index.CTRL) {
ctrlSeries.add(pcsData[0], pcsData[1]);
countCtrl++;
} else {
caseSeries.add(pcsData[0], pcsData[1]);
countCase++;
}
}
}
}
if(printInfo){
System.out.println("original number of cases :" + SampleManager.getCaseNum());
System.out.println("original number of controls :" + SampleManager.getCtrlNum());
System.out.println("number of cases :" + countCase);
System.out.println("number of controls :" + countCtrl);
System.out.println("number of outliers :" + countOut);
}
XYSeriesCollection dataCollection = new XYSeriesCollection();
dataCollection.addSeries(ctrlSeries);
dataCollection.addSeries(caseSeries);
if (includeOutlier) {
dataCollection.addSeries(outlierSeries);
}
JFreeChart chartOp = ChartFactory.createScatterPlot(plotName, xLabel, yLabel, dataCollection, PlotOrientation.HORIZONTAL, true, true, false);
//setting series colors - blue = case, green = control, red = outliers if they exist
XYPlot plotOp = (XYPlot) chartOp.getPlot();
plotOp.getRenderer().setSeriesPaint(0, new Color(0x00, 0xFF, 0x00)); //ctrl = green
plotOp.getRenderer().setSeriesPaint(1, new Color(0x00, 0x00, 0xFF)); //case = blue
if (includeOutlier) {
plotOp.getRenderer().setSeriesPaint(2, new Color(0xFF, 0x00, 0x00)); //outlier = red
}
plotOp.setSeriesRenderingOrder(SeriesRenderingOrder.FORWARD);
return chartOp;
}
public static void generateNewSampleFile(Map<String, SamplePCAInfo> sampleMap, String sampleFile, String outputFile) {
try ( BufferedWriter fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(CommonCommand.outputPath + outputFile))) ) {
Files.lines(Paths.get(sampleFile))
.map(line -> line.split("\\t"))
.filter( line -> sampleMap.containsKey( line[1]) )
.forEach(line -> printLine(fw, line));
fw.flush();
fw.close();
} catch (IOException e) {
ErrorManager.send(e);
}
}
private static void printLine(BufferedWriter fw, String[] line) {
try {
fw.write(String.join("\t", line) + "\n");
} catch (IOException e) {
ErrorManager.send(e);
}
}
public static HashSet<String> getOutliers(String fileName, String outlierFile) {
HashSet<String> outlierSet = new HashSet<>();
float zThreshSum = PedMapCommand.zThresh * PedMapCommand.numNeighbor;
try (BufferedReader br = new BufferedReader(new FileReader(fileName));
BufferedWriter writer = new BufferedWriter(new FileWriter(outlierFile))) {
String[] header = br.readLine().replaceAll("^\\s+", "").split(" +");
if (!"Z".equals(header[4])) {
throw new IllegalArgumentException("Column names in nearest neighbor file " + fileName + " are incorrect");
}
writer.write(header[0] + "\t" + header[1] + "\n");
String line;
int countLine = 1;
String iidCurr = "";
String fidCurr = "";
float sumZ = 0.0f;
while ((line = br.readLine()) != null) {
String[] dataStrLine = line.replaceAll("^\\s+", "").split(" +");
if (!dataStrLine[0].equals(fidCurr) || !dataStrLine[1].equals(iidCurr) || countLine == 1) {
if (sumZ < zThreshSum) {
System.out.println(fidCurr + "\t" + iidCurr);
writer.write(fidCurr + "\t" + iidCurr + "\n");
outlierSet.add(iidCurr);
}
countLine = PedMapCommand.numNeighbor;
fidCurr = dataStrLine[0];
iidCurr = dataStrLine[1];
sumZ = Float.valueOf(dataStrLine[4]);
} else {
countLine = countLine - 1;
sumZ = sumZ + Float.valueOf(dataStrLine[4]);
}
}
br.close();
writer.flush();
writer.close();
} catch (Exception e) {
ErrorManager.send(e);
}
System.out.println("Size of outlier set: " + outlierSet.size());
return outlierSet;
}
public static Map<String, SamplePCAInfo> getSampleMap(int ndim, String evecFileName,
String pcsFileName, ArrayList<Sample> sampleList) {
Map<String, SamplePCAInfo> sampleMap = sampleList.stream().collect(Collectors.toMap(Sample::getName, s -> new SamplePCAInfo(s, ndim)));
System.out.println("Files from which we're reading; evec: " + evecFileName + " pcs: " + pcsFileName);
try {
BufferedReader brEvec = new BufferedReader(new FileReader(evecFileName));
BufferedReader brPcs = new BufferedReader(new FileReader(pcsFileName));
brEvec.readLine();
brPcs.readLine();
String evecLine;
String pcsLine;
while ((evecLine = brEvec.readLine()) != null && (pcsLine = brPcs.readLine()) != null) {
String[] evecStrLine = evecLine.split("\\t");
String[] pcsStrLine = pcsLine.split("\\t");
if (sampleMap.containsKey(evecStrLine[1])) {
sampleMap.get(evecStrLine[1]).setEvec(ndim, evecStrLine);
sampleMap.get(evecStrLine[1]).setPcs(ndim, pcsStrLine);
sampleMap.get(evecStrLine[1]).setToFilter(false);
}
}
} catch (IOException e) {
ErrorManager.send(e);
}
return sampleMap;
}
private static void saveChartAsPDF(String fileName, List<JFreeChart> charts, float ht, float wth) {
try {
Document document = new Document(new Rectangle(wth, ht), 0, 0, 0, 0);
document.addAuthor("atav");
document.addSubject("flashpca_plot");
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
document.open();
PdfContentByte cb = writer.getDirectContent();
float indWidth = wth;
int numChartsX = 1;
if (charts.size() == 3) {
indWidth = wth / 3;
numChartsX = 3;
}
int counter = 0;
float currWth = 0;
for (int i = 0; i < numChartsX; i++) {
PdfTemplate tp = cb.createTemplate(indWidth, ht);
Graphics2D g2 = new PdfGraphics2D(tp, indWidth, ht);
Rectangle2D r2D = new Rectangle2D.Double(0, 0, indWidth, ht);
charts.get(counter).draw(g2, r2D, null);
g2.dispose();
cb.addTemplate(tp, currWth, 0);
counter = counter + 1;
currWth = currWth + indWidth;
}
document.close();
} catch (Exception e) {
ErrorManager.send(e);
}
}
public static void getevecDatafor1DPlot(String inputFileName, String pdfFileName,
String plotName, String plotTitle, String xName, String yName) {
Charset charset = Charset.defaultCharset();
XYSeries xyData = new XYSeries(plotName);
try {
List<String> fileLines;
fileLines = Files.readAllLines(Paths.get(inputFileName), charset);
if (fileLines.size() != PedMapCommand.numEvec) {
String message;
message = String.format("File %s has too many lines. #lines must equal #pcs!", inputFileName);
throw new IllegalArgumentException(message);
}
for (int i = 0; i < fileLines.size(); i++) {
xyData.add(i + 1, Double.parseDouble(fileLines.get(i)));
}
XYSeriesCollection dataset = new XYSeriesCollection();
dataset.addSeries(xyData);
List<JFreeChart> charts = new ArrayList<>(1);
charts.add(ChartFactory.createXYLineChart(plotTitle, xName, yName, (XYDataset) dataset, PlotOrientation.VERTICAL, true, true, false));
saveChartAsPDF(pdfFileName, charts, 630, 1100);
} catch (IllegalArgumentException e) {
ErrorManager.send(e);
} catch (Exception e) {
ErrorManager.send(e);
}
}
}
|
package gunn.brewski.app.sync;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SyncRequest;
import android.content.SyncResult;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.text.format.Time;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Vector;
import gunn.brewski.app.BrewskiApplication;
import gunn.brewski.app.MainActivity;
import gunn.brewski.app.ProfileActivity;
import gunn.brewski.app.R;
import gunn.brewski.app.Utility;
import gunn.brewski.app.data.BrewskiContract;
public class BrewskiSyncAdapter extends AbstractThreadedSyncAdapter {
public static final String CALLING_LIST = "callingList";
public final String LOG_TAG = BrewskiSyncAdapter.class.getSimpleName();
// Interval at which to sync with the weather, in seconds.
// 60 seconds (1 minute) * 180 = 3 hours
public static final int SYNC_INTERVAL = 1000 * 60 * 60 * 24;
public static final int SYNC_FLEXTIME = SYNC_INTERVAL/3;
private static final long DAY_IN_MILLIS = SYNC_INTERVAL;
private static final int BEER_NOTIFICATION_ID = 3004;
private static final int BREWERY_NOTIFICATION_ID = 4004;
private int beerPage = 1;
private int breweryPage = 1;
private int categoryPage = 1;
private int stylePage = 1;
private static final String[] NOTIFY_BEER_OF_THE_DAY = new String[] {
BrewskiContract.BeerEntry.COLUMN_BEER_ID,
BrewskiContract.BeerEntry.COLUMN_BEER_NAME,
BrewskiContract.BeerEntry.COLUMN_BEER_DESCRIPTION,
BrewskiContract.BeerEntry.COLUMN_LABEL_ICON
};
// these indices must match the projection
private static final int COLUMN_BEER_ID = 0;
private static final int COLUMN_BEER_NAME = 1;
private static final int COLUMN_BEER_DESCRIPTION = 2;
private static final int COLUMN_LABEL_ICON = 3;
public BrewskiSyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
}
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
Log.d(LOG_TAG, "Starting sync");
String callingList = extras.getString(CALLING_LIST);
Intent intent = new Intent();
intent.setAction("moreBeersLoaded");
if(callingList.equals("beer")) {
performBeerSync();
intent.setAction("moreBeersLoaded");
}
else if(callingList.equals("brewery")) {
performBrewerySync();
intent.setAction("moreBreweriesLoaded");
}
else if(callingList.equals("category")) {
performCategorySync();
intent.setAction("moreCategoriesLoaded");
}
else if(callingList.equals("style")) {
performStyleSync();
intent.setAction("moreStylesLoaded");
}
else {
performBeerSync();
}
getContext().sendBroadcast(intent);
return;
}
private void performBeerSync() {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection beerUrlConnection = null;
BufferedReader beerReader = null;
if(null == BrewskiApplication.getCurrentBeerPage()) {
BrewskiApplication.setCurrentBeerPage(1);
}
// Will contain the raw JSON response as a string.
String beerJsonStr = null;
String format = "json";
String api_key = "1be59a6cc44af64d5c7d6aafad061f23";
String endpoint = "beers";
String page = String.valueOf(BrewskiApplication.getCurrentBeerPage());
String withBreweries = "Y";
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
final String BREWERY_DB_BASE_URL =
"http://api.brewerydb.com/v2/" + endpoint + "?";
final String FORMAT_PARAM = "format";
final String KEY_PARAM = "key";
final String PAGE_PARAM = "p";
final String WITH_BREWERIES = "withBreweries";
Uri builtBeerUri = Uri.parse(BREWERY_DB_BASE_URL).buildUpon()
.appendQueryParameter(PAGE_PARAM, page)
.appendQueryParameter(WITH_BREWERIES, withBreweries)
.appendQueryParameter(KEY_PARAM, api_key)
.appendQueryParameter(FORMAT_PARAM, format)
.build();
URL beerUrl = new URL(builtBeerUri.toString());
// Create the request to OpenWeatherMap, and open the connection
beerUrlConnection = (HttpURLConnection) beerUrl.openConnection();
beerUrlConnection.setRequestMethod("GET");
beerUrlConnection.connect();
// Read the input stream into a String
InputStream beerInputStream = beerUrlConnection.getInputStream();
StringBuffer beerBuffer = new StringBuffer();
if (beerInputStream == null) {
// Nothing to do.
return;
}
beerReader = new BufferedReader(new InputStreamReader(beerInputStream));
String line;
while ((line = beerReader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
beerBuffer.append(line + "\n");
}
if (beerBuffer.length() == 0) {
// Stream was empty. No point in parsing.
return;
}
beerJsonStr = beerBuffer.toString();
BrewskiApplication.setCurrentBeerPage(BrewskiApplication.getCurrentBeerPage() + 1);
getBeerDataFromJson(beerJsonStr);
}
catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
e.printStackTrace();
// If the code didn't successfully get the weather data, there's no point in attempting
// to parse it.
}
catch (Exception e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
finally {
if (beerUrlConnection != null) {
beerUrlConnection.disconnect();
}
if (beerReader != null) {
try {
beerReader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
e.printStackTrace();
}
}
}
}
private void performBrewerySync() {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection breweryUrlConnection = null;
BufferedReader breweryReader = null;
if(null == BrewskiApplication.getCurrentBreweryPage()) {
BrewskiApplication.setCurrentBreweryPage(1);
}
// Will contain the raw JSON response as a string.
String breweryJsonStr = null;
String format = "json";
String api_key = "1be59a6cc44af64d5c7d6aafad061f23";
String endpoint = "breweries";
String page = String.valueOf(BrewskiApplication.getCurrentBreweryPage());
String withGuilds = "Y";
String withLocations = "Y";
String withAlternateNames = "Y";
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
final String BREWERY_DB_BASE_URL =
"http://api.brewerydb.com/v2/" + endpoint + "?";
final String FORMAT_PARAM = "format";
final String KEY_PARAM = "key";
final String PAGE_PARAM = "p";
final String WITH_GUILDS = "withGuilds";
final String WITH_LOCATIONS = "withLocations";
final String WITH_ALTERNATE_NAMES = "withAlternateNames";
Uri builtBreweryUri = Uri.parse(BREWERY_DB_BASE_URL).buildUpon()
.appendQueryParameter(PAGE_PARAM, page)
.appendQueryParameter(KEY_PARAM, api_key)
.appendQueryParameter(FORMAT_PARAM, format)
.appendQueryParameter(WITH_GUILDS, withGuilds)
.appendQueryParameter(WITH_LOCATIONS, withLocations)
.appendQueryParameter(WITH_ALTERNATE_NAMES, withAlternateNames)
.build();
URL breweryUrl = new URL(builtBreweryUri.toString());
// Create the request to OpenWeatherMap, and open the connection
breweryUrlConnection = (HttpURLConnection) breweryUrl.openConnection();
breweryUrlConnection.setRequestMethod("GET");
breweryUrlConnection.connect();
// Read the input stream into a String
InputStream breweryInputStream = breweryUrlConnection.getInputStream();
StringBuffer breweryBuffer = new StringBuffer();
if (breweryInputStream == null) {
// Nothing to do.
return;
}
breweryReader = new BufferedReader(new InputStreamReader(breweryInputStream));
String line;
while ((line = breweryReader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
breweryBuffer.append(line + "\n");
}
if (breweryBuffer.length() == 0) {
// Stream was empty. No point in parsing.
return;
}
BrewskiApplication.setCurrentBreweryPage(BrewskiApplication.getCurrentBreweryPage() + 1);
breweryJsonStr = breweryBuffer.toString();
getBreweryDataFromJson(breweryJsonStr);
}
catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attempting
// to parse it.
}
catch (Exception e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
finally {
if (breweryUrlConnection != null) {
breweryUrlConnection.disconnect();
}
if (breweryReader != null) {
try {
breweryReader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
}
private void performCategorySync() {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection categoryUrlConnection = null;
BufferedReader categoryReader = null;
// Will contain the raw JSON response as a string.
String categoryJsonStr = null;
String format = "json";
String api_key = "1be59a6cc44af64d5c7d6aafad061f23";
String endpoint = "categories";
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
final String BREWERY_DB_BASE_URL =
"http://api.brewerydb.com/v2/" + endpoint + "?";
final String FORMAT_PARAM = "format";
final String KEY_PARAM = "key";
Uri builtCategoryUri = Uri.parse(BREWERY_DB_BASE_URL).buildUpon()
.appendQueryParameter(KEY_PARAM, api_key)
.appendQueryParameter(FORMAT_PARAM, format)
.build();
URL beerUrl = new URL(builtCategoryUri.toString());
// Create the request to OpenWeatherMap, and open the connection
categoryUrlConnection = (HttpURLConnection) beerUrl.openConnection();
categoryUrlConnection.setRequestMethod("GET");
categoryUrlConnection.connect();
// Read the input stream into a String
InputStream categoryInputStream = categoryUrlConnection.getInputStream();
StringBuffer categoryBuffer = new StringBuffer();
if (categoryInputStream == null) {
// Nothing to do.
return;
}
categoryReader = new BufferedReader(new InputStreamReader(categoryInputStream));
String line;
while ((line = categoryReader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
categoryBuffer.append(line + "\n");
}
if (categoryBuffer.length() == 0) {
// Stream was empty. No point in parsing.
return;
}
categoryJsonStr = categoryBuffer.toString();
getCategoryDataFromJson(categoryJsonStr);
}
catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attempting
// to parse it.
}
catch (Exception e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
finally {
if (categoryUrlConnection != null) {
categoryUrlConnection.disconnect();
}
if (categoryReader != null) {
try {
categoryReader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
}
private void performStyleSync() {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection styleUrlConnection = null;
BufferedReader styleReader = null;
if(null == BrewskiApplication.getCurrentStylePage()) {
BrewskiApplication.setCurrentStylePage(1);
}
// Will contain the raw JSON response as a string.
String styleJsonStr = null;
String format = "json";
String api_key = "1be59a6cc44af64d5c7d6aafad061f23";
String endpoint = "styles";
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
final String BREWERY_DB_BASE_URL =
"http://api.brewerydb.com/v2/" + endpoint + "?";
final String FORMAT_PARAM = "format";
final String KEY_PARAM = "key";
Uri builtStyleUri = Uri.parse(BREWERY_DB_BASE_URL).buildUpon()
.appendQueryParameter(KEY_PARAM, api_key)
.appendQueryParameter(FORMAT_PARAM, format)
.build();
URL styleUrl = new URL(builtStyleUri.toString());
// Create the request to OpenWeatherMap, and open the connection
styleUrlConnection = (HttpURLConnection) styleUrl.openConnection();
styleUrlConnection.setRequestMethod("GET");
styleUrlConnection.connect();
// Read the input stream into a String
InputStream styleInputStream = styleUrlConnection.getInputStream();
StringBuffer styleBuffer = new StringBuffer();
if (styleInputStream == null) {
// Nothing to do.
return;
}
styleReader = new BufferedReader(new InputStreamReader(styleInputStream));
String line;
while ((line = styleReader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
styleBuffer.append(line + "\n");
}
if (styleBuffer.length() == 0) {
// Stream was empty. No point in parsing.
return;
}
styleJsonStr = styleBuffer.toString();
getStyleDataFromJson(styleJsonStr);
}
catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attempting
// to parse it.
}
catch (Exception e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
finally {
if (styleUrlConnection != null) {
styleUrlConnection.disconnect();
}
if (styleReader != null) {
try {
styleReader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
}
/**
* Take the String representing the complete beer results in JSON Format and
* pull out the data we need to construct the Strings needed for the wireframes.
*
* Fortunately parsing is easy: constructor takes the JSON string and converts it
* into an Object hierarchy for us.
*/
private void getBeerDataFromJson(String beerJsonStr) throws JSONException {
// Now we have a String representing the complete forecast in JSON Format.
// Fortunately parsing is easy: constructor takes the JSON string and converts it
// into an Object hierarchy for us.
// These are the names of the JSON objects that need to be extracted.
// Beer Information
final String BDB_CURRENT_PAGE = "currentPage";
final String BDB_NUMBER_OF_PAGES = "numberOfPages";
final String BDB_BEER_ID = "id";
final String BDB_BEER_NAME = "name";
final String BDB_BEER_DESCRIPTION = "description";
final String BDB_BEER_BREWERIES = "breweries";
final String BDB_BREWERY_ID = "id";
final String BDB_BREWERY_NAME = "name";
final String BDB_BREWERY_DESCRIPTION = "description";
final String BDB_BREWERY_WEBSITE = "website";
final String BDB_BREWERY_ESTABLISHED = "established";
final String BDB_BREWERY_IMAGES = "images";
final String BDB_BREWERY_IMAGE_LARGE = "large";
final String BDB_BREWERY_IMAGE_MEDIUM = "medium";
final String BDB_BREWERY_IMAGE_ICON = "icon";
final String BDB_BEER_STYLE = "style";
final String BDB_STYLE_ID = "id";
final String BDB_STYLE_NAME = "name";
final String BDB_STYLE_SHORT_NAME = "shortName";
final String BDB_STYLE_DESCRIPTION = "description";
final String BDB_STYLE_CATEGORY = "category";
final String BDB_CATEGORY_ID = "id";
final String BDB_CATEGORY_NAME = "name";
// TODO: INGREDIENTS_ID
final String BDB_BEER_LABELS = "labels";
final String BDB_BEER_LABEL_ICON = "icon";
final String BDB_BEER_LABEL_MEDIUM = "medium";
final String BDB_BEER_LABEL_LARGE = "large";
// Beer information. Each beer's info is an element of the "list" array.
final String BDB_DATA = "data";
final String BDB_VALUE = "value";
try {
JSONObject beerJson = new JSONObject(beerJsonStr);
String currentPage = beerJson.getString(BDB_CURRENT_PAGE);
String numberOfPages = beerJson.getString(BDB_NUMBER_OF_PAGES);
JSONArray beerArray = beerJson.getJSONArray(BDB_DATA);
BrewskiApplication.setCurrentBeerPage(Integer.parseInt(currentPage) + 1);
BrewskiApplication.setNumberOfBeerPages(Integer.parseInt(numberOfPages));
// Insert the new beer information into the database
Vector<ContentValues> beerContentValuesVector = new Vector<ContentValues>(beerArray.length());
Vector<ContentValues> breweryContentValuesVector = new Vector<ContentValues>(beerArray.length());
Vector<ContentValues> categoryContentValuesVector = new Vector<ContentValues>(beerArray.length());
Vector<ContentValues> styleContentValuesVector = new Vector<ContentValues>(beerArray.length());
for(int i = 0; i < beerArray.length(); i++) {
// These are the values that will be collected.
String beerId;
String beerName;
String beerDescription;
String beerBreweryId;
String beerCategoryId;
String beerStyleId;
// TODO: INGREDIENTS_ID
String beerLabelIcon;
String beerLabelMedium;
String beerLabelLarge;
String breweryId;
String breweryName;
String breweryDescription;
String breweryWebsite;
String breweryEstablished;
// TODO: LOCATION_ID
String breweryImageLarge;
String breweryImageMedium;
String breweryImageIcon;
String categoryId;
String categoryName;
String styleId;
String styleName;
String styleShortName;
String styleDescription;
String styleCategoryId;
// Get the JSON object representing the day
JSONObject beerInfo = beerArray.getJSONObject(i);
// Cheating to convert this to UTC time, which is what we want anyhow
beerId = beerInfo.getString(BDB_BEER_ID);
beerName = beerInfo.getString(BDB_BEER_NAME);
if(beerInfo.has(BDB_BEER_DESCRIPTION)) {
beerDescription = beerInfo.getString(BDB_BEER_DESCRIPTION);
}
else {
beerDescription = null;
}
if(beerInfo.has(BDB_BEER_LABELS)) {
JSONObject beerLabels = beerInfo.getJSONObject(BDB_BEER_LABELS);
beerLabelIcon = beerLabels.getString(BDB_BEER_LABEL_ICON);
beerLabelMedium = beerLabels.getString(BDB_BEER_LABEL_MEDIUM);
beerLabelLarge = beerLabels.getString(BDB_BEER_LABEL_LARGE);
}
else {
beerLabelIcon = null;
beerLabelMedium = null;
beerLabelLarge = null;
}
if(beerInfo.has(BDB_BEER_STYLE)) {
JSONObject styleInfo = beerInfo.getJSONObject(BDB_BEER_STYLE);
beerStyleId = styleInfo.getString(BDB_STYLE_ID);
styleId = styleInfo.getString(BDB_STYLE_ID);
styleName = styleInfo.getString(BDB_STYLE_NAME);
styleShortName = styleInfo.getString(BDB_STYLE_SHORT_NAME);
styleDescription = styleInfo.getString(BDB_STYLE_DESCRIPTION);
JSONObject categoryInfo = styleInfo.getJSONObject(BDB_STYLE_CATEGORY);
beerCategoryId = categoryInfo.getString(BDB_CATEGORY_ID);
styleCategoryId = categoryInfo.getString(BDB_CATEGORY_ID);
categoryId = categoryInfo.getString(BDB_CATEGORY_ID);
categoryName = categoryInfo.getString(BDB_CATEGORY_NAME);
}
else {
beerStyleId = null;
styleId = null;
styleName = null;
styleShortName = null;
styleDescription = null;
beerCategoryId = null;
styleCategoryId = null;
categoryId = null;
categoryName = null;
}
JSONArray breweriesArray = beerInfo.getJSONArray(BDB_BEER_BREWERIES);
JSONObject breweryInfo = breweriesArray.getJSONObject(0);
beerBreweryId = breweryInfo.getString(BDB_BREWERY_ID);
breweryId = breweryInfo.getString(BDB_BREWERY_ID);
breweryName = breweryInfo.getString(BDB_BREWERY_NAME);
if(breweryInfo.has(BDB_BREWERY_DESCRIPTION)) {
breweryDescription = breweryInfo.getString(BDB_BREWERY_DESCRIPTION);
}
else {
breweryDescription = null;
}
if(breweryInfo.has(BDB_BREWERY_WEBSITE)) {
breweryWebsite = breweryInfo.getString(BDB_BREWERY_WEBSITE);
}
else {
breweryWebsite = null;
}
if(breweryInfo.has(BDB_BREWERY_ESTABLISHED)) {
breweryEstablished = breweryInfo.getString(BDB_BREWERY_ESTABLISHED);
}
else {
breweryEstablished = null;
}
// TODO: LOCATION_ID
if(breweryInfo.has(BDB_BREWERY_IMAGES)) {
JSONObject breweryImages = breweryInfo.getJSONObject(BDB_BREWERY_IMAGES);
breweryImageLarge = breweryImages.getString(BDB_BREWERY_IMAGE_LARGE);
breweryImageMedium = breweryImages.getString(BDB_BREWERY_IMAGE_MEDIUM);
breweryImageIcon = breweryImages.getString(BDB_BREWERY_IMAGE_ICON);
}
else {
breweryImageIcon = null;
breweryImageMedium = null;
breweryImageLarge = null;
}
// TODO: PULL LOCATION INFO AND PUT INTO THE LOCATION TABLE
// TODO: INGREDIENTS_ID
// TODO: PULL INGREDIENTS INFO AND PUT INTO THE INGREDIENTS TABLE
ContentValues beerValues = new ContentValues();
ContentValues breweryValues = new ContentValues();
ContentValues categoryValues = new ContentValues();
ContentValues styleValues = new ContentValues();
beerValues.put(BrewskiContract.BeerEntry.COLUMN_BEER_ID, beerId);
beerValues.put(BrewskiContract.BeerEntry.COLUMN_BEER_NAME, beerName);
beerValues.put(BrewskiContract.BeerEntry.COLUMN_BEER_DESCRIPTION, beerDescription);
beerValues.put(BrewskiContract.BeerEntry.COLUMN_BREWERY_ID, beerBreweryId);
beerValues.put(BrewskiContract.BeerEntry.COLUMN_CATEGORY_ID, beerCategoryId);
beerValues.put(BrewskiContract.BeerEntry.COLUMN_STYLE_ID, beerStyleId);
beerValues.put(BrewskiContract.BeerEntry.COLUMN_LABEL_ICON, beerLabelIcon);
beerValues.put(BrewskiContract.BeerEntry.COLUMN_LABEL_MEDIUM, beerLabelMedium);
beerValues.put(BrewskiContract.BeerEntry.COLUMN_LABEL_LARGE, beerLabelLarge);
breweryValues.put(BrewskiContract.BreweryEntry.COLUMN_BREWERY_ID, breweryId);
breweryValues.put(BrewskiContract.BreweryEntry.COLUMN_BREWERY_NAME, breweryName);
breweryValues.put(BrewskiContract.BreweryEntry.COLUMN_BREWERY_DESCRIPTION, breweryDescription);
breweryValues.put(BrewskiContract.BreweryEntry.COLUMN_BREWERY_WEBSITE, breweryWebsite);
breweryValues.put(BrewskiContract.BreweryEntry.COLUMN_ESTABLISHED, breweryEstablished);
breweryValues.put(BrewskiContract.BreweryEntry.COLUMN_IMAGE_LARGE, breweryImageLarge);
breweryValues.put(BrewskiContract.BreweryEntry.COLUMN_IMAGE_MEDIUM, breweryImageMedium);
breweryValues.put(BrewskiContract.BreweryEntry.COLUMN_IMAGE_ICON, breweryImageIcon);
styleValues.put(BrewskiContract.StyleEntry.COLUMN_STYLE_ID, styleId);
styleValues.put(BrewskiContract.StyleEntry.COLUMN_STYLE_NAME, styleName);
styleValues.put(BrewskiContract.StyleEntry.COLUMN_STYLE_SHORT_NAME, styleShortName);
styleValues.put(BrewskiContract.StyleEntry.COLUMN_STYLE_DESCRIPTION, styleDescription);
styleValues.put(BrewskiContract.StyleEntry.COLUMN_CATEGORY_ID, styleCategoryId);
categoryValues.put(BrewskiContract.CategoryEntry.COLUMN_CATEGORY_ID, categoryId);
categoryValues.put(BrewskiContract.CategoryEntry.COLUMN_CATEGORY_NAME, categoryName);
beerContentValuesVector.add(beerValues);
breweryContentValuesVector.add(breweryValues);
categoryContentValuesVector.add(categoryValues);
styleContentValuesVector.add(styleValues);
}
// add to database
if(beerContentValuesVector.size() > 0) {
ContentValues[] beerContentValuesArray = new ContentValues[beerContentValuesVector.size()];
beerContentValuesVector.toArray(beerContentValuesArray);
getContext().getContentResolver().bulkInsert(BrewskiContract.BeerEntry.BEER_CONTENT_URI, beerContentValuesArray);
// // delete old data so we don't build up an endless history
// getContext().getContentResolver().delete(BrewskiContract.BeerEntry.BEER_CONTENT_URI,
// BrewskiContract.BeerEntry.COLUMN_DATE + " <= ?",
// new String[] {Long.toString(dayTime.setJulianDay(julianStartDay-1))});
// notifyBeerOfTheDay();
}
Log.d(LOG_TAG, "Sync Complete. " + beerContentValuesVector.size() + " Beers Inserted");
if(breweryContentValuesVector.size() > 0) {
ContentValues[] breweryContentValuesArray = new ContentValues[breweryContentValuesVector.size()];
breweryContentValuesVector.toArray(breweryContentValuesArray);
getContext().getContentResolver().bulkInsert(BrewskiContract.BreweryEntry.BREWERY_CONTENT_URI, breweryContentValuesArray);
}
Log.d(LOG_TAG, "Sync Complete. " + breweryContentValuesVector.size() + " Breweries Inserted");
if(categoryContentValuesVector.size() > 0) {
ContentValues[] categoryContentValuesArray = new ContentValues[categoryContentValuesVector.size()];
categoryContentValuesVector.toArray(categoryContentValuesArray);
getContext().getContentResolver().bulkInsert(BrewskiContract.CategoryEntry.CATEGORY_CONTENT_URI, categoryContentValuesArray);
}
Log.d(LOG_TAG, "Sync Complete. " + categoryContentValuesVector.size() + " Categories Inserted");
if(styleContentValuesVector.size() > 0) {
ContentValues[] styleContentValuesArray = new ContentValues[styleContentValuesVector.size()];
styleContentValuesVector.toArray(styleContentValuesArray);
getContext().getContentResolver().bulkInsert(BrewskiContract.StyleEntry.STYLE_CONTENT_URI, styleContentValuesArray);
}
Log.d(LOG_TAG, "Sync Complete. " + styleContentValuesVector.size() + " Styles Inserted");
}
catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
catch(SQLiteConstraintException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
}
private void getBreweryDataFromJson(String breweryJsonStr) throws JSONException {
// Brewery Information
final String BDB_CURRENT_PAGE = "currentPage";
final String BDB_NUMBER_OF_PAGES = "numberOfPages";
final String BDB_BREWERY_ID = "id";
final String BDB_BREWERY_NAME = "name";
final String BDB_BREWERY_DESCRIPTION = "description";
final String BDB_BREWERY_WEBSITE = "website";
final String BDB_BREWERY_ESTABLISHED = "established";
// TODO: LOCATION_ID
final String BDB_BREWERY_IMAGES = "images";
final String BDB_BREWERY_IMAGE_ICON = "icon";
final String BDB_BREWERY_IMAGE_MEDIUM = "medium";
final String BDB_BREWERY_IMAGE_LARGE = "large";
// Beer information. Each beer's info is an element of the "list" array.
final String BDB_DATA = "data";
try {
JSONObject breweryJson = new JSONObject(breweryJsonStr);
String currentPage = breweryJson.getString(BDB_CURRENT_PAGE);
String numberOfPages = breweryJson.getString(BDB_NUMBER_OF_PAGES);
JSONArray breweryArray = breweryJson.getJSONArray(BDB_DATA);
BrewskiApplication.setCurrentBreweryPage(Integer.parseInt(currentPage) + 1);
BrewskiApplication.setNumberOfBreweryPages(Integer.parseInt(numberOfPages));
// Insert the new beer information into the database
Vector<ContentValues> breweryContentValuesVector = new Vector<ContentValues>(breweryArray.length());
for(int i = 0; i < breweryArray.length(); i++) {
// These are the values that will be collected.
String breweryId;
String breweryName;
String breweryDescription;
String breweryWebsite;
String breweryEstablished;
// TODO: LOCATION_ID
String breweryImageLarge;
String breweryImageMedium;
String breweryImageIcon;
// TODO: PULL LOCATION INFO AND PUT INTO THE LOCATION TABLE
// Get the JSON object representing the day
JSONObject breweryInfo = breweryArray.getJSONObject(i);
breweryId = breweryInfo.getString(BDB_BREWERY_ID);
breweryName = breweryInfo.getString(BDB_BREWERY_NAME);
if(breweryInfo.has(BDB_BREWERY_DESCRIPTION)) {
breweryDescription = breweryInfo.getString(BDB_BREWERY_DESCRIPTION);
}
else {
breweryDescription = null;
}
if(breweryInfo.has(BDB_BREWERY_WEBSITE)) {
breweryWebsite = breweryInfo.getString(BDB_BREWERY_WEBSITE);
}
else {
breweryWebsite = null;
}
if(breweryInfo.has(BDB_BREWERY_ESTABLISHED)) {
breweryEstablished = breweryInfo.getString(BDB_BREWERY_ESTABLISHED);
}
else {
breweryEstablished = null;
}
if(breweryInfo.has(BDB_BREWERY_IMAGES)) {
JSONObject breweryImages = breweryInfo.getJSONObject(BDB_BREWERY_IMAGES);
breweryImageLarge = breweryImages.getString(BDB_BREWERY_IMAGE_LARGE);
breweryImageMedium = breweryImages.getString(BDB_BREWERY_IMAGE_MEDIUM);
breweryImageIcon = breweryImages.getString(BDB_BREWERY_IMAGE_ICON);
}
else {
breweryImageIcon = null;
breweryImageMedium = null;
breweryImageLarge = null;
}
ContentValues breweryValues = new ContentValues();
breweryValues.put(BrewskiContract.BreweryEntry.COLUMN_BREWERY_ID, breweryId);
breweryValues.put(BrewskiContract.BreweryEntry.COLUMN_BREWERY_NAME, breweryName);
breweryValues.put(BrewskiContract.BreweryEntry.COLUMN_BREWERY_DESCRIPTION, breweryDescription);
breweryValues.put(BrewskiContract.BreweryEntry.COLUMN_BREWERY_WEBSITE, breweryWebsite);
breweryValues.put(BrewskiContract.BreweryEntry.COLUMN_ESTABLISHED, breweryEstablished);
breweryValues.put(BrewskiContract.BreweryEntry.COLUMN_IMAGE_LARGE, breweryImageLarge);
breweryValues.put(BrewskiContract.BreweryEntry.COLUMN_IMAGE_MEDIUM, breweryImageMedium);
breweryValues.put(BrewskiContract.BreweryEntry.COLUMN_IMAGE_ICON, breweryImageIcon);
breweryContentValuesVector.add(breweryValues);
}
// add to database
if (breweryContentValuesVector.size() > 0) {
ContentValues[] breweryContentValuesArray = new ContentValues[breweryContentValuesVector.size()];
breweryContentValuesVector.toArray(breweryContentValuesArray);
getContext().getContentResolver().bulkInsert(BrewskiContract.BreweryEntry.BREWERY_CONTENT_URI, breweryContentValuesArray);
}
Log.d(LOG_TAG, "Sync Complete. " + breweryContentValuesVector.size() + "Breweries Inserted");
}
catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
}
private void getCategoryDataFromJson(String categoryJsonStr) throws JSONException {
// Category Information
final String BDB_CURRENT_PAGE = "currentPage";
final String BDB_NUMBER_OF_PAGES = "numberOfPages";
final String BDB_CATEGORY_ID = "id";
final String BDB_CATEGORY_NAME = "name";
// Beer information. Each beer's info is an element of the "list" array.
final String BDB_DATA = "data";
try {
JSONObject categoryJson = new JSONObject(categoryJsonStr);
String currentPage = categoryJson.getString(BDB_CURRENT_PAGE);
String numberOfPages = categoryJson.getString(BDB_NUMBER_OF_PAGES);
JSONArray categoryArray = categoryJson.getJSONArray(BDB_DATA);
BrewskiApplication.setCurrentCategoryPage(Integer.parseInt(currentPage) + 1);
BrewskiApplication.setNumberOfCategoryPages(Integer.parseInt(numberOfPages));
// Insert the new beer information into the database
Vector<ContentValues> categoryContentValuesVector = new Vector<ContentValues>(categoryArray.length());
for(int i = 0; i < categoryArray.length(); i++) {
// These are the values that will be collected.
String categoryId;
String categoryName;
// Get the JSON object representing the day
JSONObject categoryInfo = categoryArray.getJSONObject(i);
categoryId = categoryInfo.getString(BDB_CATEGORY_ID);
categoryName = categoryInfo.getString(BDB_CATEGORY_NAME);
ContentValues categoryValues = new ContentValues();
categoryValues.put(BrewskiContract.CategoryEntry.COLUMN_CATEGORY_ID, categoryId);
categoryValues.put(BrewskiContract.CategoryEntry.COLUMN_CATEGORY_NAME, categoryName);
categoryContentValuesVector.add(categoryValues);
}
// add to database
if(categoryContentValuesVector.size() > 0) {
ContentValues[] categoryContentValuesArray = new ContentValues[categoryContentValuesVector.size()];
categoryContentValuesVector.toArray(categoryContentValuesArray);
getContext().getContentResolver().bulkInsert(BrewskiContract.CategoryEntry.CATEGORY_CONTENT_URI, categoryContentValuesArray);
}
Log.d(LOG_TAG, "Sync Complete. " + categoryContentValuesVector.size() + "Categories Inserted");
}
catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
}
private void getStyleDataFromJson(String styleJsonStr) throws JSONException {
// Style Information
final String BDB_CURRENT_PAGE = "currentPage";
final String BDB_NUMBER_OF_PAGES = "numberOfPages";
final String BDB_STYLE_ID = "id";
final String BDB_STYLE_NAME = "name";
final String BDB_STYLE_SHORT_NAME = "shortName";
final String BDB_STYLE_DESCRIPTION = "description";
final String BDB_STYLE_CATEGORY = "category";
final String BDB_STYLE_CATEGORY_ID = "id";
// Beer information. Each beer's info is an element of the "list" array.
final String BDB_DATA = "data";
try {
JSONObject styleJson = new JSONObject(styleJsonStr);
String currentPage = styleJson.getString(BDB_CURRENT_PAGE);
String numberOfPages = styleJson.getString(BDB_NUMBER_OF_PAGES);
JSONArray styleArray = styleJson.getJSONArray(BDB_DATA);
BrewskiApplication.setCurrentStylePage(Integer.parseInt(currentPage) + 1);
BrewskiApplication.setNumberOfStylePages(Integer.parseInt(numberOfPages));
// Insert the new beer information into the database
Vector<ContentValues> styleContentValuesVector = new Vector<ContentValues>(styleArray.length());
for(int i = 0; i < styleArray.length(); i++) {
// These are the values that will be collected.
String styleId;
String styleName;
String styleShortName;
String styleDescription;
String styleCategoryId;
// Get the JSON object representing the day
JSONObject styleInfo = styleArray.getJSONObject(i);
styleId = styleInfo.getString(BDB_STYLE_ID);
styleName = styleInfo.getString(BDB_STYLE_NAME);
styleShortName = styleInfo.getString(BDB_STYLE_SHORT_NAME);
styleDescription = styleInfo.getString(BDB_STYLE_DESCRIPTION);
JSONObject categoryInfo = styleInfo.getJSONObject(BDB_STYLE_CATEGORY);
styleCategoryId = categoryInfo.getString(BDB_STYLE_CATEGORY_ID);
ContentValues styleValues = new ContentValues();
styleValues.put(BrewskiContract.StyleEntry.COLUMN_STYLE_ID, styleId);
styleValues.put(BrewskiContract.StyleEntry.COLUMN_STYLE_NAME, styleName);
styleValues.put(BrewskiContract.StyleEntry.COLUMN_STYLE_SHORT_NAME, styleShortName);
styleValues.put(BrewskiContract.StyleEntry.COLUMN_STYLE_DESCRIPTION, styleDescription);
styleValues.put(BrewskiContract.StyleEntry.COLUMN_CATEGORY_ID, styleCategoryId);
styleContentValuesVector.add(styleValues);
}
// add to database
if(styleContentValuesVector.size() > 0) {
ContentValues[] styleContentValuesArray = new ContentValues[styleContentValuesVector.size()];
styleContentValuesVector.toArray(styleContentValuesArray);
getContext().getContentResolver().bulkInsert(BrewskiContract.StyleEntry.STYLE_CONTENT_URI, styleContentValuesArray);
}
Log.d(LOG_TAG, "Sync Complete. " + styleContentValuesVector.size() + "Styles Inserted");
}
catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
}
private void notifyBeerOfTheDay() {
Context context = getContext();
//checking the last update and notify if it' the first of the day
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String displayNotificationsKey = context.getString(R.string.app_name);
boolean displayNotifications = prefs.getBoolean(displayNotificationsKey,
Boolean.parseBoolean(context.getString(R.string.app_name)));
if ( displayNotifications ) {
String lastNotificationKey = context.getString(R.string.pref_last_notification);
long lastSync = prefs.getLong(lastNotificationKey, 0);
if (System.currentTimeMillis() - lastSync >= DAY_IN_MILLIS) {
// Last sync was more than 1 day ago, let's send a notification with the weather.
// String locationQuery = Utility.getPreferredLocation(context);
Uri beerUri = BrewskiContract.BeerEntry.buildBeerUri(System.currentTimeMillis());
// we'll query our contentProvider, as always
Cursor cursor = context.getContentResolver().query(beerUri, NOTIFY_BEER_OF_THE_DAY, null, null, null);
if (cursor.moveToFirst()) {
int beerId = cursor.getInt(COLUMN_BEER_ID);
double high = cursor.getDouble(COLUMN_BEER_NAME);
double low = cursor.getDouble(COLUMN_BEER_DESCRIPTION);
String desc = cursor.getString(COLUMN_LABEL_ICON);
// int iconId = Utility.getIconResourceForWeatherCondition(beerId);
// Resources resources = context.getResources();
// Bitmap largeIcon = BitmapFactory.decodeResource(resources,
// Utility.getArtResourceForWeatherCondition(beerId));
// String title = context.getString(R.string.app_name);
// // Define the text of the forecast.
// String contentText = String.format(context.getString(R.string.format_notification),
// desc,
// Utility.formatTemperature(context, high),
// Utility.formatTemperature(context, low));
// NotificationCompatBuilder is a very convenient way to build backward-compatible
// notifications. Just throw in some data.
// NotificationCompat.Builder mBuilder =
// new NotificationCompat.Builder(getContext())
// .setColor(resources.getColor(R.color.brewski_dark_grey))
// .setSmallIcon(iconId)
// .setLargeIcon(largeIcon)
// .setContentTitle(title)
// .setContentText(contentText);
// Make something interesting happen when the user clicks on the notification.
// In this case, opening the app is sufficient.
Intent resultIntent = new Intent(context, MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
// mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
// WEATHER_NOTIFICATION_ID allows you to update the notification later on.
// mNotificationManager.notify(BEER_NOTIFICATION_ID, mBuilder.build());
//refreshing last sync
SharedPreferences.Editor editor = prefs.edit();
editor.putLong(lastNotificationKey, System.currentTimeMillis());
editor.commit();
}
cursor.close();
}
}
}
// /**
// * Helper method to handle insertion of a new location in the weather database.
// *
// * @param locationSetting The location string used to request updates from the server.
// * @param cityName A human-readable city name, e.g "Mountain View"
// * @param lat the latitude of the city
// * @param lon the longitude of the city
// * @return the row ID of the added location.
// */
// long addLocation(String locationSetting, String cityName, double lat, double lon) {
// long locationId;
// // First, check if the location with this city name exists in the db
// Cursor locationCursor = getContext().getContentResolver().query(
// BrewskiContract.LocationEntry.CONTENT_URI,
// new String[]{BrewskiContract.LocationEntry._ID},
// BrewskiContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?",
// new String[]{locationSetting},
// null);
// if (locationCursor.moveToFirst()) {
// int locationIdIndex = locationCursor.getColumnIndex(BrewskiContract.LocationEntry._ID);
// locationId = locationCursor.getLong(locationIdIndex);
// } else {
// // Now that the content provider is set up, inserting rows of data is pretty simple.
// // First create a ContentValues object to hold the data you want to insert.
// ContentValues locationValues = new ContentValues();
// // Then add the data, along with the corresponding name of the data type,
// // so the content provider knows what kind of value is being inserted.
// locationValues.put(BrewskiContract.LocationEntry.COLUMN_CITY_NAME, cityName);
// locationValues.put(BrewskiContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
// locationValues.put(BrewskiContract.LocationEntry.COLUMN_COORD_LAT, lat);
// locationValues.put(BrewskiContract.LocationEntry.COLUMN_COORD_LONG, lon);
// // Finally, insert location data into the database.
// Uri insertedUri = getContext().getContentResolver().insert(
// BrewskiContract.LocationEntry.CONTENT_URI,
// locationValues
// // The resulting URI contains the ID for the row. Extract the locationId from the Uri.
// locationId = ContentUris.parseId(insertedUri);
// locationCursor.close();
// // Wait, that worked? Yes!
// return locationId;
/**
* Helper method to schedule the sync adapter periodic execution
*/
public static void configurePeriodicSync(Context context, int syncInterval, int flexTime) {
Account account = getSyncAccount(context);
String authority = context.getString(R.string.content_authority);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// we can enable inexact timers in our periodic sync
SyncRequest request = new SyncRequest.Builder().
syncPeriodic(syncInterval, flexTime).
setSyncAdapter(account, authority).
setExtras(new Bundle()).build();
ContentResolver.requestSync(request);
} else {
ContentResolver.addPeriodicSync(account,
authority, new Bundle(), syncInterval);
}
}
/**
* Helper method to have the sync adapter sync immediately
* @param context The context used to access the account service
*/
public static void syncImmediately(Context context, String listName) {
Bundle bundle = new Bundle();
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
bundle.putString(CALLING_LIST, listName);
ContentResolver.requestSync(getSyncAccount(context), context.getString(R.string.content_authority), bundle);
}
/**
* Helper method to get the fake account to be used with SyncAdapter, or make a new one
* if the fake account doesn't exist yet. If we make a new account, we call the
* onAccountCreated method so we can initialize things.
*
* @param context The context used to access the account service
* @return a fake account.
*/
public static Account getSyncAccount(Context context) {
// Get an instance of the Android account manager
AccountManager accountManager =
(AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
// Create the account type and default account
Account newAccount = new Account(
context.getString(R.string.app_name), context.getString(R.string.sync_account_type));
// If the password doesn't exist, the account doesn't exist
if ( null == accountManager.getPassword(newAccount) ) {
/*
* Add the account and account type, no password or user data
* If successful, return the Account object, otherwise report an error.
*/
if (!accountManager.addAccountExplicitly(newAccount, "", null)) {
return null;
}
/*
* If you don't set android:syncable="true" in
* in your <provider> element in the manifest,
* then call ContentResolver.setIsSyncable(account, AUTHORITY, 1)
* here.
*/
onAccountCreated(newAccount, context);
}
return newAccount;
}
private static void onAccountCreated(Account newAccount, Context context) {
/*
* Since we've created an account
*/
BrewskiSyncAdapter.configurePeriodicSync(context, SYNC_INTERVAL, SYNC_FLEXTIME);
/*
* Without calling setSyncAutomatically, our periodic sync will not be enabled.
*/
ContentResolver.setSyncAutomatically(newAccount, context.getString(R.string.content_authority), true);
/*
* Finally, let's do a sync to get things started
*/
syncImmediately(context, "default");
}
public static void initializeSyncAdapter(Context context) {
getSyncAccount(context);
}
}
|
package hu.sebcsaba.gitrelocate;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class GitCmdLineRunner implements GitRunner {
private final CmdLineTool cmdLine;
public GitCmdLineRunner(CmdLineTool cmdLine) {
this.cmdLine = cmdLine;
}
public CommitID getCommitId(String anyGitCommitRef) {
return new CommitID(gitString("rev-parse", anyGitCommitRef).trim());
}
public List<CommitID> getCommitParentIds(CommitID commitId) {
return getCommitIDList(gitStringList("log", "--pretty=%P", "-n", "1", commitId.toString()));
}
public Collection<String> getTagNames() {
return gitStringList("tag");
}
public Collection<String> getBranchNames() {
List<String> result = gitStringList("branch");
result.remove("*");
return result;
}
public String getActualHeadName() {
String head = gitString("rev-parse", "--abbrev-ref", "HEAD");
if ("HEAD".equals(head)) {
head = gitString("rev-parse", "HEAD");
}
return head.trim();
}
public void createBranch(String branchName) {
gitExec("branch", branchName);
}
public void createBranch(String branchName, CommitID commitId) {
gitExec("branch", branchName, commitId.toString());
}
public void removeBranch(String branchName) {
gitExec("branch", "-D", branchName);
}
public void moveBranch(String branchName, CommitID commitId) {
String head = getActualHeadName();
checkOut(branchName);
gitExec("reset", "--hard", commitId.toString());
checkOut(head);
}
public void checkOut(String branchName) {
gitExec("checkout", branchName);
}
public void createTag(String tagName) {
gitExec("tag", tagName);
}
public void createTag(String tagName, CommitID commitId) {
gitExec("tag", tagName, commitId.toString());
}
public void removeTag(String tagName) {
gitExec("tag", "-D", tagName);
}
public CommitID cherryPick(CommitID commitId) {
gitExec("cherry-pick", commitId.toString());
return getCommitId("HEAD");
}
public CommitID cherryPickMergeCommit(CommitID commitId, List<CommitID> newParentsIds) {
try {
gitExec("cherry-pick", "--no-ff", "--no-commit", "--mainline", "1", commitId.toString());
String treeId = gitString("write-tree").trim();
String message = getCommitMessage(commitId);
List<String> commitParams = new ArrayList<String>();
commitParams.addAll(Arrays.asList("git", "commit-tree", treeId));
for (CommitID newParentId : newParentsIds) {
commitParams.add("-p");
commitParams.add(newParentId.toString());
}
String commit = cmdLine.withInput(message).getString(commitParams.toArray(new String[commitParams.size()])).trim();
return new CommitID(commit);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
private String getCommitMessage(CommitID commitId) {
StringBuilder result = new StringBuilder();
String[] list = gitString("show", "--format=full", commitId.toString()).split("\\r?\\n");
for (int i=5; i<list.length; ++i) {
result.append(list[i]).append("\n");
}
return result.toString();
}
private void gitExec(String... params) {
try {
cmdLine.run(unshift("git", params));
}
catch (IOException ex) {
throw new RuntimeException(ex);
}
}
private String gitString(String... params) {
try {
return cmdLine.getString(unshift("git", params));
}
catch (IOException ex) {
throw new RuntimeException(ex);
}
}
private List<String> gitStringList(String... params) {
try {
return cmdLine.getStringList(unshift("git", params));
}
catch (IOException ex) {
throw new RuntimeException(ex);
}
}
private List<CommitID> getCommitIDList(List<String> ids) {
List<CommitID> result = new ArrayList<CommitID>(ids.size());
for (String id : ids) {
result.add(new CommitID(id));
}
return result;
}
private String[] unshift(String first, String[] rest) {
String[] result = new String[rest.length+1];
result[0] = first;
System.arraycopy(rest, 0, result, 1, rest.length);
return result;
}
}
|
package info.faceland.strife.util;
import info.faceland.strife.StrifePlugin;
import org.bukkit.entity.Player;
public class PlayerDataUtil {
public static int getCraftLevel(Player player) {
return StrifePlugin.getInstance().getChampionManager().getChampion(player.getUniqueId()).getCraftingLevel();
}
public static float getCraftExp(Player player) {
return StrifePlugin.getInstance().getChampionManager().getChampion(player.getUniqueId()).getCraftingExp();
}
public static float getCraftMaxExp(Player player) {
int level = getCraftLevel(player);
return StrifePlugin.getInstance().getCraftExperienceManager().getMaxCraftExp(level);
}
public static int getEnchantLevel(Player player) {
return StrifePlugin.getInstance().getChampionManager().getChampion(player.getUniqueId()).getEnchantLevel();
}
public static float getEnchantExp(Player player) {
return StrifePlugin.getInstance().getChampionManager().getChampion(player.getUniqueId()).getEnchantExp();
}
public static float getEnchantMaxExp(Player player) {
int level = getEnchantLevel(player);
return StrifePlugin.getInstance().getEnchantExperienceManager().getMaxExp(level);
}
public static int getFishLevel(Player player) {
return StrifePlugin.getInstance().getChampionManager().getChampion(player.getUniqueId()).getFishingLevel();
}
public static float getFishExp(Player player) {
return StrifePlugin.getInstance().getChampionManager().getChampion(player.getUniqueId()).getFishingExp();
}
public static float getFishMaxExp(Player player) {
int level = getFishLevel(player);
return StrifePlugin.getInstance().getFishExperienceManager().getMaxExp(level);
}
// TODO: Something better with the crap below here...
public static int getMaxItemDestroyLevel(Player player) {
return getMaxItemDestroyLevel(
StrifePlugin.getInstance().getChampionManager().getChampion(player.getUniqueId()).getCraftingLevel());
}
private static int getMaxItemDestroyLevel(int craftLvl) {
return 10 + (int)Math.floor((double)craftLvl/3) * 5;
}
public static int getMaxCraftItemLevel(Player player) {
return getMaxCraftItemLevel(
StrifePlugin.getInstance().getChampionManager().getChampion(player.getUniqueId()).getCraftingLevel());
}
public static int getMaxCraftItemLevel(int craftLvl) {
return 5 + (int)Math.floor((double)craftLvl/5) * 8;
}
}
|
package invtweaks.forge.asm;
import cpw.mods.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper;
import cpw.mods.fml.relauncher.FMLRelaunchLog;
import invtweaks.forge.asm.compatibility.CompatibilityConfigLoader;
import invtweaks.forge.asm.compatibility.ContainerInfo;
import invtweaks.forge.asm.compatibility.MethodInfo;
import net.minecraft.launchwrapper.IClassTransformer;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.*;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
public class ContainerTransformer implements IClassTransformer {
public static final String VALID_INVENTORY_METHOD = "invtweaks$validInventory";
public static final String VALID_CHEST_METHOD = "invtweaks$validChest";
public static final String LARGE_CHEST_METHOD = "invtweaks$largeChest";
public static final String STANDARD_INVENTORY_METHOD = "invtweaks$standardInventory";
public static final String ROW_SIZE_METHOD = "invtweaks$rowSize";
public static final String SLOT_MAP_METHOD = "invtweaks$slotMap";
public static final String CONTAINER_CLASS_INTERNAL = "net/minecraft/inventory/Container";
public static final String SLOT_MAPS_VANILLA_CLASS = "invtweaks/containers/VanillaSlotMaps";
public static final String SLOT_MAPS_MODCOMPAT_CLASS = "invtweaks/containers/CompatibilitySlotMaps";
public static final String ANNOTATION_CHEST_CONTAINER = "Linvtweaks/api/container/ChestContainer;";
public static final String ANNOTATION_CHEST_CONTAINER_ROW_CALLBACK = "Linvtweaks/api/container/ChestContainer$RowSizeCallback;";
public static final String ANNOTATION_INVENTORY_CONTAINER = "Linvtweaks/api/container/InventoryContainer;";
public static final String ANNOTATION_CONTAINER_SECTION_CALLBACK = "Linvtweaks/api/container/ContainerSectionCallback;";
private static Map<String, ContainerInfo> standardClasses = new HashMap<String, ContainerInfo>();
private static Map<String, ContainerInfo> compatibilityClasses = new HashMap<String, ContainerInfo>();
private static Map<String, ContainerInfo> configClasses = new HashMap<String, ContainerInfo>();
private static String containerClassName;
public ContainerTransformer() {
}
// This needs to have access to the FML remapper so it needs to run when we know it's been set up correctly.
private void lateInit() {
// TODO: ContainerCreative handling
// Standard non-chest type
standardClasses.put("net.minecraft.inventory.ContainerPlayer",
new ContainerInfo(true, true, false, getVanillaSlotMapInfo("containerPlayerSlots")));
standardClasses.put("net.minecraft.inventory.ContainerMerchant", new ContainerInfo(true, true, false));
standardClasses.put("net.minecraft.inventory.ContainerRepair",
new ContainerInfo(true, true, false, getVanillaSlotMapInfo("containerPlayerSlots")));
standardClasses.put("net.minecraft.inventory.ContainerHopper", new ContainerInfo(true, true, false));
standardClasses.put("net.minecraft.inventory.ContainerBeacon", new ContainerInfo(true, true, false));
standardClasses.put("net.minecraft.inventory.ContainerBrewingStand",
new ContainerInfo(true, true, false, getVanillaSlotMapInfo("containerBrewingSlots")));
standardClasses.put("net.minecraft.inventory.ContainerWorkbench",
new ContainerInfo(true, true, false, getVanillaSlotMapInfo("containerWorkbenchSlots")));
standardClasses.put("net.minecraft.inventory.ContainerEnchantment",
new ContainerInfo(true, true, false, getVanillaSlotMapInfo("containerEnchantmentSlots")));
standardClasses.put("net.minecraft.inventory.ContainerFurnace",
new ContainerInfo(true, true, false, getVanillaSlotMapInfo("containerFurnaceSlots")));
// Chest-type
standardClasses.put("net.minecraft.inventory.ContainerDispenser",
new ContainerInfo(false, false, true, (short) 3,
getVanillaSlotMapInfo("containerChestDispenserSlots")));
standardClasses.put("net.minecraft.inventory.ContainerChest", new ContainerInfo(false, false, true,
getVanillaSlotMapInfo(
"containerChestDispenserSlots")));
// Mod compatibility
// Equivalent Exchange 3
compatibilityClasses.put("com.pahimar.ee3.inventory.ContainerAlchemicalBag",
new ContainerInfo(false, false, true, true, (short) 13));
compatibilityClasses.put("com.pahimar.ee3.inventory.ContainerAlchemicalChest",
new ContainerInfo(false, false, true, true, (short) 13));
compatibilityClasses.put("com.pahimar.ee3.inventory.ContainerPortableCrafting",
new ContainerInfo(true, true, false,
getCompatiblitySlotMapInfo("ee3PortableCraftingSlots")));
// Ender Storage
// TODO Row size method. A bit less important because it's a config setting and 2 of 3 options give rowsize 9.
compatibilityClasses.put("codechicken.enderstorage.storage.item.ContainerEnderItemStorage",
new ContainerInfo(false, false, true));
// Galacticraft
compatibilityClasses.put("micdoodle8.mods.galacticraft.core.inventory.GCCoreContainerPlayer",
new ContainerInfo(true, true, false,
getCompatiblitySlotMapInfo("galacticraftPlayerSlots")));
try {
configClasses = CompatibilityConfigLoader.load("config/InvTweaksCompatibility.xml");
} catch(Exception ex) {
configClasses = new HashMap<String, ContainerInfo>();
ex.printStackTrace();
}
}
@Override
public byte[] transform(String name, String transformedName, byte[] bytes) {
if(containerClassName == null) {
if(FMLPlugin.runtimeDeobfEnabled) {
containerClassName = FMLDeobfuscatingRemapper.INSTANCE.unmap(CONTAINER_CLASS_INTERNAL);
} else {
containerClassName = CONTAINER_CLASS_INTERNAL;
}
lateInit();
}
ClassReader cr = new ClassReader(bytes);
ClassNode cn = new ClassNode(Opcodes.ASM4);
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
cr.accept(cn, 0);
if("net.minecraft.inventory.Container".equals(transformedName)) {
FMLRelaunchLog.info("InvTweaks: %s", transformedName);
transformBaseContainer(cn);
cn.accept(cw);
return cw.toByteArray();
}
if("net.minecraft.client.gui.inventory.ContainerCreative".equals(transformedName)) {
FMLRelaunchLog.info("InvTweaks: %s", transformedName);
transformCreativeContainer(cn);
cn.accept(cw);
return cw.toByteArray();
}
// Transform classes with explicitly specified information
ContainerInfo info = standardClasses.get(transformedName);
if(info != null) {
FMLRelaunchLog.info("InvTweaks: %s", transformedName);
transformContainer(cn, info);
cn.accept(cw);
return cw.toByteArray();
}
if("invtweaks.InvTweaksObfuscation".equals(transformedName)) {
FMLRelaunchLog.info("InvTweaks: %s", transformedName);
Type containertype = Type.getObjectType(containerClassName);
for(MethodNode method : (List<MethodNode>) cn.methods) {
if("isValidChest".equals(method.name)) {
ASMHelper.replaceSelfForwardingMethod(method, VALID_CHEST_METHOD, containertype);
} else if("isValidInventory".equals(method.name)) {
ASMHelper.replaceSelfForwardingMethod(method, VALID_INVENTORY_METHOD, containertype);
} else if("isStandardInventory".equals(method.name)) {
ASMHelper.replaceSelfForwardingMethod(method, STANDARD_INVENTORY_METHOD, containertype);
} else if("getSpecialChestRowSize".equals(method.name)) {
ASMHelper.replaceSelfForwardingMethod(method, ROW_SIZE_METHOD, containertype);
} else if("getContainerSlotMap".equals(method.name)) {
ASMHelper.replaceSelfForwardingMethod(method, SLOT_MAP_METHOD, containertype);
} else if("isLargeChest".equals(method.name)) {
ASMHelper.replaceSelfForwardingMethod(method, LARGE_CHEST_METHOD, containertype);
}
}
cn.accept(cw);
return cw.toByteArray();
}
info = configClasses.get(transformedName);
if(info != null) {
FMLRelaunchLog.info("InvTweaks: %s", transformedName);
transformContainer(cn, info);
cn.accept(cw);
return cw.toByteArray();
}
if(cn.visibleAnnotations != null) {
for(AnnotationNode annotation : (List<AnnotationNode>) cn.visibleAnnotations) {
if(annotation != null) {
ContainerInfo apiInfo = null;
if(ANNOTATION_CHEST_CONTAINER.equals(annotation.desc)) {
short rowSize = 9;
boolean isLargeChest = false;
if(annotation.values != null) {
for(int i = 0; i < annotation.values.size(); i += 2) {
String valueName = (String) annotation.values.get(i);
Object value = annotation.values.get(i + 1);
if("rowSize".equals(valueName)) {
rowSize = (short) ((Integer) value).intValue();
} else if("isLargeChest".equals(valueName)) {
isLargeChest = (Boolean) value;
}
}
}
apiInfo = new ContainerInfo(false, false, true, isLargeChest, rowSize);
MethodNode method = findAnnotatedMethod(cn, ANNOTATION_CHEST_CONTAINER_ROW_CALLBACK);
if(method != null) {
apiInfo.rowSizeMethod = new MethodInfo(Type.getMethodType(method.desc),
Type.getObjectType(cn.name), method.name);
}
} else if(ANNOTATION_INVENTORY_CONTAINER.equals(annotation.desc)) {
boolean showOptions = true;
if(annotation.values != null) {
for(int i = 0; i < annotation.values.size(); i += 2) {
String valueName = (String) annotation.values.get(i);
Object value = annotation.values.get(i + 1);
if("showOptions".equals(valueName)) {
showOptions = (Boolean) value;
}
}
}
apiInfo = new ContainerInfo(showOptions, true, false);
}
if(apiInfo != null) {
// Search methods to see if any have the ContainerSectionCallback attribute.
MethodNode method = findAnnotatedMethod(cn, ANNOTATION_CONTAINER_SECTION_CALLBACK);
if(method != null) {
apiInfo.slotMapMethod = new MethodInfo(Type.getMethodType(method.desc),
Type.getObjectType(cn.name), method.name);
}
transformContainer(cn, apiInfo);
cn.accept(cw);
return cw.toByteArray();
}
}
}
}
info = compatibilityClasses.get(transformedName);
if(info != null) {
FMLRelaunchLog.info("InvTweaks: %s", transformedName);
transformContainer(cn, info);
cn.accept(cw);
return cw.toByteArray();
}
if("net.minecraft.client.gui.GuiTextField".equals(transformedName)) {
FMLRelaunchLog.info("InvTweaks: %s", transformedName);
transformTextField(cn);
cn.accept(cw);
return cw.toByteArray();
}
return bytes;
}
private MethodNode findAnnotatedMethod(ClassNode cn, String annotationDesc) {
for(MethodNode method : (List<MethodNode>) cn.methods) {
if(method.visibleAnnotations != null) {
for(AnnotationNode methodAnnotation : (List<AnnotationNode>) method.visibleAnnotations) {
if(annotationDesc.equals(methodAnnotation.desc)) {
return method;
}
}
}
}
return null;
}
/**
* Alter class to contain information contained by ContainerInfo
*
* @param clazz Class to alter
* @param info Information used to alter class
*/
public static void transformContainer(ClassNode clazz, ContainerInfo info) {
ASMHelper.generateBooleanMethodConst(clazz, STANDARD_INVENTORY_METHOD, info.standardInventory);
ASMHelper.generateBooleanMethodConst(clazz, VALID_INVENTORY_METHOD, info.validInventory);
ASMHelper.generateBooleanMethodConst(clazz, VALID_CHEST_METHOD, info.validChest);
ASMHelper.generateBooleanMethodConst(clazz, LARGE_CHEST_METHOD, info.largeChest);
if(info.rowSizeMethod != null) {
if(info.rowSizeMethod.isStatic) {
ASMHelper.generateForwardingToStaticMethod(clazz, ROW_SIZE_METHOD, info.rowSizeMethod.methodName,
info.rowSizeMethod.methodType.getReturnType(),
info.rowSizeMethod.methodClass,
info.rowSizeMethod.methodType.getArgumentTypes()[0]);
} else {
ASMHelper.generateSelfForwardingMethod(clazz, ROW_SIZE_METHOD, info.rowSizeMethod.methodName,
info.rowSizeMethod.methodType.getReturnType());
}
} else {
ASMHelper.generateIntegerMethodConst(clazz, ROW_SIZE_METHOD, info.rowSize);
}
if(info.slotMapMethod.isStatic) {
ASMHelper.generateForwardingToStaticMethod(clazz, SLOT_MAP_METHOD, info.slotMapMethod.methodName,
info.slotMapMethod.methodType.getReturnType(),
info.slotMapMethod.methodClass,
info.slotMapMethod.methodType.getArgumentTypes()[0]);
} else {
ASMHelper.generateSelfForwardingMethod(clazz, SLOT_MAP_METHOD, info.slotMapMethod.methodName,
info.slotMapMethod.methodType.getReturnType());
}
}
/**
* Alter class to contain default implementations of added methods.
*
* @param clazz Class to alter
*/
public static void transformBaseContainer(ClassNode clazz) {
ASMHelper.generateBooleanMethodConst(clazz, STANDARD_INVENTORY_METHOD, false);
ASMHelper.generateBooleanMethodConst(clazz, VALID_INVENTORY_METHOD, false);
ASMHelper.generateBooleanMethodConst(clazz, VALID_CHEST_METHOD, false);
ASMHelper.generateBooleanMethodConst(clazz, LARGE_CHEST_METHOD, false);
ASMHelper.generateIntegerMethodConst(clazz, ROW_SIZE_METHOD, (short) 9);
ASMHelper.generateForwardingToStaticMethod(clazz, SLOT_MAP_METHOD, "unknownContainerSlots",
Type.getObjectType("java/util/Map"),
Type.getObjectType(SLOT_MAPS_VANILLA_CLASS));
}
public static void transformCreativeContainer(ClassNode clazz) {
/* FIXME: Reqired methods cannot be compiled until SpecialSource update
ASMHelper.generateForwardingToStaticMethod(clazz, STANDARD_INVENTORY_METHOD, "containerCreativeIsInventory",
Type.BOOLEAN_TYPE, Type.getObjectType(SLOT_MAPS_VANILLA_CLASS));
ASMHelper.generateForwardingToStaticMethod(clazz, VALID_INVENTORY_METHOD, "containerCreativeIsInventory",
Type.BOOLEAN_TYPE, Type.getObjectType(SLOT_MAPS_VANILLA_CLASS));
ASMHelper.generateBooleanMethodConst(clazz, VALID_CHEST_METHOD, false);
ASMHelper.generateBooleanMethodConst(clazz, LARGE_CHEST_METHOD, false);
ASMHelper.generateIntegerMethodConst(clazz, ROW_SIZE_METHOD, (short) 9);
ASMHelper.generateForwardingToStaticMethod(clazz, SLOT_MAP_METHOD, "containerCreativeSlots",
Type.getObjectType("java/util/Map"),
Type.getObjectType(SLOT_MAPS_VANILLA_CLASS));
*/
}
private static void transformTextField(ClassNode clazz) {
for(MethodNode method : (List<MethodNode>) clazz.methods) {
String unmappedName = FMLDeobfuscatingRemapper.INSTANCE.mapMethodName(clazz.name, method.name, method.desc);
String unmappedDesc = FMLDeobfuscatingRemapper.INSTANCE.mapMethodDesc(method.desc);
if("func_146195_b".equals(unmappedName) && "(Z)V".equals(unmappedDesc)) {
InsnList code = method.instructions;
AbstractInsnNode returnNode = null;
for(ListIterator<AbstractInsnNode> iterator = code.iterator(); iterator.hasNext(); ) {
AbstractInsnNode insn = iterator.next();
if(insn.getOpcode() == Opcodes.RETURN) {
returnNode = insn;
break;
}
}
if(returnNode != null) {
// Insert a call to helper method to disable sorting while a text field is focused
code.insertBefore(returnNode, new VarInsnNode(Opcodes.ILOAD, 1));
code.insertBefore(returnNode,
new MethodInsnNode(Opcodes.INVOKESTATIC, "invtweaks/forge/InvTweaksMod",
"setTextboxModeStatic", "(Z)V"));
FMLRelaunchLog.info("InvTweaks: successfully transformed setFocused/func_146195_b");
} else {
FMLRelaunchLog.severe("InvTweaks: unable to find return in setFocused/func_146195_b");
}
}
}
}
public static MethodInfo getCompatiblitySlotMapInfo(String name) {
return getSlotMapInfo(Type.getObjectType(SLOT_MAPS_MODCOMPAT_CLASS), name, true);
}
public static MethodInfo getVanillaSlotMapInfo(String name) {
return getSlotMapInfo(Type.getObjectType(SLOT_MAPS_VANILLA_CLASS), name, true);
}
public static MethodInfo getSlotMapInfo(Type mClass, String name, boolean isStatic) {
return new MethodInfo(
Type.getMethodType(Type.getObjectType("java/util/Map"), Type.getObjectType(containerClassName)), mClass,
name, isStatic);
}
}
|
package io.cfp.controller;
import io.cfp.domain.exception.CospeakerNotFoundException;
import io.cfp.dto.TalkAdmin;
import io.cfp.entity.Role;
import io.cfp.entity.Talk;
import io.cfp.service.TalkAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@Secured(Role.ADMIN)
@RequestMapping(value = { "/v0/admin", "/api/admin" }, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class AdminSessionController {
@Autowired
private TalkAdminService talkService;
/**
* Get all sessions
*/
@RequestMapping(value="/sessions", method= RequestMethod.GET)
@ResponseBody
public List<TalkAdmin> getAllSessions(@RequestParam("status") String status) {
Talk.State[] accept;
if (status == null) {
accept = new Talk.State[] { Talk.State.CONFIRMED, Talk.State.ACCEPTED, Talk.State.REFUSED };
} else {
accept = new Talk.State[] { Talk.State.valueOf(status) };
}
return talkService.findAll(accept);
}
/**
* Get all drafts
*/
@RequestMapping(value="/drafts", method= RequestMethod.GET)
@ResponseBody
public List<TalkAdmin> getAllDrafts() {
return talkService.findAll(Talk.State.DRAFT);
}
/**
* Get a specific session
*/
@RequestMapping(value= "/sessions/{talkId}", method= RequestMethod.GET)
@ResponseBody
public TalkAdmin getTalk(@PathVariable int talkId) {
return talkService.getOne(talkId);
}
/**
* Edit a specific session
*/
@RequestMapping(value= "/sessions/{talkId}", method= RequestMethod.PUT)
@ResponseBody
public TalkAdmin editTalk(@PathVariable int talkId, @RequestBody TalkAdmin talkAdmin) throws CospeakerNotFoundException{
talkAdmin.setId(talkId);
return talkService.edit(talkAdmin);
}
/**
* Delete a session
*/
@RequestMapping(value="/sessions/{talkId}", method= RequestMethod.DELETE)
@ResponseBody
public TalkAdmin deleteGoogleSpreadsheet(@PathVariable int talkId) {
return talkService.delete(talkId);
}
}
|
package io.swagger.codegen;
import io.swagger.codegen.*;
import io.swagger.models.properties.*;
import java.util.*;
import java.io.File;
public class ElixirclientGenerator extends DefaultCodegen implements CodegenConfig {
// source folder where to write the files
protected String sourceFolder = "lib";
protected String apiVersion = "1.0.0";
/**
* Configures the type of generator.
*
* @return the CodegenType for this generator
* @see io.swagger.codegen.CodegenType
*/
public CodegenType getTag() {
return CodegenType.CLIENT;
}
/**
* Configures a friendly name for the generator. This will be used by the generator
* to select the library with the -l flag.
*
* @return the friendly name for the generator
*/
public String getName() {
return "ElixirClient";
}
/**
* Returns human-friendly help for the generator. Provide the consumer with help
* tips, parameters here
*
* @return A string value for the help message
*/
public String getHelp() {
return "Generates a ElixirClient client library.";
}
public ElixirclientGenerator() {
super();
// set the output folder here
outputFolder = "generated-code/ElixirClient";
/**
* Models. You can write model files using the modelTemplateFiles map.
* if you want to create one template for file, you can do so here.
* for multiple files for model, just put another entry in the `modelTemplateFiles` with
* a different extension
*/
modelTemplateFiles.put(
"model.mustache", // the template to use
".sample"); // the extension for each file to write
/**
* Api classes. You can write classes for each Api file with the apiTemplateFiles map.
* as with models, add multiple entries with different extensions for multiple files per
* class
*/
apiTemplateFiles.put(
"api.mustache", // the template to use
".sample"); // the extension for each file to write
/**
* Template Location. This is the location which templates will be read from. The generator
* will use the resource stream to attempt to read the templates.
*/
templateDir = "ElixirClient";
/**
* Model Package. Optional, if needed, this can be used in templates
*/
modelPackage = "io.swagger.client.model";
/**
* Reserved words. Override this with reserved words specific to your language
*/
reservedWords = new HashSet<String> (
Arrays.asList(
"sample1", // replace with static values
"sample2")
);
/**
* Additional Properties. These values can be passed to the templates and
* are available in models, apis, and supporting files
*/
additionalProperties.put("apiVersion", apiVersion);
/**
* Supporting Files. You can write single files for the generator with the
* entire object tree available. If the input file has a suffix of `.mustache
* it will be processed by the template engine. Otherwise, it will be copied
*/
supportingFiles.add(new SupportingFile("README.md.mustache", // the input template or file
"", // the destination folder, relative `outputFolder`
"README.md") // the output file
);
supportingFiles.add(new SupportingFile("config.exs.mustache",
"config",
"config.exs")
);
supportingFiles.add(new SupportingFile("mix.exs.mustache",
"",
"mix.exs")
);
supportingFiles.add(new SupportingFile("test_helper.exs.mustache",
"test",
"test_helper.exs")
);
/**
* Language Specific Primitives. These types will not trigger imports by
* the client generator
*/
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"Type1", // replace these with your types
"Type2")
);
}
/**
* Escapes a reserved word as defined in the `reservedWords` array. Handle escaping
* those terms here. This logic is only called if a variable matches the reseved words
*
* @return the escaped term
*/
@Override
public String escapeReservedWord(String name) {
return "_" + name; // add an underscore to the name
}
/**
* Location to write model files. You can use the modelPackage() as defined when the class is
* instantiated
*/
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar);
}
/**
* Location to write api files. You can use the apiPackage() as defined when the class is
* instantiated
*/
@Override
public String apiFileFolder() {
Object appName = additionalProperties.get("appName");
if(appName == null) {
appName = "";
}
// In most cases, appName represents the title of the schema as String.
assert appName instanceof String;
ArrayList<String> words = new ArrayList<String>();
for (String word : ((String) appName).split(" ")) {
words.add(snakeCase(word));
}
String apiPrefix = String.join("_", words);
if(0 < apiPrefix.length()) {
return outputFolder + "/" + sourceFolder + "/" + apiPrefix + "/" + "api";
} else {
return outputFolder + "/" + sourceFolder + "/" + "api";
}
}
@Override
public String toApiName(String name) {
if (name.length() == 0) {
return "Default";
}
return initialCaps(name);
}
@Override
public String toApiFilename(String name) {
return snakeCase(name);
}
/**
* Optional - type declaration. This is a String which is used by the templates to instantiate your
* types. There is typically special handling for different property types
*
* @return a string value used as the `dataType` field for model templates, `returnType` for api templates
*/
@Override
public String getTypeDeclaration(Property p) {
if(p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
}
else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]";
}
return super.getTypeDeclaration(p);
}
/**
* Optional - swagger type conversion. This is used to map swagger types in a `Property` into
* either language specific types via `typeMapping` or into complex models if there is not a mapping.
*
* @return a string value of the type or complex model for this property
* @see io.swagger.models.properties.Property
*/
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if(typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if(languageSpecificPrimitives.contains(type))
return toModelName(type);
}
else
type = swaggerType;
return toModelName(type);
}
}
|
package istc.bigdawg.executor.plan;
import java.util.Optional;
import istc.bigdawg.query.ConnectionInfo;
/**
* Represents a task to be completed by the Executor in order to execute a
* query.
*
* @author ankushg
*/
public interface ExecutionNode {
/**
* @return ConnectionInfo representing the database engine where the node should be
* executed
*/
public ConnectionInfo getEngine();
/**
* @return table name for where the result will be stored. If empty, then
* the result will be returned via the callback.
*/
public Optional<String> getTableName();
/**
* @return string to be used to query the engine represented by
* getEngineId(). If empty, then no query needs to be executed for
* the given node.
*/
public Optional<String> getQueryString();
}
|
package mariculture.core.handlers;
import java.util.HashMap;
import mariculture.api.core.ICastingHandler;
import mariculture.api.core.RecipeCasting;
import mariculture.api.core.RecipeCasting.RecipeBlockCasting;
import mariculture.api.core.RecipeCasting.RecipeIngotCasting;
import mariculture.api.core.RecipeCasting.RecipeNuggetCasting;
import mariculture.core.helpers.OreDicHelper;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.oredict.OreDictionary;
public class CastingHandler implements ICastingHandler {
private final HashMap<String, RecipeCasting> nuggets = new HashMap();
private final HashMap<String, RecipeCasting> ingots = new HashMap();
private final HashMap<String, RecipeCasting> blocks = new HashMap();
@Override
public void addRecipe(RecipeCasting recipe) {
if (recipe instanceof RecipeNuggetCasting) {
nuggets.put(recipe.fluid.getFluid().getName(), recipe);
}
if (recipe instanceof RecipeIngotCasting) {
ingots.put(recipe.fluid.getFluid().getName(), recipe);
}
if (recipe instanceof RecipeBlockCasting) {
blocks.put(recipe.fluid.getFluid().getName(), recipe);
}
}
@Override
public RecipeCasting getNuggetResult(FluidStack fluid) {
if (fluid == null) return null;
RecipeCasting result = nuggets.get(fluid.getFluid().getName());
if (result == null) return null;
return fluid.amount < result.fluid.amount ? null : result;
}
@Override
public RecipeCasting getIngotResult(FluidStack fluid) {
if (fluid == null) return null;
RecipeCasting result = ingots.get(fluid.getFluid().getName());
if (result == null) return null;
return fluid.amount < result.fluid.amount ? null : result;
}
@Override
public RecipeCasting getBlockResult(FluidStack fluid) {
if (fluid == null) return null;
RecipeCasting result = blocks.get(fluid.getFluid().getName());
if (result == null) return null;
return fluid.amount < result.fluid.amount ? null : result;
}
//Attempt to fetch the texture, using the ore dictionary
public static IIcon getTexture(ItemStack stack) {
String name = OreDicHelper.getDictionaryName(stack);
if (name.startsWith("nugget")) {
name = name.substring(6);
} else if (name.startsWith("ingot") || name.startsWith("block")) {
name = name.substring(5);
}
name = "block" + name;
Block block = null;
int damage = stack.getItemDamage();
if (OreDictionary.getOres(name).size() > 0) {
ItemStack item = OreDictionary.getOres(name).get(0);
block = Block.getBlockFromItem(item.getItem());
damage = item.getItemDamage();
} else if (stack.getItem() == Items.snowball) {
block = Blocks.snow;
} else if (OreDicHelper.getDictionaryName(stack).equals("foodSalt")) {
block = Blocks.wool;
damage = 0;
} else {
block = Block.getBlockFromItem(stack.getItem());
}
return block != null ? block.getIcon(0, damage) : Blocks.iron_block.getIcon(0, 0);
}
@Override
public HashMap<String, RecipeCasting> getNuggetRecipes() {
return nuggets;
}
@Override
public HashMap<String, RecipeCasting> getIngotRecipes() {
return ingots;
}
@Override
public HashMap<String, RecipeCasting> getBlockRecipes() {
return blocks;
}
}
|
package mcjty.deepresonance.blocks.tank;
import com.google.common.collect.Maps;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import elec332.core.multiblock.dynamic.IDynamicMultiBlockTile;
import elec332.core.world.WorldHelper;
import mcjty.deepresonance.DeepResonance;
import mcjty.deepresonance.api.fluid.IDeepResonanceFluidAcceptor;
import mcjty.deepresonance.api.fluid.IDeepResonanceFluidProvider;
import mcjty.deepresonance.blocks.base.ElecTileBase;
import mcjty.deepresonance.grid.fluid.event.FluidTileEvent;
import mcjty.deepresonance.grid.tank.DRTankMultiBlock;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.*;
import java.util.Map;
public class TileTank extends ElecTileBase implements IDynamicMultiBlockTile<DRTankMultiBlock>, IFluidHandler, IDeepResonanceFluidAcceptor, IDeepResonanceFluidProvider {
public static final int SETTING_NONE = 0;
public static final int SETTING_ACCEPT = 1;
public static final int SETTING_PROVIDE = 2;
public static final int SETTING_MAX = 2;
public TileTank(){
super();
this.settings = Maps.newHashMap();
for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS){
settings.put(direction, SETTING_NONE);
}
this.multiBlockSaveData = new NBTTagCompound();
}
private Fluid clientRenderFluid;
// Client only
private float renderHeight; //Value from 0.0f to 1.0f
private NBTTagCompound multiBlockSaveData;
protected Map<ForgeDirection, Integer> settings;
@Override
public void onTileLoaded() {
super.onTileLoaded();
if (!worldObj.isRemote) {
DeepResonance.worldGridRegistry.getTankRegistry().get(getWorldObj()).addTile(this);
MinecraftForge.EVENT_BUS.post(new FluidTileEvent.Load(this));
for (Map.Entry<ITankHook, ForgeDirection> entry : getConnectedHooks().entrySet()){
entry.getKey().hook(this, entry.getValue());
}
}
}
@Override
public void onTileUnloaded() {
super.onTileUnloaded();
if (!worldObj.isRemote) {
DeepResonance.worldGridRegistry.getTankRegistry().get(getWorldObj()).removeTile(this);
MinecraftForge.EVENT_BUS.post(new FluidTileEvent.Unload(this));
for (Map.Entry<ITankHook, ForgeDirection> entry : getConnectedHooks().entrySet()){
entry.getKey().unHook(this, entry.getValue());
}
}
}
private DRTankMultiBlock multiBlock;
public FluidStack myTank;
public Fluid lastSeenFluid;
public Map<ForgeDirection, Integer> getSettings() {
return settings;
}
@Override
public void readFromNBT(NBTTagCompound tagCompound) {
super.readFromNBT(tagCompound);
NBTTagList tagList = tagCompound.getTagList("settings", Constants.NBT.TAG_COMPOUND);
if (tagList != null){
for (int i = 0; i < tagList.tagCount(); i++) {
NBTTagCompound tag = tagList.getCompoundTagAt(i);
settings.put(ForgeDirection.valueOf(tag.getString("dir")), tag.getInteger("n"));
}
}
}
@Override
public void writeToNBT(NBTTagCompound tagCompound) {
super.writeToNBT(tagCompound);
NBTTagList tagList = new NBTTagList();
for (Map.Entry<ForgeDirection, Integer> entry : settings.entrySet()){
NBTTagCompound tag = new NBTTagCompound();
tag.setString("dir", entry.getKey().toString());
tag.setInteger("n", entry.getValue());
tagList.appendTag(tag);
}
tagCompound.setTag("settings", tagList);
}
@Override
public void readRestorableFromNBT(NBTTagCompound tagCompound) {
super.readRestorableFromNBT(tagCompound);
this.myTank = getFluidStackFromNBT(tagCompound);
multiBlockSaveData = tagCompound.getCompoundTag("multiBlockData");
if (tagCompound.hasKey("lastSeenFluid")) { /* legacy compat */
this.lastSeenFluid = FluidRegistry.getFluid(tagCompound.getString("lastSeenFluid"));
} else if (multiBlockSaveData.hasKey("lastSeenFluid")){
this.lastSeenFluid = FluidRegistry.getFluid(multiBlockSaveData.getString("lastSeenFluid"));
}
}
public static FluidStack getFluidStackFromNBT(NBTTagCompound tagCompound) {
NBTTagCompound mbTag = tagCompound.getCompoundTag("multiBlockData");
FluidStack s;
if (tagCompound.hasKey("fluid")) { /* legacy compat */
s = FluidStack.loadFluidStackFromNBT(tagCompound.getCompoundTag("fluid"));
} else if (mbTag.hasKey("fluid")){
s = FluidStack.loadFluidStackFromNBT(mbTag.getCompoundTag("fluid"));
} else {
s = null;
}
return s;
}
@Override
public void writeRestorableToNBT(NBTTagCompound tagCompound) {
super.writeRestorableToNBT(tagCompound);
if (multiBlock != null)
getMultiBlock().setDataToTile(this);
tagCompound.setTag("multiBlockData", multiBlockSaveData);
/*if (multiBlock != null) {
myTank = multiBlock.getFluidShare(this);
lastSeenFluid = multiBlock.getStoredFluid();
}
if (myTank != null) {
NBTTagCompound fluidTag = new NBTTagCompound();
myTank.writeToNBT(fluidTag);
tagCompound.setTag("fluid", fluidTag);
}
if (lastSeenFluid != null)
tagCompound.setString("lastSeenFluid", FluidRegistry.getFluidName(lastSeenFluid));*/
}
@Override
public boolean canUpdate() {
return false;
}
@Override
public void setMultiBlock(DRTankMultiBlock multiBlock) {
this.multiBlock = multiBlock;
}
@Override
public DRTankMultiBlock getMultiBlock() {
return multiBlock;
}
@Override
public void setSaveData(NBTTagCompound nbtTagCompound) {
this.multiBlockSaveData = nbtTagCompound;
}
@Override
public NBTTagCompound getSaveData() {
return this.multiBlockSaveData;
}
@Override
public int fill(ForgeDirection from, FluidStack resource, boolean doFill) {
if (!isInput(from))
return 0;
notifyChanges(doFill);
return multiBlock == null ? 0 : multiBlock.fill(from, resource, doFill);
}
@Override
public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) {
if (!isOutput(from))
return null;
notifyChanges(doDrain);
return multiBlock == null ? null : multiBlock.drain(from, resource, doDrain);
}
@Override
public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) {
if (!isOutput(from))
return null;
notifyChanges(doDrain);
return multiBlock == null ? null : multiBlock.drain(from, maxDrain, doDrain);
}
@Override
public boolean canFill(ForgeDirection from, Fluid fluid) {
return isInput(from) && multiBlock != null && multiBlock.canFill(from, fluid);
}
@Override
public boolean canDrain(ForgeDirection from, Fluid fluid) {
return isOutput(from) && multiBlock != null && multiBlock.canDrain(from, fluid);
}
@Override
public FluidTankInfo[] getTankInfo(ForgeDirection from) {
return multiBlock == null ? new FluidTankInfo[0] : multiBlock.getTankInfo(from);
}
@Override
public boolean canAcceptFrom(ForgeDirection direction) {
return isInput(direction);
}
@Override
public boolean canProvideTo(ForgeDirection direction) {
return isOutput(direction);
}
@Override
public FluidStack getProvidedFluid(int maxProvided, ForgeDirection from) {
if (!isOutput(from))
return null;
return getMultiBlock() == null ? null : getMultiBlock().drain(maxProvided, true);
}
@Override
public int getRequestedAmount(ForgeDirection from) {
if (!isInput(from))
return 0;
return multiBlock == null ? 0 : Math.min(multiBlock.getFreeSpace(), 1000);
}
@Override
public FluidStack acceptFluid(FluidStack fluidStack, ForgeDirection from) {
if (!isInput(from)) {
fill(from, fluidStack, true);
notifyChanges(true);
return null;
} else {
return fluidStack;
}
}
public Fluid getClientRenderFluid() {
return clientRenderFluid;
}
// Client only
public float getRenderHeight() {
return renderHeight;
}
public FluidStack getFluid() {
return multiBlock == null ? null : multiBlock.getFluid();
}
public NBTTagCompound getFluidTag() {
return getFluid() == null ? null : getFluid().tag;
}
public int getFluidAmount() {
return multiBlock == null ? 0 : multiBlock.getFluidAmount();
}
public int getCapacity() {
return multiBlock == null ? 0 : multiBlock.getCapacity();
}
private void notifyChanges(boolean b){
if (multiBlock != null && b){
for (Map.Entry<ITankHook, ForgeDirection> entry : getConnectedHooks().entrySet()){
entry.getKey().onContentChanged(this, entry.getValue());
}
}
}
protected Map<ITankHook, ForgeDirection> getConnectedHooks(){
Map<ITankHook, ForgeDirection> ret = Maps.newHashMap();
for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS){
try {
TileEntity tile = WorldHelper.getTileAt(worldObj, myLocation().atSide(direction));
if (tile instanceof ITankHook)
ret.put((ITankHook) tile, direction.getOpposite());
} catch (Exception e){
e.printStackTrace();
}
}
return ret;
}
public boolean isInput(ForgeDirection direction){
return direction == ForgeDirection.UNKNOWN || settings.get(direction) == SETTING_ACCEPT;
}
public boolean isOutput(ForgeDirection direction){
return direction == ForgeDirection.UNKNOWN || settings.get(direction) == SETTING_PROVIDE;
}
@Override
public void onDataPacket(int id, NBTTagCompound tag) {
switch (id){
case 1:
this.clientRenderFluid = FluidRegistry.getFluid(tag.getString("fluid"));
return;
case 2:
return;
case 3:
this.renderHeight = tag.getFloat("render");
}
}
}
|
package meltery.compat.jei;
import com.google.common.collect.ImmutableList;
import mezz.jei.api.ingredients.IIngredients;
import mezz.jei.api.recipe.BlankRecipeWrapper;
import net.minecraft.client.Minecraft;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidStack;
import slimeknights.tconstruct.library.TinkerRegistry;
import slimeknights.tconstruct.library.smeltery.MeltingRecipe;
import javax.annotation.Nonnull;
import java.util.List;
public class SmeltingRecipeWrapper extends BlankRecipeWrapper {
protected final List<ItemStack> inputs;
protected final List<FluidStack> outputs;
protected final int temperature;
protected final List<FluidStack> fuels;
public SmeltingRecipeWrapper(MeltingRecipe recipe) {
this.inputs = recipe.input.getInputs();
this.outputs = ImmutableList.of(recipe.getResult());
this.temperature = recipe.getTemperature();
ImmutableList.Builder<FluidStack> builder = ImmutableList.builder();
for(FluidStack fs : TinkerRegistry.getSmelteryFuels()) {
if(fs.getFluid().getTemperature(fs) >= temperature) {
fs = fs.copy();
fs.amount = 1000;
builder.add(fs);
}
}
fuels = builder.build();
}
@Override
public void getIngredients(IIngredients ingredients) {
ingredients.setInputs(ItemStack.class, inputs);
ingredients.setOutputs(FluidStack.class, outputs);
}
public void drawInfo(@Nonnull Minecraft minecraft, int recipeWidth, int recipeHeight, int mouseX, int mouseY) {
}
}
|
package mil.dds.anet.graphql;
import java.math.BigInteger;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import graphql.language.IntValue;
import graphql.schema.Coercing;
import graphql.schema.GraphQLScalarType;
public class GraphQLDateTimeType extends GraphQLScalarType {
private static final Coercing<DateTime, Long> coercing = new Coercing<DateTime, Long>() {
@Override
public Long serialize(Object input) {
return ((DateTime) input).getMillis();
}
@Override
public DateTime parseValue(Object input) {
if (input instanceof Long) {
return new DateTime((Long)input);
}
else if (input instanceof String) {
return DateTime.parse(input.toString(), ISODateTimeFormat.dateTimeParser());
}
else {
return new DateTime(Long.parseLong(input.toString()));
}
}
@Override
public DateTime parseLiteral(Object input) {
if (input.getClass().equals(IntValue.class)) {
BigInteger value = ((IntValue) input).getValue();
return new DateTime(value.longValue());
}
throw new RuntimeException("Unexpected input, expected Unix Millis as long");
}
};
public GraphQLDateTimeType() {
super("DateTime", null, coercing);
}
}
|
package mil.dds.anet.search;
import mil.dds.anet.beans.Task;
import mil.dds.anet.beans.lists.AnetBeanList;
import mil.dds.anet.beans.search.ISearchQuery.SortOrder;
import mil.dds.anet.beans.search.TaskSearchQuery;
import mil.dds.anet.database.mappers.TaskMapper;
import mil.dds.anet.search.AbstractSearchQueryBuilder.Comparison;
import ru.vyarus.guicey.jdbi3.tx.InTransaction;
public abstract class AbstractTaskSearcher extends AbstractSearcher<Task, TaskSearchQuery>
implements ITaskSearcher {
public AbstractTaskSearcher(AbstractSearchQueryBuilder<Task, TaskSearchQuery> qb) {
super(qb);
}
@InTransaction
@Override
public AnetBeanList<Task> runSearch(TaskSearchQuery query) {
buildQuery(query);
return qb.buildAndRun(getDbHandle(), query, new TaskMapper());
}
@Override
protected void buildQuery(TaskSearchQuery query) {
qb.addSelectClause("tasks.*");
qb.addTotalCount();
qb.addFromClause("tasks");
if (query.isTextPresent()) {
addTextQuery(query);
}
if (query.getResponsibleOrgUuid() != null) {
addResponsibleOrgUuidQuery(query);
}
qb.addEqualsClause("category", "tasks.category", query.getCategory());
qb.addEqualsClause("status", "tasks.status", query.getStatus());
qb.addLikeClause("projectStatus", "tasks.\"customFieldEnum1\"", query.getProjectStatus());
qb.addDateClause("plannedCompletionStart", "tasks.\"plannedCompletion\"", Comparison.AFTER,
query.getPlannedCompletionStart());
qb.addDateClause("plannedCompletionEnd", "tasks.\"plannedCompletion\"", Comparison.BEFORE,
query.getPlannedCompletionEnd());
qb.addDateClause("projectedCompletionStart", "tasks.\"projectedCompletion\"", Comparison.AFTER,
query.getProjectedCompletionStart());
qb.addDateClause("projectedCompletionEnd", "tasks.\"projectedCompletion\"", Comparison.BEFORE,
query.getProjectedCompletionEnd());
qb.addLikeClause("customField", "tasks.\"customField\"", query.getCustomField());
if (query.getCustomFieldRef1Uuid() != null) {
addCustomFieldRef1UuidQuery(query);
}
addOrderByClauses(qb, query);
}
protected abstract void addTextQuery(TaskSearchQuery query);
protected abstract void addResponsibleOrgUuidQuery(TaskSearchQuery query);
protected abstract void addCustomFieldRef1UuidQuery(TaskSearchQuery query);
protected void addOrderByClauses(AbstractSearchQueryBuilder<?, ?> qb, TaskSearchQuery query) {
switch (query.getSortBy()) {
case CREATED_AT:
qb.addAllOrderByClauses(getOrderBy(query.getSortOrder(), "tasks", "\"createdAt\""));
break;
case CATEGORY:
qb.addAllOrderByClauses(getOrderBy(query.getSortOrder(), "tasks", "category"));
break;
case NAME:
default:
qb.addAllOrderByClauses(getOrderBy(query.getSortOrder(), "tasks", "\"shortName\""));
break;
}
qb.addAllOrderByClauses(getOrderBy(SortOrder.ASC, "tasks", "uuid"));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.