answer
stringlengths
17
10.2M
package org.cyclops.integrateddynamics.core.evaluate.variable; import com.google.common.base.Optional; import lombok.ToString; import net.minecraft.item.ItemStack; import net.minecraft.nbt.JsonToNBT; import net.minecraft.nbt.NBTException; import net.minecraft.nbt.NBTTagCompound; import org.cyclops.cyclopscore.helper.ItemStackHelpers; import org.cyclops.integrateddynamics.api.evaluate.variable.IValueTypeNamed; import org.cyclops.integrateddynamics.api.evaluate.variable.IValueTypeNullable; /** * Value type with values that are itemstacks. * @author rubensworks */ public class ValueObjectTypeItemStack extends ValueObjectTypeBase<ValueObjectTypeItemStack.ValueItemStack> implements IValueTypeNamed<ValueObjectTypeItemStack.ValueItemStack>, IValueTypeNullable<ValueObjectTypeItemStack.ValueItemStack> { public ValueObjectTypeItemStack() { super("itemstack"); } @Override public ValueItemStack getDefault() { return ValueItemStack.of(null); } @Override public String toCompactString(ValueItemStack value) { Optional<ItemStack> itemStack = value.getRawValue(); return itemStack.isPresent() ? itemStack.get().getDisplayName() : ""; } @Override public String serialize(ValueItemStack value) { NBTTagCompound tag = new NBTTagCompound(); Optional<ItemStack> itemStack = value.getRawValue(); if(itemStack.isPresent()) { itemStack.get().writeToNBT(tag); tag.setInteger("Count", itemStack.get().stackSize); } return tag.toString(); } @Override public ValueItemStack deserialize(String value) { try { NBTTagCompound tag = JsonToNBT.getTagFromJson(value); ItemStack itemStack = ItemStack.loadItemStackFromNBT(tag); if (itemStack != null) { itemStack.stackSize = tag.getInteger("Count"); } return ValueItemStack.of(itemStack); } catch (NBTException e) { return null; } } @Override public String getName(ValueItemStack a) { return toCompactString(a); } @Override public boolean isNull(ValueItemStack a) { return !a.getRawValue().isPresent(); } @ToString public static class ValueItemStack extends ValueOptionalBase<ItemStack> { private ValueItemStack(ItemStack itemStack) { super(ValueTypes.OBJECT_ITEMSTACK, itemStack); } public static ValueItemStack of(ItemStack itemStack) { return new ValueItemStack(itemStack); } @Override protected boolean isEqual(ItemStack a, ItemStack b) { return ItemStackHelpers.areItemStacksIdentical(a, b); } } }
package stexfires.core; import org.jetbrains.annotations.Nullable; import stexfires.core.consumer.RecordConsumer; import stexfires.core.consumer.SystemOutConsumer; import stexfires.core.consumer.UncheckedConsumerException; import stexfires.core.filter.RecordFilter; import stexfires.core.logger.RecordLogger; import stexfires.core.mapper.RecordMapper; import stexfires.core.message.RecordMessage; import stexfires.core.modifier.RecordStreamModifier; import stexfires.core.producer.RecordProducer; import stexfires.core.producer.UncheckedProducerException; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; /** * This class consists of {@code static} utility methods * for operating on {@link Record} {@link Stream}s. * * @author Mathias Kalb * @see stexfires.core.Record * @see stexfires.core.Records * @see java.util.stream.Stream * @since 0.1 */ public final class RecordStreams { private RecordStreams() { } public static <T extends Record> Stream<T> empty() { return Stream.empty(); } public static <T extends Record> Stream<T> of(T record) { Objects.requireNonNull(record); return Stream.of(record); } @SuppressWarnings("OverloadedVarargsMethod") @SafeVarargs public static <T extends Record> Stream<T> of(T... records) { Objects.requireNonNull(records); return Stream.of(records); } public static <T extends Record> Stream<T> ofNullable(@Nullable T record) { return Stream.ofNullable(record); } public static <T extends Record> Stream<T> produce(RecordProducer<T> recordProducer) throws UncheckedProducerException { Objects.requireNonNull(recordProducer); return recordProducer.produceStream(); } public static <T extends Record> Stream<T> produceAndRestrict(RecordProducer<T> recordProducer, long skipFirst, long limitMaxSize) throws UncheckedProducerException { Objects.requireNonNull(recordProducer); return recordProducer.produceStream().skip(skipFirst).limit(limitMaxSize); } public static <T extends Record> Stream<T> generate(Supplier<T> recordSupplier) { Objects.requireNonNull(recordSupplier); return Stream.generate(recordSupplier); } public static <R extends Record> Stream<R> concat(Stream<? extends R> firstRecordStream, Stream<? extends R> secondRecordStream) { Objects.requireNonNull(firstRecordStream); Objects.requireNonNull(secondRecordStream); return Stream.concat(firstRecordStream, secondRecordStream); } @SuppressWarnings("OverloadedVarargsMethod") @SafeVarargs public static <R extends Record> Stream<R> concat(Stream<? extends R>... recordStreams) { Objects.requireNonNull(recordStreams); return Stream.of(recordStreams).flatMap(Function.identity()); } public static <R extends Record, T extends R> RecordConsumer<R> consume( Stream<T> recordStream, RecordConsumer<R> recordConsumer) throws UncheckedConsumerException { Objects.requireNonNull(recordStream); Objects.requireNonNull(recordConsumer); recordStream.forEachOrdered(recordConsumer::consume); return recordConsumer; } public static <R extends Record, T extends R> RecordConsumer<R> sortAndConsume( Stream<T> recordStream, Comparator<? super T> recordComparator, RecordConsumer<R> recordConsumer) throws UncheckedConsumerException { Objects.requireNonNull(recordStream); Objects.requireNonNull(recordComparator); Objects.requireNonNull(recordConsumer); recordStream.sorted(recordComparator).forEachOrdered(recordConsumer::consume); return recordConsumer; } public static <R extends Record, T extends Record> RecordConsumer<R> modifyAndConsume( Stream<T> recordStream, RecordStreamModifier<T, ? extends R> recordStreamModifier, RecordConsumer<R> recordConsumer) throws UncheckedConsumerException { Objects.requireNonNull(recordStream); Objects.requireNonNull(recordStreamModifier); Objects.requireNonNull(recordConsumer); recordStreamModifier.modify(recordStream).forEachOrdered(recordConsumer::consume); return recordConsumer; } public static <R extends Record, T extends R> RecordConsumer<R> logAndConsume( Stream<T> recordStream, RecordLogger<? super T> recordLogger, RecordConsumer<R> recordConsumer) throws UncheckedConsumerException { Objects.requireNonNull(recordStream); Objects.requireNonNull(recordLogger); Objects.requireNonNull(recordConsumer); recordStream.peek(recordLogger::log).forEachOrdered(recordConsumer::consume); return recordConsumer; } public static <R extends Record, T extends Record> RecordConsumer<R> mapAndConsume( Stream<T> recordStream, RecordMapper<? super T, ? extends R> recordMapper, RecordConsumer<R> recordConsumer) throws UncheckedConsumerException { Objects.requireNonNull(recordStream); Objects.requireNonNull(recordMapper); Objects.requireNonNull(recordConsumer); recordStream.map(recordMapper::map).forEachOrdered(recordConsumer::consume); return recordConsumer; } public static <T extends Record> List<T> collect(Stream<T> recordStream) { Objects.requireNonNull(recordStream); return recordStream.collect(Collectors.toList()); } public static <T extends Record> List<String> collectMessages( Stream<T> recordStream, RecordMessage<? super T> recordMessage) { Objects.requireNonNull(recordStream); Objects.requireNonNull(recordMessage); return recordStream.map(recordMessage::createMessage).collect(Collectors.toList()); } public static <T extends Record> Map<String, List<String>> groupAndCollectMessages( Stream<T> recordStream, RecordMessage<? super T> keyMessage, RecordMessage<? super T> valueMessage) { Objects.requireNonNull(recordStream); Objects.requireNonNull(keyMessage); Objects.requireNonNull(valueMessage); return recordStream.collect(Collectors.groupingBy(keyMessage::createMessage, HashMap::new, Collectors.mapping(valueMessage::createMessage, Collectors.toList()))); } public static <T extends Record> String joinMessages( Stream<T> recordStream, RecordMessage<? super T> recordMessage, String delimiter) { Objects.requireNonNull(recordStream); Objects.requireNonNull(recordMessage); Objects.requireNonNull(delimiter); return recordStream.map(recordMessage::createMessage).collect(Collectors.joining(delimiter)); } public static <T extends Record> Stream<String> mapToMessage( Stream<T> recordStream, RecordMessage<? super T> recordMessage) { Objects.requireNonNull(recordStream); Objects.requireNonNull(recordMessage); return recordStream.map(recordMessage::createMessage); } public static <T extends Record> void printLines(Stream<T> recordStream) { Objects.requireNonNull(recordStream); consume(recordStream, new SystemOutConsumer<>()); } public static <T extends Record> Stream<T> log( Stream<T> recordStream, RecordLogger<? super T> recordLogger) { Objects.requireNonNull(recordStream); Objects.requireNonNull(recordLogger); return recordStream.peek(recordLogger::log); } public static <T extends Record> Stream<T> filter( Stream<T> recordStream, RecordFilter<? super T> recordFilter) { Objects.requireNonNull(recordStream); Objects.requireNonNull(recordFilter); return recordStream.filter(recordFilter::isValid); } public static <R extends Record, T extends Record> Stream<R> map( Stream<T> recordStream, RecordMapper<? super T, ? extends R> recordMapper) { Objects.requireNonNull(recordStream); Objects.requireNonNull(recordMapper); return recordStream.map(recordMapper::map); } public static <T extends Record> Stream<T> sort( Stream<T> recordStream, Comparator<? super T> recordComparator) { Objects.requireNonNull(recordStream); Objects.requireNonNull(recordComparator); return recordStream.sorted(recordComparator); } public static <T extends Record, R extends Record> Stream<R> modify( Stream<T> recordStream, RecordStreamModifier<T, R> recordStreamModifier) { Objects.requireNonNull(recordStream); Objects.requireNonNull(recordStreamModifier); return recordStreamModifier.modify(recordStream); } }
package stexfires.core; import stexfires.core.consumer.RecordConsumer; import stexfires.core.consumer.SystemOutConsumer; import stexfires.core.consumer.UncheckedConsumerException; import stexfires.core.filter.RecordFilter; import stexfires.core.logger.RecordLogger; import stexfires.core.mapper.RecordMapper; import stexfires.core.message.RecordMessage; import stexfires.core.modifier.RecordStreamModifier; import stexfires.core.producer.RecordProducer; import stexfires.core.producer.UncheckedProducerException; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; /** * This class consists of {@code static} utility methods * for operating on {@link Record} {@link Stream}s. * * @author Mathias Kalb * @see stexfires.core.Record * @see stexfires.core.Records * @see java.util.stream.Stream * @since 0.1 */ public final class RecordStreams { private RecordStreams() { } public static <T extends Record> Stream<T> empty() { return Stream.empty(); } public static <T extends Record> Stream<T> of(T record) { Objects.requireNonNull(record); return Stream.of(record); } @SafeVarargs public static <T extends Record> Stream<T> of(T... records) { Objects.requireNonNull(records); return Stream.of(records); } public static <T extends Record> Stream<T> ofNullable(T record) { return record == null ? Stream.empty() : Stream.of(record); } public static <T extends Record> Stream<T> produce(RecordProducer<T> recordProducer) throws UncheckedProducerException { Objects.requireNonNull(recordProducer); return recordProducer.produceStream(); } public static <T extends Record> Stream<T> produceAndRestrict(RecordProducer<T> recordProducer, long skipFirst, long limitMaxSize) throws UncheckedProducerException { Objects.requireNonNull(recordProducer); return recordProducer.produceStream().skip(skipFirst).limit(limitMaxSize); } public static <T extends Record> Stream<T> generate(Supplier<T> recordSupplier) { Objects.requireNonNull(recordSupplier); return Stream.generate(recordSupplier); } public static <R extends Record> Stream<R> concat(Stream<? extends R> firstRecordStream, Stream<? extends R> secondRecordStream) { Objects.requireNonNull(firstRecordStream); Objects.requireNonNull(secondRecordStream); return Stream.concat(firstRecordStream, secondRecordStream); } @SafeVarargs public static <R extends Record> Stream<R> concat(Stream<? extends R>... recordStreams) { Objects.requireNonNull(recordStreams); return Stream.of(recordStreams).flatMap(Function.identity()); } public static <R extends Record, T extends R> RecordConsumer<R> consume( Stream<T> recordStream, RecordConsumer<R> recordConsumer) throws UncheckedConsumerException { Objects.requireNonNull(recordStream); Objects.requireNonNull(recordConsumer); recordStream.forEachOrdered(recordConsumer::consume); return recordConsumer; } public static <R extends Record, T extends Record> RecordConsumer<R> modifyAndConsume( Stream<T> recordStream, RecordStreamModifier<T, ? extends R> recordStreamModifier, RecordConsumer<R> recordConsumer) throws UncheckedConsumerException { Objects.requireNonNull(recordStream); Objects.requireNonNull(recordStreamModifier); Objects.requireNonNull(recordConsumer); recordStreamModifier.modify(recordStream).forEachOrdered(recordConsumer::consume); return recordConsumer; } public static <R extends Record, T extends R> RecordConsumer<R> logAndConsume( Stream<T> recordStream, RecordLogger<? super T> recordLogger, RecordConsumer<R> recordConsumer) throws UncheckedConsumerException { Objects.requireNonNull(recordStream); Objects.requireNonNull(recordLogger); Objects.requireNonNull(recordConsumer); recordStream.peek(recordLogger::log).forEachOrdered(recordConsumer::consume); return recordConsumer; } public static <R extends Record, T extends Record> RecordConsumer<R> mapAndConsume( Stream<T> recordStream, RecordMapper<? super T, ? extends R> recordMapper, RecordConsumer<R> recordConsumer) throws UncheckedConsumerException { Objects.requireNonNull(recordStream); Objects.requireNonNull(recordMapper); Objects.requireNonNull(recordConsumer); recordStream.map(recordMapper::map).forEachOrdered(recordConsumer::consume); return recordConsumer; } public static <T extends Record> List<T> collect(Stream<T> recordStream) { Objects.requireNonNull(recordStream); return recordStream.collect(Collectors.toList()); } public static <T extends Record> List<String> collectMessages( Stream<T> recordStream, RecordMessage<? super T> recordMessage) { Objects.requireNonNull(recordStream); Objects.requireNonNull(recordMessage); return recordStream.map(recordMessage::createMessage).collect(Collectors.toList()); } public static <T extends Record> Map<String, List<String>> groupAndCollectMessages( Stream<T> recordStream, RecordMessage<? super T> keyMessage, RecordMessage<? super T> valueMessage) { Objects.requireNonNull(recordStream); Objects.requireNonNull(keyMessage); Objects.requireNonNull(valueMessage); return recordStream.collect(Collectors.groupingBy(keyMessage::createMessage, HashMap::new, Collectors.mapping(valueMessage::createMessage, Collectors.toList()))); } public static <T extends Record> String joinMessages( Stream<T> recordStream, RecordMessage<? super T> recordMessage, String delimiter) { Objects.requireNonNull(recordStream); Objects.requireNonNull(recordMessage); Objects.requireNonNull(delimiter); return recordStream.map(recordMessage::createMessage).collect(Collectors.joining(delimiter)); } public static <T extends Record> void printLines(Stream<T> recordStream) { Objects.requireNonNull(recordStream); consume(recordStream, new SystemOutConsumer<>()); } public static <T extends Record> Stream<T> log( Stream<T> recordStream, RecordLogger<? super T> recordLogger) { Objects.requireNonNull(recordStream); Objects.requireNonNull(recordLogger); return recordStream.peek(recordLogger::log); } public static <T extends Record> Stream<T> filter( Stream<T> recordStream, RecordFilter<? super T> recordFilter) { Objects.requireNonNull(recordStream); Objects.requireNonNull(recordFilter); return recordStream.filter(recordFilter::isValid); } public static <R extends Record, T extends Record> Stream<R> map( Stream<T> recordStream, RecordMapper<? super T, ? extends R> recordMapper) { Objects.requireNonNull(recordStream); Objects.requireNonNull(recordMapper); return recordStream.map(recordMapper::map); } public static <T extends Record> Stream<T> sort( Stream<T> recordStream, Comparator<? super T> recordComparator) { Objects.requireNonNull(recordStream); Objects.requireNonNull(recordComparator); return recordStream.sorted(recordComparator); } public static <T extends Record, R extends Record> Stream<R> modify( Stream<T> recordStream, RecordStreamModifier<T, R> recordStreamModifier) { Objects.requireNonNull(recordStream); Objects.requireNonNull(recordStreamModifier); return recordStreamModifier.modify(recordStream); } }
package eu.andlabs.studiolounge.gcp; import io.socket.IOAcknowledge; import io.socket.IOCallback; import io.socket.SocketIO; import io.socket.SocketIOException; import java.util.HashMap; import java.util.HashSet; import org.json.JSONObject; import android.app.Service; import android.content.Intent; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.util.Log; import android.widget.Toast; public class GCPService extends Service { private String mName; private Handler mHandler; private SocketIO mSocketIO; private Messenger mChatGame; public static final int JOIN = 1; public static final int CHAT = 2; public static final int LEAVE = 3; @Override public void onCreate() { super.onCreate(); mName = "Lucky Luke"; mHandler = new Handler(); mSocketIO = new SocketIO(); log("starting GCP Service"); try { mSocketIO.connect("http://happylog.jit.su:80", new IOCallback() { @Override public void onConnect() { // auto login log("connected to GCP game server!"); mSocketIO.emit("Hi", "I am " + mName); } @Override public void onMessage(String text, IOAcknowledge ack) { dispatchMessage(CHAT, text); } @Override public void on(String type, IOAcknowledge ack, Object... data) { log("incoming message:" + type + " --- " + data); if (type.equals("Welcome")) { dispatchMessage(JOIN, data[0].toString()); } else { dispatchMessage(CHAT, "BAD protocol message: " + type); } } @Override public void onMessage(JSONObject json, IOAcknowledge ack) { } @Override public void onDisconnect() { log("lost game server."); } @Override public void onError(SocketIOException error) { log(error); } }); } catch (Exception e) { dispatchMessage(CHAT, "GCP Service Error: " + e.toString()); } } // bind game app(s) @Override public IBinder onBind(Intent intent) { mChatGame = (Messenger) intent.getParcelableExtra("messenger"); return mMessenger.getBinder(); } // send android system IPC message to game apps private void dispatchMessage(int what, String thing) { try { mChatGame.send(Message.obtain(mHandler, what, thing)); } catch (RemoteException e) { log("Error: " + e.toString()); } } // receive android system IPC messages from game apps final Messenger mMessenger = new Messenger(new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case CHAT: if (mSocketIO.isConnected()) { mSocketIO.send(msg.obj.toString()); } break; } }}); private void log(final Object ding) { mHandler.post(new Runnable() { @Override public void run() { Toast.makeText(GCPService.this, ding.toString(), 1000).show(); } }); Log.d("GameCommunicationsProtocol-Service", ding.toString()); } }
package org.mtransit.parser.ca_ottawa_oc_transpo_train; import org.apache.commons.lang3.StringUtils; import org.mtransit.parser.CleanUtils; import org.mtransit.parser.DefaultAgencyTools; import org.mtransit.parser.MTLog; import org.mtransit.parser.Utils; import org.mtransit.parser.gtfs.data.GCalendar; import org.mtransit.parser.gtfs.data.GCalendarDate; import org.mtransit.parser.gtfs.data.GRoute; import org.mtransit.parser.gtfs.data.GSpec; import org.mtransit.parser.gtfs.data.GStop; import org.mtransit.parser.gtfs.data.GTrip; import org.mtransit.parser.mt.data.MAgency; import org.mtransit.parser.mt.data.MRoute; import org.mtransit.parser.mt.data.MTrip; import java.util.HashSet; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; public class OttawaOCTranspoTrainAgencyTools extends DefaultAgencyTools { public static void main(String[] args) { if (args == null || args.length == 0) { args = new String[3]; args[0] = "input/gtfs.zip"; args[1] = "../../mtransitapps/ca-ottawa-oc-transpo-train-android/res/raw/"; args[2] = ""; // files-prefix } new OttawaOCTranspoTrainAgencyTools().start(args); } private HashSet<String> serviceIds; @Override public void start(String[] args) { MTLog.log("Generating OC Transpo train data..."); long start = System.currentTimeMillis(); this.serviceIds = extractUsefulServiceIds(args, this, true); super.start(args); MTLog.log("Generating OC Transpo train data... DONE in %s.", Utils.getPrettyDuration(System.currentTimeMillis() - start)); } @Override public boolean excludingAll() { return this.serviceIds != null && this.serviceIds.isEmpty(); } @Override public boolean excludeCalendar(GCalendar gCalendar) { if (this.serviceIds != null) { return excludeUselessCalendar(gCalendar, this.serviceIds); } return super.excludeCalendar(gCalendar); } @Override public boolean excludeCalendarDate(GCalendarDate gCalendarDates) { if (this.serviceIds != null) { return excludeUselessCalendarDate(gCalendarDates, this.serviceIds); } return super.excludeCalendarDate(gCalendarDates); } @Override public boolean excludeTrip(GTrip gTrip) { if (this.serviceIds != null) { return excludeUselessTrip(gTrip, this.serviceIds); } return super.excludeTrip(gTrip); } @Override public Integer getAgencyRouteType() { return MAgency.ROUTE_TYPE_TRAIN; } private static final Pattern DIGITS = Pattern.compile("[\\d]+"); @Override public long getRouteId(GRoute gRoute) { Matcher matcher = DIGITS.matcher(gRoute.getRouteId()); if (matcher.find()) { return Long.parseLong(matcher.group()); } MTLog.logFatal("Unexpected route ID %s!", gRoute); return -1L; } @Override public String getRouteShortName(GRoute gRoute) { if (StringUtils.isEmpty(gRoute.getRouteShortName())) { long routeId = getRouteId(gRoute); if (routeId == 1L) { return "1"; } if (routeId == 2L) { return "2"; } MTLog.logFatal("Unexpected route short name %s!", gRoute); return null; } return super.getRouteShortName(gRoute); } @Override public String getRouteLongName(GRoute gRoute) { if (StringUtils.isEmpty(gRoute.getRouteLongName())) { long routeId = getRouteId(gRoute); if (routeId == 1L) { return "Confederation Line"; } if (routeId == 2L) { return "Trillium Line"; } MTLog.logFatal("Unexpected route long name %s!", gRoute); return null; } return super.getRouteLongName(gRoute); } private static final String AGENCY_COLOR = "A2211F"; @Override public String getAgencyColor() { return AGENCY_COLOR; } @Override public String getRouteColor(GRoute gRoute) { if (StringUtils.isEmpty(gRoute.getRouteColor())) { Matcher matcher = DIGITS.matcher(gRoute.getRouteId()); if (matcher.find()) { int routeId = Integer.parseInt(matcher.group()); if (routeId == 1L) { return "DA291C"; } if (routeId == 2L) { return "65A233"; } } MTLog.logFatal("Unexpected route color %s!", gRoute); return null; } return super.getRouteColor(gRoute); } @Override public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), gTrip.getDirectionId()); } @Override public String cleanTripHeadsign(String tripHeadsign) { return tripHeadsign; // DO NOT CLEAN, USED TO IDENTIFY TRIP IN REAL TIME API } @Override public boolean mergeHeadsign(MTrip mTrip, MTrip mTripToMerge) { if (mTrip.getHeadsignValue() == null || !mTrip.getHeadsignValue().equals(mTripToMerge.getHeadsignValue())) { MTLog.logFatal("Can't merge headsign for trips %s and %s!", mTrip, mTripToMerge); return false; // DO NOT MERGE, USED TO IDENTIFY TRIP IN REAL TIME API } return super.mergeHeadsign(mTrip, mTripToMerge); } private static final Pattern ENDS_WITH_DIRECTION = Pattern.compile("(" + "n\\.|s\\.|e\\.|w\\.|o\\." + "|" + "north/nord|south/sud|east/est|west/ouest" + "|" + "north / nord|south / sud|east / est|west / ouest" + ")", Pattern.CASE_INSENSITIVE); private static final Pattern O_TRAIN_ = CleanUtils.cleanWords("o-train"); private static final String O_TRAIN_REPLACEMENT = CleanUtils.cleanWordsReplacement(StringUtils.EMPTY); @Override public String cleanStopName(String gStopName) { if (Utils.isUppercaseOnly(gStopName, true, true)) { gStopName = gStopName.toLowerCase(Locale.ENGLISH); } gStopName = O_TRAIN_.matcher(gStopName).replaceAll(O_TRAIN_REPLACEMENT); gStopName = ENDS_WITH_DIRECTION.matcher(gStopName).replaceAll(StringUtils.EMPTY); return super.cleanStopName(gStopName); } private static final String EE = "EE"; private static final String EO = "EO"; private static final String NG = "NG"; private static final String NO = "NO"; private static final String WA = "WA"; private static final String WD = "WD"; private static final String WH = "WH"; private static final String WI = "WI"; private static final String WL = "WL"; private static final String PLACE = "place"; private static final String RZ = "RZ"; @Override public int getStopId(GStop gStop) { String stopCode = getStopCode(gStop); if (stopCode.length() > 0 && Utils.isDigitsOnly(stopCode)) { return Integer.parseInt(stopCode); // using stop code as stop ID } Matcher matcher = DIGITS.matcher(gStop.getStopId()); if (matcher.find()) { int digits = Integer.parseInt(matcher.group()); int stopId; if (gStop.getStopId().startsWith(EE)) { stopId = 100000; } else if (gStop.getStopId().startsWith(EO)) { stopId = 200000; } else if (gStop.getStopId().startsWith(NG)) { stopId = 300000; } else if (gStop.getStopId().startsWith(NO)) { stopId = 400000; } else if (gStop.getStopId().startsWith(WA)) { stopId = 500000; } else if (gStop.getStopId().startsWith(WD)) { stopId = 600000; } else if (gStop.getStopId().startsWith(WH)) { stopId = 700000; } else if (gStop.getStopId().startsWith(WI)) { stopId = 800000; } else if (gStop.getStopId().startsWith(WL)) { stopId = 900000; } else if (gStop.getStopId().startsWith(PLACE)) { stopId = 1000000; } else if (gStop.getStopId().startsWith(RZ)) { stopId = 1100000; } else { MTLog.logFatal("Stop doesn't have an ID (start with)! %s!", gStop); stopId = -1; } return stopId + digits; } MTLog.logFatal("Unexpected stop ID for %s!", gStop); return -1; } }
package twitter4j.api; import twitter4j.Device; import twitter4j.RateLimitStatus; import twitter4j.TwitterException; import twitter4j.User; import java.io.File; /** * @author Joern Huxhorn - jhuxhorn at googlemail.com */ public interface AccountMethods { User verifyCredentials() throws TwitterException; RateLimitStatus getRateLimitStatus() throws TwitterException; User updateDeliveryDevice(Device device) throws TwitterException; User updateProfileColors(String profileBackgroundColor, String profileTextColor, String profileLinkColor, String profileSidebarFillColor, String profileSidebarBorderColor) throws TwitterException; User updateProfileImage(File image) throws TwitterException; User updateProfileBackgroundImage(File image, boolean tile) throws TwitterException; User updateProfile(String name, String email, String url, String location, String description) throws TwitterException; }
// SEQReader.java package loci.formats.in; import java.io.IOException; import java.util.StringTokenizer; import loci.formats.FormatException; import loci.formats.TiffTools; public class SEQReader extends BaseTiffReader { // -- Constants -- /** * An array of shorts (length 12) with identical values in all of our * samples; assuming this is some sort of format identifier. */ private static final int IMAGE_PRO_TAG_1 = 50288; /** Frame rate. */ private static final int IMAGE_PRO_TAG_2 = 40105; // -- Constructor -- /** Constructs a new Image-Pro SEQ reader. */ public SEQReader() { super("Image-Pro Sequence", "seq"); } // -- Internal BaseTiffReader API methods -- /* @see BaseTiffReader#initStandardMetadata() */ protected void initStandardMetadata() throws FormatException, IOException { super.initStandardMetadata(); core[0].sizeZ = 0; core[0].sizeT = 0; for (int j=0; j<ifds.length; j++) { short[] tag1 = (short[]) TiffTools.getIFDValue(ifds[j], IMAGE_PRO_TAG_1); if (tag1 != null) { String seqId = ""; for (int i=0; i<tag1.length; i++) seqId = seqId + tag1[i]; addMeta("Image-Pro SEQ ID", seqId); } int tag2 = TiffTools.getIFDIntValue(ifds[0], IMAGE_PRO_TAG_2); if (tag2 != -1) { // should be one of these for every image plane core[0].sizeZ++; addMeta("Frame Rate", tag2); } addMeta("Number of images", getSizeZ()); } if (getSizeZ() == 0) core[0].sizeZ = 1; if (getSizeT() == 0) core[0].sizeT = 1; if (getSizeZ() == 1 && getSizeT() == 1) { core[0].sizeZ = ifds.length; } // default values addMeta("frames", getSizeZ()); addMeta("channels", super.getSizeC()); addMeta("slices", getSizeT()); // parse the description to get channels, slices and times where applicable String descr = TiffTools.getComment(ifds[0]); metadata.remove("Comment"); if (descr != null) { StringTokenizer tokenizer = new StringTokenizer(descr, "\n"); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); int eq = token.indexOf("="); if (eq != -1) { String label = token.substring(0, eq); String data = token.substring(eq + 1); addMeta(label, data); if (label.equals("channels")) core[0].sizeC = Integer.parseInt(data); else if (label.equals("frames")) { core[0].sizeT = Integer.parseInt(data); } else if (label.equals("slices")) { core[0].sizeZ = Integer.parseInt(data); } } } } if (isRGB() && getSizeC() != 3) core[0].sizeC *= 3; core[0].dimensionOrder = "XY"; int maxNdx = 0, max = 0; int[] dims = {getSizeZ(), getSizeC(), getSizeT()}; String[] axes = {"Z", "C", "T"}; for (int i=0; i<dims.length; i++) { if (dims[i] > max) { max = dims[i]; maxNdx = i; } } core[0].dimensionOrder += axes[maxNdx]; if (maxNdx != 1) { if (getSizeC() > 1) { core[0].dimensionOrder += "C"; core[0].dimensionOrder += (maxNdx == 0 ? axes[2] : axes[0]); } else core[0].dimensionOrder += (maxNdx == 0 ? axes[2] : axes[0]) + "C"; } else { if (getSizeZ() > getSizeT()) core[0].dimensionOrder += "ZT"; else core[0].dimensionOrder += "TZ"; } } }
/* created 26 Oct 2008 for new cDVSTest chip * adapted apr 2011 for cDVStest30 chip by tobi * adapted 25 oct 2011 for SeeBetter10/11 chips by tobi * */ package eu.seebetter.ini.chips.sbret10; import ch.unizh.ini.jaer.projects.spatiatemporaltracking.data.histogram.AbstractHistogram; import com.sun.opengl.util.j2d.TextRenderer; import eu.seebetter.ini.chips.APSDVSchip; import static eu.seebetter.ini.chips.APSDVSchip.ADC_DATA_MASK; import static eu.seebetter.ini.chips.APSDVSchip.ADC_READCYCLE_MASK; import static eu.seebetter.ini.chips.APSDVSchip.ADDRESS_TYPE_APS; import static eu.seebetter.ini.chips.APSDVSchip.ADDRESS_TYPE_DVS; import static eu.seebetter.ini.chips.APSDVSchip.ADDRESS_TYPE_MASK; import static eu.seebetter.ini.chips.APSDVSchip.POLMASK; import static eu.seebetter.ini.chips.APSDVSchip.XMASK; import static eu.seebetter.ini.chips.APSDVSchip.XSHIFT; import static eu.seebetter.ini.chips.APSDVSchip.YMASK; import static eu.seebetter.ini.chips.APSDVSchip.YSHIFT; import java.awt.Font; import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; import javax.swing.JFrame; import net.sf.jaer.Description; import net.sf.jaer.aemonitor.AEPacketRaw; import net.sf.jaer.biasgen.BiasgenHardwareInterface; import net.sf.jaer.chip.RetinaExtractor; import net.sf.jaer.event.*; import net.sf.jaer.eventprocessing.filter.ApsDvsEventFilter; import net.sf.jaer.eventprocessing.filter.Info; import net.sf.jaer.eventprocessing.filter.RefractoryFilter; import net.sf.jaer.graphics.AEFrameChipRenderer; import net.sf.jaer.graphics.ChipRendererDisplayMethodRGBA; import net.sf.jaer.graphics.DisplayMethod; import net.sf.jaer.hardwareinterface.HardwareInterface; import net.sf.jaer.hardwareinterface.HardwareInterfaceException; /** * Describes retina and its event extractor and bias generator. Two constructors * ara available, the vanilla constructor is used for event playback and the one * with a HardwareInterface parameter is useful for live capture. * {@link #setHardwareInterface} is used when the hardware interface is * constructed after the retina object. The constructor that takes a hardware * interface also constructs the biasgen interface. * <p> * SBRet10 has 240x180 pixels and is built in 180nm technology. It has a rolling * shutter APS readout with CDS in digital domain. * * @author tobi, christian */ @Description("SBret version 1.0") public class SBret10 extends APSDVSchip { private final int ADC_NUMBER_OF_TRAILING_ZEROS = Integer.numberOfTrailingZeros(ADC_READCYCLE_MASK); // speedup in loop // following define bit masks for various hardware data types. // The hardware interface translateEvents method packs the raw device data into 32 bit 'addresses' and timestamps. // timestamps are unwrapped and timestamp resets are handled in translateEvents. Addresses are filled with either AE or ADC data. // AEs are filled in according the XMASK, YMASK, XSHIFT, YSHIFT below. /** * bit masks/shifts for cDVS AE data */ private SBret10DisplayMethod sbretDisplayMethod = null; private AEFrameChipRenderer apsDVSrenderer; private int exposure; // internal measured variable, set during rendering private int frameTime; // internal measured variable, set during rendering /** *holds measured variable in Hz for GUI rendering of rate */ protected float frameRateHz; /** * holds measured variable in ms for GUI rendering */ protected float exposureMs; /** * Holds count of frames obtained by end of frame events */ private int frameCount=0; private boolean snapshot = false; private boolean resetOnReadout = false; private SBret10config config; JFrame controlFrame = null; public static short WIDTH = 240; public static short HEIGHT = 180; int sx1 = getSizeX() - 1, sy1 = getSizeY() - 1; private int autoshotThresholdEvents=getPrefs().getInt("SBRet10.autoshotThresholdEvents",0); /** * Creates a new instance of cDVSTest20. */ public SBret10() { setName("SBret10"); setDefaultPreferencesFile("../../biasgenSettings/sbret10/SBRet10.xml"); setEventClass(ApsDvsEvent.class); setSizeX(WIDTH); setSizeY(HEIGHT); setNumCellTypes(3); // two are polarity and last is intensity setPixelHeightUm(18.5f); setPixelWidthUm(18.5f); setEventExtractor(new SBret10Extractor(this)); setBiasgen(config = new SBret10config(this)); // hardware interface is ApsDvsHardwareInterface apsDVSrenderer = new AEFrameChipRenderer(this); apsDVSrenderer.setMaxADC(MAX_ADC); setRenderer(apsDVSrenderer); sbretDisplayMethod = new SBret10DisplayMethod(this); getCanvas().addDisplayMethod(sbretDisplayMethod); getCanvas().setDisplayMethod(sbretDisplayMethod); addDefaultEventFilter(ApsDvsEventFilter.class); addDefaultEventFilter(HotPixelSupressor.class); addDefaultEventFilter(RefractoryFilter.class); addDefaultEventFilter(Info.class); } @Override public void setPowerDown(boolean powerDown) { config.powerDown.set(powerDown); try { config.sendOnChipConfigChain(); } catch (HardwareInterfaceException ex) { Logger.getLogger(SBret10.class.getName()).log(Level.SEVERE, null, ex); } } /** * Creates a new instance of SBRet10 * * @param hardwareInterface an existing hardware interface. This constructor * is preferred. It makes a new cDVSTest10Biasgen object to talk to the * on-chip biasgen. */ public SBret10(HardwareInterface hardwareInterface) { this(); setHardwareInterface(hardwareInterface); } // int pixcnt=0; // TODO debug /** * The event extractor. Each pixel has two polarities 0 and 1. * * <p> * The bits in the raw data coming from the device are as follows. * <p> * Bit 0 is polarity, on=1, off=0<br> * Bits 1-9 are x address (max value 320)<br> * Bits 10-17 are y address (max value 240) <br> * <p> */ public class SBret10Extractor extends RetinaExtractor { private int firstFrameTs = 0; private int autoshotEventsSinceLastShot=0; // autoshot counter public SBret10Extractor(SBret10 chip) { super(chip); } private void lastADCevent() { //releases the reset after the readout of a frame if the DVS is suppressed during the DVS readout if (resetOnReadout) { config.nChipReset.set(true); } } /** * extracts the meaning of the raw events. * * @param in the raw events, can be null * @return out the processed events. these are partially processed * in-place. empty packet is returned if null is supplied as in. */ @Override synchronized public EventPacket extractPacket(AEPacketRaw in) { if (!(chip instanceof APSDVSchip)) { return null; } if (out == null) { out = new ApsDvsEventPacket(chip.getEventClass()); } else { out.clear(); } out.setRawPacket(in); if (in == null) { return out; } int n = in.getNumEvents(); //addresses.length; sx1 = chip.getSizeX() - 1; sy1 = chip.getSizeY() - 1; int[] datas = in.getAddresses(); int[] timestamps = in.getTimestamps(); OutputEventIterator outItr = out.outputIterator(); // at this point the raw data from the USB IN packet has already been digested to extract timestamps, including timestamp wrap events and timestamp resets. // The datas array holds the data, which consists of a mixture of AEs and ADC values. // Here we extract the datas and leave the timestamps alone. // TODO entire rendering / processing approach is not very efficient now for (int i = 0; i < n; i++) { // TODO implement skipBy/subsampling, but without missing the frame start/end events and still delivering frames int data = datas[i]; if ((data & ADDRESS_TYPE_MASK) == ADDRESS_TYPE_DVS) { //DVS event ApsDvsEvent e = (ApsDvsEvent) outItr.nextOutput(); e.adcSample = -1; // TODO hack to mark as not an ADC sample e.startOfFrame = false; e.special = false; e.address = data; e.timestamp = (timestamps[i]); e.polarity = (data & POLMASK) == POLMASK ? ApsDvsEvent.Polarity.On : ApsDvsEvent.Polarity.Off; e.x = (short) (sx1 - ((data & XMASK) >>> XSHIFT)); e.y = (short) ((data & YMASK) >>> YSHIFT); //System.out.println(data); // autoshot triggering autoshotEventsSinceLastShot++; // number DVS events captured here } else if ((data & ADDRESS_TYPE_MASK) == ADDRESS_TYPE_APS) { //APS event ApsDvsEvent e = (ApsDvsEvent) outItr.nextOutput(); e.adcSample = data & ADC_DATA_MASK; int sampleType = (data & ADC_READCYCLE_MASK) >> ADC_NUMBER_OF_TRAILING_ZEROS; switch (sampleType) { case 0: e.readoutType = ApsDvsEvent.ReadoutType.ResetRead; break; case 1: e.readoutType = ApsDvsEvent.ReadoutType.SignalRead; //log.info("got SignalRead event"); break; case 3: log.warning("Event with readout cycle null was sent out!"); break; default: log.warning("Event with unknown readout cycle was sent out!"); } e.special = false; e.timestamp = (timestamps[i]); e.address = data; e.x = (short) (((data & XMASK) >>> XSHIFT)); e.y = (short) ((data & YMASK) >>> YSHIFT); boolean pixZero = e.x == 0 && e.y == 0; e.startOfFrame = (e.readoutType == ApsDvsEvent.ReadoutType.ResetRead) && pixZero; if (e.startOfFrame) { //if(pixCnt!=129600) System.out.println("New frame, pixCnt was incorrectly "+pixCnt+" instead of 129600 but this could happen at end of file"); frameTime = e.timestamp - firstFrameTs; firstFrameTs = e.timestamp; } if (pixZero && e.isSignalRead()) { exposure = e.timestamp - firstFrameTs; } if (e.isSignalRead() && e.x == 0 && e.y == sy1) { // if we use ResetRead+SignalRead+C readout, OR, if we use ResetRead-SignalRead readout and we are at last APS pixel, then write EOF event lastADCevent(); // TODO what does this do? //insert a new "end of frame" event not present in original data ApsDvsEvent a = (ApsDvsEvent) outItr.nextOutput(); a.startOfFrame = false; a.adcSample = 0; // set this effectively as ADC sample even though fake a.timestamp = (timestamps[i]); a.x = -1; a.y = -1; a.readoutType = ApsDvsEvent.ReadoutType.EOF; if (snapshot) { snapshot = false; config.apsReadoutControl.setAdcEnabled(false); } setFrameCount(getFrameCount() + 1); } } } if(getAutoshotThresholdEvents()>0 && autoshotEventsSinceLastShot>getAutoshotThresholdEvents()){ takeSnapshot(); autoshotEventsSinceLastShot=0; } return out; } // extractPacket @Override public AEPacketRaw reconstructRawPacket(EventPacket packet) { if (raw == null) { raw = new AEPacketRaw(); } if (!(packet instanceof ApsDvsEventPacket)) { return null; } ApsDvsEventPacket apsDVSpacket = (ApsDvsEventPacket) packet; raw.ensureCapacity(packet.getSize()); raw.setNumEvents(0); int[] a = raw.addresses; int[] ts = raw.timestamps; int n = apsDVSpacket.getSize(); Iterator evItr = apsDVSpacket.fullIterator(); int k = 0; while (evItr.hasNext()) { ApsDvsEvent e = (ApsDvsEvent) evItr.next(); // not writing out these EOF events (which were synthesized on extraction) results in reconstructed packets with giant time gaps, reason unknown if (e.isEndOfFrame()) { continue; // these EOF events were synthesized from data in first place } ts[k] = e.timestamp; a[k++] = reconstructRawAddressFromEvent(e); } raw.setNumEvents(k); return raw; } /** * To handle filtered ApsDvsEvents, this method rewrites the fields of * the raw address encoding x and y addresses to reflect the event's x * and y fields. * * @param e the ApsDvsEvent * @return the raw address */ @Override public int reconstructRawAddressFromEvent(TypedEvent e) { int address = e.address; // if(e.x==0 && e.y==0){ // log.info("start of frame event "+e); // if(e.x==-1 && e.y==-1){ // log.info("end of frame event "+e); // e.x came from e.x = (short) (chip.getSizeX()-1-((data & XMASK) >>> XSHIFT)); // for DVS event, no x flip if APS event if (((ApsDvsEvent) e).adcSample >= 0) { address = (address & ~XMASK) | ((e.x) << XSHIFT); } else { address = (address & ~XMASK) | ((sx1 - e.x) << XSHIFT); } // e.y came from e.y = (short) ((data & YMASK) >>> YSHIFT); address = (address & ~YMASK) | (e.y << YSHIFT); return address; } } // extractor /** * overrides the Chip setHardware interface to construct a biasgen if one * doesn't exist already. Sets the hardware interface and the bias * generators hardware interface * * @param hardwareInterface the interface */ @Override public void setHardwareInterface(final HardwareInterface hardwareInterface) { this.hardwareInterface = hardwareInterface; SBret10config config; try { if (getBiasgen() == null) { setBiasgen(config = new SBret10config(this)); // now we can addConfigValue the control panel } else { getBiasgen().setHardwareInterface((BiasgenHardwareInterface) hardwareInterface); } } catch (ClassCastException e) { log.warning(e.getMessage() + ": probably this chip object has a biasgen but the hardware interface doesn't, ignoring"); } } /** * Displays data from SeeBetter test chip SeeBetter10/11. * * @author Tobi */ public class SBret10DisplayMethod extends ChipRendererDisplayMethodRGBA { private TextRenderer exposureRenderer = null; public SBret10DisplayMethod(SBret10 chip) { super(chip.getCanvas()); } @Override public void display(GLAutoDrawable drawable) { if (exposureRenderer == null) { exposureRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 12), true, true); exposureRenderer.setColor(1, 1, 1, 1); } super.display(drawable); if (config.videoControl != null && config.videoControl.displayFrames) { GL gl = drawable.getGL(); exposureRender(gl); } // draw sample histogram if(showImageHistogram && renderer instanceof AEFrameChipRenderer){ // System.out.println("drawing hist"); final int size=100; AbstractHistogram hist=((AEFrameChipRenderer)renderer).getAdcSampleValueHistogram(); hist.draw(drawable, exposureRenderer, sizeX/2-size/2, sizeY/2+size/2, size, size); } } private void exposureRender(GL gl) { gl.glPushMatrix(); exposureRenderer.begin3DRendering(); // TODO make string rendering more efficient here using String.format or StringBuilder String frequency = ""; if (frameTime > 0) { setFrameRateHz((float) 1000000 / frameTime); frequency = String.format("(%.2f Hz)", frameRateHz); } setExposureMs((float) exposure / 1000); String s=String.format("Frame: %d; Exposure %.1f ms; Frame rate: %.1f Hz", getFrameCount(),exposureMs,frameRateHz); exposureRenderer.draw3D(s, 0, HEIGHT + 1, 0, .5f); // x,y,z, scale factor exposureRenderer.end3DRendering(); gl.glPopMatrix(); } } /** * Returns the preferred DisplayMethod, or ChipRendererDisplayMethod if null * preference. * * @return the method, or null. * @see #setPreferredDisplayMethod */ @Override public DisplayMethod getPreferredDisplayMethod() { return new ChipRendererDisplayMethodRGBA(getCanvas()); } @Override public int getMaxADC() { return MAX_ADC; } /** * Sets the measured frame rate. Does not change parameters, only used for * recording measured quantity and informing GUI listeners. * * @param frameRateHz the frameRateHz to set */ private void setFrameRateHz(float frameRateHz) { float old = this.frameRateHz; this.frameRateHz = frameRateHz; getSupport().firePropertyChange(PROPERTY_FRAME_RATE_HZ, old, this.frameRateHz); } /** * Sets the measured exposure. Does not change parameters, only used for * recording measured quantity. * * @param exposureMs the exposureMs to set */ private void setExposureMs(float exposureMs) { float old = this.exposureMs; this.exposureMs = exposureMs; getSupport().firePropertyChange(PROPERTY_EXPOSURE_MS, old, this.exposureMs); } @Override public float getFrameRateHz() { return frameRateHz; } @Override public float getExposureMs() { return exposureMs; } /** * Returns the frame counter. This value is set on each end-of-frame sample. * * @return the frameCount */ public int getFrameCount() { return frameCount; } /** * Sets the frame counter. * @param frameCount the frameCount to set */ public void setFrameCount(int frameCount) { this.frameCount = frameCount; } /** * Triggers shot of one APS frame */ @Override public void takeSnapshot() { snapshot = true; config.apsReadoutControl.setAdcEnabled(true); } /** Sets threshold for shooting a frame automatically * * @param thresholdEvents the number of events to trigger shot on. Less than or equal to zero disables auto-shot. */ @Override public void setAutoshotThresholdEvents(int thresholdEvents) { if(thresholdEvents<0) thresholdEvents=0; autoshotThresholdEvents=thresholdEvents; getPrefs().putInt("SBret10.autoshotThresholdEvents",thresholdEvents); if(autoshotThresholdEvents==0) config.runAdc.set(true); } /** Returns threshold for auto-shot. * * @return events to shoot frame */ @Override public int getAutoshotThresholdEvents() { return autoshotThresholdEvents; } @Override public void setAutoExposureEnabled(boolean yes) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public boolean isAutoExposureEnabled() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } private boolean showImageHistogram=getPrefs().getBoolean("SBRet10.showImageHistogram", false); public boolean isShowImageHistogram(){ return showImageHistogram; } public void setShowImageHistogram(boolean yes){ showImageHistogram=yes; getPrefs().putBoolean("SBRet10.showImageHistogram", yes); } }
package us.levk.rserve.client; import static java.net.URI.create; import static java.util.concurrent.CompletableFuture.completedFuture; import static java.util.concurrent.Executors.newWorkStealingPool; import static java.util.regex.Pattern.DOTALL; import static java.util.regex.Pattern.MULTILINE; import static java.util.regex.Pattern.compile; import static java.util.stream.Stream.of; import static javax.websocket.ContainerProvider.getWebSocketContainer; import static us.levk.rserve.client.tools.reflect.Classes.base; import java.io.Closeable; import java.io.IOException; import java.lang.reflect.Type; import java.net.URI; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.regex.Pattern; import javax.websocket.DeploymentException; import javax.websocket.WebSocketContainer; import us.levk.jackson.rserve.RserveMapper; import us.levk.rserve.client.protocol.commands.Assign; import us.levk.rserve.client.protocol.commands.Command; import us.levk.rserve.client.protocol.commands.Evaluate; import us.levk.rserve.client.protocol.commands.Resolve; import us.levk.rserve.client.websocket.Endpoint; /** * Rserve client * * @author levk */ public interface Client extends Closeable { /** * Welcome wagon regex */ static final Pattern HANDSHAKE_PATTERN = compile ("Rsrv0103QAP1.* /** * @param c * command * @return promise */ <T> CompletableFuture <T> execute (Command <T> c); /** * @param n * name * @param v * value * @return promise */ default CompletableFuture <Void> assign (String n, Object v) { return execute (new Assign (n, v)); } /** * @param n * name * @param t * type * @return promise */ default <T> CompletableFuture <T> resolve (String n, Type t) { return execute (new Resolve <> (n, t)); } /** * @param c * code * @return promise */ default CompletableFuture <Void> evaluate (String c) { return execute (new Evaluate (c)); } /** * @param j * job * @return promise */ default <T> CompletableFuture <T> batch (T j) { return base (j.getClass ()).flatMap (c -> of (c.getDeclaredFields ()).filter (f -> { return f.isAnnotationPresent (us.levk.rserve.client.Resolve.class); })).reduce (base (j.getClass ()).reduce (base (j.getClass ()).flatMap (c -> of (c.getDeclaredFields ()).filter (f -> { return f.isAnnotationPresent (us.levk.rserve.client.Assign.class); })).reduce (completedFuture ((Void) null), (p, f) -> p.thenCompose (x -> { String n = f.getAnnotation (us.levk.rserve.client.Assign.class).value (); CompletableFuture <Void> r = new CompletableFuture <> (); try { assign ("".equals (n) ? f.getName () : n, f.get (j)).thenRun ( () -> r.complete (null)); } catch (Exception e) { r.completeExceptionally (e); } return r; }), (x, y) -> { throw new UnsupportedOperationException (); }), (p, c) -> p.thenCompose (x -> { return evaluate (c.getAnnotation (R.class).value ()); }), (x, y) -> { throw new UnsupportedOperationException (); }), (p, f) -> p.thenCompose (x -> { if (!f.isAccessible ()) f.setAccessible (true); String n = f.getAnnotation (us.levk.rserve.client.Resolve.class).value (); CompletableFuture <Void> r = new CompletableFuture <> (); resolve ("".equals (n) ? f.getName () : n, f.getGenericType ()).thenAccept (v -> { try { f.set (j, v); r.complete (null); } catch (Exception e) { r.completeExceptionally (e); } }); return r; }), (x, y) -> { throw new UnsupportedOperationException (); }).thenApply (x -> j); } /** * Client builder * * @author levk */ static class Builder { /** * Object mapper */ private final RserveMapper mapper; /** * Async provider */ private final ExecutorService executor; /** * @param m * mapper * @param e * executor */ private Builder (RserveMapper m, ExecutorService e) { mapper = m; executor = e; } /** * @param m * mapper * @return copy of this builder with the specified mapper */ public Builder with (RserveMapper m) { return new Builder (m, executor); } /** * @param e * executor * @return copy of this builder with the executor specified */ public Builder with (ExecutorService e) { return new Builder (mapper, e); } /** * @return websocket client builder */ public WsBuilder websocket () { return websocket (getWebSocketContainer ()); } /** * @param c * container * @return websocket client builder */ public WsBuilder websocket (WebSocketContainer c) { return new WsBuilder (c); } /** * Websocket client builder * * @author levk */ public class WsBuilder { /** * Container */ private final WebSocketContainer container; /** * @param c * container */ private WsBuilder (WebSocketContainer c) { container = c; } /** * @param c * container * @return copy of this builder with container specified */ public WsBuilder with (WebSocketContainer c) { return new WsBuilder (c); } /** * @param u * endpoint URI * @return client * @throws DeploymentException * on connect * @throws IOException * on connect */ public Client connect (String u) throws DeploymentException, IOException { return connect (create (u)); } /** * @param u * endpoint URI * @return client * @throws DeploymentException * on connect * @throws IOException * on connect */ public Client connect (URI u) throws DeploymentException, IOException { Endpoint e = new Endpoint (mapper, executor); container.connectToServer (e, u); return e; } } } /** * @return builder */ public static Builder rserve () { return rserve (new RserveMapper ()); } /** * @param m * mapper * @return builder using the specified mapper */ public static Builder rserve (RserveMapper m) { return rserve (m, newWorkStealingPool ()); } /** * @param e * executor * @return builder using the executor specified */ public static Builder rserve (ExecutorService e) { return rserve (new RserveMapper (), e); } /** * @param m * mapper * @param e * executor * @return builder using the specified mapper and executor */ public static Builder rserve (RserveMapper m, ExecutorService e) { return new Builder (m, e); } }
package com.yahoo.squidb.data; import com.yahoo.squidb.sql.Field; import com.yahoo.squidb.sql.Property.StringProperty; import com.yahoo.squidb.sql.Query; import com.yahoo.squidb.sql.TableModelName; import com.yahoo.squidb.sql.TableStatement; import com.yahoo.squidb.test.DatabaseTestCase; import com.yahoo.squidb.test.Employee; import com.yahoo.squidb.test.SQLiteBindingProvider; import com.yahoo.squidb.test.TestDatabase; import com.yahoo.squidb.test.TestModel; import com.yahoo.squidb.test.TestViewModel; import com.yahoo.squidb.test.Thing; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; public class SquidDatabaseTest extends DatabaseTestCase { private TestHookDatabase testHookDatabase; @Override protected void setupDatabase() { super.setupDatabase(); testHookDatabase = new TestHookDatabase(); testHookDatabase.getDatabase(); // init } @Override protected void tearDownDatabase() { super.tearDownDatabase(); testHookDatabase.clear(); } public void testRawQuery() { testHookDatabase.persist(new TestModel().setFirstName("Sam").setLastName("Bosley").setBirthday(testDate)); ICursor cursor = null; try { // Sanity check that there is only one row in the table assertEquals(1, testHookDatabase.countAll(TestModel.class)); // Test that raw query binds arguments correctly--if the argument // is bound as a String, the result will be empty cursor = testHookDatabase.rawQuery("select * from testModels where abs(_id) = ?", new Object[]{1}); assertEquals(1, cursor.getCount()); } finally { if (cursor != null) { cursor.close(); } } } public void testTryAddColumn() { StringProperty goodProperty = new StringProperty( new TableModelName(TestModel.class, TestModel.TABLE.getName()), "good_column"); testHookDatabase.tryAddColumn(goodProperty); // don't care about the result, just that it didn't throw final StringProperty badProperty = new StringProperty( new TableModelName(TestViewModel.class, TestViewModel.VIEW.getName()), "bad_column"); testThrowsException(new Runnable() { @Override public void run() { testHookDatabase.tryAddColumn(badProperty); } }, IllegalArgumentException.class); } public void testMigrationFailureCalledWhenOnUpgradeReturnsFalse() { testMigrationFailureCalled(true, false, false, false); } public void testMigrationFailureCalledWhenOnUpgradeThrowsException() { testMigrationFailureCalled(true, true, false, false); } public void testMigrationFailureCalledWhenOnDowngradeReturnsFalse() { testMigrationFailureCalled(false, false, false, false); } public void testMigrationFailureCalledWhenOnDowngradeThrowsException() { testMigrationFailureCalled(false, true, false, false); } private void testMigrationFailureCalled(boolean upgrade, boolean shouldThrow, boolean shouldRecreateDuringMigration, boolean shouldRecreateOnMigrationFailed) { testHookDatabase.shouldThrowDuringMigration = shouldThrow; testHookDatabase.shouldRecreateInMigration = shouldRecreateDuringMigration; testHookDatabase.shouldRecreateInOnMigrationFailed = shouldRecreateOnMigrationFailed; // set version manually ISQLiteDatabase db = testHookDatabase.getDatabase(); final int version = db.getVersion(); final int previousVersion = upgrade ? version - 1 : version + 1; db.setVersion(previousVersion); // close and reopen to trigger an upgrade/downgrade testHookDatabase.onTablesCreatedCalled = false; testHookDatabase.close(); RuntimeException caughtException = null; try { testHookDatabase.getDatabase(); } catch (RuntimeException e) { caughtException = e; } // If throwing or returning false from migration but not handling it, we expect getDatabase to also throw // since the DB will not be open after exiting the onMigrationFailed hook if (!shouldRecreateDuringMigration) { assertNotNull(caughtException); } else { assertNull(caughtException); } assertTrue(upgrade ? testHookDatabase.onUpgradeCalled : testHookDatabase.onDowngradeCalled); if (shouldRecreateDuringMigration || shouldRecreateOnMigrationFailed) { assertTrue(testHookDatabase.onTablesCreatedCalled); } else { assertTrue(testHookDatabase.onMigrationFailedCalled); assertEquals(previousVersion, testHookDatabase.migrationFailedOldVersion); assertEquals(version, testHookDatabase.migrationFailedNewVersion); } } /** * {@link SquidDatabase} does not automatically recreate the database when a migration fails. This is really to * test that {@link SquidDatabase#recreate()} can safely be called during onUpgrade or * onDowngrade as an exemplar for client developers. */ public void testRecreateOnUpgradeFailure() { testRecreateDuringMigrationOrFailureCallback(true, false); } public void testRecreateOnDowngradeFailure() { testRecreateDuringMigrationOrFailureCallback(false, false); } public void testRecreateDuringOnMigrationFailed() { testRecreateDuringMigrationOrFailureCallback(true, true); } private void testRecreateDuringMigrationOrFailureCallback(boolean upgrade, boolean recreateDuringMigration) { // insert some data to check for later testHookDatabase.persist(new Employee().setName("Alice")); testHookDatabase.persist(new Employee().setName("Bob")); testHookDatabase.persist(new Employee().setName("Cindy")); assertEquals(3, testHookDatabase.countAll(Employee.class)); testMigrationFailureCalled(upgrade, recreateDuringMigration, true, recreateDuringMigration); // verify the db was recreated with the appropriate version and no previous data ISQLiteDatabase db = testHookDatabase.getDatabase(); assertEquals(testHookDatabase.getVersion(), db.getVersion()); assertEquals(0, testHookDatabase.countAll(Employee.class)); } public void testExceptionDuringOpenCleansUp() { testHookDatabase.shouldThrowDuringMigration = true; testHookDatabase.shouldRecreateInMigration = true; testHookDatabase.shouldRecreateInOnMigrationFailed = false; testHookDatabase.shouldRethrowInOnMigrationFailed = true; testThrowsException(new Runnable() { @Override public void run() { // set version manually ISQLiteDatabase db = testHookDatabase.getDatabase(); final int version = db.getVersion(); final int previousVersion = version - 1; db.setVersion(previousVersion); // close and reopen to trigger an upgrade/downgrade testHookDatabase.onTablesCreatedCalled = false; testHookDatabase.close(); testHookDatabase.getDatabase(); } }, SquidDatabase.MigrationFailedException.class); assertFalse(testHookDatabase.inTransaction()); assertFalse(testHookDatabase.isOpen()); } public void testAcquireExclusiveLockFailsWhenInTransaction() { testThrowsException(new Runnable() { @Override public void run() { IllegalStateException caughtException = null; testHookDatabase.beginTransaction(); try { testHookDatabase.acquireExclusiveLock(); } catch (IllegalStateException e) { // Need to do this in the catch block rather than the finally block, because otherwise tearDown is // called before we have a chance to release the transaction lock testHookDatabase.endTransaction(); caughtException = e; } finally { if (caughtException == null) { // Sanity cleanup if catch block was never reached testHookDatabase.endTransaction(); } } if (caughtException != null) { throw caughtException; } } }, IllegalStateException.class); } public void testCustomMigrationException() { final TestDatabase database = new TestDatabase(); ISQLiteDatabase db = database.getDatabase(); // force a downgrade final int version = db.getVersion(); final int previousVersion = version + 1; db.setVersion(previousVersion); database.close(); // Expect an exception here because this DB does not cleanly re-open the DB in case of errors testThrowsException(new Runnable() { @Override public void run() { database.getDatabase(); } }, RuntimeException.class); try { assertTrue(database.caughtCustomMigrationException); } finally { database.clear(); // clean up since this is the only test using it } } public void testRetryOpenDatabase() { testHookDatabase.clear(); // init opens it, we need a new db final AtomicBoolean openFailedHandlerCalled = new AtomicBoolean(); testHookDatabase.shouldThrowDuringOpen = true; testHookDatabase.dbOpenFailedHandler = new DbOpenFailedHandler() { @Override public void dbOpenFailed(RuntimeException failure, int openFailureCount) { openFailedHandlerCalled.set(true); testHookDatabase.shouldThrowDuringOpen = false; testHookDatabase.getDatabase(); } }; testHookDatabase.getDatabase(); assertTrue(testHookDatabase.isOpen()); assertTrue(openFailedHandlerCalled.get()); assertEquals(1, testHookDatabase.dbOpenFailureCount); } public void testRecreateOnOpenFailed() { final AtomicBoolean openFailedHandlerCalled = new AtomicBoolean(); testHookDatabase.persist(new Employee().setName("Alice")); testHookDatabase.persist(new Employee().setName("Bob")); testHookDatabase.persist(new Employee().setName("Cindy")); assertEquals(3, testHookDatabase.countAll(Employee.class)); ISQLiteDatabase db = testHookDatabase.getDatabase(); db.setVersion(db.getVersion() + 1); testHookDatabase.close(); testHookDatabase.shouldThrowDuringMigration = true; testHookDatabase.shouldRethrowInOnMigrationFailed = true; testHookDatabase.dbOpenFailedHandler = new DbOpenFailedHandler() { @Override public void dbOpenFailed(RuntimeException failure, int openFailureCount) { openFailedHandlerCalled.set(true); testHookDatabase.shouldThrowDuringOpen = false; testHookDatabase.recreate(); } }; testHookDatabase.getDatabase(); assertTrue(testHookDatabase.isOpen()); assertTrue(openFailedHandlerCalled.get()); assertEquals(1, testHookDatabase.dbOpenFailureCount); assertEquals(0, testHookDatabase.countAll(Employee.class)); } public void testSuppressingDbOpenFailedThrowsRuntimeException() { testHookDatabase.clear(); final AtomicBoolean openFailedHandlerCalled = new AtomicBoolean(); testHookDatabase.shouldThrowDuringOpen = true; testHookDatabase.dbOpenFailedHandler = new DbOpenFailedHandler() { @Override public void dbOpenFailed(RuntimeException failure, int openFailureCount) { openFailedHandlerCalled.set(true); } }; testThrowsException(new Runnable() { @Override public void run() { testHookDatabase.getDatabase(); } }, RuntimeException.class); assertTrue(openFailedHandlerCalled.get()); assertFalse(testHookDatabase.isOpen()); } public void testRecursiveRetryDbOpen() { testRecursiveRetryDbOpen(1, true); testRecursiveRetryDbOpen(1, false); testRecursiveRetryDbOpen(2, true); testRecursiveRetryDbOpen(2, false); testRecursiveRetryDbOpen(3, true); testRecursiveRetryDbOpen(3, false); } private void testRecursiveRetryDbOpen(final int maxRetries, final boolean eventualRecovery) { testHookDatabase.clear(); testHookDatabase.shouldThrowDuringOpen = true; testHookDatabase.dbOpenFailedHandler = new DbOpenFailedHandler() { @Override public void dbOpenFailed(RuntimeException failure, int openFailureCount) { if (openFailureCount >= maxRetries) { testHookDatabase.shouldThrowDuringOpen = false; if (!eventualRecovery) { throw failure; } } testHookDatabase.getDatabase(); } }; if (eventualRecovery) { testHookDatabase.getDatabase(); } else { testThrowsException(new Runnable() { @Override public void run() { testHookDatabase.getDatabase(); } }, RuntimeException.class); } assertEquals(maxRetries, testHookDatabase.dbOpenFailureCount); assertEquals(eventualRecovery, testHookDatabase.isOpen()); } public void testDataChangeNotifiersDisabledDuringDbOpen() { testDataChangeNotifiersDisabledDuringDbOpen(true, true); testDataChangeNotifiersDisabledDuringDbOpen(true, false); testDataChangeNotifiersDisabledDuringDbOpen(false, true); testDataChangeNotifiersDisabledDuringDbOpen(false, false); } private void testDataChangeNotifiersDisabledDuringDbOpen(boolean startEnabled, final boolean openFailure) { final AtomicBoolean notifierCalled = new AtomicBoolean(); final AtomicBoolean failOnOpen = new AtomicBoolean(openFailure); SimpleDataChangedNotifier simpleNotifier = new SimpleDataChangedNotifier(Thing.TABLE) { @Override protected void onDataChanged() { notifierCalled.set(true); } }; TestDatabase testDb = new TestDatabase() { @Override public String getName() { return super.getName() + "2"; } @Override protected void onTablesCreated(ISQLiteDatabase db) { super.onTablesCreated(db); persist(new Thing().setFoo("foo").setBar(1)); if (failOnOpen.getAndSet(false)) { throw new RuntimeException("Failed to open db"); } } @Override protected void onDatabaseOpenFailed(RuntimeException failure, int openFailureCount) { getDatabase(); } }; testDb.setDataChangedNotificationsEnabled(startEnabled); testDb.registerDataChangedNotifier(simpleNotifier); testDb.getDatabase(); assertFalse(notifierCalled.get()); assertEquals(1, testDb.countAll(Thing.class)); assertEquals(startEnabled, testDb.areDataChangedNotificationsEnabled()); testDb.persist(new Thing().setFoo("foo2").setBar(2)); assertEquals(startEnabled, notifierCalled.get()); testDb.clear(); } public void testOnCloseHook() { final AtomicReference<ISQLitePreparedStatement> preparedStatementRef = new AtomicReference<>(); testHookDatabase.onCloseTester = new DbHookTester() { @Override void onHookImpl(ISQLiteDatabase db) { assertTrue(db.isOpen()); ISQLitePreparedStatement statement = preparedStatementRef.get(); assertNotNull(statement); statement.close(); preparedStatementRef.set(null); } }; preparedStatementRef.set(testHookDatabase.prepareStatement("SELECT COUNT(*) FROM testModels")); assertNotNull(preparedStatementRef.get()); assertEquals(0, preparedStatementRef.get().simpleQueryForLong()); testHookDatabase.close(); assertTrue(testHookDatabase.onCloseTester.wasCalled); assertNull(preparedStatementRef.get()); } /** * A {@link TestDatabase} that intentionally fails in onUpgrade and onDowngrade and provides means of testing * various other SquidDatabase hooks */ private static class TestHookDatabase extends TestDatabase { private boolean onMigrationFailedCalled = false; private boolean onUpgradeCalled = false; private boolean onDowngradeCalled = false; private boolean onTablesCreatedCalled = false; private int dbOpenFailureCount = 0; private int migrationFailedOldVersion = 0; private int migrationFailedNewVersion = 0; private boolean shouldThrowDuringOpen = false; private boolean shouldThrowDuringMigration = false; private boolean shouldRecreateInMigration = false; private boolean shouldRecreateInOnMigrationFailed = false; private boolean shouldRethrowInOnMigrationFailed = false; private DbOpenFailedHandler dbOpenFailedHandler = null; private DbHookTester onCloseTester = null; public TestHookDatabase() { super(); } @Override public String getName() { return "badDb"; } @Override protected int getVersion() { return super.getVersion() + 1; } @Override protected void onTablesCreated(ISQLiteDatabase db) { onTablesCreatedCalled = true; if (shouldThrowDuringOpen) { throw new RuntimeException("Simulating DB open failure"); } } @Override protected final boolean onUpgrade(ISQLiteDatabase db, int oldVersion, int newVersion) { onUpgradeCalled = true; if (shouldThrowDuringMigration) { throw new RuntimeException("My name is \"NO! NO! BAD DATABASE!\". What's yours?"); } else if (shouldRecreateInMigration) { recreate(); } return false; } @Override protected boolean onDowngrade(ISQLiteDatabase db, int oldVersion, int newVersion) { onDowngradeCalled = true; if (shouldThrowDuringMigration) { throw new RuntimeException("My name is \"NO! NO! BAD DATABASE!\". What's yours?"); } else if (shouldRecreateInMigration) { recreate(); } return false; } @Override protected void onMigrationFailed(MigrationFailedException failure) { onMigrationFailedCalled = true; migrationFailedOldVersion = failure.oldVersion; migrationFailedNewVersion = failure.newVersion; if (shouldRecreateInOnMigrationFailed) { recreate(); } else if (shouldRethrowInOnMigrationFailed) { throw failure; } } @Override protected void onDatabaseOpenFailed(RuntimeException failure, int openFailureCount) { dbOpenFailureCount = openFailureCount; if (dbOpenFailedHandler != null) { dbOpenFailedHandler.dbOpenFailed(failure, openFailureCount); } else { super.onDatabaseOpenFailed(failure, openFailureCount); } } @Override protected void onClose(ISQLiteDatabase db) { if (onCloseTester != null) { onCloseTester.onHook(db); } } } private interface DbOpenFailedHandler { void dbOpenFailed(RuntimeException failure, int openFailureCount); } // This class can be used to add customized behavior to the optional SquidDatabase overrideable hook methods // in the TestHookDatabase class. private static abstract class DbHookTester { boolean wasCalled = false; final void onHook(ISQLiteDatabase db) { wasCalled = true; onHookImpl(db); } abstract void onHookImpl(ISQLiteDatabase db); } public void testBasicInsertAndFetch() { TestModel model = insertBasicTestModel(); TestModel fetch = database.fetch(TestModel.class, model.getRowId(), TestModel.PROPERTIES); assertEquals("Sam", fetch.getFirstName()); assertEquals("Bosley", fetch.getLastName()); assertEquals(testDate, fetch.getBirthday().longValue()); } public void testPropertiesAreNullable() { TestModel model = insertBasicTestModel(); model.setFirstName(null); model.setLastName(null); assertNull(model.getFirstName()); assertNull(model.getLastName()); database.persist(model); TestModel fetch = database.fetch(TestModel.class, model.getRowId(), TestModel.PROPERTIES); assertNull(fetch.getFirstName()); assertNull(fetch.getLastName()); } public void testBooleanProperties() { TestModel model = insertBasicTestModel(); assertTrue(model.isHappy()); model.setIsHappy(false); assertFalse(model.isHappy()); database.persist(model); TestModel fetch = database.fetch(TestModel.class, model.getRowId(), TestModel.PROPERTIES); assertFalse(fetch.isHappy()); } public void testQueriesWithBooleanPropertiesWork() { insertBasicTestModel(); TestModel model; SquidCursor<TestModel> result = database.query(TestModel.class, Query.select(TestModel.PROPERTIES).where(TestModel.IS_HAPPY.isTrue())); try { assertEquals(1, result.getCount()); result.moveToFirst(); model = new TestModel(result); assertTrue(model.isHappy()); model.setIsHappy(false); database.persist(model); } finally { result.close(); } result = database.query(TestModel.class, Query.select(TestModel.PROPERTIES).where(TestModel.IS_HAPPY.isFalse())); try { assertEquals(1, result.getCount()); result.moveToFirst(); model = new TestModel(result); assertFalse(model.isHappy()); } finally { result.close(); } } public void testConflict() { insertBasicTestModel(); TestModel conflict = new TestModel(); conflict.setFirstName("Dave"); conflict.setLastName("Bosley"); boolean result = database.persistWithOnConflict(conflict, TableStatement.ConflictAlgorithm.IGNORE); assertFalse(result); TestModel shouldntExist = database.fetchByCriterion(TestModel.class, TestModel.FIRST_NAME.eq("Dave").and(TestModel.LAST_NAME.eq("Bosley")), TestModel.PROPERTIES); assertNull(shouldntExist); RuntimeException expected = null; try { conflict.clearValue(TestModel.ID); database.persistWithOnConflict(conflict, TableStatement.ConflictAlgorithm.FAIL); } catch (RuntimeException e) { expected = e; } assertNotNull(expected); } public void testFetchByQueryResetsLimitAndTable() { TestModel model1 = new TestModel().setFirstName("Sam1").setLastName("Bosley1"); TestModel model2 = new TestModel().setFirstName("Sam2").setLastName("Bosley2"); TestModel model3 = new TestModel().setFirstName("Sam3").setLastName("Bosley3"); database.persist(model1); database.persist(model2); database.persist(model3); Query query = Query.select().limit(2, 1); TestModel fetched = database.fetchByQuery(TestModel.class, query); assertEquals(model2.getRowId(), fetched.getRowId()); assertEquals(Field.field("2"), query.getLimit()); assertEquals(Field.field("1"), query.getOffset()); assertEquals(null, query.getTable()); } public void testEqCaseInsensitive() { insertBasicTestModel(); TestModel fetch = database.fetchByCriterion(TestModel.class, TestModel.LAST_NAME.eqCaseInsensitive("BOSLEY"), TestModel.PROPERTIES); assertNotNull(fetch); } public void testInsertRow() { TestModel model = insertBasicTestModel(); assertNotNull(database.fetch(TestModel.class, model.getRowId())); database.delete(TestModel.class, model.getRowId()); assertNull(database.fetch(TestModel.class, model.getRowId())); long modelId = model.getRowId(); database.insertRow(model); // Should reinsert the row with the same id assertEquals(modelId, model.getRowId()); assertNotNull(database.fetch(TestModel.class, model.getRowId())); assertEquals(1, database.countAll(TestModel.class)); } public void testDropView() { database.tryDropView(TestViewModel.VIEW); testThrowsRuntimeException(new Runnable() { @Override public void run() { database.query(TestViewModel.class, Query.select().from(TestViewModel.VIEW)); } }); } public void testDropTable() { database.tryDropTable(TestModel.TABLE); testThrowsRuntimeException(new Runnable() { @Override public void run() { database.query(TestModel.class, Query.select().from(TestModel.TABLE)); } }); } public void testTryExecSqlReturnsFalseForInvalidSql() { assertFalse(database.tryExecSql("CREATE TABLE")); } public void testExecSqlOrThrowThrowsForInvalidSql() { testThrowsRuntimeException(new Runnable() { @Override public void run() { database.execSqlOrThrow("CREATE TABLE"); } }); testThrowsRuntimeException(new Runnable() { @Override public void run() { database.execSqlOrThrow("CREATE TABLE", null); } }); } public void testUpdateAll() { database.persist(new TestModel().setFirstName("A").setLastName("A") .setBirthday(System.currentTimeMillis() - 1).setLuckyNumber(1)); database.persist(new TestModel().setFirstName("A").setLastName("B") .setBirthday(System.currentTimeMillis() - 1).setLuckyNumber(2)); database.updateAll(new TestModel().setLuckyNumber(5)); assertEquals(0, database.count(TestModel.class, TestModel.LUCKY_NUMBER.neq(5))); } public void testDeleteAll() { insertBasicTestModel("A", "B", System.currentTimeMillis() - 1); insertBasicTestModel("C", "D", System.currentTimeMillis()); assertEquals(2, database.countAll(TestModel.class)); database.deleteAll(TestModel.class); assertEquals(0, database.countAll(TestModel.class)); } public void testBlobs() { List<byte[]> randomBlobs = new ArrayList<>(); Random r = new Random(); randomBlobs.add(new byte[0]); // Test 0-length blob int numBlobs = 10; for (int i = 0; i < numBlobs; i++) { byte[] blob = new byte[i + 1]; r.nextBytes(blob); randomBlobs.add(blob); } Thing t = new Thing(); database.beginTransaction(); try { for (byte[] blob : randomBlobs) { t.setBlob(blob); database.createNew(t); } database.setTransactionSuccessful(); } finally { database.endTransaction(); } SquidCursor<Thing> cursor = database.query(Thing.class, Query.select(Thing.BLOB).orderBy(Thing.ID.asc())); try { assertEquals(randomBlobs.size(), cursor.getCount()); for (int i = 0; i < randomBlobs.size(); i++) { cursor.moveToPosition(i); byte[] blob = cursor.get(Thing.BLOB); assertTrue(Arrays.equals(randomBlobs.get(i), blob)); } } finally { cursor.close(); } } public void testConcurrentReadsWithWAL() { // Tests that concurrent reads can happen when using WAL, but only committed changes will be visible // on other threads insertBasicTestModel(); final Semaphore sema1 = new Semaphore(0); final Semaphore sema2 = new Semaphore(0); final AtomicInteger countBeforeCommit = new AtomicInteger(); final AtomicInteger countAfterCommit = new AtomicInteger(); Thread thread = new Thread(new Runnable() { @Override public void run() { try { sema2.acquire(); } catch (InterruptedException e) { fail(e.getMessage()); } countBeforeCommit.set(database.countAll(TestModel.class)); sema1.release(); try { sema2.acquire(); } catch (InterruptedException e) { fail(e.getMessage()); } countAfterCommit.set(database.countAll(TestModel.class)); } }); database.beginTransactionNonExclusive(); try { thread.start(); insertBasicTestModel("A", "B", System.currentTimeMillis() + 100); sema2.release(); try { sema1.acquire(); } catch (InterruptedException e) { fail(e.getMessage()); } database.setTransactionSuccessful(); } finally { database.endTransaction(); sema2.release(); } try { thread.join(); } catch (InterruptedException e) { fail(e.getMessage()); } assertEquals(1, countBeforeCommit.get()); assertEquals(2, countAfterCommit.get()); } public void testConcurrencyStressTest() { int numThreads = 20; final AtomicReference<Exception> exception = new AtomicReference<>(); List<Thread> workers = new ArrayList<>(); for (int i = 0; i < numThreads; i++) { Thread t = new Thread(new Runnable() { @Override public void run() { concurrencyStressTest(exception); } }); t.start(); workers.add(t); } for (Thread t : workers) { try { t.join(); } catch (Exception e) { exception.set(e); } } assertNull(exception.get()); } private void concurrencyStressTest(AtomicReference<Exception> exception) { try { Random r = new Random(); int numOperations = 100; Thing t = new Thing(); for (int i = 0; i < numOperations; i++) { int rand = r.nextInt(10); if (rand == 0) { database.close(); } else if (rand == 1) { database.clear(); } else if (rand == 2) { database.recreate(); } else if (rand == 3) { database.beginTransactionNonExclusive(); try { for (int j = 0; j < 20; j++) { t.setFoo(Integer.toString(j)) .setBar(-j); database.createNew(t); } database.setTransactionSuccessful(); } finally { database.endTransaction(); } } else { t.setFoo(Integer.toString(i)) .setBar(-i); database.createNew(t); } } } catch (Exception e) { exception.set(e); } } public void testSimpleQueries() { database.beginTransactionNonExclusive(); try { // the changes() function only works inside a transaction, because otherwise you may not get // the same connection to the sqlite database depending on what the connection pool feels like giving you. String sql = "SELECT CHANGES()"; insertBasicTestModel(); assertEquals(1, database.simpleQueryForLong(sql, null)); assertEquals("1", database.simpleQueryForString(sql, null)); database.setTransactionSuccessful(); } finally { database.endTransaction(); } } public void testCopyDatabase() { insertBasicTestModel(); // Make sure DB is open and populated File destinationDir = new File(SQLiteBindingProvider.getInstance().getWriteableTestDir()); File dbFile = new File(database.getDatabasePath()); File walFile = new File(database.getDatabasePath() + "-wal"); assertTrue(dbFile.exists()); assertTrue(walFile.exists()); File destinationDbFile = new File(destinationDir.getPath() + File.separator + database.getName()); File destinationWalFile = new File(destinationDir.getPath() + File.separator + database.getName() + "-wal"); destinationDbFile.delete(); destinationWalFile.delete(); assertFalse(destinationDbFile.exists()); assertFalse(destinationWalFile.exists()); assertTrue(database.copyDatabase(destinationDir)); assertTrue(destinationDbFile.exists()); assertTrue(destinationWalFile.exists()); assertTrue(filesAreEqual(dbFile, destinationDbFile)); assertTrue(filesAreEqual(walFile, destinationWalFile)); } private boolean filesAreEqual(File f1, File f2) { if (f1.length() != f2.length()) { return false; } try { FileInputStream f1in = new FileInputStream(f1); FileInputStream f2in = new FileInputStream(f2); int f1Bytes; int f2Bytes; byte[] f1Buffer; byte[] f2Buffer; int BUFFER_SIZE = 1024; f1Buffer = new byte[BUFFER_SIZE]; f2Buffer = new byte[BUFFER_SIZE]; while ((f1Bytes = f1in.read(f1Buffer)) != -1) { f2Bytes = f2in.read(f2Buffer); if (f1Bytes != f2Bytes) { return false; } if (!Arrays.equals(f1Buffer, f2Buffer)) { return false; } } return f2in.read(f2Buffer) == -1; } catch (IOException e) { throw new RuntimeException(e); } } // public void testValidIdentifierCharacters() { // database.getDatabase(); // testIdentifiersInRange((char) 0x00A1, (char) 0xd7ff); // testIdentifiersInRange((char) 0xe000, (char) 0xffff); // testIdentifiersInRange('a', 'z'); // testIdentifiersInRange('A', 'Z'); // testIdentifiersInRange('_', '_'); // private void testIdentifiersInRange(char min, char max) { // for (char c = min; c >= min && c <= max; c++) { // if (!database.tryExecSql("create table " + tableName + " (" + tableName + " text)")) { // if (!database.tryExecSql("insert into " + tableName + " (" + tableName + ") values ('a')")) { // if (database.simpleQueryForLong("select count(*) from " + tableName, null) != 1) { // fail("Thought insert into table named " + tableName + " had worked but count wasn't 1" + // if (!database.tryExecSql("drop table " + tableName)) { // Logger.d(Logger.LOG_TAG, "Identifier character " + c + " is valid"); }
package loci.formats.in; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import loci.common.RandomAccessInputStream; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.MetadataTools; import loci.formats.codec.JPEG2000BoxType; import loci.formats.codec.JPEG2000Codec; import loci.formats.codec.JPEG2000CodecOptions; import loci.formats.meta.MetadataStore; public class JPEG2000Reader extends FormatReader { // -- Constants -- /** Logger for this class. */ private static final Logger LOGGER = LoggerFactory.getLogger(JPEG2000Reader.class); // -- Fields -- /** The number of JPEG 2000 resolution levels the file has. */ private Integer resolutionLevels; /** The color lookup table associated with this file. */ private int[][] lut; private long pixelsOffset; private int lastSeries = -1; private byte[] lastSeriesPlane; // -- Constructor -- /** Constructs a new JPEG2000Reader. */ public JPEG2000Reader() { super("JPEG-2000", new String[] {"jp2", "j2k", "jpf"}); suffixSufficient = false; suffixNecessary = false; domains = new String[] {FormatTools.GRAPHICS_DOMAIN}; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { final int blockLen = 8; if (!FormatTools.validStream(stream, blockLen, false)) return false; boolean validStart = (stream.readShort() & 0xffff) == 0xff4f; if (!validStart) { stream.skipBytes(2); validStart = stream.readInt() == JPEG2000BoxType.SIGNATURE.getCode(); } stream.seek(stream.length() - 2); boolean validEnd = (stream.readShort() & 0xffff) == 0xffd9; return validStart && validEnd; } /* @see loci.formats.IFormatReader#get8BitLookupTable() */ public byte[][] get8BitLookupTable() { FormatTools.assertId(currentId, true, 1); if (lut == null || FormatTools.getBytesPerPixel(getPixelType()) != 1) { return null; } byte[][] byteLut = new byte[lut.length][lut[0].length]; for (int i=0; i<lut.length; i++) { for (int j=0; j<lut[i].length; j++) { byteLut[i][j] = (byte) (lut[i][j] & 0xff); } } return byteLut; } /* @see loci.formats.IFormatReader#get16BitLookupTable() */ public short[][] get16BitLookupTable() { FormatTools.assertId(currentId, true, 1); if (lut == null || FormatTools.getBytesPerPixel(getPixelType()) != 2) { return null; } short[][] shortLut = new short[lut.length][lut[0].length]; for (int i=0; i<lut.length; i++) { for (int j=0; j<lut[i].length; j++) { shortLut[i][j] = (short) (lut[i][j] & 0xffff); } } return shortLut; } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { resolutionLevels = null; lut = null; pixelsOffset = 0; lastSeries = -1; lastSeriesPlane = null; } } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); if (lastSeries == getSeries() && lastSeriesPlane != null) { RandomAccessInputStream s = new RandomAccessInputStream(lastSeriesPlane); readPlane(s, x, y, w, h, buf); s.close(); return buf; } JPEG2000CodecOptions options = JPEG2000CodecOptions.getDefaultOptions(); options.interleaved = isInterleaved(); options.littleEndian = isLittleEndian(); if (resolutionLevels != null) { options.resolution = Math.abs(series - resolutionLevels); } else if (getSeriesCount() > 1) { options.resolution = series; } in.seek(pixelsOffset); lastSeriesPlane = new JPEG2000Codec().decompress(in, options); RandomAccessInputStream s = new RandomAccessInputStream(lastSeriesPlane); readPlane(s, x, y, w, h, buf); s.close(); lastSeries = getSeries(); return buf; } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); in = new RandomAccessInputStream(id); JPEG2000MetadataParser metadataParser = new JPEG2000MetadataParser(in); if (metadataParser.isRawCodestream()) { LOGGER.info("Codestream is raw, using codestream dimensions."); core[0].sizeX = metadataParser.getCodestreamSizeX(); core[0].sizeY = metadataParser.getCodestreamSizeY(); core[0].sizeC = metadataParser.getCodestreamSizeC(); core[0].pixelType = metadataParser.getCodestreamPixelType(); } else { LOGGER.info("Codestream is JP2 boxed, using header dimensions."); core[0].sizeX = metadataParser.getHeaderSizeX(); core[0].sizeY = metadataParser.getHeaderSizeY(); core[0].sizeC = metadataParser.getHeaderSizeC(); core[0].pixelType = metadataParser.getHeaderPixelType(); } lut = metadataParser.getLookupTable(); pixelsOffset = metadataParser.getCodestreamOffset(); core[0].sizeZ = 1; core[0].sizeT = 1; core[0].imageCount = 1; core[0].dimensionOrder = "XYCZT"; core[0].rgb = getSizeC() > 1; core[0].interleaved = true; core[0].littleEndian = false; core[0].indexed = !isRGB() && lut != null; // New core metadata now that we know how many sub-resolutions we have. if (resolutionLevels != null) { CoreMetadata[] newCore = new CoreMetadata[resolutionLevels + 1]; newCore[0] = core[0]; for (int i = 1; i < newCore.length; i++) { newCore[i] = new CoreMetadata(this, 0); newCore[i].sizeX = newCore[i - 1].sizeX / 2; newCore[i].sizeY = newCore[i - 1].sizeY / 2; newCore[i].thumbnail = true; } core = newCore; } MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this, true); } // -- Helper methods -- }
package utask.logic.parser; import java.util.regex.Pattern; import utask.logic.parser.ArgumentTokenizer.Prefix; /** * Contains Command Line Interface (CLI) syntax definitions common to multiple commands */ public class CliSyntax { /* Prefix definitions */ public static final Prefix PREFIX_NAME = new Prefix("/name"); public static final Prefix PREFIX_DEADLINE = new Prefix("/by"); public static final Prefix PREFIX_TIMESTAMP = new Prefix("/from"); public static final Prefix PREFIX_FREQUENCY = new Prefix("/repeat"); public static final Prefix PREFIX_DONE = new Prefix("/done"); public static final Prefix PREFIX_TAG = new Prefix("/tag"); /* Patterns definitions */ public static final Pattern KEYWORDS_ARGS_FORMAT = Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace }
package com.vimeo.stag.processor.generators; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.TypeVariableName; import com.vimeo.stag.GsonAdapterKey; import com.vimeo.stag.processor.generators.model.AnnotatedClass; import com.vimeo.stag.processor.generators.model.ClassInfo; import com.vimeo.stag.processor.generators.model.SupportedTypesModel; import com.vimeo.stag.processor.utils.FileGenUtils; import com.vimeo.stag.processor.utils.TypeUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.Modifier; import javax.lang.model.type.ArrayType; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.type.TypeVariable; @SuppressWarnings("StringConcatenationMissingWhitespace") public class TypeAdapterGenerator { private static final String TYPE_ADAPTER_FIELD_PREFIX = "mTypeAdapter"; @NotNull private final ClassInfo mInfo; private boolean mGsonVariableUsed = false; private boolean mStagFactoryUsed = false; public TypeAdapterGenerator(@NotNull ClassInfo info) { mInfo = info; } private static class AdapterFieldInfo { @NotNull private final Map<String, String> mAdapterFields; @Nullable private Map<String, String> mKnownAdapterStagFunctionCalls; public AdapterFieldInfo(int capacity) { mAdapterFields = new HashMap<>(capacity); } /** * Used to get the stag adapter for a typeMirror if it is already generated in Stag.Factory */ @Nullable public String getKnownAdapterStagFunctionCalls(TypeMirror typeMirror) { return mKnownAdapterStagFunctionCalls != null ? mKnownAdapterStagFunctionCalls.get(typeMirror.toString()) : null; } /** * Add the getter method name against a field name */ public void addTypeToFunctionName(String name, String functionName) { if (null == mKnownAdapterStagFunctionCalls) { mKnownAdapterStagFunctionCalls = new HashMap<>(); } mKnownAdapterStagFunctionCalls.put(name, functionName); } public String getAdapter(@NotNull TypeMirror typeMirror) { String typeName = typeMirror.toString(); String result = null != mKnownAdapterStagFunctionCalls ? mKnownAdapterStagFunctionCalls.get(typeName) : null; if (null == result) { result = mAdapterFields.get(typeName); } return result; } public String getFieldName(@NotNull TypeMirror fieldType) { return mAdapterFields.get(fieldType.toString()); } public int size() { return mAdapterFields.size(); } public void addField(@NotNull TypeMirror fieldType, @NotNull String fieldName) { mAdapterFields.put(fieldType.toString(), fieldName); } } @NotNull private AdapterFieldInfo addAdapterFields(@NotNull TypeSpec.Builder adapterBuilder, @NotNull MethodSpec.Builder constructorBuilder, @NotNull Map<Element, TypeMirror> memberVariables, @NotNull TypeTokenConstantsGenerator typeTokenConstantsGenerator, @NotNull Map<TypeVariable, String> typeVarsMap, @NotNull StagGenerator stagGenerator) { HashSet<TypeMirror> typeSet = new HashSet<>(memberVariables.values()); AdapterFieldInfo result = new AdapterFieldInfo(typeSet.size()); HashSet<TypeMirror> exclusiveTypeSet = new HashSet<>(); for (TypeMirror fieldType : typeSet) { if (isSupportedNative(fieldType.toString())) { continue; } if (isArray(fieldType)) { fieldType = getArrayInnerType(fieldType); if (isSupportedNative(fieldType.toString())) { continue; } } exclusiveTypeSet.add(fieldType); } for (TypeMirror fieldType : exclusiveTypeSet) { String getterField = stagGenerator.getClassAdapterFactoryMethod(fieldType); if(null != getterField) { /** * If we already have the adapter generated for the fieldType in Stag.Factory class */ result.addTypeToFunctionName(fieldType.toString(), "mStagFactory.get" + getterField + "(mGson)"); mGsonVariableUsed = true; mStagFactoryUsed = true; } else if (TypeUtils.isConcreteType(fieldType)) { getterField = stagGenerator.addFieldType(fieldType); result.addTypeToFunctionName(fieldType.toString(), "mStagFactory.get" + getterField + "(mGson)"); mGsonVariableUsed = true; mStagFactoryUsed = true; } else { String fieldName = result.getFieldName(fieldType); if (null == fieldName) { fieldName = TYPE_ADAPTER_FIELD_PREFIX + result.size(); result.addField(fieldType, fieldName); String originalFieldName = FileGenUtils.unescapeEscapedString(fieldName); TypeName typeName = getAdapterFieldTypeName(fieldType); adapterBuilder.addField(typeName, originalFieldName, Modifier.PRIVATE, Modifier.FINAL); constructorBuilder.addStatement(fieldName + " = (TypeAdapter<" + fieldType + ">) gson.getAdapter(" + getTypeTokenCode(fieldType, typeVarsMap, typeTokenConstantsGenerator) + ")"); } } } return result; } @Nullable private static String getTypeTokenCode(@NotNull TypeMirror fieldType, @NotNull Map<TypeVariable, String> typeVarsMap, @NotNull TypeTokenConstantsGenerator typeTokenConstantsGenerator) { String result = null; if (!TypeUtils.isConcreteType(fieldType)) { if (fieldType.getKind() == TypeKind.TYPEVAR) { result = " com.google.gson.reflect.TypeToken.get(" + typeVarsMap.get(fieldType) + ")"; } else if (fieldType instanceof DeclaredType) { /** * If it is of ParameterizedType, {@link com.vimeo.stag.utils.ParameterizedTypeUtil} is used to get the * type token of the parameter type. */ DeclaredType declaredFieldType = (DeclaredType) fieldType; List<? extends TypeMirror> typeMirrors = ((DeclaredType) fieldType).getTypeArguments(); result = "com.google.gson.reflect.TypeToken.getParameterized(" + declaredFieldType.asElement().toString() + ".class"; /** * Iterate through all the types from the typeArguments and generate typetoken code accordingly */ for (TypeMirror parameterTypeMirror : typeMirrors) { if (isSupportedNative(parameterTypeMirror.toString())) { result += ", " + parameterTypeMirror.toString() + ".class"; } else if (parameterTypeMirror.getKind() == TypeKind.TYPEVAR) { result += ", " + typeVarsMap.get(parameterTypeMirror); } else { result += ",\n" + getTypeTokenCode(parameterTypeMirror, typeVarsMap, typeTokenConstantsGenerator) + ".getType()"; } } result += ")"; } } else { result = typeTokenConstantsGenerator.addTypeToken(fieldType); } return result; } static boolean isSupportedPrimitive(@NotNull String type) { return type.equals(long.class.getName()) || type.equals(double.class.getName()) || type.equals(boolean.class.getName()) || type.equals(float.class.getName()) || type.equals(int.class.getName()); } private static boolean isNativeArray(@NotNull TypeMirror type) { return (type instanceof ArrayType); } static boolean isArray(@NotNull TypeMirror type) { if(isNativeArray(type)) { return true; } String outerClassType = TypeUtils.getOuterClassType(type); return outerClassType.equals(ArrayList.class.getName()) || outerClassType.equals(List.class.getName()) || outerClassType.equals(Collection.class.getName()); } @NotNull private static TypeName getAdapterFieldTypeName(@NotNull TypeMirror type) { TypeName typeName = TypeVariableName.get(type); return ParameterizedTypeName.get(ClassName.get(TypeAdapter.class), typeName); } /** * If the element is not annotated with {@link SerializedName}, the variable name is used. */ @NotNull private static String getJsonName(@NotNull Element element) { String name = element.getAnnotation(GsonAdapterKey.class).value(); if (name.isEmpty()) { name = element.getSimpleName().toString(); } return name; } static boolean isSupportedNative(@NotNull String type) { return isSupportedPrimitive(type) || type.equals(String.class.getName()) || type.equals(Long.class.getName()) || type.equals(Integer.class.getName()) || type.equals(Boolean.class.getName()) || type.equals(Double.class.getName()) || type.equals(Float.class.getName()) || type.equals(Number.class.getName()); } /** * Check if the type is one of the numbers */ private static boolean isNumberType(@NotNull String typeString) { return typeString.equals(long.class.getName()) || typeString.equals(Long.class.getName()) || typeString.equals(double.class.getName()) || typeString.equals(Double.class.getName()) || typeString.equals(int.class.getName()) || typeString.equals(Integer.class.getName()) || typeString.equals(float.class.getName()) || typeString.equals(Float.class.getName()); } @Nullable private static String getReadTokenType(@NotNull TypeMirror type) { String typeString = type.toString(); if (isNumberType(typeString)) { return "com.google.gson.stream.JsonToken.NUMBER"; } else if (type.toString().equals(boolean.class.getName())) { return "com.google.gson.stream.JsonToken.BOOLEAN"; } else if (type.toString().equals(String.class.getName())) { return "com.google.gson.stream.JsonToken.STRING"; } else if (isArray(type)) { return "com.google.gson.stream.JsonToken.BEGIN_ARRAY"; } else { return null; } } @NotNull private static TypeMirror getArrayInnerType(@NotNull TypeMirror type) { return (type instanceof ArrayType) ? ((ArrayType)type).getComponentType() : ((DeclaredType) type).getTypeArguments().get(0); } @NotNull private MethodSpec getWriteMethodSpec(@NotNull TypeName typeName, @NotNull Map<Element, TypeMirror> memberVariables, @NotNull AdapterFieldInfo adapterFieldInfo) { MethodSpec.Builder builder = MethodSpec.methodBuilder("write") .addParameter(JsonWriter.class, "writer") .addParameter(typeName, "object") .returns(void.class) .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .addException(IOException.class); builder.addCode("\twriter.beginObject();\n" + "\tif (object == null) {\n" + "\t\twriter.endObject();\n" + "\t\treturn;\n" + "\t}\n"); for (Map.Entry<Element, TypeMirror> element : memberVariables.entrySet()) { String name = getJsonName(element.getKey()); String variableName = element.getKey().getSimpleName().toString(); String variableType = element.getValue().toString(); boolean isPrimitive = isSupportedPrimitive(variableType); String prefix = isPrimitive ? "\t" : "\t\t"; if (!isPrimitive) { builder.addCode("\tif (object." + variableName + " != null) {\n"); } builder.addCode(getWriteCode(element.getKey(), prefix, element.getValue(), name, "object." + variableName, adapterFieldInfo)); if (!isPrimitive) { builder.addCode("\t}\n"); } /** * If the element is annotated with NonNull annotation, throw {@link IOException} if it is null. */ for (AnnotationMirror annotationMirror : element.getKey().getAnnotationMirrors()) { switch (annotationMirror.toString()) { case "@android.support.annotation.NonNull": builder.addCode("\n\telse if (object." + variableName + " == null) {"); builder.addCode("\n\t\tthrow new java.io.IOException(\"" + variableName + " cannot be null\");"); builder.addCode("\n\t}\n\n"); break; } } } builder.addCode("\twriter.endObject();\n"); return builder.build(); } /** * Generates the TypeSpec for the TypeAdapter * that this class generates. * * @return a valid TypeSpec that can be written * to a file or added to another class. */ @NotNull public TypeSpec getTypeAdapterSpec(@NotNull TypeTokenConstantsGenerator typeTokenConstantsGenerator, @NotNull StagGenerator stagGenerator) { mGsonVariableUsed = false; mStagFactoryUsed = false; TypeMirror typeMirror = mInfo.getType(); TypeName typeVariableName = TypeVariableName.get(typeMirror); List<? extends TypeMirror> typeArguments = mInfo.getTypeArguments(); TypeVariableName stagFactoryTypeName = stagGenerator.getGeneratedClassName(); MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addParameter(Gson.class, "gson") .addParameter(stagFactoryTypeName, "stagFactory"); String className = FileGenUtils.unescapeEscapedString(mInfo.getTypeAdapterClassName()); TypeSpec.Builder adapterBuilder = TypeSpec.classBuilder(className) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .superclass(ParameterizedTypeName.get(ClassName.get(TypeAdapter.class), typeVariableName)); Map<TypeVariable, String> typeVarsMap = new HashMap<>(); int idx = 0; if (null != typeArguments) { for (TypeMirror argType : typeArguments) { if (argType.getKind() == TypeKind.TYPEVAR) { TypeVariable typeVariable = (TypeVariable) argType; String simpleName = typeVariable.asElement().getSimpleName().toString(); adapterBuilder.addTypeVariable(TypeVariableName.get(simpleName, TypeVariableName.get(typeVariable.getUpperBound()))); String paramName = "type" + "[" + String.valueOf(idx) + "]"; typeVarsMap.put(typeVariable, paramName); idx++; } } if (idx > 0) { constructorBuilder.addParameter(Type[].class, "type"); constructorBuilder.varargs(true); } } AnnotatedClass annotatedClass = SupportedTypesModel.getInstance().getSupportedType(typeMirror); Map<Element, TypeMirror> memberVariables = annotatedClass.getMemberVariables(); AdapterFieldInfo adapterFieldInfo = addAdapterFields(adapterBuilder, constructorBuilder, memberVariables, typeTokenConstantsGenerator, typeVarsMap, stagGenerator); MethodSpec writeMethod = getWriteMethodSpec(typeVariableName, memberVariables, adapterFieldInfo); MethodSpec readMethod = getReadMethodSpec(typeVariableName, memberVariables, adapterFieldInfo); if(mGsonVariableUsed) { adapterBuilder.addField(Gson.class, "mGson", Modifier.FINAL, Modifier.PRIVATE); constructorBuilder.addStatement("this.mGson = gson"); } if(mStagFactoryUsed) { adapterBuilder.addField(stagFactoryTypeName, "mStagFactory", Modifier.FINAL, Modifier.PRIVATE); constructorBuilder.addStatement("this.mStagFactory = stagFactory"); } adapterBuilder.addMethod(constructorBuilder.build()); adapterBuilder.addMethod(writeMethod); adapterBuilder.addMethod(readMethod); return adapterBuilder.build(); } @NotNull private String getArrayListType(@NotNull TypeMirror innerArrayType) { String innerArrayTypeString = innerArrayType.toString(); if(innerArrayTypeString.equals(long.class.getName())) { return Long.class.getName(); } if(innerArrayTypeString.equals(double.class.getName())) { return Double.class.getName(); } if(innerArrayTypeString.equals(Boolean.class.getName())) { return Boolean.class.getName(); } if(innerArrayTypeString.equals(float.class.getName())) { return Float.class.getName(); } if(innerArrayTypeString.equals(int.class.getName())) { return Integer.class.getName(); } else { return innerArrayType.toString(); } } @NotNull private String getReadCode(@NotNull String prefix, @NotNull String variableName, @NotNull Element key, @NotNull TypeMirror type, @NotNull AdapterFieldInfo adapterFieldInfo) { if (isArray(type)) { TypeMirror innerType = getArrayInnerType(type); boolean isNativeArray = isNativeArray(type); String innerRead = getReadType(type, innerType, adapterFieldInfo); String arrayListVariableName = isNativeArray ? "tmpArray" : "object." + variableName; String stagGetterName = adapterFieldInfo.getKnownAdapterStagFunctionCalls(innerType); String result = prefix + "reader.beginArray();\n" + prefix + (isNativeArray ? "java.util.ArrayList<" + getArrayListType(innerType) + "> " : "") + arrayListVariableName + " = new java.util.ArrayList<>();\n" + (stagGetterName != null ? prefix + "TypeAdapter<" + innerType + "> adapter = " + stagGetterName + ";\n" : "") + prefix + "while (reader.hasNext()) {\n" + prefix + "\t" + arrayListVariableName + ".add(" + innerRead + ");\n" + prefix + "}\n" + prefix + "reader.endArray();\n"; if(isNativeArray) { result += prefix + "object." + variableName + "= new "+ innerType.toString() + "[" + arrayListVariableName + ".size()];\n"; result += prefix + "for(int idx = 0; idx < " + arrayListVariableName + ".size(); idx++) {\n"; result += prefix + "\tobject." + variableName + "[idx] = " + arrayListVariableName + ".get(idx);\n"; result += prefix + "}\n"; } return result; } else { return prefix + "object." + variableName + " = " + getReadType(type, type, adapterFieldInfo) + ";"; } } @NotNull private String getReadType(@NotNull TypeMirror parentType, @NotNull TypeMirror type, @NotNull AdapterFieldInfo adapterFieldInfo) { String typeString = type.toString(); if (typeString.equals(long.class.getName()) || typeString.equals(Long.class.getName())) { return "reader.nextLong()"; } else if (typeString.equals(double.class.getName()) || typeString.equals(Double.class.getName())) { return "reader.nextDouble()"; } else if (typeString.equals(boolean.class.getName()) || typeString.equals(Boolean.class.getName())) { return "reader.nextBoolean()"; } else if (typeString.equals(String.class.getName())) { return "reader.nextString()"; } else if (typeString.equals(int.class.getName()) || typeString.equals(Integer.class.getName())) { return "reader.nextInt()"; } else if (typeString.equals(float.class.getName()) || typeString.equals(Float.class.getName())) { return "(float) reader.nextDouble()"; } else { return getAdapterRead(parentType, type, adapterFieldInfo); } } @NotNull private String getWriteCode(@NotNull Element key, @NotNull String prefix, @NotNull TypeMirror type, @NotNull String jsonName, @NotNull String variableName, @NotNull AdapterFieldInfo adapterFieldInfo) { if (isArray(type)) { TypeMirror innerType = getArrayInnerType(type); String innerWrite = getWriteType(key, innerType, "item", adapterFieldInfo); return prefix + "writer.name(\"" + jsonName + "\");\n" + prefix + "writer.beginArray();\n" + prefix + "for (" + innerType + " item : " + variableName + ") {\n" + prefix + "\t" + innerWrite + "\n" + prefix + "}\n" + prefix + "writer.endArray();\n"; } else { return prefix + "writer.name(\"" + jsonName + "\");\n" + prefix + getWriteType(key, type, variableName, adapterFieldInfo) + '\n'; } } @NotNull private String getWriteType(@NotNull Element key, @NotNull TypeMirror type, @NotNull String variableName , @NotNull AdapterFieldInfo adapterFieldInfo) { if (isSupportedNative(type.toString())) { return "writer.value(" + variableName + ");"; } else { return getAdapterWrite(key, type, variableName, adapterFieldInfo) + ";"; } } @NotNull private String getAdapterWrite(@NotNull Element key, @NotNull TypeMirror type, @NotNull String variableName, @NotNull AdapterFieldInfo adapterFieldInfo) { String adapterField = adapterFieldInfo.getAdapter(type); return adapterField + ".write(writer, " + variableName + ")"; } @NotNull private String getAdapterRead(@NotNull TypeMirror parentType, @NotNull TypeMirror type, @NotNull AdapterFieldInfo adapterFieldInfo) { String adapterCode; if(adapterFieldInfo.getKnownAdapterStagFunctionCalls(type) != null && isArray(parentType)){ adapterCode = "adapter.read(reader)"; }else{ adapterCode = adapterFieldInfo.getAdapter(type) + ".read(reader)"; } return adapterCode; } @NotNull private MethodSpec getReadMethodSpec(@NotNull TypeName typeName, @NotNull Map<Element, TypeMirror> elements, @NotNull AdapterFieldInfo adapterFieldInfo) { MethodSpec.Builder builder = MethodSpec.methodBuilder("read") .addParameter(JsonReader.class, "reader") .returns(typeName) .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .addException(IOException.class); builder.addCode("\tif (reader.peek() == com.google.gson.stream.JsonToken.NULL) {\n" + "\t\treader.nextNull();\n" + "\t\treturn null;\n" + "\t}\n" + "\tif (reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) {\n" + "\t\treader.skipValue();\n" + "\t\treturn null;\n" + "\t}\n" + "\treader.beginObject();\n" + '\n' + '\t' + typeName + " object = new " + typeName + "();\n" + "\twhile (reader.hasNext()) {\n" + "\t\tString name = reader.nextName();\n" + "\t\tcom.google.gson.stream.JsonToken jsonToken = reader.peek();\n" + "\t\tif (jsonToken == com.google.gson.stream.JsonToken.NULL) {\n" + "\t\t\treader.skipValue();\n" + "\t\t\tcontinue;\n" + "\t\t}\n" + "\t\tswitch (name) {\n"); List<String> nonNullFields = new ArrayList<>(); for (Map.Entry<Element, TypeMirror> element : elements.entrySet()) { String name = getJsonName(element.getKey()); String variableName = element.getKey().getSimpleName().toString(); String jsonTokenType = getReadTokenType(element.getValue()); if (jsonTokenType != null) { builder.addCode("\t\t\tcase \"" + name + "\":\n" + "\t\t\t\tif (jsonToken == " + jsonTokenType + ") {\n" + getReadCode("\t\t\t\t\t", variableName, element.getKey(), element.getValue(), adapterFieldInfo) + "\n\t\t\t\t} else {" + "\n\t\t\t\t\treader.skipValue();" + "\n\t\t\t\t}"); } else { builder.addCode("\t\t\tcase \"" + name + "\":\n" + getReadCode("\t\t\t\t\t", variableName, element.getKey(), element.getValue(), adapterFieldInfo)); } builder.addCode("\n\t\t\t\tbreak;\n"); for (AnnotationMirror annotationMirror : element.getKey().getAnnotationMirrors()) { switch (annotationMirror.toString()) { case "@android.support.annotation.NonNull": nonNullFields.add(variableName); break; } } } builder.addCode("\t\t\tdefault:\n" + "\t\t\t\treader.skipValue();\n" + "\t\t\t\tbreak;\n" + "\t\t}\n" + "\t}\n" + '\n' + "\treader.endObject();\n"); for (String nonNullField : nonNullFields) { builder.addCode("\n\tif (object." + nonNullField + " == null) {"); builder.addCode("\n\t\tthrow new java.io.IOException(\"" + nonNullField + " cannot be null\");"); builder.addCode("\n\t}\n\n"); } builder.addCode("\treturn object;\n"); return builder.build(); } }
package com.yahoo.squidb.sql; import android.util.Log; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Matcher; import java.util.regex.Pattern; class CompiledArgumentResolver { private static final Pattern REPLACEABLE_ARRAY_PARAM_PATTERN = Pattern.compile(SqlStatement.REPLACEABLE_ARRAY_PARAMETER_REGEX); private final String compiledSql; private final List<Object> argsOrReferences; private final boolean hasCollectionArgs; private boolean hasImmutableArgs = false; private List<Collection<?>> collectionArgs = new ArrayList<Collection<?>>(); private static final int CACHE_SIZE = 5; private SimpleLruCache<String, String> compiledSqlCache; private SimpleLruCache<String, Object[]> argArrayCache; private Object[] compiledArgs = null; public CompiledArgumentResolver(String compiledSql, List<Object> argsOrReferences) { this.compiledSql = compiledSql; this.argsOrReferences = argsOrReferences; this.hasCollectionArgs = compiledSql.contains(SqlStatement.REPLACEABLE_ARRAY_PARAMETER); if (hasCollectionArgs) { findCollectionArgs(); compiledSqlCache = new SimpleLruCache<String, String>(CACHE_SIZE); argArrayCache = new SimpleLruCache<String, Object[]>(CACHE_SIZE); } } private void findCollectionArgs() { for (Object arg : argsOrReferences) { if (arg instanceof Collection<?>) { collectionArgs.add((Collection<?>) arg); } } } public CompiledStatement resolveToCompiledStatement() { String cacheKey = hasCollectionArgs ? getCacheKey() : null; int totalArgSize = calculateArgsSizeWithCollectionArgs(); boolean largeArgMode = totalArgSize > SqlStatement.MAX_VARIABLE_NUMBER; return new CompiledStatement(resolveSqlString(cacheKey, largeArgMode), resolveSqlArguments(cacheKey, totalArgSize, largeArgMode)); } private String getCacheKey() { StringBuilder cacheKey = new StringBuilder(); for (Collection<?> collection : collectionArgs) { cacheKey.append(collection.size()).append(":"); } return cacheKey.toString(); } private String resolveSqlString(String cacheKey, boolean largeArgMode) { if (hasCollectionArgs) { if (!largeArgMode) { String cachedResult = compiledSqlCache.get(cacheKey); if (cachedResult != null) { return cachedResult; } } StringBuilder result = new StringBuilder(compiledSql.length()); Matcher m = REPLACEABLE_ARRAY_PARAM_PATTERN.matcher(compiledSql); int index = 0; int lastStringIndex = 0; while (m.find()) { result.append(compiledSql.substring(lastStringIndex, m.start())); Collection<?> values = collectionArgs.get(index); if (largeArgMode) { SqlUtils.addInlineCollectionToSqlString(result, values); } else { appendCollectionVariableStringForSize(result, values.size()); } lastStringIndex = m.end(); index++; } result.append(compiledSql.substring(lastStringIndex, compiledSql.length())); String resultSql = result.toString(); if (!largeArgMode) { compiledSqlCache.put(cacheKey, resultSql); } else { Log.w("squidb", "The SQL statement \"" + resultSql.substring(0, Math.min(200, resultSql.length())) + " ...\" had too many arguments to bind, so arguments were inlined into the SQL instead." + " Consider revising your statement to have fewer arguments."); } return resultSql; } else { return compiledSql; } } private void appendCollectionVariableStringForSize(StringBuilder builder, int size) { for (int i = 0; i < size; i++) { if (i > 0) { builder.append(", "); } builder.append(SqlStatement.REPLACEABLE_PARAMETER); } } private Object[] resolveSqlArguments(String cacheKey, int totalArgSize, boolean largeArgMode) { if (!hasImmutableArgs) { if (hasCollectionArgs) { Object[] cachedResult = argArrayCache.get(cacheKey); if (cachedResult == null) { int size = largeArgMode ? calculateArgsSizeWithoutCollectionArgs() : totalArgSize; if (compiledArgs == null || compiledArgs.length != size) { cachedResult = new Object[size]; } else { cachedResult = compiledArgs; } argArrayCache.put(cacheKey, cachedResult); } compiledArgs = cachedResult; } else { if (compiledArgs == null) { compiledArgs = new Object[argsOrReferences.size()]; } } populateCompiledArgs(largeArgMode); } return compiledArgs; } private int calculateArgsSizeWithCollectionArgs() { int startSize = argsOrReferences.size(); for (Collection<?> collection : collectionArgs) { startSize += (collection.size() - 1); } return startSize; } private int calculateArgsSizeWithoutCollectionArgs() { return argsOrReferences.size() - collectionArgs.size(); } private void populateCompiledArgs(boolean largeArgMode) { boolean foundReferenceArgument = false; int i = 0; for (Object arg : argsOrReferences) { if (arg instanceof AtomicReference<?>) { foundReferenceArgument = true; compiledArgs[i] = ((AtomicReference<?>) arg).get(); i++; } else if (arg instanceof Collection<?>) { foundReferenceArgument = true; if (!largeArgMode) { Collection<?> values = (Collection<?>) arg; for (Object obj : values) { compiledArgs[i] = obj; i++; } } } else { if (arg instanceof AtomicBoolean) { // Not a subclass of number so needs special handling foundReferenceArgument = true; compiledArgs[i] = ((AtomicBoolean) arg).get() ? 1 : 0; } else { compiledArgs[i] = arg; } i++; } } hasImmutableArgs = !foundReferenceArgument; } @SuppressWarnings("serial") static class SimpleLruCache<K, V> extends LinkedHashMap<K, V> { private final int maxCapacity; public SimpleLruCache(int maxCapacity) { super(0, 0.75f, true); this.maxCapacity = maxCapacity; } @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > maxCapacity; } } }
package visitors; import javax.annotation.processing.ProcessingEnvironment; import annotations.Morph; import checkers.types.AnnotatedTypeFactory; import com.sun.source.util.TreePath; import com.sun.tools.javac.code.Scope; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.comp.Attr; import com.sun.tools.javac.comp.Enter; import com.sun.tools.javac.comp.MemberEnter; import com.sun.tools.javac.comp.Resolve; import com.sun.tools.javac.processing.JavacProcessingEnvironment; import com.sun.tools.javac.tree.JCTree.*; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.TreeInfo; import com.sun.tools.javac.tree.TreeMaker; import com.sun.tools.javac.tree.TreeTranslator; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.Name; import com.sun.tools.javac.util.Names; public class ExpansionTranslator extends TreeTranslator { protected static final String SYN_PREFIX = "__"; protected Context context; private Symtab syms; protected TreeMaker make; protected Names names; protected Enter enter; private Resolve rs; protected MemberEnter memberEnter; protected TreePath path; protected Attr attr; protected AnnotatedTypeFactory atypeFactory; public ExpansionTranslator( ProcessingEnvironment processingEnv, TreePath path) { context = ((JavacProcessingEnvironment) processingEnv).getContext(); syms = Symtab.instance(context); make = TreeMaker.instance(context); names = Names.instance(context); enter = Enter.instance(context); rs = Resolve.instance(context); memberEnter = MemberEnter.instance(context); attr = Attr.instance(context); } @Override public void visitVarDef(JCVariableDecl tree) { super.visitVarDef(tree); if (tree.getType().type.tsym.getAnnotation(Morph.class) != null) { if (tree.init.getTag() == Tag.NEWCLASS) { List<JCExpression> oldInitializerList = ((JCNewClass) tree.init).args; Name dummyName = names.fromString("__Logged$Stack"); Type clazz = tree.sym.enclClass().members().lookup(dummyName).sym.type; JCNewClass newClassExpression = make.NewClass(null, null, make.QualIdent(clazz.tsym), oldInitializerList, null); JCVariableDecl newVarDef = make.VarDef(tree.mods, tree.name, make.QualIdent(clazz.tsym), newClassExpression); System.out.println("# old var decl: " + tree); System.out.println("# new var decl: " + newVarDef); result = newVarDef; } } } public JCExpression makeDotExpression(String chain) { String[] symbols = chain.split("\\."); JCExpression node = make.Ident(names.fromString(symbols[0])); for (int i = 1; i < symbols.length; i++) { com.sun.tools.javac.util.Name nextName = names.fromString(symbols[i]); node = make.Select(node, nextName); } return node; } }
package cgeo.geocaching.apps.cache.navi; import cgeo.geocaching.Geocache; import cgeo.geocaching.R; import cgeo.geocaching.Waypoint; import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.utils.Log; import android.app.Activity; import android.content.Intent; import android.net.Uri; class GoogleMapsApp extends AbstractPointNavigationApp { GoogleMapsApp() { super(getString(R.string.cache_menu_map_ext), R.id.cache_app_google_maps, null); } @Override public boolean isInstalled() { return true; } @Override public void navigate(Activity activity, Geopoint point) { navigate(activity, point, activity.getString(R.string.waypoint)); } private static void navigate(Activity activity, Geopoint point, String label) { try { final String geoLocation = "geo:" + point.getLatitude() + "," + point.getLongitude(); final String query = point.getLatitude() + "," + point.getLongitude() + "(" + label + ")"; final String uriString = geoLocation + "?q=" + Uri.encode(query); activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(uriString))); return; } catch (RuntimeException e) { // nothing } Log.i("GoogleMapsApp.navigate: No maps application available."); ActivityMixin.showToast(activity, getString(R.string.err_application_no)); } @Override public void navigate(Activity activity, Geocache cache) { navigate(activity, cache.getCoords(), cache.getName()); } @Override public void navigate(Activity activity, Waypoint waypoint) { navigate(activity, waypoint.getCoords(), waypoint.getName()); } }
package za.redbridge.experiment; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import org.encog.Encog; import org.encog.ml.ea.train.EvolutionaryAlgorithm; import za.redbridge.experiment.MMNEAT.MMNEATPopulation; import za.redbridge.experiment.MMNEAT.MMNEATUtil; import za.redbridge.simulator.config.SimConfig; public class Main { public static void main(String[] args) { Args options = new Args(); new JCommander(options, args); SimConfig simConfig; if (options.configFile != null && !options.configFile.isEmpty()) { simConfig = new SimConfig(options.configFile); } else { simConfig = new SimConfig(); } MMNEATPopulation population = new MMNEATPopulation(options.numSensors, 2, options.populationSize); population.reset(); ScoreCalculator calculateScore = new ScoreCalculator(simConfig); EvolutionaryAlgorithm train = MMNEATUtil.constructNEATTrainer(population, calculateScore); for (int i = 0; i < options.numIterations; i++) { train.iteration(); System.out.println("Epoch #" + train.getIteration() + " Score: " + calculateScore.getLastScore()); } System.out.println("Training complete"); Encog.getInstance().shutdown(); } private static class Args { @Parameter(names = "-c", description = "Simulation config file to load") private String configFile = null; @Parameter(names = "-i", description = "Number of simulation iterations to train for") private int numIterations = 500; @Parameter(names = "-s", description = "Number of sensors") private int numSensors = 4; @Parameter(names = "--ui", description = "Display GUI") private boolean ui = false; @Parameter(names = "-p", description = "Initial population size") private int populationSize = 100; } }
package info.guardianproject.otr; import info.guardianproject.otr.OtrDataHandler.Transfer; import info.guardianproject.otr.app.im.R; import info.guardianproject.otr.app.im.engine.ChatSession; import info.guardianproject.otr.app.im.engine.ImErrorInfo; import info.guardianproject.otr.app.im.engine.Message; import info.guardianproject.otr.app.im.engine.MessageListener; import info.guardianproject.util.Debug; import java.util.ArrayList; import java.util.List; import net.java.otr4j.OtrException; import net.java.otr4j.session.SessionID; import net.java.otr4j.session.SessionStatus; import net.java.otr4j.session.TLV; public class OtrChatListener implements MessageListener { public static final int TLV_DATA_REQUEST = 0x100; public static final int TLV_DATA_RESPONSE = 0x101; private OtrChatManager mOtrChatManager; private MessageListener mMessageListener; public OtrChatListener(OtrChatManager otrChatManager, MessageListener listener) { this.mOtrChatManager = otrChatManager; this.mMessageListener = listener; } @Override public boolean onIncomingMessage(ChatSession session, Message msg) { // OtrDebugLogger.log("processing incoming message: " + msg.getID()); String body = msg.getBody(); String from = msg.getFrom().getAddress(); String to = msg.getTo().getAddress(); body = Debug.injectErrors(body); SessionID sessionID = mOtrChatManager.getSessionId(to, from); SessionStatus otrStatus = mOtrChatManager.getSessionStatus(sessionID); List<TLV> tlvs = new ArrayList<TLV>(); try { // No OTR for groups (yet) if (!session.getParticipant().isGroup()) { body = mOtrChatManager.decryptMessage(to, from, body, tlvs); } if (body != null) { msg.setBody(body); mMessageListener.onIncomingMessage(session, msg); } } catch (OtrException e) { // OtrDebugLogger.log("error decrypting message",e); // msg.setBody("[" + "You received an unreadable encrypted message" + "]"); // mMessageListener.onIncomingMessage(session, msg); // mOtrChatManager.injectMessage(sessionID, "[error please stop/start encryption]"); } for (TLV tlv : tlvs) { if (tlv.getType() == TLV_DATA_REQUEST) { mMessageListener.onIncomingDataRequest(session, msg, tlv.getValue()); } else if (tlv.getType() == TLV_DATA_RESPONSE) { mMessageListener.onIncomingDataResponse(session, msg, tlv.getValue()); } } SessionStatus newStatus = mOtrChatManager.getSessionStatus(to, from); if (newStatus != otrStatus) { mMessageListener.onStatusChanged(session, newStatus); } return true; } @Override public void onIncomingDataRequest(ChatSession session, Message msg, byte[] value) { throw new UnsupportedOperationException(); } @Override public void onIncomingDataResponse(ChatSession session, Message msg, byte[] value) { throw new UnsupportedOperationException(); } @Override public void onSendMessageError(ChatSession session, Message msg, ImErrorInfo error) { mMessageListener.onSendMessageError(session, msg, error); OtrDebugLogger.log("onSendMessageError: " + msg.toString()); } @Override public void onIncomingReceipt(ChatSession ses, String id) { mMessageListener.onIncomingReceipt(ses, id); } @Override public void onMessagePostponed(ChatSession ses, String id) { mMessageListener.onMessagePostponed(ses, id); } @Override public void onReceiptsExpected(ChatSession ses) { mMessageListener.onReceiptsExpected(ses); } @Override public void onStatusChanged(ChatSession session, SessionStatus status) { mMessageListener.onStatusChanged(session, status); } @Override public void onIncomingTransferRequest(Transfer transfer) { mMessageListener.onIncomingTransferRequest(transfer); } }
// $Id: TilePath.java,v 1.15 2003/04/27 03:53:41 mdb Exp $ package com.threerings.miso.client; import java.awt.*; import java.util.List; import com.threerings.util.DirectionCodes; import com.threerings.media.sprite.Sprite; import com.threerings.media.util.LineSegmentPath; import com.threerings.media.util.MathUtil; import com.threerings.media.util.PathNode; import com.threerings.media.util.Pathable; import com.threerings.miso.Log; import com.threerings.miso.util.MisoSceneMetrics; import com.threerings.miso.util.MisoUtil; /** * The tile path represents a path of tiles through a scene. The path is * traversed by treating each pair of connected tiles as a line segment. * Only ambulatory sprites can follow a tile path, and their tile * coordinates are updated as the path is traversed. */ public class TilePath extends LineSegmentPath implements DirectionCodes { /** * Constructs a tile path. * * @param metrics the metrics for the scene the with which the path is * associated. * @param sprite the sprite to follow the path. * @param tiles the tiles to be traversed during the path. * @param destx the destination x-position in screen pixel * coordinates. * @param desty the destination y-position in screen pixel * coordinates. */ public TilePath (MisoSceneMetrics metrics, Sprite sprite, List tiles, int destx, int desty) { _metrics = metrics; // set up the path nodes createPath(sprite, tiles, destx, desty); } /** * Returns the estimated number of millis that we'll be traveling * along this path. */ public long getEstimTravelTime () { return (long)(_estimPixels / _vel); } // documentation inherited public boolean tick (Pathable pable, long timestamp) { boolean moved = super.tick(pable, timestamp); if (moved) { Sprite mcs = (Sprite)pable; int sx = mcs.getX(), sy = mcs.getY(); Point pos = new Point(); // check whether we've arrived at the destination tile if (!_arrived) { // get the sprite's latest tile coordinates MisoUtil.screenToTile(_metrics, sx, sy, pos); // if the sprite has reached the destination tile, // update the sprite's tile location and remember // we've arrived int dtx = _dest.getTileX(), dty = _dest.getTileY(); if (pos.x == dtx && pos.y == dty) { // Log.info("Sprite arrived [dtx=" + dtx + // ", dty=" + dty + "]."); _arrived = true; } } // Log.info("Sprite moved [s=" + mcs + "]."); } return moved; } // documentation inherited protected PathNode getNextNode () { // upgrade the path node to a tile path node _dest = (TilePathNode)super.getNextNode(); // note that we've not yet arrived at the destination tile _arrived = false; return _dest; } /** * Populate the path with the tile path nodes that lead the sprite * from its starting position to the given destination coordinates * following the given list of tile coordinates. */ protected void createPath (Sprite sprite, List tiles, int destx, int desty) { // constrain destination pixels to fine coordinates Point fpos = new Point(); MisoUtil.screenToFull(_metrics, destx, desty, fpos); // add the starting path node Point ipos = new Point(); int sx = sprite.getX(), sy = sprite.getY(); MisoUtil.screenToTile(_metrics, sx, sy, ipos); addNode(ipos.x, ipos.y, sx, sy, NORTH); // TODO: make more visually appealing path segments from start // to second tile, and penultimate to ultimate tile. // add all remaining path nodes excepting the last one Point prev = new Point(ipos.x, ipos.y); Point spos = new Point(); int size = tiles.size(); for (int ii = 1; ii < size - 1; ii++) { Point next = (Point)tiles.get(ii); // determine the direction from previous to next node int dir = MisoUtil.getIsoDirection(prev.x, prev.y, next.x, next.y); // determine the node's position in screen pixel coordinates MisoUtil.tileToScreen(_metrics, next.x, next.y, spos); // add the node to the path, wandering through the middle // of each tile in the path for now int dsx = spos.x + _metrics.tilehwid; int dsy = spos.y + _metrics.tilehhei; addNode(next.x, next.y, dsx, dsy, dir); prev = next; } // get the final destination point's screen coordinates // constrained to the closest full coordinate MisoUtil.fullToScreen(_metrics, fpos.x, fpos.y, spos); // get the tile coordinates for the final destination tile int tdestx = MisoUtil.fullToTile(fpos.x); int tdesty = MisoUtil.fullToTile(fpos.y); // get the facing direction for the final node int dir; if (prev.x == ipos.x && prev.y == ipos.y) { // if destination is within starting tile, direction is // determined by studying the fine coordinates dir = MisoUtil.getDirection(_metrics, sx, sy, spos.x, spos.y); } else { // else it's based on the last tile we traversed dir = MisoUtil.getIsoDirection(prev.x, prev.y, tdestx, tdesty); } // add the final destination path node addNode(tdestx, tdesty, spos.x, spos.y, dir); } /** * Add a node to the path with the specified destination * coordinates and facing direction. * * @param tx the tile x-position. * @param ty the tile y-position. * @param x the x-position. * @param y the y-position. * @param dir the facing direction. */ protected void addNode (int tx, int ty, int x, int y, int dir) { if (_last == null) { _last = new Point(); } else { _estimPixels += MathUtil.distance(_last.x, _last.y, x, y); } _last.setLocation(x, y); _nodes.add(new TilePathNode(tx, ty, x, y, dir)); } /** Whether the sprite has arrived at the current destination tile. */ protected boolean _arrived; /** The destination tile path node. */ protected TilePathNode _dest; /** Used to compute estimated travel time. */ protected Point _last; /** Estimated pixels traveled. */ protected int _estimPixels; /** The scene metrics. */ protected MisoSceneMetrics _metrics; }
package org.jaxen.util; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.NoSuchElementException; import java.util.Set; import org.jaxen.Navigator; /** * @deprecated this iterator is no longer used to implement any of the Jaxen axes. If you have implemented * a navigator-specific axis based on this class, take a look at the DescendantAxisIterator for ideas * on how to remove that dependency. */ public abstract class StackedIterator implements Iterator { private LinkedList iteratorStack; private Navigator navigator; private Set created; public StackedIterator(Object contextNode, Navigator navigator) { this.iteratorStack = new LinkedList(); this.created = new HashSet(); init( contextNode, navigator ); } protected StackedIterator() { this.iteratorStack = new LinkedList(); this.created = new HashSet(); } protected void init(Object contextNode, Navigator navigator) { this.navigator = navigator; //pushIterator( internalCreateIterator( contextNode ) ); } protected Iterator internalCreateIterator(Object contextNode) { if ( this.created.contains( contextNode ) ) { return null; } this.created.add( contextNode ); return createIterator( contextNode ); } public boolean hasNext() { Iterator curIter = currentIterator(); if ( curIter == null ) { return false; } return curIter.hasNext(); } public Object next() throws NoSuchElementException { if ( ! hasNext() ) { throw new NoSuchElementException(); } Iterator curIter = currentIterator(); Object object = curIter.next(); pushIterator( internalCreateIterator( object ) ); return object; } public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } abstract protected Iterator createIterator(Object contextNode); protected void pushIterator(Iterator iter) { if ( iter != null ) { this.iteratorStack.addFirst(iter); //addLast( iter ); } } private Iterator currentIterator() { while ( iteratorStack.size() > 0 ) { Iterator curIter = (Iterator) iteratorStack.getFirst(); if ( curIter.hasNext() ) { return curIter; } iteratorStack.removeFirst(); } return null; } protected Navigator getNavigator() { return this.navigator; } }
package org.objectweb.proactive.core.component; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Vector; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import javax.naming.NamingException; import org.apache.log4j.Logger; import org.objectweb.fractal.api.Component; import org.objectweb.fractal.api.NoSuchInterfaceException; import org.objectweb.fractal.api.Type; import org.objectweb.fractal.api.factory.Factory; import org.objectweb.fractal.api.factory.GenericFactory; import org.objectweb.fractal.api.factory.InstantiationException; import org.objectweb.fractal.api.type.ComponentType; import org.objectweb.fractal.api.type.InterfaceType; import org.objectweb.fractal.api.type.TypeFactory; import org.objectweb.proactive.ActiveObjectCreationException; import org.objectweb.proactive.ProActive; import org.objectweb.proactive.core.ProActiveRuntimeException; import org.objectweb.proactive.core.body.ProActiveMetaObjectFactory; import org.objectweb.proactive.core.body.UniversalBody; import org.objectweb.proactive.core.body.http.HttpBodyAdapter; import org.objectweb.proactive.core.body.ibis.IbisBodyAdapter; import org.objectweb.proactive.core.body.rmi.RmiBodyAdapter; import org.objectweb.proactive.core.body.rmi.SshRmiBodyAdapter; import org.objectweb.proactive.core.component.body.ComponentBody; import org.objectweb.proactive.core.component.controller.ComponentParametersController; import org.objectweb.proactive.core.component.controller.GathercastController; import org.objectweb.proactive.core.component.controller.MembraneController; import org.objectweb.proactive.core.component.controller.MigrationController; import org.objectweb.proactive.core.component.controller.MulticastController; import org.objectweb.proactive.core.component.controller.ProActiveBindingController; import org.objectweb.proactive.core.component.controller.ProActiveContentController; import org.objectweb.proactive.core.component.exceptions.InstantiationExceptionListException; import org.objectweb.proactive.core.component.factory.ProActiveGenericFactory; import org.objectweb.proactive.core.component.identity.ProActiveComponent; import org.objectweb.proactive.core.component.representative.ProActiveComponentRepresentative; import org.objectweb.proactive.core.component.representative.ProActiveComponentRepresentativeFactory; import org.objectweb.proactive.core.component.type.Composite; import org.objectweb.proactive.core.component.type.ProActiveInterfaceType; import org.objectweb.proactive.core.component.type.ProActiveTypeFactory; import org.objectweb.proactive.core.component.type.ProActiveTypeFactoryImpl; import org.objectweb.proactive.core.descriptor.data.VirtualNode; import org.objectweb.proactive.core.group.ProActiveComponentGroup; import org.objectweb.proactive.core.group.ProActiveGroup; import org.objectweb.proactive.core.mop.StubObject; import org.objectweb.proactive.core.node.Node; import org.objectweb.proactive.core.node.NodeException; import org.objectweb.proactive.core.util.UrlBuilder; import org.objectweb.proactive.core.util.log.Loggers; import org.objectweb.proactive.core.util.log.ProActiveLogger; /** * This class is used for creating components. It acts as : * <ol> * <li> a bootstrap component</li> * <li> a specialized GenericFactory for instantiating new components on remote nodes (a ProActiveGenericFactory)</li> * <li> a utility class providing static methods to create collective interfaces * and retreive references to ComponentParametersController</li> * </ol> * * @author Matthieu Morel */ public class Fractive implements ProActiveGenericFactory, Component, Factory { private static Fractive instance = null; private TypeFactory typeFactory = (TypeFactory) ProActiveTypeFactoryImpl.instance(); private Type type = null; private static Logger logger = ProActiveLogger.getLogger(Loggers.COMPONENTS); /** * no-arg constructor (used by Fractal to get a bootstrap component) * */ public Fractive() { } /** * Returns singleton * * @return Fractive a singleton */ private static Fractive instance() { if (instance == null) { instance = new Fractive(); } return instance; } /** * Returns the {@link org.objectweb.proactive.core.component.controller.ComponentParametersController ComponentParametersController} * interface of the given component. * * @param component a component. * @return the {@link org.objectweb.proactive.core.component.controller.ComponentParametersController ComponentParametersController} * interface of the given component. * @throws NoSuchInterfaceException if there is no such interface. */ public static ComponentParametersController getComponentParametersController( final Component component) throws NoSuchInterfaceException { return (ComponentParametersController) component.getFcInterface(Constants.COMPONENT_PARAMETERS_CONTROLLER); } public static ProActiveBindingController getBindingController( final ProActiveComponent component) throws NoSuchInterfaceException { return (ProActiveBindingController) component.getFcInterface(Constants.BINDING_CONTROLLER); } /** * Returns the {@link org.objectweb.proactive.core.component.controller.MulticastController MulticastController} * interface of the given component. * * @param component a component. * @return the {@link org.objectweb.proactive.core.component.controller.MulticastController MulticastController} * interface of the given component. * @throws NoSuchInterfaceException if there is no such interface. */ public static MulticastController getMulticastController( final Component component) throws NoSuchInterfaceException { return (MulticastController) component.getFcInterface(Constants.MULTICAST_CONTROLLER); } /** * Returns the {@link org.objectweb.proactive.core.component.controller.ProActiveContentController ProActiveContentController} * interface of the given component. * * @param component a component. * @return the {@link org.objectweb.proactive.core.component.controller.ProActiveContentController ProActiveContentController} * interface of the given component. * @throws NoSuchInterfaceException if there is no such interface. */ public static ProActiveContentController getProActiveContentController( final Component component) throws NoSuchInterfaceException { return (ProActiveContentController) component.getFcInterface(Constants.CONTENT_CONTROLLER); } /** * Returns the {@link org.objectweb.proactive.core.component.controller.MembraneController MembraneController} * interface of the given component. * @param component omponent a component. * @return the {@link org.objectweb.proactive.core.component.controller.MembraneController MembraneController} * @throws NoSuchInterfaceException if there is no such interface. */ public static MembraneController getMembraneController( final Component component) throws NoSuchInterfaceException { return (MembraneController) component.getFcInterface(Constants.MEMBRANE_CONTROLLER); } /** * Returns the {@link org.objectweb.proactive.core.component.controller.GathercastController GatherController} * interface of the given component. * * @param component a component. * @return the {@link org.objectweb.proactive.core.component.controller.GathercastController GatherController} * interface of the given component. * @throws NoSuchInterfaceException if there is no such interface. */ public static GathercastController getGathercastController( final Component component) throws NoSuchInterfaceException { return (GathercastController) component.getFcInterface(Constants.GATHERCAST_CONTROLLER); } /** * Returns the {@link org.objectweb.proactive.core.component.controller.MigrationController MigrationController} * interface of the given component. * * @param component a component. * @return the {@link org.objectweb.proactive.core.component.controller.MigrationController MigrationController} * interface of the given component. * @throws NoSuchInterfaceException if there is no such interface. */ public static MigrationController getMigrationController( final Component component) throws NoSuchInterfaceException { return (MigrationController) component.getFcInterface(Constants.MIGRATION_CONTROLLER); } /** * Returns a generated interface reference, whose impl field is a group It * is able to handle multiple bindings, and automatically adds it to a given * * @param itfName the name of the interface * @param itfSignature the signature of the interface * @param owner the component to which this interface belongs * @return ProActiveInterface the resulting collective client interface * @throws ProActiveRuntimeException in case of a problem while creating the collective interface */ public static ProActiveInterface createCollectiveClientInterface( String itfName, String itfSignature, Component owner) throws ProActiveRuntimeException { try { ProActiveInterfaceType itf_type = (ProActiveInterfaceType) ProActiveTypeFactoryImpl.instance() .createFcItfType(itfName, itfSignature, TypeFactory.CLIENT, TypeFactory.MANDATORY, TypeFactory.COLLECTION); ProActiveInterface itf_ref_group = ProActiveComponentGroup.newComponentInterfaceGroup(itf_type, owner); return itf_ref_group; } catch (Exception e) { throw new ProActiveRuntimeException("Impossible to create a collective client interface ", e); } } /** * Returns a generated interface reference, whose impl field is a group It * is able to handle multiple bindings, and automatically adds it to a given * * @param itfName the name of the interface * @param itfSignature the signature of the interface * @param owner the component to which this interface belongs * @return ProActiveInterface the resulting collective client interface * @throws ProActiveRuntimeException in case of a problem while creating the collective interface */ public static ProActiveInterface createMulticastClientInterface( String itfName, String itfSignature, Component owner) throws ProActiveRuntimeException { try { ProActiveInterfaceType itf_type = (ProActiveInterfaceType) ProActiveTypeFactoryImpl.instance() .createFcItfType(itfName, itfSignature, TypeFactory.CLIENT, TypeFactory.MANDATORY, ProActiveTypeFactory.MULTICAST_CARDINALITY); ProActiveInterface itf_ref_group = ProActiveComponentGroup.newComponentInterfaceGroup(itf_type, owner); return itf_ref_group; } catch (Exception e) { throw new ProActiveRuntimeException("Impossible to create a collective client interface ", e); } } /** * Returns a generated interface reference, whose impl field is a group It * is able to handle multiple bindings * * @param itfName the name of the interface * @param itfSignature the signature of the interface * @return ProActiveInterface the resulting collective client interface * @throws ProActiveRuntimeException in case of a problem while creating the collective interface */ // public static ProActiveInterface createCollectiveClientInterface( // String itfName, String itfSignature) throws ProActiveRuntimeException { // return Fractive.createCollectiveClientInterface(itfName, itfSignature, // null); /** * Returns a generated interface reference, whose impl field is a group It * is able to handle multiple bindings * * @param itfName the name of the interface * @param itfSignature the signature of the interface * @return ProActiveInterface the resulting collective client interface * @throws ProActiveRuntimeException in case of a problem while creating the collective interface */ public static ProActiveInterface createMulticastClientInterface( String itfName, String itfSignature) throws ProActiveRuntimeException { return Fractive.createCollectiveClientInterface(itfName, itfSignature, null); } /* * * @see org.objectweb.proactive.core.component.factory.ProActiveGenericFactory#newFcInstance(org.objectweb.fractal.api.Type, org.objectweb.proactive.core.component.ControllerDescription, org.objectweb.proactive.core.component.ContentDescription) */ public Component newFcInstance(Type type, ControllerDescription controllerDesc, ContentDescription contentDesc) throws InstantiationException { return newFcInstance(type, controllerDesc, contentDesc, (Node) null); } /** * @see org.objectweb.proactive.core.component.factory.ProActiveGenericFactory#newNFcInstance(org.objectweb.fractal.api.Type, org.objectweb.proactive.core.component.ControllerDescription, org.objectweb.proactive.core.component.ContentDescription) */ public Component newNFcInstance(Type type, ControllerDescription controllerDesc, ContentDescription contentDesc) throws InstantiationException { return newNFcInstance(type, controllerDesc, contentDesc, (Node) null); } /* * * @see org.objectweb.fractal.api.factory.GenericFactory#newFcInstance(org.objectweb.fractal.api.Type, java.lang.Object, java.lang.Object) */ public Component newFcInstance(Type type, Object controllerDesc, Object contentDesc) throws InstantiationException { try { return newFcInstance(type, (ControllerDescription) controllerDesc, (ContentDescription) contentDesc); } catch (ClassCastException e) { if ((type == null) && (controllerDesc == null) && (contentDesc instanceof Map)) { // for compatibility with the new // org.objectweb.fractal.util.Fractal class return this; } if ((controllerDesc instanceof ControllerDescription) && ((contentDesc instanceof String) || (contentDesc == null))) { // for the ADL, when only type and ControllerDescription are // given return newFcInstance(type, controllerDesc, (contentDesc == null) ? null : new ContentDescription( (String) contentDesc)); } // code compatibility with Julia if ("composite".equals(controllerDesc) && (contentDesc == null)) { return newFcInstance(type, new ControllerDescription(null, Constants.COMPOSITE), null); } if ("primitive".equals(controllerDesc) && (contentDesc instanceof String)) { return newFcInstance(type, new ControllerDescription(null, Constants.PRIMITIVE), new ContentDescription((String) contentDesc)); } // any other case throw new InstantiationException( "With this implementation, parameters must be of respective types : " + Type.class.getName() + ',' + ControllerDescription.class.getName() + ',' + ContentDescription.class.getName()); } } /* * * @see org.objectweb.fractal.api.factory.GenericFactory#newNFcInstance(org.objectweb.fractal.api.Type, java.lang.Object, java.lang.Object) */ public Component newNFcInstance(Type type, Object controllerDesc, Object contentDesc) throws InstantiationException { try { return newNFcInstance(type, (ControllerDescription) controllerDesc, (ContentDescription) contentDesc); } catch (ClassCastException e) { if ((type == null) && (controllerDesc == null) && (contentDesc instanceof Map)) { // for compatibility with the new // org.objectweb.fractal.util.Fractal class return this; } if ((controllerDesc instanceof ControllerDescription) && ((contentDesc instanceof String) || (contentDesc == null))) { // for the ADL, when only type and ControllerDescription are // given return newNFcInstance(type, controllerDesc, (contentDesc == null) ? null : new ContentDescription( (String) contentDesc)); } // code compatibility with Julia if ("composite".equals(controllerDesc) && (contentDesc == null)) { return newNFcInstance(type, new ControllerDescription(null, Constants.COMPOSITE), null); } if ("primitive".equals(controllerDesc) && (contentDesc instanceof String)) { return newNFcInstance(type, new ControllerDescription(null, Constants.PRIMITIVE), new ContentDescription((String) contentDesc)); } // any other case throw new InstantiationException( "With this implementation, parameters must be of respective types : " + Type.class.getName() + ',' + ControllerDescription.class.getName() + ',' + ContentDescription.class.getName()); } } /* * * @see org.objectweb.proactive.core.component.factory.ProActiveGenericFactory#newFcInstance(org.objectweb.fractal.api.Type, org.objectweb.proactive.core.component.ControllerDescription, org.objectweb.proactive.core.component.ContentDescription, org.objectweb.proactive.core.node.Node) */ public Component newFcInstance(Type type, ControllerDescription controllerDesc, ContentDescription contentDesc, Node node) throws InstantiationException { try { ActiveObjectWithComponentParameters container = commonInstanciation(type, controllerDesc, contentDesc, node); return fComponent(type, container); } catch (ActiveObjectCreationException e) { logger.error( "Active object creation error while creating component; throws exception with the following message: " + e.getMessage() + ".", e); throw new InstantiationException(e.getMessage()); } catch (NodeException e) { throw new InstantiationException(e.getMessage()); } } /* * * @see org.objectweb.proactive.core.component.factory.ProActiveGenericFactory#newNFcInstance(org.objectweb.fractal.api.Type, org.objectweb.proactive.core.component.ControllerDescription, org.objectweb.proactive.core.component.ContentDescription, org.objectweb.proactive.core.node.Node) */ public Component newNFcInstance(Type type, ControllerDescription controllerDesc, ContentDescription contentDesc, Node node) throws InstantiationException { try { ActiveObjectWithComponentParameters container = commonInstanciation(type, controllerDesc, contentDesc, node); return nfComponent(type, container); } catch (ActiveObjectCreationException e) { e.printStackTrace(); throw new InstantiationException(e.getMessage()); } catch (NodeException e) { throw new InstantiationException(e.getMessage()); } } /* * * @see org.objectweb.proactive.core.component.factory.ProActiveGenericFactory#newFcInstance(org.objectweb.fractal.api.Type, org.objectweb.proactive.core.component.ControllerDescription, org.objectweb.proactive.core.component.ContentDescription, org.objectweb.proactive.core.descriptor.data.VirtualNode) */ public Component newFcInstance(Type type, ControllerDescription controllerDesc, ContentDescription contentDesc, VirtualNode virtualNode) throws InstantiationException { if (virtualNode == null) { return newFcInstance(type, controllerDesc, contentDesc, (Node) null); } try { virtualNode.activate(); if (virtualNode.getNodes().length == 0) { throw new InstantiationException( "Cannot create component on virtual node as no node is associated with this virtual node"); } return newFcInstance(type, controllerDesc, contentDesc, virtualNode.getNode()); } catch (NodeException e) { throw new InstantiationException( "could not instantiate components due to a deployment problem : " + e.getMessage()); } } /* * * @see org.objectweb.proactive.core.component.factory.ProActiveGenericFactory#newNFcInstance(org.objectweb.fractal.api.Type, org.objectweb.proactive.core.component.ControllerDescription, org.objectweb.proactive.core.component.ContentDescription, org.objectweb.proactive.core.descriptor.data.VirtualNode) */ public Component newNFcInstance(Type type, ControllerDescription controllerDesc, ContentDescription contentDesc, VirtualNode virtualNode) throws InstantiationException { if (virtualNode == null) { return newNFcInstance(type, controllerDesc, contentDesc, (Node) null); } try { virtualNode.activate(); if (virtualNode.getNodes().length == 0) { throw new InstantiationException( "Cannot create component on virtual node as no node is associated with this virtual node"); } return newNFcInstance(type, controllerDesc, contentDesc, virtualNode.getNode()); } catch (NodeException e) { throw new InstantiationException( "could not instantiate components due to a deployment problem : " + e.getMessage()); } } /* * @see org.objectweb.proactive.core.component.factory.ProActiveGenericFactory#newFcInstanceAsList(org.objectweb.fractal.api.Type, * org.objectweb.proactive.core.component.ControllerDescription, * org.objectweb.proactive.core.component.ContentDescription, * org.objectweb.proactive.core.descriptor.data.VirtualNode) */ public List<Component> newFcInstanceAsList(Type type, ControllerDescription controllerDesc, ContentDescription contentDesc, VirtualNode virtualNode) throws InstantiationException { if (virtualNode == null) { return newFcInstanceAsList(type, controllerDesc, contentDesc, (Node[]) null); } try { virtualNode.activate(); return newFcInstanceAsList(type, controllerDesc, contentDesc, virtualNode.getNodes()); } catch (NodeException e) { throw new InstantiationException( "could not instantiate components due to a deployment problem : " + e.getMessage()); } } /* * @see org.objectweb.proactive.core.component.factory.ProActiveGenericFactory#newNFcInstanceAsList(org.objectweb.fractal.api.Type, * org.objectweb.proactive.core.component.ControllerDescription, * org.objectweb.proactive.core.component.ContentDescription, * org.objectweb.proactive.core.descriptor.data.VirtualNode) */ public List<Component> newNFcInstanceAsList(Type type, ControllerDescription controllerDesc, ContentDescription contentDesc, VirtualNode virtualNode) throws InstantiationException { if (virtualNode == null) { return newNFcInstanceAsList(type, controllerDesc, contentDesc, (Node[]) null); } try { virtualNode.activate(); return newNFcInstanceAsList(type, controllerDesc, contentDesc, virtualNode.getNodes()); } catch (NodeException e) { throw new InstantiationException( "could not instantiate components due to a deployment problem : " + e.getMessage()); } } /* * @see org.objectweb.proactive.core.component.factory.ProActiveGenericFactory#newFcInstanceAsList(org.objectweb.fractal.api.Type, * org.objectweb.proactive.core.component.ControllerDescription, * org.objectweb.proactive.core.component.ContentDescription, * org.objectweb.proactive.core.node.Node[]) */ public List<Component> newFcInstanceAsList(Type type, ControllerDescription controllerDesc, ContentDescription contentDesc, Node[] nodes) throws InstantiationException { ContentDescription[] contentDescArray = new ContentDescription[nodes.length]; Arrays.fill(contentDescArray, contentDesc); return newFcInstanceAsList(type, controllerDesc, contentDescArray, nodes); } /* * @see org.objectweb.proactive.core.component.factory.ProActiveGenericFactory#newNFcInstanceAsList(org.objectweb.fractal.api.Type, * org.objectweb.proactive.core.component.ControllerDescription, * org.objectweb.proactive.core.component.ContentDescription, * org.objectweb.proactive.core.node.Node[]) */ public List<Component> newNFcInstanceAsList(Type type, ControllerDescription controllerDesc, ContentDescription contentDesc, Node[] nodes) throws InstantiationException { ContentDescription[] contentDescArray = new ContentDescription[nodes.length]; Arrays.fill(contentDescArray, contentDesc); return newNFcInstanceAsList(type, controllerDesc, contentDescArray, nodes); } /* * * @see org.objectweb.proactive.core.component.factory.ProActiveGenericFactory#newFcInstanceAsList(org.objectweb.fractal.api.Type, org.objectweb.proactive.core.component.ControllerDescription, org.objectweb.proactive.core.component.ContentDescription[], org.objectweb.proactive.core.node.Node[]) */ public List<Component> newFcInstanceAsList(Type type, ControllerDescription controllerDesc, ContentDescription[] contentDesc, Node[] nodes) throws InstantiationException { return groupInstance(type, controllerDesc, contentDesc, nodes, true); } /* * * @see org.objectweb.proactive.core.component.factory.ProActiveGenericFactory#newNFcInstanceAsList(org.objectweb.fractal.api.Type, org.objectweb.proactive.core.component.ControllerDescription, org.objectweb.proactive.core.component.ContentDescription[], org.objectweb.proactive.core.node.Node[]) */ public List<Component> newNFcInstanceAsList(Type type, ControllerDescription controllerDesc, ContentDescription[] contentDesc, Node[] nodes) throws InstantiationException { return groupInstance(type, controllerDesc, contentDesc, nodes, false); } /* * * @see org.objectweb.proactive.core.component.factory.ProActiveGenericFactory#newFcInstanceAsList(org.objectweb.fractal.api.Type, org.objectweb.proactive.core.component.ControllerDescription, org.objectweb.proactive.core.component.ContentDescription[], org.objectweb.proactive.core.descriptor.data.VirtualNode) */ public List<Component> newFcInstanceAsList(Type type, ControllerDescription controllerDesc, ContentDescription[] contentDesc, VirtualNode virtualNode) throws InstantiationException { if (virtualNode == null) { return newFcInstanceAsList(type, controllerDesc, contentDesc, (Node[]) null); } try { virtualNode.activate(); return newFcInstanceAsList(type, controllerDesc, contentDesc, virtualNode.getNodes()); } catch (NodeException e) { throw new InstantiationException( "could not instantiate components due to a deployment problem : " + e.getMessage()); } } /* * * @see org.objectweb.proactive.core.component.factory.ProActiveGenericFactory#newNFcInstanceAsList(org.objectweb.fractal.api.Type, org.objectweb.proactive.core.component.ControllerDescription, org.objectweb.proactive.core.component.ContentDescription[], org.objectweb.proactive.core.descriptor.data.VirtualNode) */ public List<Component> newNFcInstanceAsList(Type type, ControllerDescription controllerDesc, ContentDescription[] contentDesc, VirtualNode virtualNode) throws InstantiationException { if (virtualNode == null) { return newNFcInstanceAsList(type, controllerDesc, contentDesc, (Node[]) null); } try { virtualNode.activate(); return newNFcInstanceAsList(type, controllerDesc, contentDesc, virtualNode.getNodes()); } catch (NodeException e) { throw new InstantiationException( "could not instantiate components due to a deployment problem : " + e.getMessage()); } } /* * * @see org.objectweb.fractal.api.Component#getFcInterface(java.lang.String) */ public Object getFcInterface(String itfName) throws NoSuchInterfaceException { if ("generic-factory".equals(itfName)) { return this; } else if ("type-factory".equals(itfName)) { return typeFactory; } else { throw new NoSuchInterfaceException(itfName); } } /* * * @see org.objectweb.fractal.api.Component#getFcInterfaces() */ public Object[] getFcInterfaces() { return null; } /* * * @see org.objectweb.fractal.api.Component#getFcType() */ public Type getFcType() { if (type == null) { try { return type = typeFactory.createFcType(new InterfaceType[] { typeFactory.createFcItfType("generic-factory", GenericFactory.class.getName(), false, false, false), typeFactory.createFcItfType("type-factory", TypeFactory.class.getName(), false, false, false) }); } catch (InstantiationException e) { ProActiveLogger.getLogger(Loggers.COMPONENTS) .error(e.getMessage()); return null; } } else { return type; } } /* * * @see org.objectweb.fractal.api.factory.Factory#getFcContentDesc() */ public Object getFcContentDesc() { return null; } /* * * @see org.objectweb.fractal.api.factory.Factory#getFcControllerDesc() */ public Object getFcControllerDesc() { return null; } /* * * @see org.objectweb.fractal.api.factory.Factory#getFcInstanceType() */ public Type getFcInstanceType() { return null; } /* * * @see org.objectweb.fractal.api.factory.Factory#newFcInstance() */ public Component newFcInstance() throws InstantiationException { return this; } /** * Helper method for extracting the types of client interfaces from the type * of a component * * @param componentType a component type * @return the types of client interfaces */ public static InterfaceType[] getClientInterfaceTypes( ComponentType componentType) { ArrayList<InterfaceType> client_interfaces = new ArrayList<InterfaceType>(); InterfaceType[] interfaceTypes = componentType.getFcInterfaceTypes(); for (int i = 0; i < interfaceTypes.length; i++) { if (interfaceTypes[i].isFcClientItf()) { client_interfaces.add(interfaceTypes[i]); } } return client_interfaces.toArray(new InterfaceType[client_interfaces.size()]); } /** * Returns a component representative pointing to the component associated * to the component whose active thread is calling this method. It can be * used for a component to pass callback references to itself. * * @return a component representative for the component in which the current * thread is running */ public static Component getComponentRepresentativeOnThis() { ComponentBody componentBody; try { componentBody = (ComponentBody) ProActive.getBodyOnThis(); } catch (ClassCastException e) { logger.error( "Cannot get a component representative from the current object, because this object is not a component"); return null; } ProActiveComponent currentComponent = componentBody.getProActiveComponentImpl(); return currentComponent.getRepresentativeOnThis(); } /** * Registers a reference on a component with an URL * * @param ref * a reference on a component (it should be an instance of * ProActiveComponentRepresentative) * @param url * the registration address * @throws IOException * if the component cannot be registered */ public static void register(Component ref, String url) throws IOException { if (!(ref instanceof ProActiveComponentRepresentative)) { throw new IllegalArgumentException( "This method can only register ProActive components"); } ProActive.register(ref, url); } /** * Returns a reference on a component (a component representative) for the * component associated with the specified name.<br> * * @param url the registered location of the component * @return a reference on the component corresponding to the given name * @throws IOException if there is a communication problem with the registry * @throws NamingException if a reference on a component could not be found at the * specified URL */ public static ProActiveComponentRepresentative lookup(String url) throws IOException, NamingException { UniversalBody b = null; String protocol = UrlBuilder.getProtocol(url); // First step towards Body factory, will be introduced after the release if (protocol.equals( org.objectweb.proactive.core.Constants.RMI_PROTOCOL_IDENTIFIER)) { b = new RmiBodyAdapter().lookup(url); } else if (protocol.equals( org.objectweb.proactive.core.Constants.RMISSH_PROTOCOL_IDENTIFIER)) { b = new SshRmiBodyAdapter().lookup(url); } else if (protocol.equals( org.objectweb.proactive.core.Constants.XMLHTTP_PROTOCOL_IDENTIFIER)) { b = new HttpBodyAdapter().lookup(url); } else if (protocol.equals( org.objectweb.proactive.core.Constants.IBIS_PROTOCOL_IDENTIFIER)) { b = new IbisBodyAdapter().lookup(url); } else { throw new IOException("Protocol " + protocol + " not defined"); } try { StubObject stub = (StubObject) ProActive.createStubObject(ProActiveComponentRepresentative.class.getName(), b); return ProActiveComponentRepresentativeFactory.instance() .createComponentRepresentative(stub.getProxy()); } catch (Throwable t) { t.printStackTrace(); logger.error("Could not perform lookup for component at URL: " + url + ", because construction of component representative failed." + t.toString()); throw new NamingException( "Could not perform lookup for component at URL: " + url + ", because construction of component representative failed."); } } /** * Returns the {@link ProActiveGenericFactory} interface of the given * component. * * @param component the component to get the factory from * @return the {@link ProActiveGenericFactory} interface of the given * component. * @throws NoSuchInterfaceException if there is no such interface. */ public static ProActiveGenericFactory getGenericFactory( final Component component) throws NoSuchInterfaceException { return (ProActiveGenericFactory) component.getFcInterface( "generic-factory"); } /** * Common instanciation method called during creation both functional and non functional components * @param type * @param controllerDesc * @param contentDesc * @param node * @return A container object, containing objects for the generation of the component representative * @throws InstantiationException * @throws ActiveObjectCreationException * @throws NodeException */ private ActiveObjectWithComponentParameters commonInstanciation(Type type, ControllerDescription controllerDesc, ContentDescription contentDesc, Node node) throws InstantiationException, ActiveObjectCreationException, NodeException { if (contentDesc == null) { // either a parallel or a composite component, no // activitiy/factory/node specified if (Constants.COMPOSITE.equals(controllerDesc.getHierarchicalType())) { contentDesc = new ContentDescription(Composite.class.getName()); } else { throw new InstantiationException( "Content can be null only if the hierarchical type of the component is composite"); } } // instantiate the component metaobject factory with parameters of // the component // type must be a component type if (!(type instanceof ComponentType)) { throw new InstantiationException( "Argument type must be an instance of ComponentType"); } ComponentParameters componentParameters = new ComponentParameters((ComponentType) type, controllerDesc); if (contentDesc.getFactory() == null) { // first create a map with the parameters Map<String, Object> factory_params = new Hashtable<String, Object>(1); factory_params.put(ProActiveMetaObjectFactory.COMPONENT_PARAMETERS_KEY, componentParameters); if (controllerDesc.isSynchronous() && (Constants.COMPOSITE.equals( controllerDesc.getHierarchicalType()))) { factory_params.put(ProActiveMetaObjectFactory.SYNCHRONOUS_COMPOSITE_COMPONENT_KEY, Constants.SYNCHRONOUS); } contentDesc.setFactory(new ProActiveMetaObjectFactory( factory_params)); // factory = // ProActiveComponentMetaObjectFactory.newInstance(componentParameters); } // TODO_M : add controllers in the component metaobject factory? Object ao = null; ao = ProActive.newActive(contentDesc.getClassName(), null, contentDesc.getConstructorParameters(), node, contentDesc.getActivity(), contentDesc.getFactory()); return new ActiveObjectWithComponentParameters((StubObject) ao, componentParameters); } /** * Creates a component representative for a functional component (to be used with commonInstanciation method) * @param container The container containing objects for the generation of component representative * @return The created component */ private ProActiveComponentRepresentative fComponent(Type type, ActiveObjectWithComponentParameters container) { ComponentParameters componentParameters = container.getParameters(); StubObject ao = container.getActiveObject(); org.objectweb.proactive.core.mop.Proxy myProxy = (ao).getProxy(); if (myProxy == null) { throw new ProActiveRuntimeException( "Cannot find a Proxy on the stub object: " + ao); } ProActiveComponentRepresentative representative = ProActiveComponentRepresentativeFactory.instance() .createComponentRepresentative((ComponentType) type, componentParameters.getHierarchicalType(), myProxy, componentParameters.getControllerDescription() .getControllersConfigFileLocation()); representative.setStubOnBaseObject((StubObject) ao); return representative; } /** * Creates a component representative for a non functional component (to be used with commonInstanciation method) * @param container The container containing objects for the generation of component representative * @return The created component */ private ProActiveComponentRepresentative nfComponent(Type type, ActiveObjectWithComponentParameters container) { ComponentParameters componentParameters = container.getParameters(); StubObject ao = container.getActiveObject(); org.objectweb.proactive.core.mop.Proxy myProxy = (ao).getProxy(); if (myProxy == null) { throw new ProActiveRuntimeException( "Cannot find a Proxy on the stub object: " + ao); } ProActiveComponentRepresentative representative = ProActiveComponentRepresentativeFactory.instance() .createNFComponentRepresentative((ComponentType) type, componentParameters.getHierarchicalType(), myProxy, componentParameters.getControllerDescription() .getControllersConfigFileLocation()); representative.setStubOnBaseObject((StubObject) ao); return representative; } private List<Component> groupInstance(Type type, ControllerDescription controllerDesc, ContentDescription[] contentDesc, Node[] nodes, boolean isFunctional) throws InstantiationException { try { Component components = null; if (isFunctional) { /*Functional components */ components = ProActiveComponentGroup.newComponentRepresentativeGroup((ComponentType) type, controllerDesc); } else { /*Non functional components*/ components = ProActiveComponentGroup.newNFComponentRepresentativeGroup((ComponentType) type, (ControllerDescription) controllerDesc); } List<Component> componentsList = ProActiveGroup.getGroup(components); if (Constants.PRIMITIVE.equals(controllerDesc.getHierarchicalType())) { if (contentDesc.length > 1) { // cyclic // node // instance // per // node // task = instantiate a component with a different name // on each of the node mapped to the given virtual node String original_component_name = controllerDesc.getName(); // TODO: reuse pool for whole class ? ExecutorService threadPool = Executors.newCachedThreadPool(); List<InstantiationException> exceptions = new Vector<InstantiationException>(); Component c = new MockComponent(); for (int i = 0; i < nodes.length; i++) { componentsList.add(c); } if (isFunctional) { /*Case of functional components*/ for (int i = 0; i < nodes.length; i++) { ComponentBuilderTask task = new ComponentBuilderTask(exceptions, componentsList, i, type, controllerDesc, original_component_name, contentDesc, nodes); threadPool.execute(task); } } else { /*Case of non functional components*/ for (int i = 0; i < nodes.length; i++) { NFComponentBuilderTask task = new NFComponentBuilderTask(exceptions, componentsList, i, type, (ControllerDescription) controllerDesc, original_component_name, contentDesc, nodes); threadPool.execute(task); } } threadPool.shutdown(); try { threadPool.awaitTermination(new Integer( System.getProperty( "components.creation.timeout")), TimeUnit.SECONDS); } catch (InterruptedException e) { logger.info("Interruption when waiting for thread pool termination.", e); } if (!exceptions.isEmpty()) { InstantiationException e = new InstantiationException( "Creation of some of the components failed"); e.initCause(new InstantiationExceptionListException( exceptions)); throw e; } } else { // component is a composite : it will be if (isFunctional) { /*Functional components*/ componentsList.add(newFcInstance(type, controllerDesc, contentDesc[0], nodes[0])); } else { /*Non functional components*/ componentsList.add(newNFcInstance(type, (ControllerDescription) controllerDesc, contentDesc[0], nodes[0])); } } } return componentsList; } catch (ClassNotFoundException e) { throw new InstantiationException(e.getMessage()); } } private static class ComponentBuilderTask implements Runnable { List<InstantiationException> exceptions; List<Component> targetList; int indexInList; Type type; ControllerDescription controllerDesc; ContentDescription[] contentDesc; String originalName; Node[] nodes; public ComponentBuilderTask(List<InstantiationException> exceptions, List<Component> targetList, int indexInList, Type type, ControllerDescription controllerDesc, String originalName, ContentDescription[] contentDesc, Node[] nodes) { this.exceptions = exceptions; this.targetList = targetList; this.indexInList = indexInList; this.type = type; this.controllerDesc = controllerDesc; this.contentDesc = contentDesc; this.originalName = originalName; this.nodes = nodes; } public void run() { controllerDesc.setName(originalName + Constants.CYCLIC_NODE_SUFFIX + indexInList); Component instance; try { instance = Fractive.instance() .newFcInstance(type, controllerDesc, contentDesc[indexInList], nodes[indexInList % nodes.length]); // System.out.println("[fractive] created component " + originalName + Constants.CYCLIC_NODE_SUFFIX + indexInList); targetList.set(indexInList, instance); } catch (InstantiationException e) { e.printStackTrace(); // targetList.add(null); exceptions.add(e); } } } private static class NFComponentBuilderTask extends ComponentBuilderTask implements Runnable { public NFComponentBuilderTask(List<InstantiationException> exceptions, List<Component> targetList, int indexInList, Type type, ControllerDescription controllerDesc, String originalName, ContentDescription[] contentDesc, Node[] nodes) { super(exceptions, targetList, indexInList, type, controllerDesc, originalName, contentDesc, nodes); } public void run() { controllerDesc.setName(originalName + Constants.CYCLIC_NODE_SUFFIX + indexInList); Component instance; try { instance = Fractive.instance() .newNFcInstance(type, controllerDesc, contentDesc[indexInList], nodes[indexInList % nodes.length]); // System.out.println("[fractive] created component " + originalName + Constants.CYCLIC_NODE_SUFFIX + indexInList); targetList.set(indexInList, instance); } catch (InstantiationException e) { e.printStackTrace(); // targetList.add(null); exceptions.add(e); } } } // a utility class mocking a component private static class MockComponent implements Component, Serializable { public Object getFcInterface(String interfaceName) throws NoSuchInterfaceException { return null; } public Object[] getFcInterfaces() { return null; } public Type getFcType() { return null; } } private static class ActiveObjectWithComponentParameters { StubObject activeObject; ComponentParameters parameters; public ActiveObjectWithComponentParameters(StubObject ao, ComponentParameters par) { this.activeObject = ao; this.parameters = par; } public StubObject getActiveObject() { return activeObject; } public ComponentParameters getParameters() { return parameters; } } }
package algorithms.imageProcessing; import algorithms.misc.Misc; import algorithms.util.DisjointSet2Helper; import algorithms.util.DisjointSet2Node; import algorithms.util.PairInt; import java.util.ArrayDeque; import java.util.ArrayList; 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; public class WaterShed { private int[][] distToLowerIntensityPixel = null; private Set<PairInt> regionalMinima = new HashSet<PairInt>(); /** * This method alters the image, specifically the plateaus, so that a best * path to lowest intensity is possible and less ambiguous. A plateau is a * region of where the pixels have the same intensities. * After this has finished, there should be no pixel which does not * have a neighbor of lower intensity if the pixel is not a regional * minimum. * runtime complexity is O(N). * * @param img * @return */ protected int[][] lower(GreyscaleImage img, Set<PairInt> points) { /* TODO: create a helper method to determine the bounds of points and then pass the offsets for that into this method to allow using a smaller returned two dimensional array whose coordinate reference frame is (x - xOffset, y - yOffset). The algorithm below would need to be adjusted for it where int[][] lc is used. */ PairInt sentinel = new PairInt(-1, -1); int w = img.getWidth(); int h = img.getHeight(); int[][] lc = new int[w][]; for (int i = 0; i < w; ++i) { lc[i] = new int[h]; } distToLowerIntensityPixel = new int[w][]; for (int i = 0; i < w; ++i) { distToLowerIntensityPixel[i] = new int[h]; } int[] dxs8 = Misc.dx8; int[] dys8 = Misc.dy8; int dist; ArrayDeque<PairInt> queue = new ArrayDeque<PairInt>(points.size()); for (PairInt p : points) { int x = p.getX(); int y = p.getY(); int v = img.getValue(x, y); for (int vIdx = 0; vIdx < dxs8.length; ++vIdx) { int x2 = x + dxs8[vIdx]; int y2 = y + dys8[vIdx]; PairInt p2 = new PairInt(x2, y2); if (points.contains(p2)) { int v2 = img.getValue(x2, y2); if (v2 < v) { queue.add(p); lc[x][y] = -1; break; } } } } if (queue.isEmpty()) { // points contains only pixels of same intensity return null; } dist = 1; queue.add(sentinel); while (!queue.isEmpty()) { PairInt p = queue.poll(); if (p.equals(sentinel)) { if (!queue.isEmpty()) { queue.add(sentinel); //any point originally lacking lower intensity neighbors, //now gets a larger distance dist++; } continue; } int x = p.getX(); int y = p.getY(); lc[x][y] = dist; for (int vIdx = 0; vIdx < dxs8.length; ++vIdx) { int x2 = x + dxs8[vIdx]; int y2 = y + dys8[vIdx]; if (x2 < 0 || y2 < 0 || (x2 > (img.getWidth() - 1)) || (y2 > (img.getHeight() - 1))) { continue; } if ((img.getValue(x, y) == img.getValue(x2, y2)) && (lc[x2][y2] == 0)) { queue.add(new PairInt(x2, y2)); lc[x2][y2] = -1; } } } for (PairInt p : points) { int x = p.getX(); int y = p.getY(); distToLowerIntensityPixel[x][y] = lc[x][y]; if (lc[x][y] != 0) { lc[x][y] = dist * img.getValue(x, y) + lc[x][y] - 1; } else { regionalMinima.add(p); //as suggested by later paper, adapted for watershed by Union-Find lc[x][y] = dist * img.getValue(x, y); } } return lc; } /** * get the two dimensional matrix of the shortest distance of a pixel to * a lower intensity pixel with respect to the original image reference * frame. For example, if a pixel is surrounded by pixels with the same * intensity, the shortest distance for it will be larger than '1' because * no neighbors have a smaller intensity. * @return the distToLowerIntensityPixel */ public int[][] getDistToLowerIntensityPixel() { return distToLowerIntensityPixel; } public Set<PairInt> getRegionalMinima() { return regionalMinima; } protected int[][] unionFindComponentLabelling(int[][] im) { /* TODO: when make changes above to use a reduced portion of the image via the points set, can consider visiting a smaller number of points here too. A LinkedHashSet can be created with lexicographical ordering rules. The LinkedHashSet can be created with one pass through 0 to width and 0 to height or the points set can be sorted and entered into LinkedHashSet in lexicographical order depending upon comparison of n_points in points set and n_pixels = width*height, O(N_points*lg2(N_points)) vs O(N_pixels), respectively. */ int w = im.length; int h = im[0].length; int[] dLOX = new int[]{-1, -1, -1, 0}; int[] dLOY = new int[]{ 1, 0, -1, -1}; DisjointSet2Helper disjointSetHelper = new DisjointSet2Helper(); Map<PairInt, DisjointSet2Node<PairInt>> parentMap = new HashMap<PairInt, DisjointSet2Node<PairInt>>(); // init map or create entries upon need? for (int i = 0; i < w; ++i) { for (int j = 0; j < h; ++j) { PairInt pPoint = new PairInt(i, j); DisjointSet2Node<PairInt> pNode = disjointSetHelper.makeSet(new DisjointSet2Node<PairInt>(pPoint)); parentMap.put(pPoint, pNode); } } //Firstpass PairInt reprPoint; for (int i = 0; i < w; ++i) { for (int j = 0; j < h; ++j) { PairInt pPoint = new PairInt(i, j); reprPoint = pPoint; int x = pPoint.getX(); int y = pPoint.getY(); int vP = im[x][y]; List<PairInt> qPoints = new ArrayList<PairInt>(); for (int vIdx = 0; vIdx < dLOX.length; ++vIdx) { int x2 = x + dLOX[vIdx]; int y2 = y + dLOY[vIdx]; if (x2 < 0 || y2 < 0 || (x2 > (w - 1)) || (y2 > (h - 1))) { continue; } PairInt qPoint = new PairInt(x2, y2); int vQ = im[x2][y2]; if (vP == vQ) { // find r, the representative of the neighbors with // same image intensity, as the lexicographically // smallest location DisjointSet2Node<PairInt> qParent = disjointSetHelper.findSet( parentMap.get(qPoint)); if (qParent.getMember().getX() < reprPoint.getX()) { reprPoint = qPoint; } else if ((qParent.getMember().getX() == reprPoint.getX()) && (qParent.getMember().getY() < reprPoint.getY())) { reprPoint = qPoint; } qPoints.add(qPoint); } } if (!qPoints.isEmpty()) { DisjointSet2Node<PairInt> parent = disjointSetHelper.union( parentMap.get(reprPoint), parentMap.get(pPoint)); for (PairInt qPoint : qPoints) { if (qPoint.equals(reprPoint)) { continue; } //PathCompress(q, r) DisjointSet2Node<PairInt> qParent = disjointSetHelper.union( parentMap.get(reprPoint), parentMap.get(qPoint)); } } } // end j loop } // end i loop System.out.println(printParents(parentMap)); /* In a second pass through the input image, the output image lab is created. All root pixels get a distinct label; for any other pixel p its path is compressed, making explicit use of the order imposed on parent (see line 29 in Algorithm 4.7), and p gets the label of its representative. */ int[][] label = new int[w][]; for (int i = 0; i < w; ++i) { label[i] = new int[h]; } //Secondpass int curLabel = 1; for (int i = 0; i < w; ++i) { for (int j = 0; j < h; ++j) { PairInt pPoint = new PairInt(i, j); } } throw new UnsupportedOperationException("not yet implemented"); //return label; } /** * Algorithm 4.8 Watershed transform w.r.t. topographical distance based on disjoint sets. * @param im a lower complete image * @return */ protected int[][] unionFindWatershed(int[][] im) { /* input is a lower complete image. internally uses a DAG and disjoint sets algorithm 4.8 of reference above */ throw new UnsupportedOperationException("not yet implemented"); } private String printParents(Map<PairInt, DisjointSet2Node<PairInt>> parentMap) { DisjointSet2Helper dsHelper = new DisjointSet2Helper(); Map<PairInt, List<PairInt>> parentValueMap = new HashMap<PairInt, List<PairInt>>(); for (Entry<PairInt, DisjointSet2Node<PairInt>> entry : parentMap.entrySet()) { PairInt child = entry.getKey(); PairInt parent = dsHelper.findSet(entry.getValue()).getMember(); List<PairInt> children = parentValueMap.get(parent); if (children == null) { children = new ArrayList<PairInt>(); parentValueMap.put(parent, children); } children.add(child); } StringBuilder sb = new StringBuilder(); for (Entry<PairInt, List<PairInt>> entry : parentValueMap.entrySet()) { PairInt parent = entry.getKey(); List<PairInt> children = entry.getValue(); sb.append("parent: ").append(parent.toString()); sb.append(" children: "); for (PairInt c : children) { sb.append(" ").append(c.toString()); } sb.append("\n"); } return sb.toString(); } }
//This library is free software; you can redistribute it and/or //modify it under the terms of the GNU Lesser General Public //This library is distributed in the hope that it will be useful, //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //You should have received a copy of the GNU Lesser General Public //Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. package opennlp.tools.namefind; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Map; import opennlp.maxent.EventStream; import opennlp.maxent.GIS; import opennlp.maxent.GISModel; import opennlp.maxent.MaxentModel; import opennlp.maxent.PlainTextByLineDataStream; import opennlp.maxent.TwoPassDataIndexer; import opennlp.maxent.io.SuffixSensitiveGISModelWriter; import opennlp.tools.util.BeamSearch; import opennlp.tools.util.Sequence; public class NameFinderME implements NameFinder { protected MaxentModel _npModel; protected NameContextGenerator _contextGen; private Sequence bestSequence; private int beamSize; private BeamSearch beam; public static final String START = "start"; public static final String CONTINUE = "cont"; public static final String OTHER = "other"; public NameFinderME(MaxentModel mod) { this(mod, new DefaultNameContextGenerator(), 10); } public NameFinderME(MaxentModel mod, NameContextGenerator cg) { this(mod, cg, 10); } public NameFinderME(MaxentModel mod, NameContextGenerator cg, int beamSize) { _npModel = mod; _contextGen = cg; this.beamSize = beamSize; beam = new NameBeamSearch(beamSize, cg, mod); } public List find(List toks, Map prevTags) { bestSequence = beam.bestSequence(toks, new Object[] { prevTags }); return bestSequence.getOutcomes(); } public String[] find(Object[] toks, Map prevTags) { bestSequence = beam.bestSequence(Arrays.asList(toks), new Object[] { prevTags }); List c = bestSequence.getOutcomes(); return (String[]) c.toArray(new String[c.size()]); } /** * This method determines wheter the outcome is valid for the preceeding sequence. * This can be used to implement constraints on what sequences are valid. * @param outcome The outcome. * @param sequence The precceding sequence of outcomes assignments. * @return true is the outcome is valid for the sequence, false otherwise. */ protected boolean validOutcome(String outcome, Sequence sequence) { if (outcome.equals(CONTINUE)) { List tags = sequence.getOutcomes(); int li = tags.size() - 1; if (li == -1) { return false; } else if (((String) tags.get(li)).equals(OTHER)) { return false; } } return true; } private class NameBeamSearch extends BeamSearch { public NameBeamSearch(int size, NameContextGenerator cg, MaxentModel model) { super(size, cg, model); } protected boolean validSequence(int i, List sequence, Sequence s, String outcome) { return validOutcome(outcome, s); } } public void probs(double[] probs) { bestSequence.getProbs(probs); } public double[] probs() { return bestSequence.getProbs(); } public static GISModel train(EventStream es, int iterations, int cut) throws IOException { return GIS.trainModel(iterations, new TwoPassDataIndexer(es, cut)); } public static void main(String[] args) throws IOException { if (args.length == 0) { System.err.println("usage: NameFinderME training_file model"); System.exit(1); } try { File inFile = new File(args[0]); File outFile = new File(args[1]); GISModel mod; EventStream es = new NameFinderEventStream(new PlainTextByLineDataStream(new FileReader(inFile))); if (args.length > 3) mod = train(es, Integer.parseInt(args[2]), Integer.parseInt(args[3])); else mod = train(es, 100, 5); System.out.println("Saving the model as: " + args[1]); new SuffixSensitiveGISModelWriter(mod, outFile).persist(); } catch (Exception e) { e.printStackTrace(); } } }
//This library is free software; you can redistribute it and/or //modify it under the terms of the GNU Lesser General Public //This library is distributed in the hope that it will be useful, //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //You should have received a copy of the GNU Lesser General Public //Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. package opennlp.tools.namefind; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import opennlp.maxent.EventStream; import opennlp.maxent.GIS; import opennlp.maxent.GISModel; import opennlp.maxent.MaxentModel; import opennlp.maxent.TwoPassDataIndexer; import opennlp.tools.util.BeamSearch; import opennlp.tools.util.Sequence; import opennlp.tools.util.Span; /** * Class for creating a maximum-entropy-based name finder. */ public class NameFinderME implements TokenNameFinder { private static String[][] EMPTY = new String[0][0]; /** * Implementation of the abstract beam search to allow the name finder to use * the common beam search code. */ private class NameBeamSearch extends BeamSearch { /** * Creams a beam search of the specified size sing the specified model with * the specified context generator. * * @param size * The size of the beam. * @param cg * The context generator used with the specified model. * @param model * The model used to determine names. * @param beamSize */ public NameBeamSearch(int size, NameContextGenerator cg, MaxentModel model, int beamSize) { super(size, cg, model, beamSize); } /** * This method determines whether the outcome is valid for the preceding * sequence. This can be used to implement constraints on what sequences are * valid. * * @param outcome The outcome. * @param inputSequence The preceding sequence of outcomes assignments. * @return true is the outcome is valid for the sequence, false otherwise. */ protected boolean validSequence(int size, Object[] inputSequence, String[] outcomesSequence, String outcome) { if (outcome.equals(CONTINUE)) { int li = outcomesSequence.length - 1; if (li == -1) { return false; } else if (outcomesSequence[li].equals(OTHER)) { return false; } } return true; } } public static final String START = "start"; public static final String CONTINUE = "cont"; public static final String OTHER = "other"; protected MaxentModel model; protected NameContextGenerator contextGenerator; private Sequence bestSequence; private BeamSearch beam; private AdditionalContextFeatureGenerator additionalContextFeatureGenerator = new AdditionalContextFeatureGenerator(); /** * Creates a new name finder with the specified model. * @param mod The model to be used to find names. */ public NameFinderME(MaxentModel mod) { this(mod, new DefaultNameContextGenerator(), 3); } /** * Creates a new name finder with the specified model and context generator. * @param mod The model to be used to find names. * @param cg The context generator to be used with this name finder. */ public NameFinderME(MaxentModel mod, NameContextGenerator cg) { this(mod, cg, 3); } /** * Creates a new name finder with the specified model and context generator. * @param mod The model to be used to find names. * @param cg The context generator to be used with this name finder. * @param beamSize The size of the beam to be used in decoding this model. */ public NameFinderME(MaxentModel mod, NameContextGenerator cg, int beamSize) { model = mod; contextGenerator = cg; contextGenerator.addFeatureGenerator(new WindowFeatureGenerator(additionalContextFeatureGenerator, 8, 8)); beam = new NameBeamSearch(beamSize, cg, mod, beamSize); } public Span[] find(String[] tokens) { return find(tokens, EMPTY); } /** Generates name tags for the given sequence, typically a sentence, returning token spans for any identified names. * @param tokens an array of the tokens or words of the sequence, typically a sentence. * @param additionalContext features which are based on context outside of the sentence but which should also be used. * @return an array of spans for each of the names identified. */ public Span[] find(String[] tokens, String[][] additionalContext) { additionalContextFeatureGenerator.setCurrentContext(additionalContext); bestSequence = beam.bestSequence(tokens, additionalContext); List c = bestSequence.getOutcomes(); contextGenerator.updateAdaptiveData(tokens, (String[]) c.toArray(new String[c.size()])); int start = -1; int end = -1; List spans = new ArrayList(tokens.length); for (int li = 0; li < c.size(); li++) { String chunkTag = (String) c.get(li); if (chunkTag.equals(NameFinderME.START)) { if (start != -1) { spans.add(new Span(start, end)); } start = li; end = li + 1; } else if (chunkTag.equals(NameFinderME.CONTINUE)) { end = li + 1; } else if (chunkTag.equals(NameFinderME.OTHER)) { if (start != -1) { spans.add(new Span(start, end)); start = -1; end = -1; } } } if (start != -1) { spans.add(new Span(start,end)); } return (Span[]) spans.toArray(new Span[spans.size()]); } /** * Forgets all adaptive data which was collected during previous * calls to one of the find methods. * * This method is typical called at the end of a document. */ public void clearAdaptiveData() { contextGenerator.clearAdaptiveData(); } /** * Populates the specified array with the probabilities of the last decoded * sequence. The sequence was determined based on the previous call to * <code>chunk</code>. The specified array should be at least as large as * the number of tokens in the previous call to <code>chunk</code>. * * @param probs * An array used to hold the probabilities of the last decoded * sequence. */ public void probs(double[] probs) { bestSequence.getProbs(probs); } /** * Returns an array with the probabilities of the last decoded sequence. The * sequence was determined based on the previous call to <code>chunk</code>. * @return An array with the same number of probabilities as tokens were sent to <code>chunk</code> * when it was last called. */ public double[] probs() { return bestSequence.getProbs(); } /** * Returns an array of probabilities for each of the specified spans which is the product * the probabilities for each of the outcomes which make up the span. * @param spans The spans of the names for which probabilities are desired. * @return an array of probabilities for each of the specified spans. */ public double[] probs(Span[] spans) { double[] sprobs = new double[spans.length]; double[] probs = bestSequence.getProbs(); for (int si=0;si<spans.length;si++) { double p = 1; for (int oi=spans[si].getStart();oi<spans[si].getEnd();oi++) { p*=probs[oi]; } sprobs[si] = p; } return sprobs; } public static GISModel train(EventStream es, int iterations, int cut) throws IOException { return GIS.trainModel(iterations, new TwoPassDataIndexer(es, cut)); } public static void usage(){ System.err.println("Usage: opennlp.tools.namefind.NameFinderME -encoding encoding training_file model"); System.exit(1); } /** * Trains a new named entity model on the specified training file using the specified encoding to read it in. * @param args [-encoding encoding] training_file model_file * @throws java.io.IOException */ public static void main(String[] args) throws java.io.IOException { if (args.length == 0) { usage(); } int ai = 0; String encoding = null; while (args[ai].startsWith("-")) { if (args[ai].equals("-encoding") && ai+1 < args.length) { ai++; encoding = args[ai]; } else { System.err.println("Unknown option: "+args[ai]); usage(); } ai++; } java.io.File inFile = null; java.io.File outFile = null; if (ai < args.length) { inFile = new java.io.File(args[ai++]); } else { usage(); } if (ai < args.length) { outFile = new java.io.File(args[ai++]); } else { usage(); } int iterations = 100; int cutoff = 5; if (args.length > ai) { iterations = Integer.parseInt(args[ai++]); } if (args.length > ai) { cutoff = Integer.parseInt(args[ai++]); } GISModel mod; opennlp.maxent.EventStream es; if (encoding != null) { es = new NameFinderEventStream(new NameSampleDataStream(new opennlp.maxent.PlainTextByLineDataStream(new InputStreamReader(new FileInputStream(inFile),encoding)))); } else { es = new NameFinderEventStream(new NameSampleDataStream(new opennlp.maxent.PlainTextByLineDataStream(new java.io.FileReader(inFile)))); } mod = train(es, iterations, cutoff); System.out.println("Saving the model as: " + outFile.toString()); new opennlp.maxent.io.SuffixSensitiveGISModelWriter(mod, outFile).persist(); } }
package org.apache.commons.lang; import java.util.StringTokenizer; import java.util.Iterator; public class StringUtils { /** * <p><code>StringUtils<code> instances should NOT be constructed in * standard programming. Instead, the class should be used as * <code>StringUtils.trim(" foo ");</code>.</p> * * <p>This constructor is public to permit tools that require a JavaBean * instance to operate.</p> */ public StringUtils() { } // Empty /** * <p>Removes control characters, including whitespace, from both * ends of this String, handling <code>null</code> by returning * an empty String.</p> * * @see java.lang.String#trim() * @param str the String to check * @return the trimmed text (never <code>null</code>) */ public static String clean(String str) { return (str == null ? "" : str.trim()); } /** * <p>Removes control characters, including whitespace, from both * ends of this String, handling <code>null</code> by returning * <code>null</code>.</p> * * @see java.lang.String#trim() * @param str the String to check * @return the trimmed text (or <code>null</code>) */ public static String trim(String str) { return (str == null ? null : str.trim()); } /** * <p>Deletes all 'space' characters from a String.</p> * * <p>Spaces are defined as <code>{' ', '\t', '\r', '\n', '\b'}</code> * in line with the deprecated {@link Character#isSpace(char)}.</p> * * @param str String target to delete spaces from * @return the String without spaces * @throws NullPointerException */ public static String deleteSpaces(String str) { return CharSetUtils.delete(str, " \t\r\n\b"); } /** * <p>Deletes all whitespaces from a String.</p> * * <p>Whitespace is defined by * {@link Character#isWhitespace(char)}.</p> * * @param str String target to delete whitespace from * @return the String without whitespaces * @throws NullPointerException */ public static String deleteWhitespace(String str) { StringBuffer buffer = new StringBuffer(); int sz = str.length(); for (int i=0; i<sz; i++) { if(!Character.isWhitespace(str.charAt(i))) { buffer.append(str.charAt(i)); } } return buffer.toString(); } /** * <p>Checks if a String is non <code>null</code> and is * not empty (<code>length > 0</code>).</p> * * @param str the String to check * @return true if the String is non-null, and not length zero */ public static boolean isNotEmpty(String str) { return (str != null && str.length() > 0); } /** * <p>Checks if a (trimmed) String is <code>null</code> or empty.</p> * * @param str the String to check * @return <code>true</code> if the String is <code>null</code>, or * length zero once trimmed */ public static boolean isEmpty(String str) { return (str == null || str.trim().length() == 0); } // Equals and IndexOf /** * <p>Compares two Strings, returning <code>true</code> if they are equal.</p> * * <p><code>null</code>s are handled without exceptions. Two <code>null</code> * references are considered to be equal. The comparison is case sensitive.</p> * * @see java.lang.String#equals(Object) * @param str1 the first string * @param str2 the second string * @return <code>true</code> if the Strings are equal, case sensitive, or * both <code>null</code> */ public static boolean equals(String str1, String str2) { return (str1 == null ? str2 == null : str1.equals(str2)); } /** * <p>Compares two Strings, returning <code>true</code> if they are equal ignoring * the case.</p> * * <p><code>Nulls</code> are handled without exceptions. Two <code>null</code> * references are considered equal. Comparison is case insensitive.</p> * * @see java.lang.String#equalsIgnoreCase(String) * @param str1 the first string * @param str2 the second string * @return <code>true</code> if the Strings are equal, case insensitive, or * both <code>null</code> */ public static boolean equalsIgnoreCase(String str1, String str2) { return (str1 == null ? str2 == null : str1.equalsIgnoreCase(str2)); } /** * <p>Find the first index of any of a set of potential substrings.</p> * * <p><code>null</code> String will return <code>-1</code>.</p> * * @param str the String to check * @param searchStrs the Strings to search for * @return the first index of any of the searchStrs in str * @throws NullPointerException if any of searchStrs[i] is <code>null</code> */ public static int indexOfAny(String str, String[] searchStrs) { if ((str == null) || (searchStrs == null)) { return -1; } int sz = searchStrs.length; // String's can't have a MAX_VALUEth index. int ret = Integer.MAX_VALUE; int tmp = 0; for (int i = 0; i < sz; i++) { tmp = str.indexOf(searchStrs[i]); if (tmp == -1) { continue; } if (tmp < ret) { ret = tmp; } } return (ret == Integer.MAX_VALUE) ? -1 : ret; } /** * <p>Find the latest index of any of a set of potential substrings.</p> * * <p><code>null</code> string will return <code>-1</code>.</p> * * @param str the String to check * @param searchStrs the Strings to search for * @return the last index of any of the Strings * @throws NullPointerException if any of searchStrs[i] is <code>null</code> */ public static int lastIndexOfAny(String str, String[] searchStrs) { if ((str == null) || (searchStrs == null)) { return -1; } int sz = searchStrs.length; int ret = -1; int tmp = 0; for (int i = 0; i < sz; i++) { tmp = str.lastIndexOf(searchStrs[i]); if (tmp > ret) { ret = tmp; } } return ret; } // Substring /** * <p>Gets a substring from the specified string avoiding exceptions.</p> * * <p>A negative start position can be used to start <code>n</code> * characters from the end of the String.</p> * * @param str the String to get the substring from * @param start the position to start from, negative means * count back from the end of the String by this many characters * @return substring from start position */ public static String substring(String str, int start) { if (str == null) { return null; } // handle negatives, which means last n characters if (start < 0) { start = str.length() + start; // remember start is negative } if (start < 0) { start = 0; } if (start > str.length()) { return ""; } return str.substring(start); } /** * <p>Gets a substring from the specified String avoiding exceptions.</p> * * <p>A negative start position can be used to start/end <code>n</code> * characters from the end of the String.</p> * * @param str the String to get the substring from * @param start the position to start from, negative means * count back from the end of the string by this many characters * @param end the position to end at (exclusive), negative means * count back from the end of the String by this many characters * @return substring from start position to end positon */ public static String substring(String str, int start, int end) { if (str == null) { return null; } // handle negatives if (end < 0) { end = str.length() + end; // remember end is negative } if (start < 0) { start = str.length() + start; // remember start is negative } // check length next if (end > str.length()) { // check this works. end = str.length(); } // if start is greater than end, return "" if (start > end) { return ""; } if (start < 0) { start = 0; } if (end < 0) { end = 0; } return str.substring(start, end); } public static String left(String str, int len) { if (len < 0) { throw new IllegalArgumentException("Requested String length " + len + " is less than zero"); } if ((str == null) || (str.length() <= len)) { return str; } else { return str.substring(0, len); } } public static String right(String str, int len) { if (len < 0) { throw new IllegalArgumentException("Requested String length " + len + " is less than zero"); } if ((str == null) || (str.length() <= len)) { return str; } else { return str.substring(str.length() - len); } } public static String mid(String str, int pos, int len) { if ((pos < 0) || (str != null && pos > str.length())) { throw new StringIndexOutOfBoundsException("String index " + pos + " is out of bounds"); } if (len < 0) { throw new IllegalArgumentException("Requested String length " + len + " is less than zero"); } if (str == null) { return null; } if (str.length() <= (pos + len)) { return str.substring(pos); } else { return str.substring(pos, pos + len); } } // Splitting /** * <p>Splits the provided text into a array, using whitespace as the * separator.</p> * * <p>The separator is not included in the returned String array.</p> * * @param str the String to parse * @return an array of parsed Strings */ public static String[] split(String str) { return split(str, null, -1); } /** * @see #split(String, String, int) */ public static String[] split(String text, String separator) { return split(text, separator, -1); } /** * <p>Splits the provided text into a array, based on a given separator.</p> * * <p>The separator is not included in the returned String array. The * maximum number of splits to perfom can be controlled. A <code>null</code> * separator will cause parsing to be on whitespace.</p> * * <p>This is useful for quickly splitting a String directly into * an array of tokens, instead of an enumeration of tokens (as * <code>StringTokenizer</code> does).</p> * * @param str The string to parse. * @param separator Characters used as the delimiters. If * <code>null</code>, splits on whitespace. * @param max The maximum number of elements to include in the * array. A zero or negative value implies no limit. * @return an array of parsed Strings */ public static String[] split(String str, String separator, int max) { StringTokenizer tok = null; if (separator == null) { // Null separator means we're using StringTokenizer's default // delimiter, which comprises all whitespace characters. tok = new StringTokenizer(str); } else { tok = new StringTokenizer(str, separator); } int listSize = tok.countTokens(); if (max > 0 && listSize > max) { listSize = max; } String[] list = new String[listSize]; int i = 0; int lastTokenBegin = 0; int lastTokenEnd = 0; while (tok.hasMoreTokens()) { if (max > 0 && i == listSize - 1) { // In the situation where we hit the max yet have // tokens left over in our input, the last list // element gets all remaining text. String endToken = tok.nextToken(); lastTokenBegin = str.indexOf(endToken, lastTokenEnd); list[i] = str.substring(lastTokenBegin); break; } else { list[i] = tok.nextToken(); lastTokenBegin = str.indexOf(list[i], lastTokenEnd); lastTokenEnd = lastTokenBegin + list[i].length(); } i++; } return list; } // Joining /** * <p>Concatenates elements of an array into a single String.</p> * * <p>The difference from join is that concatenate has no delimiter.</p> * * @param array the array of values to concatenate. * @return the concatenated string. */ public static String concatenate(Object[] array) { return join(array, ""); } /** * <p>Joins the elements of the provided array into a single String * containing the provided list of elements.</p> * * <p>No delimiter is added before or after the list. A * <code>null</code> separator is the same as a blank String.</p> * * @param array the array of values to join together * @param separator the separator character to use * @return the joined String */ public static String join(Object[] array, String separator) { if (separator == null) { separator = ""; } int arraySize = array.length; int bufSize = (arraySize == 0 ? 0 : (array[0].toString().length() + separator.length()) * arraySize); StringBuffer buf = new StringBuffer(bufSize); for (int i = 0; i < arraySize; i++) { if (i > 0) { buf.append(separator); } buf.append(array[i]); } return buf.toString(); } /** * <p>Joins the elements of the provided <code>Iterator</code> into * a single String containing the provided elements.</p> * * <p>No delimiter is added before or after the list. A * <code>null</code> separator is the same as a blank String.</p> * * @param iterator the <code>Iterator</code> of values to join together * @param separator the separator character to use * @return the joined String */ public static String join(Iterator iterator, String separator) { if (separator == null) { separator = ""; } StringBuffer buf = new StringBuffer(256); // Java default is 16, probably too small while (iterator.hasNext()) { buf.append(iterator.next()); if (iterator.hasNext()) { buf.append(separator); } } return buf.toString(); } // Replacing /** * <p>Replace a String with another String inside a larger String, once.</p> * * @see #replace(String text, String repl, String with, int max) * @param text text to search and replace in * @param repl String to search for * @param with String to replace with * @return the text with any replacements processed */ public static String replaceOnce(String text, String repl, String with) { return replace(text, repl, with, 1); } /** * <p>Replace all occurances of a String within another String.</p> * * @see #replace(String text, String repl, String with, int max) * @param text text to search and replace in * @param repl String to search for * @param with String to replace with * @return the text with any replacements processed */ public static String replace(String text, String repl, String with) { return replace(text, repl, with, -1); } /** * <p>Replace a String with another String inside a larger String, * for the first <code>max</code> values of the search String.</p> * * <p>A <code>null</code> reference is passed to this method is a * no-op.</p> * * @param text text to search and replace in * @param repl String to search for * @param with String to replace with * @param max maximum number of values to replace, or * <code>-1</code> if no maximum * @return the text with any replacements processed * @throws NullPointerException if repl is <code>null</code> */ public static String replace(String text, String repl, String with, int max) { if (text == null) { return null; } StringBuffer buf = new StringBuffer(text.length()); int start = 0, end = 0; while ((end = text.indexOf(repl, start)) != -1) { buf.append(text.substring(start, end)).append(with); start = end + repl.length(); if (--max == 0) { break; } } buf.append(text.substring(start)); return buf.toString(); } /** * <p>Overlay a part of a String with another String.</p> * * @param text String to do overlaying in * @param overlay String to overlay * @param start int to start overlaying at * @param end int to stop overlaying before * @return String with overlayed text * @throws NullPointerException if text or overlay is <code>null</code> */ public static String overlayString(String text, String overlay, int start, int end) { return new StringBuffer(start + overlay.length() + text.length() - end + 1) .append(text.substring(0, start)) .append(overlay) .append(text.substring(end)) .toString(); } // Centering /** * <p>Center a String in a larger String of size <code>n</code>.<p> * * <p>Uses spaces as the value to buffer the String with. * Equivalent to <code>center(str, size, " ")</code>.</p> * * @param str String to center * @param size int size of new String * @return String containing centered String * @throws NullPointerException if str is <code>null</code> */ public static String center(String str, int size) { return center(str, size, " "); } /** * <p>Center a String in a larger String of size <code>n</code>.</p> * * <p>Uses a supplied String as the value to buffer the String with.</p> * * @param str String to center * @param size int size of new String * @param delim String to buffer the new String with * @return String containing centered String * @throws NullPointerException if str or delim is <code>null</code> * @throws ArithmeticException if delim is the empty String */ public static String center(String str, int size, String delim) { int sz = str.length(); int p = size - sz; if (p < 1) { return str; } str = leftPad(str, sz + p / 2, delim); str = rightPad(str, size, delim); return str; } // Chomping /** * <p>Remove the last newline, and everything after it from a String.</p> * * @param str String to chomp the newline from * @return String without chomped newline * @throws NullPointerException if str is <code>null</code> */ public static String chomp(String str) { return chomp(str, "\n"); } /** * <p>Remove the last value of a supplied String, and everything after * it from a String.</p> * * @param str String to chomp from * @param sep String to chomp * @return String without chomped ending * @throws NullPointerException if str or sep is <code>null</code> */ public static String chomp(String str, String sep) { int idx = str.lastIndexOf(sep); if (idx != -1) { return str.substring(0, idx); } else { return str; } } /** * <p>Remove a newline if and only if it is at the end * of the supplied String.</p> * * @param str String to chomp from * @return String without chomped ending * @throws NullPointerException if str is <code>null</code> */ public static String chompLast(String str) { return chompLast(str, "\n"); } /** * <p>Remove a value if and only if the String ends with that value.</p> * * @param str String to chomp from * @param sep String to chomp * @return String without chomped ending * @throws NullPointerException if str or sep is <code>null</code> */ public static String chompLast(String str, String sep) { if (str.length() == 0) { return str; } String sub = str.substring(str.length() - sep.length()); if (sep.equals(sub)) { return str.substring(0, str.length() - sep.length()); } else { return str; } } /** * <p>Remove everything and return the last value of a supplied String, and * everything after it from a String.</p> * * @param str String to chomp from * @param sep String to chomp * @return String chomped * @throws NullPointerException if str or sep is <code>null</code> */ public static String getChomp(String str, String sep) { int idx = str.lastIndexOf(sep); if (idx == str.length() - sep.length()) { return sep; } else if (idx != -1) { return str.substring(idx); } else { return ""; } } /** * <p>Remove the first value of a supplied String, and everything before it * from a String.</p> * * @param str String to chomp from * @param sep String to chomp * @return String without chomped beginning * @throws NullPointerException if str or sep is <code>null</code> */ public static String prechomp(String str, String sep) { int idx = str.indexOf(sep); if (idx != -1) { return str.substring(idx + sep.length()); } else { return str; } } /** * <p>Remove and return everything before the first value of a * supplied String from another String.</p> * * @param str String to chomp from * @param sep String to chomp * @return String prechomped * @throws NullPointerException if str or sep is <code>null</code> */ public static String getPrechomp(String str, String sep) { int idx = str.indexOf(sep); if (idx != -1) { return str.substring(0, idx + sep.length()); } else { return ""; } } // Chopping /** * <p>Remove the last character from a String.</p> * * <p>If the String ends in <code>\r\n</code>, then remove both * of them.</p> * * @param str String to chop last character from * @return String without last character * @throws NullPointerException if str is <code>null</code> */ public static String chop(String str) { if ("".equals(str)) { return ""; } if (str.length() == 1) { return ""; } int lastIdx = str.length() - 1; String ret = str.substring(0, lastIdx); char last = str.charAt(lastIdx); if (last == '\n') { if (ret.charAt(lastIdx - 1) == '\r') { return ret.substring(0, lastIdx - 1); } } return ret; } /** * <p>Remove <code>\n</code> from end of a String if it's there. * If a <code>\r</code> precedes it, then remove that too.</p> * * @param str String to chop a newline from * @return String without newline * @throws NullPointerException if str is <code>null</code> */ public static String chopNewline(String str) { int lastIdx = str.length() - 1; char last = str.charAt(lastIdx); if (last == '\n') { if (str.charAt(lastIdx - 1) == '\r') { lastIdx } } else { lastIdx++; } return str.substring(0, lastIdx); } // Conversion // spec 3.10.6 /** * <p>Escapes any values it finds into their String form.</p> * * <p>So a tab becomes the characters <code>'\\'</code> and * <code>'t'</code>.</p> * * @param str String to escape values in * @return String with escaped values * @throws NullPointerException if str is <code>null</code> */ public static String escape(String str) { // improved with code from cybertiger@cyberiantiger.org // unicode from him, and defaul for < 32's. int sz = str.length(); StringBuffer buffer = new StringBuffer(2 * sz); for (int i = 0; i < sz; i++) { char ch = str.charAt(i); // handle unicode if (ch > 0xfff) { buffer.append("\\u" + Integer.toHexString(ch)); } else if (ch > 0xff) { buffer.append("\\u0" + Integer.toHexString(ch)); } else if (ch > 0x7f) { buffer.append("\\u00" + Integer.toHexString(ch)); } else if (ch < 32) { switch (ch) { case '\b' : buffer.append('\\'); buffer.append('b'); break; case '\n' : buffer.append('\\'); buffer.append('n'); break; case '\t' : buffer.append('\\'); buffer.append('t'); break; case '\f' : buffer.append('\\'); buffer.append('f'); break; case '\r' : buffer.append('\\'); buffer.append('r'); break; default : if (ch > 0xf) { buffer.append("\\u00" + Integer.toHexString(ch)); } else { buffer.append("\\u000" + Integer.toHexString(ch)); } break; } } else { switch (ch) { case '\'' : buffer.append('\\'); buffer.append('\''); break; case '"' : buffer.append('\\'); buffer.append('"'); break; case '\\' : buffer.append('\\'); buffer.append('\\'); break; default : buffer.append(ch); break; } } } return buffer.toString(); } // Padding /** * <p>Repeat a String <code>n</code> times to form a * new string.</p> * * @param str String to repeat * @param repeat number of times to repeat str * @return String with repeated String * @throws NegativeArraySizeException if <code>repeat < 0</code> * @throws NullPointerException if str is <code>null</code> */ public static String repeat(String str, int repeat) { StringBuffer buffer = new StringBuffer(repeat * str.length()); for (int i = 0; i < repeat; i++) { buffer.append(str); } return buffer.toString(); } /** * <p>Right pad a String with spaces.</p> * * <p>The String is padded to the size of <code>n</code>.</p> * * @param str String to repeat * @param size number of times to repeat str * @return right padded String * @throws NullPointerException if str is <code>null</code> */ public static String rightPad(String str, int size) { return rightPad(str, size, " "); } /** * <p>Right pad a String with a specified string.</p> * * <p>The String is padded to the size of <code>n</code>.</p> * * @param str String to pad out * @param size size to pad to * @param delim String to pad with * @return right padded String * @throws NullPointerException if str or delim is <code>null<code> * @throws ArithmeticException if delim is the empty String */ public static String rightPad(String str, int size, String delim) { size = (size - str.length()) / delim.length(); if (size > 0) { str += repeat(delim, size); } return str; } /** * <p>Left pad a String with spaces.</p> * * <p>The String is padded to the size of <code>n<code>.</p> * * @param str String to pad out * @param size size to pad to * @return left padded String * @throws NullPointerException if str or delim is <code>null<code> */ public static String leftPad(String str, int size) { return leftPad(str, size, " "); } /** * Left pad a String with a specified string. Pad to a size of n. * * @param str String to pad out * @param size size to pad to * @param delim String to pad with * @return left padded String * @throws NullPointerException if str or delim is null * @throws ArithmeticException if delim is the empty string */ public static String leftPad(String str, int size, String delim) { size = (size - str.length()) / delim.length(); if (size > 0) { str = repeat(delim, size) + str; } return str; } // Stripping /** * <p>Remove whitespace from the front and back of a String.</p> * * @param str the String to remove whitespace from * @return the stripped String */ public static String strip(String str) { return strip(str, null); } /** * <p>Remove a specified String from the front and back of a * String.</p> * * <p>If whitespace is wanted to be removed, used the * {@link #strip(java.lang.String)} method.</p> * * @param str the String to remove a string from * @param delim the String to remove at start and end * @return the stripped String */ public static String strip(String str, String delim) { str = stripStart(str, delim); return stripEnd(str, delim); } /** * <p>Strip whitespace from the front and back of every String * in the array.</p> * * @param strs the Strings to remove whitespace from * @return the stripped Strings */ public static String[] stripAll(String[] strs) { return stripAll(strs, null); } /** * <p>Strip the specified delimiter from the front and back of * every String in the array.</p> * * @param strs the Strings to remove a String from * @param delimiter the String to remove at start and end * @return the stripped Strings */ public static String[] stripAll(String[] strs, String delimiter) { if ((strs == null) || (strs.length == 0)) { return strs; } int sz = strs.length; String[] newArr = new String[sz]; for (int i = 0; i < sz; i++) { newArr[i] = strip(strs[i], delimiter); } return newArr; } /** * <p>Strip any of a supplied String from the end of a String.</p> * * <p>If the strip String is <code>null</code>, whitespace is * stripped.</p> * * @param str the String to remove characters from * @param strip the String to remove * @return the stripped String */ public static String stripEnd(String str, String strip) { if (str == null) { return null; } int end = str.length(); if (strip == null) { while ((end != 0) && Character.isWhitespace(str.charAt(end - 1))) { end } } else { while ((end != 0) && (strip.indexOf(str.charAt(end - 1)) != -1)) { end } } return str.substring(0, end); } /** * <p>Strip any of a supplied String from the start of a String.</p> * * <p>If the strip String is <code>null</code>, whitespace is * stripped.</p> * * @param str the String to remove characters from * @param strip the String to remove * @return the stripped String */ public static String stripStart(String str, String strip) { if (str == null) { return null; } int start = 0; int sz = str.length(); if (strip == null) { while ((start != sz) && Character.isWhitespace(str.charAt(start))) { start++; } } else { while ((start != sz) && (strip.indexOf(str.charAt(start)) != -1)) { start++; } } return str.substring(start); } // Case conversion /** * <p>Convert a String to upper case, <code>null</code> String * returns <code>null</code>.</p> * * @param str the String to uppercase * @return the upper cased String */ public static String upperCase(String str) { if (str == null) { return null; } return str.toUpperCase(); } /** * <p>Convert a String to lower case, <code>null</code> String * returns <code>null</code>.</p> * * @param str the string to lowercase * @return the lower cased String */ public static String lowerCase(String str) { if (str == null) { return null; } return str.toLowerCase(); } /** * <p>Uncapitalise a String.</p> * * <p>That is, convert the first character into lower-case. * <code>null</code> is returned as <code>null</code>.</p> * * @param str the String to uncapitalise * @return uncapitalised String */ public static String uncapitalise(String str) { if (str == null) { return null; } if (str.length() == 0) { return ""; } return new StringBuffer(str.length()) .append(Character.toLowerCase(str.charAt(0))) .append(str.substring(1)) .toString(); } /** * <p>Capitalise a String.</p> * * <p>That is, convert the first character into title-case. * <code>null</code> is returned as <code>null</code>.</p> * * @param str the String to capitalise * @return capitalised String */ public static String capitalise(String str) { if (str == null) { return null; } if (str.length() == 0) { return ""; } return new StringBuffer(str.length()) .append(Character.toTitleCase(str.charAt(0))) .append(str.substring(1)) .toString(); } /** * <p>Swaps the case of String.</p> * * <p>Properly looks after making sure the start of words * are Titlecase and not Uppercase.</p> * * <p><code>null</code> is returned as <code>null</code>.</p> * * @param str the String to swap the case of * @return the modified String */ public static String swapCase(String str) { if (str == null) { return null; } int sz = str.length(); StringBuffer buffer = new StringBuffer(sz); boolean whitespace = false; char ch = 0; char tmp = 0; for (int i = 0; i < sz; i++) { ch = str.charAt(i); if (Character.isUpperCase(ch)) { tmp = Character.toLowerCase(ch); } else if (Character.isTitleCase(ch)) { tmp = Character.toLowerCase(ch); } else if (Character.isLowerCase(ch)) { if (whitespace) { tmp = Character.toTitleCase(ch); } else { tmp = Character.toUpperCase(ch); } } else { tmp = ch; } buffer.append(tmp); whitespace = Character.isWhitespace(ch); } return buffer.toString(); } /** * <p>Capitalise all the words in a String.</p> * * <p>Uses {@link Character#isWhitespace(char)} as a * separator between words.</p> * * <p><code>null</code> will return <code>null</code>.</p> * * @param str the String to capitalise * @return capitalised String */ public static String capitaliseAllWords(String str) { if (str == null) { return null; } int sz = str.length(); StringBuffer buffer = new StringBuffer(sz); boolean space = true; for (int i = 0; i < sz; i++) { char ch = str.charAt(i); if (Character.isWhitespace(ch)) { buffer.append(ch); space = true; } else if (space) { buffer.append(Character.toTitleCase(ch)); space = false; } else { buffer.append(ch); } } return buffer.toString(); } /** * <p>Uncapitalise all the words in a string.</p> * * <p>Uses {@link Character#isWhitespace(char)} as a * separator between words.</p> * * <p><code>null</code> will return <code>null</code>.</p> * * @param str the string to uncapitalise * @return uncapitalised string */ public static String uncapitaliseAllWords(String str) { if (str == null) { return null; } int sz = str.length(); StringBuffer buffer = new StringBuffer(sz); boolean space = true; for (int i = 0; i < sz; i++) { char ch = str.charAt(i); if (Character.isWhitespace(ch)) { buffer.append(ch); space = true; } else if (space) { buffer.append(Character.toLowerCase(ch)); space = false; } else { buffer.append(ch); } } return buffer.toString(); } // Nested extraction /** * <p>Get the String that is nested in between two instances of the * same String.</p> * * <p>If <code>str</code> is <code>null</code>, will * return <code>null</code>.</p> * * @param str the String containing nested-string * @param tag the String before and after nested-string * @return the String that was nested, or <code>null</code> * @throws NullPointerException if tag is <code>null</code> */ public static String getNestedString(String str, String tag) { return getNestedString(str, tag, tag); } /** * <p>Get the String that is nested in between two Strings.</p> * * @param str the String containing nested-string * @param open the String before nested-string * @param close the String after nested-string * @return the String that was nested, or <code>null</code> * @throws NullPointerException if open or close is <code>null</code> */ public static String getNestedString(String str, String open, String close) { if (str == null) { return null; } int start = str.indexOf(open); if (start != -1) { int end = str.indexOf(close, start + open.length()); if (end != -1) { return str.substring(start + open.length(), end); } } return null; } /** * <p>How many times is the substring in the larger String.</p> * * <p><code>null</code> returns <code>0</code>.</p> * * @param str the String to check * @param sub the substring to count * @return the number of occurances, 0 if the String is <code>null</code> * @throws NullPointerException if sub is <code>null</code> */ public static int countMatches(String str, String sub) { if (str == null) { return 0; } int count = 0; int idx = 0; while ((idx = str.indexOf(sub, idx)) != -1) { count++; idx += sub.length(); } return count; } // Character Tests /** * <p>Checks if the String contains only unicode letters.</p> * * <p><code>null</code> will return <code>false</code>. * An empty String will return <code>true</code>.</p> * * @param str the String to check * @return <code>true</code> if only contains letters, and is non-null */ public static boolean isAlpha(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if (Character.isLetter(str.charAt(i)) == false) { return false; } } return true; } /** * <p>Checks if the String contains only whitespace.</p> * * <p><code>null</code> will return <code>false</code>. An * empty String will return <code>true</code>.</p> * * @param str the String to check * @return <code>true</code> if only contains whitespace, and is non-null */ public static boolean isWhitespace(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if ((Character.isWhitespace(str.charAt(i)) == false) ) { return false; } } return true; } /** * <p>Checks if the String contains only unicode letters and * space (<code>' '</code>).</p> * * <p><code>null</code> will return <code>false</code>. An * empty String will return <code>true</code>.</p> * * @param str the String to check * @return <code>true</code> if only contains letters and space, * and is non-null */ public static boolean isAlphaSpace(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if ((Character.isLetter(str.charAt(i)) == false) && (str.charAt(i) != ' ')) { return false; } } return true; } /** * <p>Checks if the String contains only unicode letters or digits.</p> * * <p><code>null</code> will return <code>false</code>. An empty * String will return <code>true</code>.</p> * * @param str the String to check * @return <code>true</code> if only contains letters or digits, * and is non-null */ public static boolean isAlphanumeric(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if (Character.isLetterOrDigit(str.charAt(i)) == false) { return false; } } return true; } /** * <p>Checks if the String contains only unicode letters, digits * or space (<code>' '</code>).</p> * * <p><code>null</code> will return <code>false</code>. An empty * String will return <code>true</code>.</p> * * @param str the String to check * @return <code>true</code> if only contains letters, digits or space, * and is non-null */ public static boolean isAlphanumericSpace(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if ((Character.isLetterOrDigit(str.charAt(i)) == false) && (str.charAt(i) != ' ')) { return false; } } return true; } /** * <p>Checks if the String contains only unicode digits.</p> * * <p><code>null</code> will return <code>false</code>. * An empty String will return <code>true</code>.</p> * * @param str the String to check * @return <code>true</code> if only contains digits, and is non-null */ public static boolean isNumeric(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if (Character.isDigit(str.charAt(i)) == false) { return false; } } return true; } /** * <p>Checks if the String contains only unicode digits or space * (<code>' '</code>).</p> * * <p><code>null</code> will return <code>false</code>. An empty * String will return <code>true</code>.</p> * * @param str the String to check * @return <code>true</code> if only contains digits or space, * and is non-null */ public static boolean isNumericSpace(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if ((Character.isDigit(str.charAt(i)) == false) && (str.charAt(i) != ' ')) { return false; } } return true; } /** * <p>Checks if the String contains a 'true' value.</p> * * <p>These values are defined as the words * <code>'true'</code>, <code>'on'</code> and * <code>'yes'</code>, case insensitive.</p> * * @param str the String to check * @return <code>true</code> if the string is 'true|on|yes' case * insensitive */ public static boolean isTrue(String str) { if ("true".equalsIgnoreCase(str)) { return true; } else if ("on".equalsIgnoreCase(str)) { return true; } else if ("yes".equalsIgnoreCase(str)) { return true; } return false; } // Defaults /** * <p>Returns either the passed in <code>Object</code> as a String, * or, if the <code>Object</code> is <code>null</code>, an empty * String.</p> * * @param obj the Object to check * @return the passed in Object's toString, or blank if it was * <code>null</code> */ public static String defaultString(Object obj) { return defaultString(obj, ""); } /** * <p>Returns either the passed in <code>Object</code> as a String, * or, if the <code>Object</code> is <code>null</code>, a passed * in default String.</p> * * @param obj the Object to check * @param defaultString the default String to return if str is * <code>null</code> * @return the passed in string, or the default if it was * <code>null</code> */ public static String defaultString(Object obj, String defaultString) { return (obj == null) ? defaultString : obj.toString(); } // Reversing /** * <p>Reverse a String.</p> * * <p><code>null</code> String returns <code>null</code>.</p> * * @param str the String to reverse * @return the reversed String */ public static String reverse(String str) { if (str == null) { return null; } return new StringBuffer(str).reverse().toString(); } /** * <p>Reverses a String that is delimited by a specific character.</p> * * <p>The Strings between the delimiters are not reversed. * Thus java.lang.String becomes String.lang.java (if the delimiter * is <code>'.'</code>).</p> * * @param str the String to reverse * @param delimiter the delimiter to use * @return the reversed String */ public static String reverseDelimitedString(String str, String delimiter) { // could implement manually, but simple way is to reuse other, // probably slower, methods. String[] strs = split(str, delimiter); reverseArray(strs); return join(strs, delimiter); } /** * <p>Reverses an array.</p> * * <p>TAKEN FROM CollectionsUtils.</p> * * @param array the array to reverse */ private static void reverseArray(Object[] array) { int i = 0; int j = array.length - 1; Object tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j i++; } } // Misc public static int getLevenshteinDistance(String s, String t) { int d[][]; // matrix int n; // length of s int m; // length of t int i; // iterates through s int j; // iterates through t char s_i; // ith character of s char t_j; // jth character of t int cost; // cost // Step 1 n = s.length(); m = t.length(); if (n == 0) { return m; } if (m == 0) { return n; } d = new int[n + 1][m + 1]; // Step 2 for (i = 0; i <= n; i++) { d[i][0] = i; } for (j = 0; j <= m; j++) { d[0][j] = j; } // Step 3 for (i = 1; i <= n; i++) { s_i = s.charAt(i - 1); // Step 4 for (j = 1; j <= m; j++) { t_j = t.charAt(j - 1); // Step 5 if (s_i == t_j) { cost = 0; } else { cost = 1; } // Step 6 d[i][j] = NumberUtils.minimum(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost); } } // Step 7 return d[n][m]; } /** * <p>Checks if the String contains only certain chars.</p> * * @param str the String to check * @param valid an array of valid chars * @return true if it only contains valid chars and is non-null */ public static boolean containsOnly(String str, char[] valid) { if (str == null || valid == null) { return false; } int strSize = str.length(); int validSize = valid.length; for (int i = 0; i < strSize; i++) { boolean contains = false; for (int j = 0; j < validSize; j++) { if (valid[j] == str.charAt(i)) { contains = true; break; } } if (!contains) { return false; } } return true; } }
package org.apache.lucene.index; import java.io.IOException; import java.io.File; import java.io.PrintStream; import java.util.Vector; import org.apache.lucene.store.Directory; import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.Lock; import org.apache.lucene.store.InputStream; import org.apache.lucene.store.OutputStream; import org.apache.lucene.document.Document; import org.apache.lucene.analysis.Analyzer; /** An IndexWriter creates and maintains an index. The third argument to the <a href="#IndexWriter"><b>constructor</b></a> determines whether a new index is created, or whether an existing index is opened for the addition of new documents. In either case, documents are added with the <a href="#addDocument"><b>addDocument</b></a> method. When finished adding documents, <a href="#close"><b>close</b></a> should be called. If an index will not have more documents added for a while and optimal search performance is desired, then the <a href="#optimize"><b>optimize</b></a> method should be called before the index is closed. */ public final class IndexWriter { private Directory directory; // where this index resides private Analyzer analyzer; // how to analyze text private SegmentInfos segmentInfos = new SegmentInfos(); // the segments private final Directory ramDirectory = new RAMDirectory(); // for temp segs /** Constructs an IndexWriter for the index in <code>path</code>. Text will be analyzed with <code>a</code>. If <code>create</code> is true, then a new, empty index will be created in <code>path</code>, replacing the index already there, if any. */ public IndexWriter(String path, Analyzer a, boolean create) throws IOException { this(FSDirectory.getDirectory(path, create), a, create); } /** Constructs an IndexWriter for the index in <code>path</code>. Text will be analyzed with <code>a</code>. If <code>create</code> is true, then a new, empty index will be created in <code>path</code>, replacing the index already there, if any. */ public IndexWriter(File path, Analyzer a, boolean create) throws IOException { this(FSDirectory.getDirectory(path, create), a, create); } /** Constructs an IndexWriter for the index in <code>d</code>. Text will be analyzed with <code>a</code>. If <code>create</code> is true, then a new, empty index will be created in <code>d</code>, replacing the index already there, if any. */ public IndexWriter(Directory d, Analyzer a, final boolean create) throws IOException { directory = d; analyzer = a; Lock writeLock = directory.makeLock("write.lock"); if (!writeLock.obtain()) // obtain write lock throw new IOException("Index locked for write: " + writeLock); synchronized (directory) { // in- & inter-process sync new Lock.With(directory.makeLock("commit.lock")) { public Object doBody() throws IOException { if (create) segmentInfos.write(directory); else segmentInfos.read(directory); return null; } }.run(); } } /** Flushes all changes to an index, closes all associated files, and closes the directory that the index is stored in. */ public final synchronized void close() throws IOException { flushRamSegments(); ramDirectory.close(); directory.makeLock("write.lock").release(); // release write lock directory.close(); } /** Returns the number of documents currently in this index. */ public final synchronized int docCount() { int count = 0; for (int i = 0; i < segmentInfos.size(); i++) { SegmentInfo si = segmentInfos.info(i); count += si.docCount; } return count; } /** The maximum number of terms that will be indexed for a single field in a document. This limits the amount of memory required for indexing, so that collections with very large files will not crash the indexing process by running out of memory. <p>By default, no more than 10,000 terms will be indexed for a field. */ public int maxFieldLength = 10000; /** Adds a document to this index.*/ public final void addDocument(Document doc) throws IOException { DocumentWriter dw = new DocumentWriter(ramDirectory, analyzer, maxFieldLength); String segmentName = newSegmentName(); dw.addDocument(segmentName, doc); synchronized (this) { segmentInfos.addElement(new SegmentInfo(segmentName, 1, ramDirectory)); maybeMergeSegments(); } } private final synchronized String newSegmentName() { return "_" + Integer.toString(segmentInfos.counter++, Character.MAX_RADIX); } /** Determines how often segment indexes are merged by addDocument(). With * smaller values, less RAM is used while indexing, and searches on * unoptimized indexes are faster, but indexing speed is slower. With larger * values more RAM is used while indexing and searches on unoptimized indexes * are slower, but indexing is faster. Thus larger values (> 10) are best * for batched index creation, and smaller values (< 10) for indexes that are * interactively maintained. * * <p>This must never be less than 2. The default value is 10.*/ public int mergeFactor = 10; /** Determines the largest number of documents ever merged by addDocument(). * Small values (e.g., less than 10,000) are best for interactive indexing, * as this limits the length of pauses while indexing to a few seconds. * Larger values are best for batched indexing and speedier searches. * * <p>The default value is {@link Integer#MAX_VALUE}. */ public int maxMergeDocs = Integer.MAX_VALUE; /** If non-null, information about merges will be printed to this. */ public PrintStream infoStream = null; /** Merges all segments together into a single segment, optimizing an index for search. */ public final synchronized void optimize() throws IOException { flushRamSegments(); while (segmentInfos.size() > 1 || (segmentInfos.size() == 1 && (SegmentReader.hasDeletions(segmentInfos.info(0)) || segmentInfos.info(0).dir != directory))) { int minSegment = segmentInfos.size() - mergeFactor; mergeSegments(minSegment < 0 ? 0 : minSegment); } } public final synchronized void addIndexes(Directory[] dirs) throws IOException { optimize(); // start with zero or 1 seg for (int i = 0; i < dirs.length; i++) { SegmentInfos sis = new SegmentInfos(); // read infos from dir sis.read(dirs[i]); for (int j = 0; j < sis.size(); j++) { segmentInfos.addElement(sis.info(j)); // add each info } } optimize(); // final cleanup } /** Merges all RAM-resident segments. */ private final void flushRamSegments() throws IOException { int minSegment = segmentInfos.size()-1; int docCount = 0; while (minSegment >= 0 && (segmentInfos.info(minSegment)).dir == ramDirectory) { docCount += segmentInfos.info(minSegment).docCount; minSegment } if (minSegment < 0 || // add one FS segment? (docCount + segmentInfos.info(minSegment).docCount) > mergeFactor || !(segmentInfos.info(segmentInfos.size()-1).dir == ramDirectory)) minSegment++; if (minSegment >= segmentInfos.size()) return; // none to merge mergeSegments(minSegment); } /** Incremental segment merger. */ private final void maybeMergeSegments() throws IOException { long targetMergeDocs = mergeFactor; while (targetMergeDocs <= maxMergeDocs) { // find segments smaller than current target size int minSegment = segmentInfos.size(); int mergeDocs = 0; while (--minSegment >= 0) { SegmentInfo si = segmentInfos.info(minSegment); if (si.docCount >= targetMergeDocs) break; mergeDocs += si.docCount; } if (mergeDocs >= targetMergeDocs) // found a merge to do mergeSegments(minSegment+1); else break; targetMergeDocs *= mergeFactor; // increase target size } } /** Pops segments off of segmentInfos stack down to minSegment, merges them, and pushes the merged index onto the top of the segmentInfos stack. */ private final void mergeSegments(int minSegment) throws IOException { String mergedName = newSegmentName(); int mergedDocCount = 0; if (infoStream != null) infoStream.print("merging segments"); SegmentMerger merger = new SegmentMerger(directory, mergedName); final Vector segmentsToDelete = new Vector(); for (int i = minSegment; i < segmentInfos.size(); i++) { SegmentInfo si = segmentInfos.info(i); if (infoStream != null) infoStream.print(" " + si.name + " (" + si.docCount + " docs)"); SegmentReader reader = new SegmentReader(si); merger.add(reader); if ((reader.directory == this.directory) || // if we own the directory (reader.directory == this.ramDirectory)) segmentsToDelete.addElement(reader); // queue segment for deletion mergedDocCount += si.docCount; } if (infoStream != null) { infoStream.println(); infoStream.println(" into "+mergedName+" ("+mergedDocCount+" docs)"); } merger.merge(); segmentInfos.setSize(minSegment); // pop old infos & add new segmentInfos.addElement(new SegmentInfo(mergedName, mergedDocCount, directory)); synchronized (directory) { // in- & inter-process sync new Lock.With(directory.makeLock("commit.lock")) { public Object doBody() throws IOException { segmentInfos.write(directory); // commit before deleting deleteSegments(segmentsToDelete); // delete now-unused segments return null; } }.run(); } } /* Some operating systems (e.g. Windows) don't permit a file to be deleted while it is opened for read (e.g. by another process or thread). So we assume that when a delete fails it is because the file is open in another process, and queue the file for subsequent deletion. */ private final void deleteSegments(Vector segments) throws IOException { Vector deletable = new Vector(); deleteFiles(readDeleteableFiles(), deletable); // try to delete deleteable for (int i = 0; i < segments.size(); i++) { SegmentReader reader = (SegmentReader)segments.elementAt(i); if (reader.directory == this.directory) deleteFiles(reader.files(), deletable); // try to delete our files else deleteFiles(reader.files(), reader.directory); // delete, eg, RAM files } writeDeleteableFiles(deletable); // note files we can't delete } private final void deleteFiles(Vector files, Directory directory) throws IOException { for (int i = 0; i < files.size(); i++) directory.deleteFile((String)files.elementAt(i)); } private final void deleteFiles(Vector files, Vector deletable) throws IOException { for (int i = 0; i < files.size(); i++) { String file = (String)files.elementAt(i); try { directory.deleteFile(file); // try to delete each file } catch (IOException e) { // if delete fails if (directory.fileExists(file)) { if (infoStream != null) infoStream.println(e.getMessage() + "; Will re-try later."); deletable.addElement(file); // add to deletable } } } } private final Vector readDeleteableFiles() throws IOException { Vector result = new Vector(); if (!directory.fileExists("deletable")) return result; InputStream input = directory.openFile("deletable"); try { for (int i = input.readInt(); i > 0; i--) // read file names result.addElement(input.readString()); } finally { input.close(); } return result; } private final void writeDeleteableFiles(Vector files) throws IOException { OutputStream output = directory.createFile("deleteable.new"); try { output.writeInt(files.size()); for (int i = 0; i < files.size(); i++) output.writeString((String)files.elementAt(i)); } finally { output.close(); } directory.renameFile("deleteable.new", "deletable"); } }
package org.knowm.xchange.bithumb.dto.marketdata; import static org.assertj.core.api.Assertions.assertThat; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.util.List; import org.junit.Test; import org.knowm.xchange.bithumb.BithumbAdapters; import org.knowm.xchange.bithumb.BithumbAdaptersTest; import org.knowm.xchange.bithumb.dto.BithumbResponse; import org.knowm.xchange.currency.Currency; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order; import org.knowm.xchange.dto.marketdata.Trade; public class BithumbMarketDataTest { private ObjectMapper mapper = new ObjectMapper(); @Test public void testUnmarshallTicker() throws IOException { final InputStream is = BithumbMarketDataTest.class.getResourceAsStream( "/org/knowm/xchange/bithumb/dto/marketdata/example-ticker.json"); final BithumbTicker bithumbTicker = mapper.readValue(is, BithumbTicker.class); assertThat(bithumbTicker.getOpeningPrice()).isEqualTo("151300"); assertThat(bithumbTicker.getClosingPrice()).isEqualTo("168900"); assertThat(bithumbTicker.getMinPrice()).isEqualTo("148600"); assertThat(bithumbTicker.getMaxPrice()).isEqualTo("171600"); assertThat(bithumbTicker.getAveragePrice()).isEqualTo("161373.9643"); assertThat(bithumbTicker.getUnitsTraded()).isEqualTo("294028.02849871"); assertThat(bithumbTicker.getVolume1day()).isEqualTo("294028.02849871"); assertThat(bithumbTicker.getVolume7day()).isEqualTo("1276650.256763659925784183"); assertThat(bithumbTicker.getBuyPrice()).isEqualTo("168800"); assertThat(bithumbTicker.getSellPrice()).isEqualTo("168900"); assertThat(bithumbTicker.get_24HFluctate()).isEqualTo("17600"); assertThat(bithumbTicker.get_24HFluctateRate()).isEqualTo("11.63"); assertThat(bithumbTicker.getDate()).isEqualTo(1546440237614L); } @Test public void testUnmarshallTickers() throws IOException { // given final InputStream is = BithumbMarketDataTest.class.getResourceAsStream( "/org/knowm/xchange/bithumb/dto/marketdata/all-ticker-data.json"); // when final BithumbTickersReturn bithumbTickers = mapper.readValue(is, BithumbTickersReturn.class); // then assertThat(bithumbTickers.getTickers()).hasSize(3); assertThat(bithumbTickers.getTickers()).containsKeys("BTC", "ETH", "DASH"); final BithumbTicker btc = bithumbTickers.getTickers().get("BTC"); assertThat(btc.getOpeningPrice()).isEqualTo(BigDecimal.valueOf(4185000L)); assertThat(btc.getClosingPrice()).isEqualTo(BigDecimal.valueOf(4297000L)); assertThat(btc.getMinPrice()).isEqualTo(BigDecimal.valueOf(4137000L)); assertThat(btc.getMaxPrice()).isEqualTo(BigDecimal.valueOf(4328000L)); assertThat(btc.getAveragePrice()).isEqualTo(BigDecimal.valueOf(4252435.9159)); assertThat(btc.getUnitsTraded()).isEqualTo(BigDecimal.valueOf(3815.4174696)); assertThat(btc.getVolume1day()).isEqualTo(BigDecimal.valueOf(3815.4174696)); assertThat(btc.getVolume7day()).isEqualTo(BigDecimal.valueOf(31223.31245306)); assertThat(btc.getBuyPrice()).isEqualTo(BigDecimal.valueOf(4296000)); assertThat(btc.getSellPrice()).isEqualTo(BigDecimal.valueOf(4297000)); assertThat(btc.get_24HFluctate()).isEqualTo(BigDecimal.valueOf(112000)); assertThat(btc.get_24HFluctateRate()).isEqualTo(BigDecimal.valueOf(2.67)); assertThat(btc.getDate()).isEqualTo(1546440191110L); } @Test public void testUnmarshallOrderbook() throws IOException { final InputStream is = BithumbMarketDataTest.class.getResourceAsStream( "/org/knowm/xchange/bithumb/dto/marketdata/example-orderbook.json"); final BithumbOrderbook bithumbOrderbook = mapper.readValue(is, BithumbOrderbook.class); assertThat(bithumbOrderbook.getPaymentCurrency()).isEqualTo("KRW"); assertThat(bithumbOrderbook.getOrderCurrency()).isEqualTo("ETH"); final List<BithumbOrderbookEntry> bids = bithumbOrderbook.getBids(); final List<BithumbOrderbookEntry> asks = bithumbOrderbook.getAsks(); assertThat(bids.size()).isEqualTo(2); assertThat(bids.get(0).getQuantity()).isEqualTo("28.0241"); assertThat(bids.get(0).getPrice()).isEqualTo("168400"); assertThat(asks.size()).isEqualTo(2); assertThat(asks.get(0).getQuantity()).isEqualTo("49.5577"); assertThat(asks.get(0).getPrice()).isEqualTo("168500"); } @Test public void testUnmarshallOrderbookAll() throws IOException { final InputStream is = BithumbMarketDataTest.class.getResourceAsStream( "/org/knowm/xchange/bithumb/dto/marketdata/example-orderbook-all.json"); final BithumbOrderbookAll bithumbOrderbook = mapper.readValue(is, BithumbOrderbookAll.class); assertThat(bithumbOrderbook.getPaymentCurrency()).isEqualTo("KRW"); assertThat(bithumbOrderbook.getTimestamp()).isEqualTo(1547301204217L); assertThat(bithumbOrderbook.getAdditionalProperties().size()).isEqualTo(2); assertThat(bithumbOrderbook.getAdditionalProperties()).containsKeys("BTC", "ETH"); } @Test public void testAdaptTransactionHistory() throws IOException { // given InputStream is = BithumbAdaptersTest.class.getResourceAsStream( "/org/knowm/xchange/bithumb/dto/marketdata/example-transaction-history.json"); final BithumbResponse<List<BithumbTransactionHistory>> transactionHistory = mapper.readValue( is, new TypeReference<BithumbResponse<List<BithumbTransactionHistory>>>() {}); assertThat(transactionHistory.getData().size()).isEqualTo(3); // when final Trade trade = BithumbAdapters.adaptTransactionHistory( transactionHistory.getData().get(0), CurrencyPair.BTC_KRW); // then assertThat(trade.getType()).isEqualTo(Order.OrderType.BID); assertThat(trade.getOriginalAmount()).isEqualTo(new BigDecimal("1.0")); assertThat(trade.getCurrencyPair()).isEqualTo(new CurrencyPair(Currency.BTC, Currency.KRW)); assertThat(trade.getPrice()).isEqualTo(BigDecimal.valueOf(6779000)); assertThat(trade.getTimestamp()).isNotNull(); assertThat(trade.getId()).isNotNull(); } }
package org.objectweb.proactive.examples.jmx; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import javax.management.MBeanAttributeInfo; import javax.management.ObjectName; import org.objectweb.proactive.extensions.jmx.ProActiveConnection; import org.objectweb.proactive.extensions.jmx.client.ClientConnector; /** * This example connects remotely a MBean Server and shows informations * about the operating system (such as the OS name, the OS version, ...) * @author ProActive Team */ public class ShowOS { private ClientConnector cc; private ProActiveConnection connection; private String url; public ShowOS() throws Exception { System.out.println("Enter the url of the JMX MBean Server :"); this.url = read(); connect(); infos(); System.out.println("Good Bye!"); System.exit(0); } public static void main(String[] args) throws Exception { new ShowOS(); } private String read() { String what = null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { what = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return what; } private void connect() { System.out.println("Connecting to : " + this.url); this.cc = new ClientConnector(this.url); this.connection = cc.getConnection(); } private void infos() throws Exception { ObjectName name = new ObjectName("java.lang:type=OperatingSystem"); String attribute = ""; System.out.println("Attributes :"); help(name); while (true) { System.out.println("Enter the name of the attribute :"); attribute = read(); if (attribute.equals("help")) { help(name); } else if (attribute.equals("quit")) { return; } else { Object att = this.connection.getAttribute(name, attribute); System.out.println("==> " + att); } } } private void help(ObjectName name) throws Exception { System.out.println("List of attributes :"); MBeanAttributeInfo[] atts = this.connection.getMBeanInfo(name) .getAttributes(); for (int i = 0, size = atts.length; i < size; i++) System.out.println("> " + atts[i].getName()); System.out.println("> help"); System.out.println("> quit"); } }
package fi.vrk.xroad.catalog.collector.actors; import fi.vrk.xroad.catalog.collector.util.ClientTypeUtil; import fi.vrk.xroad.catalog.collector.util.MethodListUtil; import fi.vrk.xroad.catalog.collector.util.XRoadClient; import fi.vrk.xroad.catalog.collector.wsimport.ClientType; import fi.vrk.xroad.catalog.collector.wsimport.XRoadObjectType; import fi.vrk.xroad.catalog.collector.wsimport.XRoadServiceIdentifierType; import fi.vrk.xroad.catalog.persistence.CatalogService; import fi.vrk.xroad.catalog.persistence.entity.Member; import fi.vrk.xroad.catalog.persistence.entity.Service; import fi.vrk.xroad.catalog.persistence.entity.Subsystem; import akka.actor.ActorRef; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; /** * Actor which fetches all clients, and delegates listing * their methods to ListMethodsActors */ @Component @Scope("prototype") @Slf4j public class ListMethodsActor extends XRoadCatalogActor { private static AtomicInteger COUNTER = new AtomicInteger(0); private static boolean organizationsFetched = false; @Value("${xroad-catalog.security-server-host}") private String xroadSecurityServerHost; @Value("${xroad-catalog.xroad-instance}") private String xroadInstance; @Value("${xroad-catalog.member-code}") private String memberCode; @Value("${xroad-catalog.member-class}") private String memberClass; @Value("${xroad-catalog.subsystem-code}") private String subsystemCode; @Value("${xroad-catalog.webservices-endpoint}") private String webservicesEndpoint; @Value("${xroad-catalog.fetch-companies-time-after-hour}") private Integer fetchCompaniesTimeAfterHour; @Value("${xroad-catalog.fetch-companies-time-before-hour}") private Integer fetchCompaniesTimeBeforeHour; @Value("${xroad-catalog.fetch-companies-run-unlimited}") private Boolean fetchCompaniesUnlimited; @Value("${xroad-catalog.error-log-length-in-days}") private Integer errorLogLengthInDays; @Value("${xroad-catalog.flush-log-time-after-hour}") private Integer flushLogTimeAfterHour; @Value("${xroad-catalog.flush-log-time-before-hour}") private Integer flushLogTimeBeforeHour; @Autowired protected CatalogService catalogService; // supervisor-created pool of list methods actors private ActorRef fetchWsdlPoolRef; private ActorRef fetchOpenApiPoolRef; private ActorRef fetchOrganizationsPoolRef; private ActorRef fetchCompaniesPoolRef; private XRoadClient xroadClient; public ListMethodsActor(ActorRef fetchWsdlPoolRef, ActorRef fetchOpenApiPoolRef, ActorRef fetchOrganizationsPoolRef, ActorRef fetchCompaniesPoolRef) { this.fetchWsdlPoolRef = fetchWsdlPoolRef; this.fetchOpenApiPoolRef = fetchOpenApiPoolRef; this.fetchOrganizationsPoolRef = fetchOrganizationsPoolRef; this.fetchCompaniesPoolRef = fetchCompaniesPoolRef; } @Override public void preStart() throws Exception { xroadClient = new XRoadClient( ClientTypeUtil.toSubsystem(xroadInstance, memberClass, memberCode, subsystemCode), new URL(webservicesEndpoint)); } @Override protected boolean handleMessage(Object message) { if (message instanceof ClientType) { log.info("{} onReceive {}", COUNTER.addAndGet(1), this.hashCode()); ClientType clientType = (ClientType) message; // Fetch organizations only once, not for each client if (!organizationsFetched) { fetchOrganizationsPoolRef.tell(clientType, getSelf()); organizationsFetched = true; } // Fetch companies only during a limited period if not unlimited if (MethodListUtil.shouldFetchCompanies(fetchCompaniesUnlimited, fetchCompaniesTimeAfterHour, fetchCompaniesTimeBeforeHour)) { fetchCompaniesPoolRef.tell(clientType, getSelf()); } // Flush errorLog entries only during a limited period if (MethodListUtil.shouldFlushLogEntries(flushLogTimeAfterHour, flushLogTimeBeforeHour)) { catalogService.deleteOldErrorLogEntries(errorLogLengthInDays); } if (XRoadObjectType.SUBSYSTEM.equals(clientType.getId().getObjectType())) { Subsystem subsystem = new Subsystem( new Member(clientType.getId().getXRoadInstance(), clientType.getId().getMemberClass(), clientType.getId().getMemberCode(), clientType.getName()), clientType.getId().getSubsystemCode()); log.info("{} Handling subsystem {} ", COUNTER, subsystem); List<XRoadServiceIdentifierType> restServices = MethodListUtil.methodListFromResponse(clientType, xroadSecurityServerHost, catalogService); log.info("Received all REST methods for client {} ", ClientTypeUtil.toString(clientType)); // fetch the methods //List<XRoadServiceIdentifierType> soapServices = xroadClient.getMethods(clientType.getId()); //log.info("Received all SOAP methods for client {} ", ClientTypeUtil.toString(clientType)); // Save services for subsystems List<Service> services = new ArrayList<>(); for (XRoadServiceIdentifierType service : restServices) { services.add(new Service(subsystem, service.getServiceCode(), service.getServiceVersion())); } //for (XRoadServiceIdentifierType service : soapServices) { // services.add(new Service(subsystem, service.getServiceCode(), service.getServiceVersion())); catalogService.saveServices(subsystem.createKey(), services); // get wsdls //for (XRoadServiceIdentifierType service : soapServices) { // fetchWsdlPoolRef.tell(service, getSender()); // get openApis for (XRoadServiceIdentifierType service : restServices) { fetchOpenApiPoolRef.tell(service, getSender()); } } return true; } else { return false; } } }
package org.apache.velocity.runtime; import java.io.InputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URL; import java.net.MalformedURLException; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.Hashtable; import java.util.Properties; import java.util.Stack; import java.util.Enumeration; import java.util.TreeMap; import java.util.Vector; import org.apache.log.LogKit; import org.apache.log.Logger; import org.apache.log.LogTarget; import org.apache.log.Formater; import org.apache.log.output.FileOutputLogTarget; import org.apache.velocity.runtime.log.VelocityFormater; import org.apache.velocity.Template; import org.apache.velocity.runtime.parser.Parser; import org.apache.velocity.runtime.parser.ParseException; import org.apache.velocity.runtime.parser.node.SimpleNode; import org.apache.velocity.runtime.loader.TemplateFactory; import org.apache.velocity.runtime.loader.TemplateLoader; import org.apache.velocity.runtime.directive.Foreach; import org.apache.velocity.runtime.directive.Dummy; import org.apache.velocity.runtime.directive.Include; import org.apache.velocity.runtime.directive.Parse; import org.apache.velocity.runtime.directive.Macro; import org.apache.velocity.runtime.directive.Directive; import org.apache.velocity.runtime.VelocimacroFactory; import org.apache.velocity.util.SimplePool; import org.apache.velocity.util.StringUtils; import org.apache.velocity.runtime.configuration.VelocityResources; /** * This is the Runtime system for Velocity. It is the * single access point for all functionality in Velocity. * It adheres to the mediator pattern and is the only * structure that developers need to be familiar with * in order to get Velocity to perform. * * <pre> * Runtime.init(properties); * * Template template = Runtime.getTemplate("template.vm"); * * Runtime.warn(message); * Runtime.info(message); * Runtime.error(message); * Runtime.debug(message); * </pre> * * The Runtime will also cooperate with external * systems like Turbine. Normally the Runtime will * be fully initialized from a properties file, but * certain phases of initialization can be delayed * if vital pieces of information are provided by * an external system. * * Turbine for example knows where the templates * are to be loaded from, and where the velocity * log file should be placed. * * In order for this to happen the velocity.properties * file must look something like the following: * * runtime.log = system * template.path = system * * Having these properties set to 'system' lets the * Velocity Runtime know that an external system * will set these properties and initialized * the appropriates sub systems when these properties * are set. * * So in the case of Velocity cooperating with Turbine * the code might look something like the following: * * <pre> * Runtime.setProperty(Runtime.RUNTIME_LOG, pathToVelocityLog); * Runtime.initializeLogger(); * * Runtime.setProperty(Runtime.TEMPLATE_PATH, pathToTemplates); * Runtime.initializeTemplateLoader(); * </pre> * * It is simply a matter of setting the appropriate property * an initializing the matching sub system. * * @author <a href="mailto:jvanzyl@periapt.com">Jason van Zyl</a> * @author <a href="mailto:jlb@houseofdistraction.com">Jeff Bowden</a> * @author <a href="mailto:geirm@optonline.net">Geir Magusson Jr.</a> * @version $Id: Runtime.java,v 1.58 2000/11/28 00:10:05 jvanzyl Exp $ */ public class Runtime implements RuntimeConstants { /** Prefix for warning messages */ private final static String WARN = " [warn] "; /** Prefix for info messages */ private final static String INFO = " [info] "; /** Prefix for debug messages */ private final static String DEBUG = " [debug] "; /** Prefix for error messages */ private final static String ERROR = " [error] "; /** Turn Runtime debugging on with this field */ private final static boolean DEBUG_ON = true; /** Default Runtime properties */ private final static String DEFAULT_RUNTIME_PROPERTIES = "org/apache/velocity/runtime/defaults/velocity.properties"; /** Default Runtime properties */ private final static String DEFAULT_RUNTIME_DIRECTIVES = "org/apache/velocity/runtime/defaults/directive.properties"; /** Include paths property used by Runtime for #included content */ private final static String INCLUDE_PATHS = "include.path"; /** * Number of parsers to create */ private static final int NUMBER_OF_PARSERS = 20; /** * VelocimacroFactory object to manage VMs */ private static VelocimacroFactory vmFactory_ = new VelocimacroFactory(); /** A list of paths that we can pull static content from. */ private static String[] includePaths; /** The Runtime logger */ private static Logger logger; /** TemplateLoader used by the Runtime */ private static TemplateLoader templateLoader; /** The caching system used by the Velocity Runtime */ //private static GlobalCache globalCache; private static Hashtable globalCache; /** * The List of templateLoaders that the Runtime will * use to locate the InputStream source of a template. */ private static List templateLoaders; /** * The Runtime parser. This has to be changed to * a pool of parsers! */ private static SimplePool parserPool; /** Indicate whether the Runtime has been fully initialized */ private static boolean initialized; private static boolean initializedPublic = false; /** * The logging systems initialization may be defered if * it is to be initialized by an external system. There * may be messages that need to be stored until the * logger is instantiated. They will be stored here * until the logger is alive. */ private static Vector pendingMessages = new Vector(); /** * This is a list of the template stream source * initializers, basically properties for a particular * template stream source. The order in this list * reflects numbering of the properties i.e. * template.loader.1.<property> = <value> * template.loader.2.<property> = <value> */ private static List sourceInitializerList; /** * This is a map of public name of the template * stream source to it's initializer. This is so * that clients of velocity can set properties of * a template source stream with its public name. * So for example, a client could set the * File.template.path property and this would * change the template.path property for the * file template stream source. */ private static Map sourceInitializerMap; private static boolean sourceInitializersAssembled = false; /** * This is a hashtable of initialized directives. * The directives that populate this hashtable are * taken from the RUNTIME_DEFAULT_DIRECTIVES * property file. This hashtable is passed * to each parser that is created. */ private static Hashtable runtimeDirectives; /** * Initializes the Velocity Runtime. */ public synchronized static void init( Properties p ) throws Exception { if (initializedPublic) return; /* * set the default properties, and don't call assembleSourceInitializers() */ setDefaultProperties( false); /* * now add the new ones from the calling app */ if (p != null) addPropertiesFromProperties( p ); /* * now call init to do the real work */ init(); initializedPublic = true; } public synchronized static void init(String propertiesFileName) throws Exception { /* * if we have been initialized fully, don't do it again */ if (initializedPublic) return; /* * new way. Start by loading the default properties to have a hopefully complete * base of properties to work from. * then load the local properties to layover the default ones. This should make * life easy for users. */ setDefaultProperties( false ); /* * if we were passed propertis, try loading propertiesFile as a straight file first, * if that fails, then try and use the classpath */ if (propertiesFileName != null && !propertiesFileName.equals("")) { File file = new File(propertiesFileName); try { if( file.exists() ) { FileInputStream is = new FileInputStream( file ); addPropertiesFromStream( is, propertiesFileName ); } else { info ("Override Properties : " + file.getPath() + " not found. Looking in classpath."); /* * lets try the classpath */ ClassLoader classLoader = Runtime.class.getClassLoader(); InputStream inputStream = classLoader.getResourceAsStream( propertiesFileName ); if (inputStream!= null) addPropertiesFromStream( inputStream, propertiesFileName ); else info ("Override Properties : " + propertiesFileName + " not found in classpath."); } } catch (Exception ex) { error("Exception finding properties " + propertiesFileName + " : " + ex); } } /* * now call init to do the real work */ init(); initializedPublic = true; } /** * adds / replaces properties in VelocityResources from a stream. */ private static boolean addPropertiesFromStream( InputStream is, String sourceName ) throws Exception { if( is == null) return false; /* * lets load the properties, and then iterate them out */ Properties p = new Properties(); p.load( is ); info ("Override Properties : " + sourceName ); return addPropertiesFromProperties( p ); } /** * adds / replaces properties in VelocityResources from a properties object. */ private static boolean addPropertiesFromProperties( Properties p ) throws Exception { if( p == null) return false; /* * iterate them out */ for (Enumeration e = p.keys(); e.hasMoreElements() ; ) { String s = (String) e.nextElement(); VelocityResources.setProperty( s, p.getProperty(s) ); info (" ** Property Override : " + s + " = " + p.getProperty(s)); } return true; } /* * This is the primary initialization method in the Velocity * Runtime. The systems that are setup/initialized here are * as follows: * * <ul> * <li>Logging System</li> * <li>Template Sources</li> * <li>Parser Pool</li> * <li>Global Cache</li> * <li>Static Content Include System</li> * <li>Velocimacro System</li> * </ul> */ public synchronized static void init() throws Exception { if (! initialized) { try { initializeLogger(); initializeTemplateLoader(); initializeDirectives(); initializeParserPool(); initializeGlobalCache(); initializeIncludePaths(); /* * initialize the VM Factory. It will use the properties * accessable from Runtime, so keep this here at the end. */ vmFactory_.initVelocimacro(); info("Velocity successfully started."); initialized = true; } catch (Exception e) { System.out.println(e); e.printStackTrace(); } } } /** * Allow an external mechanism to set the properties for * Velocity Runtime. This is being use right now by Turbine. * There is a standard velocity properties file that is * employed by Turbine/Velocity apps, but certain properties * like the location of log file, and the template path * must be set by Turbine because the location of the * log file, and the template path are based on * the location of the context root. * * So common properties can be set with a standard properties * file, then certain properties can be changed before * the Velocity Runtime is initialized. */ public static void setProperties(String propertiesFileName) throws Exception { /* * Try loading propertiesFile as a straight file first, * if that fails, then try and use the classpath, if * that fails then use the default values. */ try { VelocityResources.setPropertiesFileName( propertiesFileName ); assembleSourceInitializers(); info ("Properties File: " + new File(propertiesFileName).getAbsolutePath()); } catch(Exception ex) { ClassLoader classLoader = Runtime.class.getClassLoader(); InputStream inputStream = classLoader.getResourceAsStream(propertiesFileName); if (inputStream != null) { VelocityResources.setPropertiesInputStream( inputStream ); assembleSourceInitializers(); info ("Properties File: " + new File(propertiesFileName).getAbsolutePath()); } else throw new Exception("Cannot find " + propertiesFileName + "!"); } } /** * Initializes the Velocity Runtime with properties file. * The properties file may be in the file system proper, * or the properties file may be in the classpath. */ public static void setDefaultProperties() { setDefaultProperties( true ); } private static void setDefaultProperties( boolean doAssoc) { ClassLoader classLoader = Runtime.class.getClassLoader(); try { InputStream inputStream = classLoader.getResourceAsStream( DEFAULT_RUNTIME_PROPERTIES ); VelocityResources.setPropertiesInputStream( inputStream ); if (doAssoc) assembleSourceInitializers(); info ("Default Properties File: " + new File(DEFAULT_RUNTIME_PROPERTIES).getPath()); } catch (IOException ioe) { System.err.println("Cannot get Velocity Runtime default properties!"); } } /** * Allows an external system to set a property in * the Velocity Runtime. */ public static void setProperty(String key, String value) { VelocityResources.setProperty( key, value ); } /** * Initialize the Velocity logging system. */ private static void initializeLogger() throws MalformedURLException { /* * Let's look at the log file entry and * correct it if it is not a property * fomratted URL. */ String logFile = VelocityResources.getString(RUNTIME_LOG); /* * Initialize the logger. */ logger = LogKit.createLogger("velocity", fileToURL(logFile), "DEBUG"); LogTarget[] t = logger.getLogTargets(); ((FileOutputLogTarget)t[0]) .setFormater((Formater) new VelocityFormater()); ((FileOutputLogTarget)t[0]) .setFormat("%{time} %{message}\\n%{throwable}" ); if ( !pendingMessages.isEmpty()) { /* * iterate and log each individual message... */ for( Enumeration e = pendingMessages.elements(); e.hasMoreElements(); ) logger.info( (String) e.nextElement()); } Runtime.info("Log file being used is: " + new File(logFile).getAbsolutePath()); } /** * This was borrowed form xml-fop. Convert a file * name into a string that represents a well-formed * URL. * * d:\path\to\logfile * file://d:/path/to/logfile * * NOTE: this is a total hack-a-roo! This should * be dealt with in the org.apache.log package. Client * packages should not have to mess around making * properly formed URLs when log files are almost * always going to be specified with file paths! */ private static String fileToURL(String filename) throws MalformedURLException { File file = new File(filename); String path = file.getAbsolutePath(); String fSep = System.getProperty("file.separator"); if (fSep != null && fSep.length() == 1) path = "file://" + path.replace(fSep.charAt(0), '/'); return path; } /** * Initialize the template loader if there * is a real path set for the template.path * property. Otherwise defer initialization * of the template loader because it is going * to be set by some external mechanism: Turbine * for example. */ private static void initializeTemplateLoader() throws Exception { if(!sourceInitializersAssembled) assembleSourceInitializers(); templateLoaders = new ArrayList(); for (int i = 0; i < sourceInitializerList.size(); i++) { Map initializer = (Map) sourceInitializerList.get(i); String loaderClass = (String) initializer.get("class"); templateLoader = TemplateFactory.getLoader(loaderClass); templateLoader.init(initializer); templateLoaders.add(templateLoader); } } /** * This will produce a List of Hashtables, each * hashtable contains the intialization info for * a particular template loader. This Hastable * will be passed in when initializing the * the template loader. */ private static void assembleSourceInitializers() { sourceInitializerList = new ArrayList(); sourceInitializerMap = new Hashtable(); for (int i = 0; i < 10; i++) { String loaderID = "template.loader." + new Integer(i).toString(); Enumeration e = VelocityResources.getKeys(loaderID); if (!e.hasMoreElements()) continue; Hashtable sourceInitializer = new Hashtable(); while (e.hasMoreElements()) { String property = (String) e.nextElement(); String value = VelocityResources.getString(property); property = property.substring(loaderID.length() + 1); sourceInitializer.put(property, value); /* * Make a Map of the public names for the sources * to the sources property identifier so that external * clients can set source properties. For example: * File.template.path would get translated into * template.loader.1.template.path and the translated * name would be used to set the property. */ if (property.equals("public.name")) sourceInitializerMap.put(value, sourceInitializer); } sourceInitializerList.add(sourceInitializer); sourceInitializersAssembled = true; } } /** * This methods initializes all the directives * that are used by the Velocity Runtime. The * directives to be initialized are listed in * the RUNTIME_DEFAULT_DIRECTIVES properties * file. */ private static void initializeDirectives() throws Exception { /* * Initialize the runtime directive table. * This will be used for creating parsers. */ runtimeDirectives = new Hashtable(); Properties directiveProperties = new Properties(); /* * Grab the properties file with the list of directives * that we should initialize. */ ClassLoader classLoader = Runtime.class.getClassLoader(); InputStream inputStream = classLoader .getResourceAsStream(DEFAULT_RUNTIME_DIRECTIVES); directiveProperties.load(inputStream); /* * Grab all the values of the properties. These * are all class names for example: * * org.apache.velocity.runtime.directive.Foreach * */ Enumeration directiveClasses = directiveProperties.elements(); while (directiveClasses.hasMoreElements()) { String directiveClass = (String) directiveClasses.nextElement(); try { /* * Attempt to instantiate the directive class. This * should usually happen without error because the * properties file that lists the directives is * not visible. It's in a package that isn't * readily accessible. * * After the directive is instantiated, use * reflection to grab the values of the name and * type fields as they have been defined in the * individual directive. * * After the name and type are nabbed, then * set them. */ Class clazz = Class.forName(directiveClass); Directive directive = (Directive) clazz.newInstance(); String name = (String) clazz .getField(Directive.NAME_FIELD).get(directive); directive.setName(name); directive.setType(clazz.getField(Directive.TYPE_FIELD) .getInt(directive)); runtimeDirectives.put(name, directive); Runtime.info("Loaded Pluggable Directive: " + directiveClass); } catch (Exception e) { Runtime.error("Error Loading Pluggable Directive: " + directiveClass); } } } /** * Allow clients of Velocity to set a template stream * source property before the template source streams * are initialized. This would for example allow clients * to set the template path that would be used by the * file template stream source. Right now these properties * have to be set before the template stream source is * initialized. Maybe we should allow these properties * to be changed on the fly. */ public static void setSourceProperty(String key, String value) { String publicName = key.substring(0, key.indexOf(".")); String property = key.substring(key.indexOf(".") + 1); ((Map)sourceInitializerMap.get(publicName)).put(property, value); } /** * Initializes the Velocity parser pool. * This still needs to be implemented. */ private static void initializeParserPool() { parserPool = new SimplePool(NUMBER_OF_PARSERS); for (int i=0;i<NUMBER_OF_PARSERS ;i++ ) { parserPool.put (createNewParser()); } Runtime.info ("Created: " + NUMBER_OF_PARSERS + " parsers."); } /** * Returns a parser */ public static Parser createNewParser() { Parser parser = new Parser(); /* Hashtable directives = new Hashtable(); directives.put("foreach", new Foreach()); directives.put("dummy", new Dummy()); directives.put("include", new Include() ); directives.put("parse", new Parse() ); directives.put("macro", new Macro() ); */ parser.setDirectives(runtimeDirectives); return parser; } /** * Parse the input stream and return the root of * AST node structure. */ public static SimpleNode parse(InputStream inputStream) throws ParseException { SimpleNode AST = null; Parser parser = (Parser) parserPool.get(); if (parser != null) { AST = parser.parse(inputStream); parserPool.put(parser); return AST; } else error("Runtime : ran out of parsers!"); return null; } /** * Initialize the global cache use by the Velocity * runtime. Cached templates will be stored here, * as well as cached content pulled in by the #include * directive. Who knows what else we'll find to * cache. */ private static void initializeGlobalCache() { //globalCache = new GlobalCache(); globalCache = new Hashtable(); } private static void initializeIncludePaths() { includePaths = VelocityResources.getStringArray(INCLUDE_PATHS); } public static String[] getIncludePaths() { return includePaths; } /** * Set an object in the global cache for * subsequent use. */ public static void setCacheObject(String key, Object object) { globalCache.put(key,object); } /** * Get an object from the cache. * * Hmm. Getting an object requires catching * an ObjectExpiredException, but how can we do * this without tying ourselves to the to * the caching system? */ public static Object getCacheObject(String key) { try { return globalCache.get(key); } catch (Exception e) { /* * This is an ObjectExpiredException, but * I don't want to try the structure of the * caching system to the Runtime. */ return null; } } /** * Get a template via the TemplateLoader. */ public static Template getTemplate(String template) throws Exception { InputStream is = null; Template t= null; TemplateLoader tl = null; /* * Check to see if the template was placed in the cache. * If it was placed in the cache then we will use * the cached version of the template. If not we * will load it. */ if (globalCache.containsKey(template)) { t = (Template) globalCache.get(template); tl = t.getTemplateLoader(); /* * The template knows whether it needs to be checked * or not, and the template's loader can check to * see if the source has been modified. If both * these conditions are true then we must reload * the input stream and parse it to make a new * AST for the template. */ if (t.requiresChecking() && tl.isSourceModified(t)) { try { is = tl.getTemplateStream(template); t.setDocument(parse(is)); return t; } catch (Exception e) { error(e); } } return t; } else { try { t = new Template(); t.setName(template); /* * Now we have to try to find the appropriate * loader for this template. We have to cycle through * the list of available template loaders and see * which one gives us a stream that we can use to * make a template with. */ for (int i = 0; i < templateLoaders.size(); i++) { tl = (TemplateLoader) templateLoaders.get(i); is = tl.getTemplateStream(template); /* * If we get an InputStream then we have found * our loader. */ if (is != null) break; } /* * Return null if we can't find a template. */ if (is == null) throw new Exception("Can't find " + template + "!"); t.setLastModified(tl.getLastModified(t)); t.setModificationCheckInterval(tl.getModificationCheckInterval()); t.setTemplateLoader(tl); t.setDocument(parse(is)); t.touch(); /* * Place the template in the cache if the template * loader says to. */ if (tl.useCache()) globalCache.put(template, t); } catch (Exception e) { error(e); } } return t; } private static void log(String message) { if (logger != null) logger.info(message); else pendingMessages.addElement(message); } /** Log a warning message */ public static void warn(Object message) { String out = null; if ( getBoolean(RUNTIME_LOG_WARN_STACKTRACE, false) && (message instanceof Throwable || message instanceof Exception) ) out = StringUtils.stackTrace((Throwable)message); else out = message.toString(); log(WARN + out); } /** Log an info message */ public static void info(Object message) { String out = null; if ( getBoolean(RUNTIME_LOG_INFO_STACKTRACE, false) && ( message instanceof Throwable || message instanceof Exception) ) out = StringUtils.stackTrace((Throwable)message); else out = message.toString(); log(INFO + out); } /** Log an error message */ public static void error(Object message) { String out = null; if ( getBoolean(RUNTIME_LOG_ERROR_STACKTRACE, false) && ( message instanceof Throwable || message instanceof Exception ) ) out = StringUtils.stackTrace((Throwable)message); else out = message.toString(); log(ERROR + out); } /** Log a debug message */ public static void debug(Object message) { if (DEBUG_ON) log(DEBUG + message.toString()); } public static void main(String[] args) throws Exception { System.out.println(fileToURL(args[0])); } /** * String property accessor method with defaultto hide the VelocityResources implementation * @param strKey property key * @param strDefault default value to return if key not found in resource manager * @return String value of key or default */ public static String getString( String strKey, String strDefault) { return VelocityResources.getString(strKey, strDefault); } /** * returns the appropriate VelocimacroProxy object if strVMname * is a valid current Velocimacro * * @param strVMName Name of velocimacro requested * @return VelocimacroProxy */ public static Directive getVelocimacro( String strVMName ) { return vmFactory_.getVelocimacro( strVMName ); } public static boolean addVelocimacro( String strName, String strMacro, String strArgArray[], String strMacroArray[], TreeMap tmArgIndexMap ) { return vmFactory_.addVelocimacro( strName, strMacro, strArgArray, strMacroArray, tmArgIndexMap); } /** * Checks to see if a VM exists * * @param strName Name of velocimacro * @return boolean True if VM by that name exists, false if not */ public static boolean isVelocimacro( String strVMName ) { return vmFactory_.isVelocimacro( strVMName ); } /** * String property accessor method to hide the VelocityResources implementation * @param strKey property key * @return value of key or null */ public static String getString( String strKey) { return VelocityResources.getString( strKey ); } /** * int property accessor method to hide the VelocityResources implementation * @param strKey property key * @return int alue */ public static int getInt( String strKey ) { return VelocityResources.getInt( strKey ); } /** * boolean property accessor method to hide the VelocityResources implementation * @param strKey property key * @param default default value if property not found * @return boolean value of key or default value */ public static boolean getBoolean( String strKey, boolean def ) { return VelocityResources.getBoolean( strKey, def ); } }
package org.gameon.map.filter; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Duration; import java.time.Instant; import java.time.format.DateTimeParseException; import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import javax.annotation.Resource; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import javax.inject.Inject; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ReadListener; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; @WebFilter( filterName = "mapAuthFilter", /** CDI injection of client for Player CRUD operations */ /** * We need to hash the request body.. which is read via an input stream that can only be read once * so if we need to read it, then we need to keep hold of it so the client servlet can read it too. * Thus we use a ServletRequestWrapper.. */ public static class ServletAuthWrapper extends HttpServletRequestWrapper{ private final HttpServletRequest req; private final String body; public ServletAuthWrapper (HttpServletRequest req) throws IOException{ super(req); this.req = req; try (BufferedReader buffer = new BufferedReader( new InputStreamReader(req.getInputStream(),"UTF-8"))) { body = buffer.lines().collect(Collectors.joining("\n")); } } public String getId(){ return req.getHeader("gameon-id"); } public String getDate(){ return req.getHeader("gameon-date"); } public String getSigBody(){ return req.getHeader("gameon-sig-body"); } public String getSignature(){ return req.getHeader("gameon-signature"); } public String getBody(){ return body; } @Override public ServletInputStream getInputStream() throws IOException { final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes("UTF-8")); ServletInputStream inputStream = new ServletInputStream() { public int read () throws IOException { return byteArrayInputStream.read(); } @Override public boolean isFinished() { return byteArrayInputStream.available()==0; } @Override public boolean isReady() { return true; } @Override public void setReadListener(ReadListener readListener) { throw new RuntimeException("Not implemented"); } }; return inputStream; } } private String buildHmac(List<String> stuffToHash, String key) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException{ Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256")); StringBuffer hashData = new StringBuffer(); for(String s: stuffToHash){ hashData.append(s); } return Base64.getEncoder().encodeToString( mac.doFinal(hashData.toString().getBytes("UTF-8")) ); } private String buildHash(String data) throws NoSuchAlgorithmException, UnsupportedEncodingException{ MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(data.getBytes("UTF-8")); byte[] digest = md.digest(); return Base64.getEncoder().encodeToString( digest ); } /** * Timestamped Key * Equality / Hashcode is determined by key string alone. * Sort order is provided by key timestamp. */ private final static class TimestampedKey implements Comparable<TimestampedKey> { private final String apiKey; private final Long time; public TimestampedKey(String a){ this.apiKey=a; this.time=System.currentTimeMillis(); } public TimestampedKey(String a,Long t){ this.apiKey=a; this.time=t; } @Override public int compareTo(TimestampedKey o) { return o.time.compareTo(time); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((apiKey == null) ? 0 : apiKey.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TimestampedKey other = (TimestampedKey) obj; if (apiKey == null) { if (other.apiKey != null) return false; } else if (!apiKey.equals(other.apiKey)) return false; return true; } } /** * Obtain the apiKey for the given id, using a local cache to avoid hitting couchdb too much. */ private String getKeyForId(String id){ //first.. handle our built-in key if("game-on.org".equals(id)){ return registrationSecret; } String key = null; //check cache for this id. TimestampedKey t = apiKeyForId.get(id); if(t!=null){ //cache hit, but is the key still valid? long current = System.currentTimeMillis(); current -= t.time; //if the key is older than this time period.. we'll consider it dead. boolean valid = current < TimeUnit.DAYS.toMillis(1); if(valid){ //key is good.. we'll use it. System.out.println("Map using cached key for "+id); key = t.apiKey; }else{ //key has expired.. forget it. System.out.println("Map expired cached key for "+id); apiKeyForId.remove(id); t=null; } } if(t == null){ //key was not in cache, or was expired.. //go obtain the apiKey via player Rest endpoint. try{ System.out.println("Map asking player service for key for id "+id); key = playerClient.getApiKey(id); }catch(Exception e){ System.out.println("Map unable to get key for id "+id); e.printStackTrace(); key=null; } //got a key ? add it to the cache. if(key!=null){ t = new TimestampedKey(key); apiKeyForId.put(id, t); } } return key; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if(request instanceof HttpServletRequest){ HttpServletRequest httpRequest = (HttpServletRequest)request; String requestUri = httpRequest.getRequestURI(); System.out.println("Evaluating uri of "+requestUri); if(requestUri.startsWith("/map/v1/health")){ System.out.println("No auth needed for health"); //no auth needed for health. chain.doFilter(request, response); return; } if(requestUri.startsWith("/map/v1/sites")){ //auth needed for sites endpoints. ServletAuthWrapper saw = new ServletAuthWrapper(httpRequest); String id = saw.getId(); if ( id == null ) id = "game-on.org"; String gameonDate = saw.getDate(); try{ //we protect Map, and our requirements vary per http method switch(httpRequest.getMethod()){ case "GET":{ //if there's no auth.. we continue but set id to null. if(saw.getId() == null){ id = null; }else{ if(!validateHeaderBasedAuth(response, saw, id, gameonDate, false)){ return; } } break; } case "POST":{ if(!validateHeaderBasedAuth(response, saw, id, gameonDate, true)){ return; } break; } case "DELETE":{ if(!validateHeaderBasedAuth(response, saw, id, gameonDate, false)){ return; } return; } case "PUT":{ if(!validateHeaderBasedAuth(response, saw, id, gameonDate, true)){ return; } return; } default:{ ((HttpServletResponse)response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unsupported Http Method "+httpRequest.getMethod()); return; } } }catch(UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException e){ e.printStackTrace(); ((HttpServletResponse)response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error processing headers "+e.getMessage()); return; } request.setAttribute("player.id", id); //pass our request wrapper to the chain.. NOT the original request, because we may have //already burnt the input stream by reading it to hash the body. chain.doFilter(saw, response); return; } ((HttpServletResponse)response).sendError(HttpServletResponse.SC_FORBIDDEN, "Request made to unknown url pattern. "+httpRequest.getRequestURI()); }else{ ((HttpServletResponse)response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Only supports http servlet requests"); } } private boolean validateHeaderBasedAuth(ServletResponse response, ServletAuthWrapper saw, String id, String gameonDate, boolean postData) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException, IOException { String secret = getKeyForId(id); if(secret == null){ ((HttpServletResponse)response).sendError(HttpServletResponse.SC_FORBIDDEN,"Unable to obtain shared secret for player "+id+" from player service"); return false; } String body = postData ? saw.getBody() : ""; String bodyHash = postData ? buildHash(body) : ""; String bodyHashHeader = postData ? saw.getSigBody() : ""; if(bodyHash!=null && bodyHash.equals(bodyHashHeader)){ String hmac = buildHmac(Arrays.asList( new String[] { id,gameonDate,bodyHashHeader} ), secret); String hmacHeader = saw.getSignature(); if(hmac!=null && hmac.equals(hmacHeader)){ Instant now = Instant.now(); Instant then = Instant.parse(gameonDate); try{ if(Duration.between(now,then).toMillis() > 5000){ //fail.. time delta too much. ((HttpServletResponse)response).sendError(HttpServletResponse.SC_FORBIDDEN,"Time delta of "+Duration.between(now,then).toMillis()+"ms is too great."); return false; }else{ //TODO: add replay check.. //otherwise.. we're done here.. auth is good, we'll come out the switch //and pass control to the original method. return true; } }catch(DateTimeParseException e){ ((HttpServletResponse)response).sendError(HttpServletResponse.SC_FORBIDDEN,"Unable to parse gameon-date header"); return false; } }else{ System.out.println("Had hmac "+hmacHeader+" and calculated "+hmac+" using key(first2chars) "+secret.substring(0, 2)+" for id "+id); ((HttpServletResponse)response).sendError(HttpServletResponse.SC_FORBIDDEN,"Had hmac "+hmacHeader+" and calculated (first 4chars) "+hmac.substring(0,4)+" using key(first2chars) "+secret.substring(0, 2)+" for id "+id); return false; } }else{ ((HttpServletResponse)response).sendError(HttpServletResponse.SC_FORBIDDEN,"Bad gameon-sig-body value"); return false; } } @Override public void destroy() { } }
package org.apache.velocity.runtime; import java.io.InputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URL; import java.net.MalformedURLException; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.Hashtable; import java.util.Properties; import java.util.Stack; import java.util.Enumeration; import java.util.TreeMap; import java.util.Vector; import org.apache.log.Logger; import org.apache.velocity.Template; import org.apache.velocity.runtime.log.LogManager; import org.apache.velocity.runtime.parser.Parser; import org.apache.velocity.runtime.parser.ParseException; import org.apache.velocity.runtime.parser.node.SimpleNode; import org.apache.velocity.runtime.directive.Directive; import org.apache.velocity.runtime.VelocimacroFactory; import org.apache.velocity.runtime.resource.Resource; import org.apache.velocity.runtime.resource.ContentResource; import org.apache.velocity.runtime.resource.ResourceManager; import org.apache.velocity.util.SimplePool; import org.apache.velocity.util.StringUtils; import org.apache.velocity.runtime.configuration.VelocityResources; public class Runtime implements RuntimeConstants { /** * VelocimacroFactory object to manage VMs */ private static VelocimacroFactory vmFactory = new VelocimacroFactory(); /** The Runtime logger */ private static Logger logger; /** The caching system used by the Velocity Runtime */ private static Hashtable globalCache; /** The Runtime parser pool */ private static SimplePool parserPool; /** Indicate whether the Runtime has been fully initialized */ private static boolean initialized; private static Properties overridingProperties = null; /** * The logging systems initialization may be defered if * it is to be initialized by an external system. There * may be messages that need to be stored until the * logger is instantiated. They will be stored here * until the logger is alive. */ private static Vector pendingMessages = new Vector(); /** * This is a hashtable of initialized directives. * The directives that populate this hashtable are * taken from the RUNTIME_DEFAULT_DIRECTIVES * property file. This hashtable is passed * to each parser that is created. */ private static Hashtable runtimeDirectives; /* * This is the primary initialization method in the Velocity * Runtime. The systems that are setup/initialized here are * as follows: * * <ul> * <li>Logging System</li> * <li>ResourceManager</li> * <li>Parser Pool</li> * <li>Global Cache</li> * <li>Static Content Include System</li> * <li>Velocimacro System</li> * </ul> */ public synchronized static void init() throws Exception { if (initialized == false) { try { initializeProperties(); initializeLogger(); ResourceManager.initialize(); initializeDirectives(); initializeParserPool(); initializeGlobalCache(); /* * initialize the VM Factory. It will use the properties * accessable from Runtime, so keep this here at the end. */ vmFactory.initVelocimacro(); info("Velocity successfully started."); initialized = true; } catch (Exception e) { System.out.println(e); e.printStackTrace(); } } } /** * Initializes the Velocity Runtime. */ public synchronized static void init( Properties props ) throws Exception { overridingProperties = props; init(); } public synchronized static void init( String props ) throws Exception { setProperties(props); init(); } /** * Allow an external mechanism to set the properties for * Velocity Runtime. This is being use right now by Turbine. * There is a standard velocity properties file that is * employed by Turbine/Velocity apps, but certain properties * like the location of log file, and the template path * must be set by Turbine because the location of the * log file, and the template path are based on * the location of the context root. * * So common properties can be set with a standard properties * file, then certain properties can be changed before * the Velocity Runtime is initialized. */ public synchronized static void setProperties(String propertiesFileName) throws Exception { /* * Set the default properties because client apps are * using the: * * 1) Runtime.setProperties(); * 2) Runtime.setProperty() | Runtime.setSourceProperty() * 3) Runtime.init(); * * Sequence and the default props have to be present * in order for 2) to work. */ setDefaultProperties(); Properties p = new Properties(); /* * if we were passed propertis, try loading propertiesFile as a straight file first, * if that fails, then try and use the classpath */ if (propertiesFileName != null && !propertiesFileName.equals("")) { File file = new File(propertiesFileName); try { if( file.exists() ) { FileInputStream is = new FileInputStream( file ); p.load(is); } else { info ("Override Properties : " + file.getPath() + " not found. Looking in classpath."); /* * lets try the classpath */ ClassLoader classLoader = Runtime.class.getClassLoader(); InputStream inputStream = classLoader .getResourceAsStream( propertiesFileName ); if (inputStream!= null) { p.load(inputStream); } else { info ("Override Properties : " + propertiesFileName + " not found in classpath."); } } } catch (Exception ex) { error("Exception finding properties " + propertiesFileName + " : " + ex); } } overridingProperties = p; } /** * Initializes the Velocity Runtime with properties file. * The properties file may be in the file system proper, * or the properties file may be in the classpath. */ public static void setDefaultProperties() { ClassLoader classLoader = Runtime.class.getClassLoader(); try { InputStream inputStream = classLoader .getResourceAsStream( DEFAULT_RUNTIME_PROPERTIES ); VelocityResources.setPropertiesInputStream( inputStream ); info ("Default Properties File: " + new File(DEFAULT_RUNTIME_PROPERTIES).getPath()); } catch (IOException ioe) { System.err.println("Cannot get Velocity Runtime default properties!"); } } /** * Allows an external system to set a property in * the Velocity Runtime. */ public static void setProperty(String key, String value) { if (overridingProperties == null) overridingProperties = new Properties(); overridingProperties.setProperty( key, value ); } private static void initializeProperties() { /* * Always lay down the default properties first as * to provide a solid base. */ if (VelocityResources.isInitialized() == false) setDefaultProperties(); if( overridingProperties != null) { /* Override each default property specified */ for (Enumeration e = overridingProperties.keys(); e.hasMoreElements() ; ) { String s = (String) e.nextElement(); VelocityResources.setProperty( s, overridingProperties.getProperty(s) ); info (" ** Property Override : " + s + " = " + overridingProperties.getProperty(s)); } } } /** * Initialize the Velocity logging system. */ private static void initializeLogger() throws Exception { /* * Grab the log file entry from the velocity * properties file. */ String logFile = VelocityResources.getString(RUNTIME_LOG); /* * Initialize the logger. We will eventually move all * logging into the logging manager. */ logger = LogManager.createLogger(logFile); if ( !pendingMessages.isEmpty()) { /* * iterate and log each individual message... */ for( Enumeration e = pendingMessages.elements(); e.hasMoreElements(); ) { logger.info( (String) e.nextElement()); } } Runtime.info("Log file being used is: " + new File(logFile).getAbsolutePath()); } /** * This methods initializes all the directives * that are used by the Velocity Runtime. The * directives to be initialized are listed in * the RUNTIME_DEFAULT_DIRECTIVES properties * file. */ private static void initializeDirectives() throws Exception { /* * Initialize the runtime directive table. * This will be used for creating parsers. */ runtimeDirectives = new Hashtable(); Properties directiveProperties = new Properties(); /* * Grab the properties file with the list of directives * that we should initialize. */ ClassLoader classLoader = Runtime.class.getClassLoader(); InputStream inputStream = classLoader .getResourceAsStream(DEFAULT_RUNTIME_DIRECTIVES); if (inputStream == null) throw new Exception("Error loading directive.properties! " + "Something is very wrong if these properties " + "aren't being located. Either your Velocity " + "distribution is incomplete or your Velocity " + "jar file is corrupted!"); directiveProperties.load(inputStream); /* * Grab all the values of the properties. These * are all class names for example: * * org.apache.velocity.runtime.directive.Foreach */ Enumeration directiveClasses = directiveProperties.elements(); while (directiveClasses.hasMoreElements()) { String directiveClass = (String) directiveClasses.nextElement(); try { /* * Attempt to instantiate the directive class. This * should usually happen without error because the * properties file that lists the directives is * not visible. It's in a package that isn't * readily accessible. * */ Class clazz = Class.forName(directiveClass); Directive directive = (Directive) clazz.newInstance(); runtimeDirectives.put(directive.getName(), directive); Runtime.info("Loaded Pluggable Directive: " + directiveClass); } catch (Exception e) { Runtime.error("Error Loading Pluggable Directive: " + directiveClass); } } } /** * Allow clients of Velocity to set a template stream * source property before the template source streams * are initialized. This would for example allow clients * to set the template path that would be used by the * file template stream source. Right now these properties * have to be set before the template stream source is * initialized. Maybe we should allow these properties * to be changed on the fly. */ public static void setSourceProperty(String key, String value) { info (" ** !!! Resource Loader Property Override : " + key + " = " + value); ResourceManager.setSourceProperty(key, value); } /** * Initializes the Velocity parser pool. * This still needs to be implemented. */ private static void initializeParserPool() { parserPool = new SimplePool(NUMBER_OF_PARSERS); for (int i=0;i<NUMBER_OF_PARSERS ;i++ ) { parserPool.put (createNewParser()); } Runtime.info ("Created: " + NUMBER_OF_PARSERS + " parsers."); } /** * Returns a parser */ public static Parser createNewParser() { Parser parser = new Parser(); parser.setDirectives(runtimeDirectives); return parser; } /** * Parse the input stream and return the root of * AST node structure. */ public static SimpleNode parse(InputStream inputStream, String strTemplateName ) throws ParseException { SimpleNode ast = null; Parser parser = (Parser) parserPool.get(); if (parser != null) { try { ast = parser.parse(inputStream, strTemplateName); } finally { parserPool.put(parser); } } else { error("Runtime : ran out of parsers!"); } return ast; } /** * Initialize the global cache use by the Velocity * runtime. Cached templates will be stored here, * as well as cached content pulled in by the #include * directive. Who knows what else we'll find to * cache. */ private static void initializeGlobalCache() { //globalCache = new GlobalCache(); globalCache = new Hashtable(); } /** * Set an object in the global cache for * subsequent use. */ public static void setCacheObject(String key, Object object) { globalCache.put(key,object); } /** * Get an object from the cache. * * Hmm. Getting an object requires catching * an ObjectExpiredException, but how can we do * this without tying ourselves to the to * the caching system? */ public static Object getCacheObject(String key) { try { return globalCache.get(key); } catch (Exception e) { /* * This is an ObjectExpiredException, but * I don't want to try the structure of the * caching system to the Runtime. */ return null; } } /** * Returns a Template from the resource manager */ public static Template getTemplate(String name) throws Exception { return (Template) ResourceManager .getResource(name,ResourceManager.RESOURCE_TEMPLATE); } /** * Returns a static content resource from the * resource manager. */ public static ContentResource getContent(String name) throws Exception { return (ContentResource) ResourceManager .getResource(name,ResourceManager.RESOURCE_CONTENT); } /** * Handle logging */ private static void log(String message) { if (logger != null) { logger.info(message); } else { pendingMessages.addElement(message); } } /** * Added this to check and make sure that the VelocityResources * is initialized before trying to get properties from it. * This occurs when there are errors during initialization * and the default properties have yet to be layed down. */ private static boolean showStackTrace() { if (VelocityResources.isInitialized()) return getBoolean(RUNTIME_LOG_WARN_STACKTRACE, false); else return false; } /** * Log a warning message */ public static void warn(Object message) { String out = null; if ( showStackTrace() && (message instanceof Throwable || message instanceof Exception) ) { out = StringUtils.stackTrace((Throwable)message); } else { out = message.toString(); } log(WARN + out); } /** Log an info message */ public static void info(Object message) { String out = null; if ( showStackTrace() && ( message instanceof Throwable || message instanceof Exception) ) { out = StringUtils.stackTrace((Throwable)message); } else { out = message.toString(); } log(INFO + out); } /** * Log an error message */ public static void error(Object message) { String out = null; if ( showStackTrace() && ( message instanceof Throwable || message instanceof Exception ) ) { out = StringUtils.stackTrace((Throwable)message); } else { out = message.toString(); } log(ERROR + out); } /** * Log a debug message */ public static void debug(Object message) { if (DEBUG_ON) { log(DEBUG + message.toString()); } } /** * String property accessor method with defaultto hide the VelocityResources implementation * @param strKey property key * @param strDefault default value to return if key not found in resource manager * @return String value of key or default */ public static String getString( String strKey, String strDefault) { return VelocityResources.getString(strKey, strDefault); } /** * returns the appropriate VelocimacroProxy object if strVMname * is a valid current Velocimacro * * @param strVMName Name of velocimacro requested * @return VelocimacroProxy */ public static Directive getVelocimacro( String strVMName, String strTemplateName ) { return vmFactory.getVelocimacro( strVMName, strTemplateName ); } public static boolean addVelocimacro( String strName, String strMacro, String strArgArray[], String strMacroArray[], TreeMap tmArgIndexMap, String strSourceTemplate ) { return vmFactory.addVelocimacro( strName, strMacro, strArgArray, strMacroArray, tmArgIndexMap, strSourceTemplate); } /** * Checks to see if a VM exists * * @param strName Name of velocimacro * @return boolean True if VM by that name exists, false if not */ public static boolean isVelocimacro( String strVMName, String strTemplateName ) { return vmFactory.isVelocimacro( strVMName, strTemplateName ); } /** * tells the vmFactory to dump the specified namespace. This is to support * clearing the VM list when in inline-VM-local-scope mode */ public static boolean dumpVMNamespace( String strNamespace ) { return vmFactory.dumpVMNamespace( strNamespace ); } /** * String property accessor method to hide the VelocityResources implementation * @param strKey property key * @return value of key or null */ public static String getString(String key) { return VelocityResources.getString( key ); } /** * int property accessor method to hide the VelocityResources implementation * @param strKey property key * @return int alue */ public static int getInt( String strKey ) { return VelocityResources.getInt( strKey ); } public static int getInt( String strKey, int defaultValue ) { return VelocityResources.getInt( strKey, defaultValue ); } /** * boolean property accessor method to hide the VelocityResources implementation * @param strKey property key * @param default default value if property not found * @return boolean value of key or default value */ public static boolean getBoolean( String strKey, boolean def ) { return VelocityResources.getBoolean( strKey, def ); } }
package org.apache.velocity.runtime; import java.io.InputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URL; import java.net.MalformedURLException; import java.util.Hashtable; import java.util.Properties; import org.apache.log.LogKit; import org.apache.log.Logger; import org.apache.log.LogTarget; import org.apache.log.Formater; import org.apache.log.output.FileOutputLogTarget; import org.apache.velocity.runtime.log.VelocityFormater; import org.apache.velocity.Template; import org.apache.velocity.runtime.parser.Parser; import org.apache.velocity.runtime.parser.ParseException; import org.apache.velocity.runtime.parser.node.SimpleNode; import org.apache.velocity.runtime.loader.TemplateFactory; import org.apache.velocity.runtime.loader.TemplateLoader; import org.apache.velocity.runtime.directive.Foreach; import org.apache.velocity.runtime.directive.Dummy; import org.apache.velocity.util.*; import org.apache.velocity.runtime.configuration.VelocityResources; /** * This is the Runtime system for Velocity. It is the * single access point for all functionality in Velocity. * It adheres to the mediator pattern and is the only * structure that developers need to be familiar with * in order to get Velocity to perform. * * <pre> * Runtime.init(properties); * * Template template = Runtime.getTemplate("template.vm"); * * Runtime.warn(message); * Runtime.info(message); * Runtime.error(message); * Runtime.debug(message); * </pre> * * The Runtime will also cooperate with external * systems like Turbine. Normally the Runtime will * be fully initialized from a properties file, but * certain phases of initialization can be delayed * if vital pieces of information are provided by * an external system. * * Turbine for example knows where the templates * are to be loaded from, and where the velocity * log file should be placed. * * In order for this to happen the velocity.properties * file must look something like the following: * * runtime.log = system * template.path = system * * Having these properties set to 'system' lets the * Velocity Runtime know that an external system * will set these properties and initialized * the appropriates sub systems when these properties * are set. * * So in the case of Velocity cooperating with Turbine * the code might look something like the following: * * <pre> * Runtime.setProperty(Runtime.RUNTIME_LOG, pathToVelocityLog); * Runtime.initializeLogger(); * * Runtime.setProperty(Runtime.TEMPLATE_PATH, pathToTemplates); * Runtime.initializeTemplateLoader(); * </pre> * * It is simply a matter of setting the appropriate property * an initializing the matching sub system. * * @author <a href="mailto:jvanzyl@periapt.com">Jason van Zyl</a> * @author <a href="mailto:jlb@houseofdistraction.com">Jeff Bowden</a> * @version $Id: Runtime.java,v 1.30 2000/11/02 13:40:44 geirm Exp $ */ public class Runtime { /** Location of the log file */ public static final String RUNTIME_LOG = "runtime.log"; /** Location of templates */ public static final String TEMPLATE_PATH = "template.path"; /** Template loader to be used */ public static final String TEMPLATE_LOADER = "template.loader"; /** Specify template caching true/false */ public static final String TEMPLATE_CACHE = "template.cache"; /** The encoding to use for the template */ public static final String TEMPLATE_ENCODING = "template.encoding"; /** Enable the speed up provided by FastWriter */ public static final String TEMPLATE_ASCIIHACK = "template.asciihack"; /** How often to check for modified templates. */ public static final String TEMPLATE_MOD_CHECK_INTERVAL = "template.modificationCheckInterval"; /** Initial counter value in #foreach directives */ public static final String COUNTER_NAME = "counter.name"; /** Initial counter value in #foreach directives */ public static final String COUNTER_INITIAL_VALUE = "counter.initial.value"; /** Content type */ public static final String DEFAULT_CONTENT_TYPE = "default.contentType"; /** Prefix for warning messages */ private final static String WARN = " [warn] "; /** Prefix for info messages */ private final static String INFO = " [info] "; /** Prefix for debug messages */ private final static String DEBUG = " [debug] "; /** Prefix for error messages */ private final static String ERROR = " [error] "; /** TemplateLoader used by the Runtime */ private static TemplateLoader templateLoader; /** Turn Runtime debugging on with this field */ private final static boolean DEBUG_ON = true; /** Default Runtime properties */ private final static String DEFAULT_RUNTIME_PROPERTIES = "org/apache/velocity/runtime/defaults/velocity.properties"; /** The Runtime logger */ private static Logger logger; /** * The Runtime parser. This has to be changed to * a pool of parsers! */ private static Parser parser; /** Indicate whether the Runtime has been fully initialized */ private static boolean initialized; /** * The logging systems initialization may be defered if * it is to be initialized by an external system. There * may be messages that need to be stored until the * logger is instantiated. They will be stored here * until the logger is alive. */ private static StringBuffer pendingMessages = new StringBuffer(); /** * Get the default properties for the Velocity Runtime. * This would allow the retrieval and modification of * the base properties before initializing the Velocity * Runtime. */ public static void setDefaultProperties() { ClassLoader classLoader = Runtime.class.getClassLoader(); try { InputStream inputStream = classLoader.getResourceAsStream( DEFAULT_RUNTIME_PROPERTIES); VelocityResources.setPropertiesInputStream( inputStream ); } catch (IOException ioe) { System.err.println("Cannot get Velocity Runtime default properties!"); } } /** * Initializes the Velocity Runtime. */ public synchronized static void init(String propertiesFileName) throws Exception { /* * Try loading the properties from the named properties * file. If that fails then set the default values. * From the command line and for testing the default * values should work fine, and makes initializing * the Velocity runtime as easy as Runtime.init(); */ try { VelocityResources.setPropertiesFileName( propertiesFileName ); } catch(Exception ex) { // Do Default setDefaultProperties(); } init(); } public synchronized static void init() throws Exception { if (! initialized) { try { initializeLogger(); initializeTemplateLoader(); initializeParserPool(); info("Velocity successfully started."); initialized = true; } catch (Exception e) { System.out.println(e); e.printStackTrace(); } } } /** * Allows an external system to set a property in * the Velocity Runtime. */ public static void setProperty(String key, String value) { VelocityResources.setProperty( key, value ); } /** * Initialize the Velocity logging system. */ public static void initializeLogger() throws MalformedURLException { if (!getString(RUNTIME_LOG).equals("system")) { // Let's look at the log file entry and // correct it if it is not a property // fomratted URL. String logFile = getString(RUNTIME_LOG); // Initialize the logger. logger = LogKit.createLogger("velocity", fileToURL(logFile), "DEBUG"); LogTarget[] t = logger.getLogTargets(); ((FileOutputLogTarget)t[0]) .setFormater((Formater) new VelocityFormater()); ((FileOutputLogTarget)t[0]) .setFormat("%{time} %{message}\\n%{throwable}" ); if (pendingMessages.length() > 0) { logger.info(pendingMessages.toString()); } Runtime.info("Log file being used is: " + logFile); } } /** * This was borrowed form xml-fop. Convert a file * name into a string that represents a well-formed * URL. * * d:\path\to\logfile * file://d:/path/to/logfile * * NOTE: this is a total hack-a-roo! This should * be dealt with in the org.apache.log package. Client * packages should not have to mess around making * properly formed URLs when log files are almost * always going to be specified with file paths! */ private static String fileToURL(String filename) throws MalformedURLException { File file = new File(filename); String path = file.getAbsolutePath(); String fSep = System.getProperty("file.separator"); if (fSep != null && fSep.length() == 1) path = "file://" + path.replace(fSep.charAt(0), '/'); return path; } /** * Initialize the template loader if there * is a real path set for the template.path * property. Otherwise defer initialization * of the template loader because it is going * to be set by some external mechanism: Turbine * for example. */ public static void initializeTemplateLoader() throws Exception { if (!getString(TEMPLATE_PATH).equals("system")) { templateLoader = TemplateFactory .getLoader(getString(TEMPLATE_LOADER)); templateLoader.init(); } } /** * Initializes the Velocity parser pool. * This still needs to be implemented. */ private static void initializeParserPool() { // put this in a method and make a pool of // parsers. parser = new Parser(); Hashtable directives = new Hashtable(); directives.put("foreach", new Foreach()); directives.put("dummy", new Dummy()); parser.setDirectives(directives); } /** * Parse the input stream and return the root of * AST node structure. */ public synchronized static SimpleNode parse(InputStream inputStream) throws ParseException { return parser.parse(inputStream); } /** * Get a template via the TemplateLoader. */ public static Template getTemplate(String template) { try { return templateLoader.getTemplate(template); } catch (Exception e) { error(e); return null; } } /** * Get a boolean property. */ public static boolean getBoolean(String property) { return VelocityResources.getBoolean( property ); } /** * Get a string property. */ public static String getString(String property) { return VelocityResources.getString( property ); } /** * Get a string property. with a default value */ public static String getString(String property, String defaultValue) { String prop = getString( property ); return (prop == null ? defaultValue : prop); } private static void log(String message) { if (logger != null) logger.info(message); else pendingMessages.append(message); } /** Log a warning message */ public static void warn(Object message) { log(WARN + message.toString()); } /** Log an info message */ public static void info(Object message) { log(INFO + message.toString()); } /** Log an error message */ public static void error(Object message) { log(ERROR + message.toString()); } /** Log a debug message */ public static void debug(Object message) { if (DEBUG_ON) log(DEBUG + message.toString()); } public static void main(String[] args) throws Exception { System.out.println(fileToURL(args[0])); } }
package imagej.ext.plugin; import imagej.ext.AbstractUIDetails; import imagej.ext.Accelerator; import imagej.ext.Instantiable; import imagej.ext.InstantiableException; import imagej.ext.MenuEntry; import imagej.ext.MenuPath; import imagej.util.StringMaker; import java.net.URL; /** * A collection of metadata about a particular plugin. For performance reasons, * the metadata is populated without actually loading the plugin class, by * reading from an efficient binary cache (see {@link PluginService} for * details). As such, ImageJ can very quickly build a complex menu structure * containing all available {@link ImageJPlugin}s without waiting for the Java * class loader. * * @author Curtis Rueden * @see ImageJPlugin * @see Plugin * @see PluginService */ public class PluginInfo<P extends IPlugin> extends AbstractUIDetails implements Instantiable<P> { /** Fully qualified class name of this plugin. */ private String className; /** Class object for this plugin. Lazily loaded. */ private Class<P> pluginClass; /** Type of this entry's plugin; e.g., {@link ImageJPlugin}. */ private Class<P> pluginType; /** Annotation describing the plugin. */ protected Plugin plugin; /** TODO */ public PluginInfo(final String className, final Class<P> pluginType) { setClassName(className); setPluginType(pluginType); setMenuPath(null); setMenuRoot(Plugin.APPLICATION_MENU_ROOT); } /** TODO */ public PluginInfo(final String className, final Class<P> pluginType, final Plugin plugin) { this(className, pluginType); this.plugin = plugin; populateValues(); } // -- PluginInfo methods -- /** Sets the fully qualified name of the {@link Class} of the item objects. */ public void setClassName(final String className) { this.className = className; } /** TODO */ public void setPluginType(final Class<P> pluginType) { this.pluginType = pluginType; } /** TODO */ public Class<P> getPluginType() { return pluginType; } /** * Gets the URL corresponding to the icon resource path. * * @see #getIconPath() */ public URL getIconURL() throws InstantiableException { // See also: imagej.ext.menu.ShadowMenu#getIconURL() final String iconPath = getIconPath(); if (iconPath == null || iconPath.isEmpty()) return null; return loadClass().getResource(iconPath); } /** Gets whether tool is always active, rather than part of the toolbar. */ public boolean isAlwaysActive() { return plugin.alwaysActive(); } /** * Gets whether the tool receives input events when the main application frame * has the focus. */ public boolean isActiveInAppFrame() { return plugin.activeInAppFrame(); } // -- Object methods -- @Override public String toString() { final StringMaker sm = new StringMaker(); sm.append("class", className); sm.append(super.toString()); sm.append("pluginType", pluginType); return sm.toString(); } // -- Instantiable methods -- @Override public String getClassName() { return className; } @Override @SuppressWarnings("unchecked") public Class<P> loadClass() throws InstantiableException { if (pluginClass == null) { final Class<?> c; try { c = Class.forName(className); } catch (final ClassNotFoundException e) { throw new InstantiableException("Class not found: " + className, e); } pluginClass = (Class<P>) c; } return pluginClass; } @Override public P createInstance() throws InstantiableException { final Class<P> c = loadClass(); // instantiate plugin final P instance; try { instance = c.newInstance(); } catch (final InstantiationException e) { throw new InstantiableException(e); } catch (final IllegalAccessException e) { throw new InstantiableException(e); } return instance; } // -- Helper methods -- /** Populates the entry to match the associated @{@link Plugin} annotation. */ private void populateValues() { setName(plugin.name()); setLabel(plugin.label()); setDescription(plugin.description()); final MenuPath menuPath; final Menu[] menu = plugin.menu(); if (menu.length > 0) { menuPath = parseMenuPath(menu); } else { // parse menuPath attribute menuPath = new MenuPath(plugin.menuPath()); } setMenuPath(menuPath); setMenuRoot(plugin.menuRoot()); final String iconPath = plugin.iconPath(); setIconPath(iconPath); setPriority(plugin.priority()); setEnabled(plugin.enabled()); setSelectable(plugin.selectable()); setSelectionGroup(plugin.selectionGroup()); // add default icon if none attached to leaf final MenuEntry menuLeaf = menuPath.getLeaf(); if (menuLeaf != null && !iconPath.isEmpty()) { final String menuIconPath = menuLeaf.getIconPath(); if (menuIconPath == null || menuIconPath.isEmpty()) { menuLeaf.setIconPath(iconPath); } } } private MenuPath parseMenuPath(final Menu[] menu) { final MenuPath menuPath = new MenuPath(); for (int i = 0; i < menu.length; i++) { final String name = menu[i].label(); final double weight = menu[i].weight(); final char mnemonic = menu[i].mnemonic(); final Accelerator acc = Accelerator.create(menu[i].accelerator()); final String iconPath = menu[i].iconPath(); menuPath.add(new MenuEntry(name, weight, mnemonic, acc, iconPath)); } return menuPath; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package leaptest.controller; import com.leapmotion.leap.Controller; import com.leapmotion.leap.Frame; import com.leapmotion.leap.Gesture; import com.leapmotion.leap.GestureList; import com.leapmotion.leap.Hand; import com.leapmotion.leap.SwipeGesture; import com.leapmotion.leap.Vector; import java.util.ArrayList; import leaptest.model.Grid; import leaptest.model.GridCam; /** * * @author Jasper van der Waa & Annet Meijers */ public class GestureRotateControl extends LeapControl { /* * Variables to fine tune what swipe for horizontal rotation is accepted * Duration & location sensitivities should be positive non-zero value. * When == 1 : All swipes rejected * When > 1 : more swipes between user's extremes are accepted * When < 1 : all swipes between user's extremes are accepted and * more (how much more depends on how close to zero the * sensitivity is. CAREFULL WITH THIS! * Example 1: sensitivity=100, then 99% of the preceived RotateSwipes * between the users expected extremes values are accepted. The 1% that is * not accepted are the swipes close to those expected extremes. * Example 2: sensitivity=0.9, then all swipes within the user's extremes are * accepted. PLUS the swipes that are 11% more extreme than the expected * extreme swipes. */ private final double ROTATE_Z_SENSITIVITY = 0.9; private final double ROTATE_DURATION_SENSITIVITY = 0.25; private final double ROTATE_TIME_BETWEEN_SENSITIVITY = 1; private final double ROTATE_PART_SENSITIVITY = 0.5; private final double ROTATE_MIN_ACCEPT_DURATION = 75000; private final double CAMERA_Z_SENSITIVITY = 0.9; private final double CAMERA_DURATION_SENSITIVITY = 0.75; private final double CAMERA_TIME_BETWEEN_SENSITIVITY = 0.5; private final double CAMERA_PART_SENSITIVITY = 0.5; private final double CAMERA_MIN_ACCEPT_DURATION = 75000; /* * Variables that get adjusted over time for a user. * Change the initial values to match more the initial preferences of the * user. */ private double averageZPartialRotateSwipe = 0.0; private double stdevZPartialRotateSwipe = 60; private double averagePartialDurationRotate = 10000; private double stdevPartialDurationRotate = 1000; private double averageDurationRotateSwipe = 200000; private double stdevDurationRotateSwipe = 20000; private double averageZPartialCameraSwipe = 0.0; private double stdevZPartialCameraSwipe = 80; private double averagePartialDurationCamera = 20000; private double stdevPartialDurationCamera = 2000; private double averageDurationCameraSwipe = 200000; private double stdevDurationCameraSwipe = 100000; /* * Variables to fine tune the movement of the grid. */ private double ROTATE_SPEED_INCREASE = 100000; private double CAMERA_SPEED_INCREASE = 70000; private double ROTATE_DECAY_CONSTANT = 0.85; private double CAMERA_DECAY_CONSTANT = 0.65; private double MAX_VELOCITY_ROTATE = 0.25; private double MIN_VELOCITY_ROTATE = 0.001; private double MAX_VELOCITY_CAMERA = 0.025; private double MIN_VELOCITY_CAMERA = 0.0001; private boolean IS_RIGHT_HANDED = false; private boolean INVERT_Y_AXIS_FOR_CAMERA = false; private Frame frame; private Grid grid; private SwipeGesture rotateSwipe; private SwipeGesture cameraSwipe; private GridCam camera; private final double ROTATION_DELTA = Math.PI; private boolean isRotateSwipe; private Vector lastDirectionRotate; private double rotateVelocity; private double summedPartialRotateSwipes; private int nrPartialRotateSwipes; private long timeBetweenRotateSwipes; private double minimalTimeBetweenRotateSwipes; private int nrIntendedRotateSwipes; private boolean isCameraSwipe; private Vector lastDirectionCamera; private double cameraVelocity; private double summedPartialCameraSwipes; private int nrPartialCameraSwipes; private long timeBetweenCameraSwipes; private double minimalTimeBetweenCameraSwipes; private int nrIntendedCameraSwipes; private long timePreviousIntendedRotateSwipe; private int previousRotateID; private long timePreviousIntendedCameraSwipe; private int previousCameraID; private final double ROTATE_Z_SENS_VALUE; private final double ROTATE_DURATION_SENS_VALUE; private final double ROTATE_PART_DURATION_SENS_VALUE; private final double CAMERA_Z_SENS_VALUE; private final double CAMERA_DURATION_SENS_VALUE; private final double CAMERA_PART_DURATION_SENS_VALUE; private final boolean isShowWhyRejected = true; private final boolean isShowSwipeData = true; private final boolean isShowUserVariables = true; private String rejectedOn = ""; public GestureRotateControl(Controller leap, Grid grid, GridCam camera) { super(leap); this.grid = grid; this.camera = camera; isRotateSwipe = false; isCameraSwipe = false; rotateVelocity = 0; cameraVelocity = 0; nrPartialRotateSwipes = 0; nrPartialCameraSwipes = 0; timeBetweenRotateSwipes = 0; timePreviousIntendedRotateSwipe = Long.MAX_VALUE; timeBetweenCameraSwipes = 0; timePreviousIntendedCameraSwipe = Long.MAX_VALUE; minimalTimeBetweenRotateSwipes = calculateMinimalTimeBetweenGestures(averageDurationRotateSwipe, stdevDurationRotateSwipe, ROTATE_TIME_BETWEEN_SENSITIVITY); minimalTimeBetweenCameraSwipes = calculateMinimalTimeBetweenGestures(averageDurationCameraSwipe, stdevDurationCameraSwipe, CAMERA_TIME_BETWEEN_SENSITIVITY); ROTATE_Z_SENS_VALUE = calculateSensitivyValue(ROTATE_Z_SENSITIVITY); ROTATE_DURATION_SENS_VALUE = calculateSensitivyValue(ROTATE_DURATION_SENSITIVITY); CAMERA_Z_SENS_VALUE = calculateSensitivyValue(CAMERA_Z_SENSITIVITY); CAMERA_DURATION_SENS_VALUE = calculateSensitivyValue(CAMERA_DURATION_SENSITIVITY); ROTATE_PART_DURATION_SENS_VALUE = calculateSensitivyValue(ROTATE_PART_SENSITIVITY); CAMERA_PART_DURATION_SENS_VALUE = calculateSensitivyValue(CAMERA_PART_SENSITIVITY); } @Override public void update(float tpf) { if (frame != null) { rotateVelocity = decayVelocity(rotateVelocity); cameraVelocity = decayVelocity(cameraVelocity); double rotateSwipeSpeed = 0.0, cameraSwipeSpeed = 0.0; boolean isIntended = false; if(isSwiped()) { if(isRotateSwipe) { lastDirectionRotate = rotateSwipe.direction(); if(isIntendedAsRotateSwipe(rotateSwipe)) { isIntended = true; timePreviousIntendedRotateSwipe = rotateSwipe.frame().timestamp(); rotateSwipeSpeed = rotateSwipe.speed(); } else { timeBetweenRotateSwipes = Math.abs(timePreviousIntendedRotateSwipe - rotateSwipe.frame().timestamp()); } printDebugData("rotate"); boolean isNewAndIntended = isIntended && rotateSwipe.id() != previousRotateID; calculateUserVariablesForRotate(rotateSwipe, isNewAndIntended); previousRotateID = rotateSwipe.id(); } else { lastDirectionCamera = cameraSwipe.direction(); if(isIntendedAsCameraSwipe(cameraSwipe)) { isIntended = true; timePreviousIntendedCameraSwipe = cameraSwipe.frame().timestamp(); cameraSwipeSpeed = cameraSwipe.speed(); } else { timeBetweenCameraSwipes = Math.abs(timePreviousIntendedCameraSwipe - cameraSwipe.frame().timestamp()); } printDebugData("camera"); boolean isNewAndIntended = isIntended && cameraSwipe.id() != previousCameraID; calculateUserVariablesForCamera(cameraSwipe, isNewAndIntended); previousCameraID = cameraSwipe.id(); } } rotateVelocity = calculateVelocity(rotateSwipeSpeed); cameraVelocity = calculateVelocity(cameraSwipeSpeed); adjustGrid(); } } @Override protected void onFrame(Controller leap) { frame = controller.frame(); } @Override protected void onConnect(Controller leap) { leap.enableGesture(Gesture.Type.TYPE_SWIPE); } @Override protected void onInit(Controller leap) { leap.enableGesture(Gesture.Type.TYPE_SWIPE); } private boolean isSwiped() { SwipeGesture s = getSwipe(); if(isRotateSwipe && s != null) { rotateSwipe = s; return true; } else if(isCameraSwipe && s != null) { cameraSwipe = s; return true; } return false; } private void adjustGrid() { if(isRotateSwipe && rotateVelocity != 0 ) { grid.rotate((float) (ROTATION_DELTA*rotateVelocity)); } else if(isCameraSwipe && cameraVelocity != 0) { if(!INVERT_Y_AXIS_FOR_CAMERA) camera.rotate((float) (ROTATION_DELTA*cameraVelocity)); else camera.rotate((float) (ROTATION_DELTA*cameraVelocity*-1)); } } private SwipeGesture getSwipe() { ArrayList<SwipeGesture> allSwipes = getSwipes(); SwipeGesture aCorrectSwipe = null; if(allSwipes.isEmpty()) return null; else { for(SwipeGesture s : allSwipes) { if(isCorrectSwipe(s)) { aCorrectSwipe = s; } } } return aCorrectSwipe; } private ArrayList<SwipeGesture> getSwipes() { GestureList allGestures = frame.gestures(); ArrayList<SwipeGesture> swipes = new ArrayList(); for(Gesture g : allGestures) { if(g.type() == Gesture.Type.TYPE_SWIPE) { SwipeGesture oneSwipe = new SwipeGesture(g); swipes.add(oneSwipe); } } return swipes; } private boolean isCorrectSwipe(SwipeGesture s) { boolean isCorrectRotateDirection = (Math.abs(s.direction().getX())>Math.abs(s.direction().getY()) && Math.abs(s.direction().getX())>Math.abs(s.direction().getZ())); boolean isCorrectCameraDirection = (Math.abs(s.direction().getY())>Math.abs(s.direction().getZ()) && Math.abs(s.direction().getY())>Math.abs(s.direction().getX())); if(isCorrectRotateDirection) { isRotateSwipe = true; isCameraSwipe = false; if( isDirectionChanged(s) ) timeBetweenRotateSwipes = Math.abs(timePreviousIntendedRotateSwipe - s.frame().timestamp()); } else if(isCorrectCameraDirection) { isCameraSwipe = true; isRotateSwipe = false; if( isDirectionChanged(s) ) timeBetweenCameraSwipes = Math.abs(timePreviousIntendedCameraSwipe - s.frame().timestamp()); } /*boolean isMostRightOrLeftSwipe = (s2 == null) || ((IS_RIGHT_HANDED && s1.startPosition().getX() < s2.startPosition().getX()) || (!IS_RIGHT_HANDED && s1.startPosition().getX() > s2.startPosition().getX())); */ boolean isCorrectHand = false; if(!s.hands().isEmpty()) isCorrectHand = (s.hands().get(0).equals(getRotateHand())); if(!"".equals(rejectedOn)) rejectedOn = ""; if(!isCorrectRotateDirection && !isCorrectCameraDirection) rejectedOn = rejectedOn + " + swipe direction "; if(!isCorrectHand) rejectedOn = rejectedOn + " + left/right hand "; return (isCorrectRotateDirection || isCorrectCameraDirection) && isCorrectHand; //&&is MostRightOrLeftSwipe; } private boolean isIntendedAsRotateSwipe(SwipeGesture s) { boolean isAtRegularSwipePosition = (s.position().getZ() >= (averageZPartialRotateSwipe-ROTATE_Z_SENS_VALUE*stdevZPartialRotateSwipe) && s.position().getZ() <= (averageZPartialRotateSwipe+ROTATE_Z_SENS_VALUE*stdevZPartialRotateSwipe)); boolean isOffRegularSwipeDuration = (s.duration() == 0) || (s.duration() >= (averagePartialDurationRotate-ROTATE_PART_DURATION_SENS_VALUE*stdevPartialDurationRotate) && s.duration() <= (averagePartialDurationRotate+ROTATE_PART_DURATION_SENS_VALUE*stdevPartialDurationRotate)); boolean isFakeSwipe = timeBetweenRotateSwipes < minimalTimeBetweenRotateSwipes; if(!isAtRegularSwipePosition) rejectedOn = rejectedOn + "+ Regular Swipe Position "; if(!isOffRegularSwipeDuration) rejectedOn = rejectedOn + "+ swipe duration "; if(isFakeSwipe) rejectedOn = rejectedOn + "+ time between swipes "; return isAtRegularSwipePosition && isOffRegularSwipeDuration && !isFakeSwipe; } private boolean isIntendedAsCameraSwipe(SwipeGesture s) { boolean isAtRegularSwipePosition = (s.position().getZ() >= (averageZPartialCameraSwipe-CAMERA_Z_SENS_VALUE*stdevZPartialCameraSwipe) && s.position().getZ() <= (averageZPartialCameraSwipe+CAMERA_Z_SENS_VALUE*stdevZPartialCameraSwipe)); boolean isOffRegularSwipeDuration = (s.duration() == 0) || (s.duration() >= (averagePartialDurationCamera-CAMERA_PART_DURATION_SENS_VALUE*stdevPartialDurationCamera) && s.duration() <= (averagePartialDurationCamera+CAMERA_PART_DURATION_SENS_VALUE*stdevPartialDurationCamera)); boolean isFakeSwipe = timeBetweenCameraSwipes < minimalTimeBetweenCameraSwipes; if(!isAtRegularSwipePosition) rejectedOn = rejectedOn + "+ Regular Swipe Position "; if(!isOffRegularSwipeDuration) rejectedOn = rejectedOn + "+ swipe duration"; if(isFakeSwipe) rejectedOn = rejectedOn + "+ time between swipes"; return isAtRegularSwipePosition && isOffRegularSwipeDuration && !isFakeSwipe; } private Hand getRotateHand() { if(IS_RIGHT_HANDED) return frame.hands().leftmost(); else return frame.hands().rightmost(); } private double calculateVelocity(double speed) { double velocity =0.0; if(isRotateSwipe) { if(lastDirectionRotate == null || speed == 0.0) velocity = rotateVelocity; else if(lastDirectionRotate.getX()>0) velocity = rotateVelocity + ((1/frame.currentFramesPerSecond())+(speed/ROTATE_SPEED_INCREASE)); else if(lastDirectionRotate.getX()<0) velocity = rotateVelocity - ((1/frame.currentFramesPerSecond())+(speed/ROTATE_SPEED_INCREASE)); if(Math.abs(velocity) > MAX_VELOCITY_ROTATE ) return Math.signum(velocity)*MAX_VELOCITY_ROTATE; if(Math.abs(velocity) < MIN_VELOCITY_ROTATE ) return 0.0; } else if(isCameraSwipe) { if(lastDirectionCamera == null || speed == 0.0) velocity = cameraVelocity; else if(lastDirectionCamera.getY()>0) velocity = cameraVelocity + ((1/frame.currentFramesPerSecond())+(speed/CAMERA_SPEED_INCREASE)); else if(lastDirectionCamera.getY()<0) velocity = cameraVelocity - ((1/frame.currentFramesPerSecond())+(speed/CAMERA_SPEED_INCREASE)); if(Math.abs(velocity) > MAX_VELOCITY_CAMERA ) return Math.signum(velocity)*MAX_VELOCITY_CAMERA; if(Math.abs(velocity) < MIN_VELOCITY_CAMERA ) return 0.0; } return velocity; } private double decayVelocity(double velocity) { if(isRotateSwipe) return velocity*ROTATE_DECAY_CONSTANT; else if(isCameraSwipe) return velocity*CAMERA_DECAY_CONSTANT; else return 0; } private void calculateUserVariablesForRotate(SwipeGesture rotateSwipe, boolean isNewAndIntended) { nrPartialRotateSwipes++; double previousAverage = averageZPartialRotateSwipe, zCoordinate = rotateSwipe.position().getZ(), duration = rotateSwipe.duration(); averageZPartialRotateSwipe = calculateAverage(averageZPartialRotateSwipe, zCoordinate, nrPartialRotateSwipes); if(nrPartialRotateSwipes > 1) stdevZPartialRotateSwipe = calculateStdev(stdevZPartialRotateSwipe, previousAverage, averageZPartialRotateSwipe, zCoordinate); previousAverage = averagePartialDurationRotate; averagePartialDurationRotate = calculateAverage(averagePartialDurationRotate, duration, nrPartialRotateSwipes); if(nrPartialRotateSwipes > 1) stdevPartialDurationRotate = calculateStdev(stdevPartialDurationRotate, previousAverage, averagePartialDurationRotate, duration); summedPartialRotateSwipes += duration; if(isNewAndIntended) { nrIntendedRotateSwipes++; previousAverage = averageDurationRotateSwipe; averageDurationRotateSwipe = calculateAverage(averageDurationRotateSwipe, summedPartialRotateSwipes, nrIntendedRotateSwipes); if(nrIntendedRotateSwipes > 1) { stdevDurationRotateSwipe = calculateStdev(stdevDurationRotateSwipe, previousAverage, averageDurationRotateSwipe, summedPartialRotateSwipes); } if(averageDurationRotateSwipe < (ROTATE_MIN_ACCEPT_DURATION-ROTATE_DURATION_SENS_VALUE*stdevDurationRotateSwipe)) averageDurationRotateSwipe = ROTATE_MIN_ACCEPT_DURATION; summedPartialRotateSwipes = 0.0; minimalTimeBetweenRotateSwipes = calculateMinimalTimeBetweenGestures(averageDurationRotateSwipe, stdevDurationRotateSwipe, ROTATE_TIME_BETWEEN_SENSITIVITY); } } private void calculateUserVariablesForCamera(SwipeGesture cameraSwipe, boolean isNewAndIntended) { nrPartialCameraSwipes++; double previousAverage = averageZPartialCameraSwipe, zCoordinate = cameraSwipe.position().getZ(), duration = cameraSwipe.duration(); averageZPartialCameraSwipe = calculateAverage(averageZPartialCameraSwipe, zCoordinate, nrPartialCameraSwipes); if(nrPartialCameraSwipes > 1) stdevZPartialCameraSwipe = calculateStdev(stdevZPartialCameraSwipe, previousAverage, averageZPartialCameraSwipe, zCoordinate); previousAverage = averagePartialDurationCamera; averagePartialDurationCamera = calculateAverage(averagePartialDurationCamera, duration, nrPartialCameraSwipes); if(nrPartialCameraSwipes > 1) stdevPartialDurationCamera = calculateStdev(stdevPartialDurationCamera, previousAverage, averagePartialDurationCamera, duration); summedPartialCameraSwipes += duration; if(isNewAndIntended) { nrIntendedCameraSwipes++; previousAverage = averageDurationCameraSwipe; averageDurationCameraSwipe = calculateAverage(averageDurationCameraSwipe, summedPartialCameraSwipes, nrIntendedCameraSwipes); if(nrIntendedCameraSwipes > 1) { stdevDurationCameraSwipe = calculateStdev(stdevDurationCameraSwipe, previousAverage, averageDurationCameraSwipe, summedPartialCameraSwipes); } if(averageDurationCameraSwipe < (CAMERA_MIN_ACCEPT_DURATION-CAMERA_DURATION_SENS_VALUE*stdevDurationCameraSwipe)) averageDurationCameraSwipe = CAMERA_MIN_ACCEPT_DURATION; summedPartialCameraSwipes = 0.0; minimalTimeBetweenCameraSwipes = calculateMinimalTimeBetweenGestures(averageDurationCameraSwipe, stdevDurationCameraSwipe, CAMERA_TIME_BETWEEN_SENSITIVITY); } } private void printDebugData(String swipeType) { if(isShowWhyRejected || isShowUserVariables || isShowSwipeData) System.out.println("\n"); if(!"".equals(rejectedOn) && isShowWhyRejected) System.out.println(swipeType + " Swipe rejected on:\n\t" + rejectedOn); if(isShowUserVariables) { if("rotate".equals(swipeType)) { System.out.println("User variables of a " + swipeType + " swipe:"); System.out.println("\tPart. Duration:\t\t" + averagePartialDurationRotate + " +/- " + stdevPartialDurationRotate*ROTATE_PART_DURATION_SENS_VALUE + "\t\tsensValue = "+ROTATE_PART_DURATION_SENS_VALUE); System.out.println("\tPart. Z coordinate:\t" + averageZPartialRotateSwipe + " +/- " + stdevZPartialRotateSwipe*ROTATE_Z_SENS_VALUE + "\t\tsensValue = "+ROTATE_Z_SENS_VALUE); System.out.println("\tSwipe Duration:\t\t" + averageDurationRotateSwipe + " +/- " + stdevDurationRotateSwipe*ROTATE_DURATION_SENS_VALUE + "\t\tsensValue = "+ROTATE_DURATION_SENS_VALUE); System.out.println("\tMin. Time between:\t" + minimalTimeBetweenRotateSwipes); } else if("camera".equals(swipeType)) { System.out.println("User variables of a " + swipeType + " swipe:"); System.out.println("\tPart. Duration:\t\t" + averagePartialDurationCamera + " +/- " + stdevPartialDurationCamera*CAMERA_PART_DURATION_SENS_VALUE + "\t\tsensValue = "+ CAMERA_PART_DURATION_SENS_VALUE); System.out.println("\tPart. Z coordinate:\t" + averageZPartialCameraSwipe + " +/- " + stdevZPartialCameraSwipe*CAMERA_Z_SENS_VALUE + "\t\tsensValue = "+ CAMERA_Z_SENS_VALUE); System.out.println("\tSwipe Duration:\t\t" + averageDurationCameraSwipe + " +/- " + stdevDurationCameraSwipe*CAMERA_DURATION_SENS_VALUE + "\t\tsensValue = "+ CAMERA_DURATION_SENS_VALUE); System.out.println("\tMin. Time between:\t" + minimalTimeBetweenCameraSwipes); } } if(isShowSwipeData && ((rotateSwipe != null && isRotateSwipe) || (cameraSwipe != null && isCameraSwipe))) { if("rotate".equals(swipeType)) { System.out.println(swipeType + " Swipe data (id:"+ rotateSwipe.id() +"):"); System.out.println("State:\t" + rotateSwipe.state().toString()); System.out.println("\tDirection:\t" + rotateSwipe.direction()); System.out.println("\tDuration:\t" + rotateSwipe.duration()); System.out.println("\tSpeed:\t\t" + rotateSwipe.speed()); System.out.println("\tZ coordinate:\t" + rotateSwipe.position().getZ()); System.out.println("\tTime between:\t" + timeBetweenRotateSwipes); } else if("camera".equals(swipeType)) { System.out.println(swipeType + " Swipe data (id:"+ cameraSwipe.id() +"):"); System.out.println("State:\t" + cameraSwipe.state().toString()); System.out.println("\tDirection:\t" + cameraSwipe.direction()); System.out.println("\tDuration:\t" + cameraSwipe.duration()); System.out.println("\tSpeed:\t\t" + cameraSwipe.speed()); System.out.println("\tZ coordinate:\t" + cameraSwipe.position().getZ()); System.out.println("\tTime between:\t" + timeBetweenCameraSwipes); } } } private double calculateStdev(double stdev, double prevAverage, double average, double x) { return Math.sqrt(stdev+(x-prevAverage)*(x-average)); } private double calculateAverage(double average, double x, int N) { return (x+(N-1)*average)/N; } private double calculateSensitivyValue(double sensitivity) { if(sensitivity > 1) return 1-1/sensitivity; else if(sensitivity == 1) return 0; else if(sensitivity < 1) return Math.abs(1/sensitivity); else { System.exit(1); System.err.println("ERROR: Sensitivity must be a non-zero positive value."); } return -1; } private double calculateMinimalTimeBetweenGestures(double average, double stdev, double sensitivityValue) { //double relativeStdev = stdev/(stdev+average); //return average*relativeStdev*sensitivityValue; return sensitivityValue * (average + stdev); } private boolean isDirectionChanged(SwipeGesture s) { if(isRotateSwipe) { if(lastDirectionRotate == null) return true; return Math.signum(lastDirectionRotate.getX()) != Math.signum(s.direction().getX()); } else if(isCameraSwipe) { if(lastDirectionCamera == null) return true; return Math.signum(lastDirectionCamera.getY()) != Math.signum(s.direction().getY()); } else return false; } }
package de.fu_berlin.cdv.chasingpictures.security; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.KeySpec; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.util.Base64; import android.util.Log; import de.fu_berlin.cdv.chasingpictures.R; public class SecurePreferences { private static final String TAG = "SecurePreferences"; public static class SecurePreferencesException extends RuntimeException { public SecurePreferencesException(Throwable e) { super(e); } } public static final String TRANSFORMATION = "AES/CBC/PKCS5Padding"; private static final String KEY_TRANSFORMATION = "AES/ECB/PKCS5Padding"; private static final String SECRET_KEY_HASH_TRANSFORMATION = "SHA-256"; private static final String CHARSET = "UTF-8"; private final boolean encryptKeys; private final Cipher writer; private final Cipher reader; private final Cipher keyWriter; private final SharedPreferences preferences; /** * Returns an instance with the key and IV stored in the resources of this app. * @param context Application context * @param preferenceNameId Resource ID for preference name. */ public static SecurePreferences getInstanceFromResources(Context context, int preferenceNameId) { SecretKey key = base64DecodeKey(context.getString(R.string.security_KEY)); IvParameterSpec iv = new IvParameterSpec(Base64.decode(context.getString(R.string.security_IV), Base64.DEFAULT)); return new SecurePreferences(context, context.getString(preferenceNameId), key, iv, true); } /** * Returns an instance with the key and IV stored in the resources of this app. * @param context Application context * @param preferenceName Name of preferences to use. */ public static SecurePreferences getInstanceFromResources(Context context, String preferenceName) { SecretKey key = base64DecodeKey(context.getString(R.string.security_KEY)); IvParameterSpec iv = new IvParameterSpec(Base64.decode(context.getString(R.string.security_IV), Base64.DEFAULT)); return new SecurePreferences(context, preferenceName, key, iv, true); } /** * ACCESS TO THE KEYSTORE CURRENTLY DOES NOT WORK! * * Returns an instance with the stored key and IV for this app. * If these do not exist, they are generated the first time the preferences are used. * @param context Application context * @param preferenceNameId Resource ID for preference name. */ @Deprecated public static SecurePreferences getInstance(Context context, int preferenceNameId) { return SecurePreferences.getInstance(context, context.getString(preferenceNameId)); } /** * ACCESS TO THE KEYSTORE CURRENTLY DOES NOT WORK! * * Returns an instance with the stored key and IV for this app. * If these do not exist, they are generated the first time the preferences are used. * @param context Application context * @param preferenceName Name of preferences to use. */ @Deprecated public static SecurePreferences getInstance(Context context, String preferenceName) { KeyStore keyStore = KeyStore.getInstance(); byte[] keyBytes, ivBytes; SecretKey key; IvParameterSpec iv; String secretKeyKey = context.getString(R.string.security_secretKey_storeKey); final String ivKey = context.getString(R.string.security_IV_storeKey); keyBytes = keyStore.get(secretKeyKey); if (keyBytes != null) { key = new SecretKeySpec(keyBytes, "AES"); } else { Log.d(TAG, "No secret key in keystore, generating new key."); KeyGenerator aes = null; try { aes = KeyGenerator.getInstance("AES"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } key = aes.generateKey(); keyStore.put(secretKeyKey, key.getEncoded()); } ivBytes = keyStore.get(ivKey); if (ivBytes != null) { iv = new IvParameterSpec(ivBytes); } else { Log.d(TAG, "No IV in keystore, generating new IV."); iv = SecurePreferences.getIv(); keyStore.put(ivKey, iv.getIV()); } return new SecurePreferences(context, preferenceName, key, iv, true); } /** * This will initialize an instance of the SecurePreferences class * @param context your current context. * @param preferenceName name of preferences file (preferenceName.xml) * @param secureKey the key used for encryption, finding a good key scheme is hard. * Hardcoding your key in the application is bad, but better than plaintext preferences. Having the user enter the key upon application launch is a safe(r) alternative, but annoying to the user. * @param encryptKeys settings this to false will only encrypt the values, * true will encrypt both values and keys. Keys can contain a lot of information about * the plaintext value of the value which can be used to decipher the value. * @throws SecurePreferencesException */ public SecurePreferences(Context context, String preferenceName, SecretKey secureKey, IvParameterSpec ivSpec, boolean encryptKeys) throws SecurePreferencesException { try { this.writer = Cipher.getInstance(TRANSFORMATION); this.reader = Cipher.getInstance(TRANSFORMATION); this.keyWriter = Cipher.getInstance(KEY_TRANSFORMATION); initCiphers(secureKey, ivSpec); this.preferences = context.getSharedPreferences(preferenceName, Context.MODE_PRIVATE); this.encryptKeys = encryptKeys; } catch (GeneralSecurityException | UnsupportedEncodingException e) { throw new SecurePreferencesException(e); } } protected void initCiphers(SecretKey secretKey, IvParameterSpec ivSpec) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException { writer.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec); reader.init(Cipher.DECRYPT_MODE, secretKey, ivSpec); keyWriter.init(Cipher.ENCRYPT_MODE, secretKey); } public static IvParameterSpec getIv() { byte[] iv; try { iv = new byte[Cipher.getInstance(TRANSFORMATION).getBlockSize()]; } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { throw new SecurePreferencesException(e); } new SecureRandom().nextBytes(iv); return new IvParameterSpec(iv); } protected static SecretKeySpec base64DecodeKey(String key) { byte[] keyBytes = Base64.decode(key, Base64.DEFAULT); return new SecretKeySpec(keyBytes, TRANSFORMATION); } protected static SecretKeySpec getSecretKey(String key) throws UnsupportedEncodingException, NoSuchAlgorithmException { byte[] keyBytes = createKeyBytes(key); return new SecretKeySpec(keyBytes, TRANSFORMATION); } protected static byte[] createKeyBytes(String key) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance(SECRET_KEY_HASH_TRANSFORMATION); md.reset(); return md.digest(key.getBytes(CHARSET)); } public void put(String key, String value) { if (value == null) { preferences.edit().remove(toKey(key)).commit(); } else { putValue(toKey(key), value); } } public boolean containsKey(String key) { return preferences.contains(toKey(key)); } public void removeValue(String key) { preferences.edit().remove(toKey(key)).commit(); } public String getString(String key) throws SecurePreferencesException { if (preferences.contains(toKey(key))) { String securedEncodedValue = preferences.getString(toKey(key), ""); return decrypt(securedEncodedValue); } return null; } public void clear() { preferences.edit().clear().commit(); } private String toKey(String key) { if (encryptKeys) return encrypt(key, keyWriter); else return key; } private void putValue(String key, String value) throws SecurePreferencesException { String secureValueEncoded = encrypt(value, writer); preferences.edit().putString(key, secureValueEncoded).commit(); } protected String encrypt(String value, Cipher writer) throws SecurePreferencesException { byte[] secureValue; try { secureValue = convert(writer, value.getBytes(CHARSET)); } catch (UnsupportedEncodingException e) { throw new SecurePreferencesException(e); } String secureValueEncoded = Base64.encodeToString(secureValue, Base64.NO_WRAP); return secureValueEncoded; } protected String decrypt(String securedEncodedValue) { byte[] securedValue = Base64.decode(securedEncodedValue, Base64.NO_WRAP); byte[] value = convert(reader, securedValue); try { return new String(value, CHARSET); } catch (UnsupportedEncodingException e) { throw new SecurePreferencesException(e); } } private static byte[] convert(Cipher cipher, byte[] bs) throws SecurePreferencesException { try { return cipher.doFinal(bs); } catch (Exception e) { throw new SecurePreferencesException(e); } } }
package asia.sonix.android.orm; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class AbatisService extends SQLiteOpenHelper { /** * Debug TAG */ private static final String TAG = "aBatis"; /** * DBSQLID */ private static final String INIT_CREATE_SQL = "initialize"; /** * Default DB file name */ private static final String DB_FILE_NAME = "database.db"; /** * instance object */ private static AbatisService instance = null; /** * SQLiteDatabase object */ private SQLiteDatabase dbObj; /** * Context object */ private Context context; /** * Default DB file nameConstructor * * @param context * Context * */ protected AbatisService(Context context) { super(context, DB_FILE_NAME, null, 1); this.context = context; } /** * DB file nameConstructor * * @param context * Context * @param dbName * DB file name * */ protected AbatisService(Context context, String dbName) { super(context, dbName.concat(".db"), null, 1); this.context = context; } /** * Default DB file nameConstructor * * @param context * Context * @param dbName * DB file name * */ protected static AbatisService getInstance(Context context) { if (instance == null) { instance = new AbatisService(context); } return instance; } /** * DB file nameConstructor * * @param context * Context * @param dbName * DB file name * */ protected static AbatisService getInstance(Context context, String dbName) { if (instance == null) { instance = new AbatisService(context, dbName); } return instance; } /** * DB connector * * @param db * SQLiteDatabase object * */ @Override public void onCreate(SQLiteDatabase db) { int pointer = context.getResources().getIdentifier(INIT_CREATE_SQL, "string", context.getPackageName()); if (pointer == 0) { Log.e(TAG, "undefined sql id - initialize"); } else { String createTabelSql = context.getResources().getString(pointer); for (String sql : createTabelSql.split(";")) { db.execSQL(sql); } } } /** * for upgrade (0.1) * * @param db * SQLiteDatabase object * @param oldVersion * old version value * @param newVersion * new version value * */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // no poc } /** * SQLIDparametermappingmap * * <p> * mappingparameternull null * </p> * * @param sqlId * SQLID * @param bindParams * sql parameter * * @return Map<String, Object> result */ public Map<String, Object> executeForMap(int sqlId, Map<String, ? extends Object> bindParams) { getDbObject(); String sql = context.getResources().getString(sqlId); if (bindParams != null) { Iterator<String> mapIterator = bindParams.keySet().iterator(); while (mapIterator.hasNext()) { String key = mapIterator.next(); Object value = bindParams.get(key); sql = sql.replaceAll("#" + key + "#", "'" + value.toString() + "'"); } } if (sql.indexOf(' Log.e(TAG, "undefined parameter in sql: " + sql); return null; } Cursor cursor = dbObj.rawQuery(sql, null); List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>(); if (cursor == null) { return null; } String[] columnNames = cursor.getColumnNames(); while (cursor.moveToNext()) { Map<String, Object> map = new HashMap<String, Object>(); int i = 0; for (String columnName : columnNames) { map.put(columnName, cursor.getString(i)); i++; } mapList.add(map); } if (mapList.size() <= 0) { return null; } cursor.close(); dbObj.close(); return mapList.get(0); } /** * SQLIDparametermappingmap * * <p> * mappingparameternull * </p> * * @param sqlId * SQLID * @param bindParams * sql parameter * * @return List<Map<String, Object>> result */ public List<Map<String, Object>> executeForMapList(int sqlId, Map<String, ? extends Object> bindParams) { getDbObject(); String sql = context.getResources().getString(sqlId); if (bindParams != null) { Iterator<String> mapIterator = bindParams.keySet().iterator(); while (mapIterator.hasNext()) { String key = mapIterator.next(); Object value = bindParams.get(key); sql = sql.replaceAll("#" + key + "#", "'" + value.toString() + "'"); } } if (sql.indexOf(' Log.e(TAG, "undefined parameter in sql: " + sql); return null; } Cursor cursor = dbObj.rawQuery(sql, null); List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>(); if (cursor == null) { return null; } String[] columnNames = cursor.getColumnNames(); while (cursor.moveToNext()) { Map<String, Object> map = new HashMap<String, Object>(); int i = 0; for (String columnName : columnNames) { map.put(columnName, cursor.getString(i)); i++; } mapList.add(map); } cursor.close(); dbObj.close(); return mapList; } /** * SQLIDparametermappingbean * * <p> * mappingparameternull null * </p> * * @param sqlId * SQLID * @param bindParams * sql parameter * @param bean * bean class of result * * @return List<Map<String, Object>> result */ @SuppressWarnings({ "unchecked", "rawtypes" }) public <T> T executeForBean(int sqlId, Map<String, ? extends Object> bindParams, Class bean) { getDbObject(); String sql = context.getResources().getString(sqlId); if (bindParams != null) { Iterator<String> mapIterator = bindParams.keySet().iterator(); while (mapIterator.hasNext()) { String key = mapIterator.next(); Object value = bindParams.get(key); sql = sql.replaceAll("#" + key + "#", "'" + value.toString() + "'"); } } if (sql.indexOf(' Log.e(TAG, "undefined parameter in sql: " + sql); return null; } Cursor cursor = dbObj.rawQuery(sql, null); List<T> objectList = new ArrayList<T>(); if (cursor == null) { return null; } String[] columnNames = cursor.getColumnNames(); List<String> dataNames = new ArrayList<String>(); for (String columnName : columnNames) { dataNames.add(chgDataName(columnName)); } T beanObj = null; // get bean class package Package beanPackage = bean.getPackage(); while (cursor.moveToNext()) { Map<String, Object> map = new HashMap<String, Object>(); int i = 0; for (String dataName : dataNames) { map.put(dataName, cursor.getString(i)); i++; } JSONObject json = new JSONObject(map); try { beanObj = (T) parse(json.toString(), bean, beanPackage.getName()); } catch (Exception e) { Log.d(TAG, e.toString()); return null; } objectList.add(beanObj); } if (objectList.size() <= 0) { return null; } cursor.close(); dbObj.close(); return objectList.get(0); } /** * SQLIDparametermappingbean * * <p> * mappingparameternull * </p> * * @param sqlId * SQLID * @param bindParams * sql parameter * @param bean * bean class of result * * @return List<Map<String, Object>> result */ @SuppressWarnings({ "unchecked", "rawtypes" }) public <T> List<T> executeForBeanList(int sqlId, Map<String, ? extends Object> bindParams, Class bean) { getDbObject(); String sql = context.getResources().getString(sqlId); if (bindParams != null) { Iterator<String> mapIterator = bindParams.keySet().iterator(); while (mapIterator.hasNext()) { String key = mapIterator.next(); Object value = bindParams.get(key); sql = sql.replaceAll("#" + key + "#", "'" + value.toString() + "'"); } } if (sql.indexOf(' Log.e(TAG, "undefined parameter in sql: " + sql); return null; } Cursor cursor = dbObj.rawQuery(sql, null); List<T> objectList = new ArrayList<T>(); if (cursor == null) { return null; } String[] columnNames = cursor.getColumnNames(); List<String> dataNames = new ArrayList<String>(); for (String columnName : columnNames) { dataNames.add(chgDataName(columnName)); } T beanObj = null; // get bean class package Package beanPackage = bean.getPackage(); while (cursor.moveToNext()) { Map<String, Object> map = new HashMap<String, Object>(); int i = 0; for (String dataName : dataNames) { map.put(dataName, cursor.getString(i)); i++; } JSONObject json = new JSONObject(map); try { beanObj = (T) parse(json.toString(), bean, beanPackage.getName()); } catch (Exception e) { Log.d(TAG, e.toString()); return null; } objectList.add(beanObj); } cursor.close(); dbObj.close(); return objectList; } /** * SQLIDparametermapping * * <p> * mappingparameter0 * </p> * * @param sqlId * SQLiteDatabase object * @param bindParams * old version value * * @return int */ public int execute(int sqlId, Map<String, ? extends Object> bindParams) { getDbObject(); int row = 0; String sql = context.getResources().getString(sqlId); if (bindParams != null) { Iterator<String> mapIterator = bindParams.keySet().iterator(); while (mapIterator.hasNext()) { String key = mapIterator.next(); Object value = bindParams.get(key); sql = sql.replaceAll("#" + key + "#", "'" + value.toString() + "'"); } } if (sql.indexOf(' Log.e(TAG, "undefined parameter in sql: " + sql); return row; } try { dbObj.execSQL(sql); dbObj.close(); row += 1; } catch (SQLException e) { return row; } return row; } /** * SQLiteDatabase Object * * @return SQLiteDatabase SQLiteDatabase Object */ private SQLiteDatabase getDbObject() { if (dbObj == null || !dbObj.isOpen()) { dbObj = getWritableDatabase(); } return dbObj; } /** * JsonStringBean * * @param jsonStr * JSON String * @param beanClass * Bean class * @param basePackage * Base package name which includes all Bean classes * @return Object Bean * @throws Exception */ @SuppressWarnings({ "rawtypes", "unchecked" }) public Object parse(String jsonStr, Class beanClass, String basePackage) throws Exception { Object obj = null; JSONObject jsonObj = new JSONObject(jsonStr); // Check bean object if (beanClass == null) { Log.d(TAG, "Bean class is null"); return null; } // Read Class member fields Field[] props = beanClass.getDeclaredFields(); if (props == null || props.length == 0) { Log.d(TAG, "Class" + beanClass.getName() + " has no fields"); return null; } // Create instance of this Bean class obj = beanClass.newInstance(); // Set value of each member variable of this object for (int i = 0; i < props.length; i++) { String fieldName = props[i].getName(); fieldName = fieldName.replaceAll("_", ""); // Skip public and static fields if (props[i].getModifiers() == (Modifier.PUBLIC | Modifier.STATIC)) { continue; } // Date Type of Field Class type = props[i].getType(); String typeName = type.getName(); // Check for Custom type if (typeName.equals("int") || typeName.equals("java.lang.Integer")) { Class[] parms = { type }; try { Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms); m.setAccessible(true); // Set value m.invoke(obj, jsonObj.getInt(fieldName)); } catch (Exception ex) { Log.d(TAG, ex.getMessage()); } } else if (typeName.equals("long") || typeName.equals("java.lang.Long")) { Class[] parms = { type }; try { Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms); m.setAccessible(true); // Set value m.invoke(obj, jsonObj.getLong(fieldName)); } catch (Exception ex) { Log.d(TAG, ex.getMessage()); } } else if (typeName.equals("java.lang.String")) { Class[] parms = { type }; try { Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms); m.setAccessible(true); // Set value m.invoke(obj, jsonObj.getString(fieldName)); } catch (Exception ex) { Log.d(TAG, ex.getMessage()); } } else if (typeName.equals("double") || typeName.equals("java.lang.Double")) { Class[] parms = { type }; try { Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms); m.setAccessible(true); // Set value m.invoke(obj, jsonObj.getDouble(fieldName)); } catch (Exception ex) { Log.d(TAG, ex.getMessage()); } } else if (type.getName().equals(List.class.getName()) || type.getName().equals(ArrayList.class.getName())) { // Find out the Generic String generic = props[i].getGenericType().toString(); if (generic.indexOf("<") != -1) { String genericType = generic.substring(generic.lastIndexOf("<") + 1, generic.lastIndexOf(">")); if (genericType != null) { JSONArray array = null; try { array = jsonObj.getJSONArray(fieldName); } catch (Exception ex) { Log.d(TAG, ex.getMessage()); array = null; } if (array == null) { continue; } ArrayList arrayList = new ArrayList(); for (int j = 0; j < array.length(); j++) { arrayList.add(parse(array.getJSONObject(j).toString(), Class.forName(genericType), basePackage)); } // Set value Class[] parms = { type }; try { Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms); m.setAccessible(true); m.invoke(obj, arrayList); } catch (Exception ex) { Log.d(TAG, ex.getMessage()); } } } else { // No generic defined generic = null; } } else if (typeName.startsWith(basePackage)) { Class[] parms = { type }; try { Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms); m.setAccessible(true); // Set value JSONObject customObj = jsonObj.getJSONObject(fieldName); if (customObj != null) { m.invoke(obj, parse(customObj.toString(), type, basePackage)); } } catch (JSONException ex) { Log.d(TAG, ex.getMessage()); } } else { // Skip Log.d(TAG, "Field " + fieldName + "#" + typeName + " is skip"); } } return obj; } /** * BeanClass fieldsmethod * * @param fieldName * @param type * @return String MethodName */ private String getBeanMethodName(String fieldName, int type) { if (fieldName == null || fieldName == "") { return ""; } String methodName = ""; if (type == 0) { methodName = "get"; } else { methodName = "set"; } methodName += fieldName.substring(0, 1).toUpperCase(); if (fieldName.length() == 1) { return methodName; } methodName += fieldName.substring(1); //Log.d(TAG, "fieldName: " + fieldName + " beanMethod: " + methodName); return methodName; } /** * Databasejava bean * * @param targetStr * database * @return String bean data */ private String chgDataName(String targetStr) { Pattern p = Pattern.compile("_([a-z])"); Matcher m = p.matcher(targetStr); StringBuffer sb = new StringBuffer(targetStr.length()); while (m.find()) { m.appendReplacement(sb, m.group(1).toUpperCase()); } m.appendTail(sb); return sb.toString(); } }
package arez.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Target; /** * Annotate the method that will be overridden to provide the "name" of the Arez component. * This is useful when the user wants to manually create Arez elements (i.e. {@link arez.ObservableValue} instances, * {@link arez.Observer} instances or {@link arez.ComputableValue} instances etc) and wants to use the same naming * convention as the generated Arez subclass. * * <p>This annotation should appear at most once on a component. The * annotation should be on a method that accepts no parameters and returns * a String.</p> * * <p>The method that is annotated with the annotation must comply with the additional constraints:</p> * <ul> * <li>Must not be annotated with any other arez annotation</li> * <li>Must have 0 parameters</li> * <li>Must return a String</li> * <li>Must not be private</li> * <li>Must not be static</li> * <li>Must not be final</li> * <li>Must be abstract</li> * <li>Must not throw exceptions</li> * </ul> * * @see ComponentId * @see ComponentTypeNameRef */ @Documented @Target( ElementType.METHOD ) public @interface ComponentNameRef { }
package org.videolan; import java.io.File; import java.io.IOException; import java.io.BDFileSystem; class CacheDir { private static LockFile lockCache(String path) { return LockFile.create(path + File.separator + "lock"); } private static void cleanupCache() { String[] files = BDFileSystem.nativeList(baseDir); if (files != null) { for (int i = 0; i < files.length; i++) { File dir = new File(baseDir, files[i]); if (dir.isDirectory()) { LockFile lock = lockCache(dir.getPath()); if (lock != null) { lock.release(); removeImpl(dir); } } } } } private static synchronized File getCacheRoot() throws IOException { if (cacheRoot != null) { return cacheRoot; } BDJSecurityManager sm = (BDJSecurityManager)System.getSecurityManager(); if (sm != null) { sm.setCacheRoot(System.getProperty("java.io.tmpdir")); baseDir.mkdirs(); sm.setCacheRoot(baseDir.getPath()); } cleanupCache(); for (int i = 0; i < 100; i++) { File tmpDir = new File(baseDir, "" + System.nanoTime()); tmpDir = new File(tmpDir.getCanonicalPath()); if (tmpDir.mkdirs()) { cacheRoot = tmpDir; lockFile = lockCache(cacheRoot.getPath()); logger.info("Created cache in " + tmpDir.getPath()); if (sm != null) { sm.setCacheRoot(cacheRoot.getPath()); } return cacheRoot; } logger.error("error creating " + tmpDir.getPath()); } logger.error("failed to create temporary cache directory"); throw new IOException(); } public static synchronized File create(String domain) throws IOException { File tmpDir = new File(getCacheRoot(), domain); if (!tmpDir.exists() && !tmpDir.mkdirs()) { logger.error("Error creating " + tmpDir.getPath()); throw new IOException(); } return tmpDir; } public static File create(String domain, String name) throws IOException { return create(domain + File.separator + name); } private static void removeImpl(File dir) { String[] files = BDFileSystem.nativeList(dir); if (files != null) { for (int i = 0; i < files.length; i++) { File file = new File(dir, files[i]); if (file.isDirectory()) { removeImpl(file); } else { if (!file.delete()) { logger.info("Error removing " + file.getPath()); } } } } if (!dir.delete()) { logger.error("Error removing " + dir.getPath()); } } public static synchronized void remove(File dir) { String path = dir.getPath(); if (path.indexOf(cacheRoot.getPath()) != 0) { logger.error("Error removing " + dir.getPath() + ": not inside cache !"); return; } if (path.indexOf("..") >= 0) { logger.error("Error removing " + dir.getPath() + ": not canonical path !"); return; } removeImpl(dir); } public static synchronized void remove() { if (lockFile != null) { lockFile.release(); lockFile = null; } if (cacheRoot != null) { remove(cacheRoot); cacheRoot = null; } } private static File cacheRoot = null; private static LockFile lockFile = null; private static final File baseDir = new File(System.getProperty("java.io.tmpdir"), "libbluray-bdj-cache"); private static final Logger logger = Logger.getLogger(CacheDir.class.getName()); }
package ca.teamTen.recitopia; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import com.google.gson.Gson; import com.google.gson.JsonObject; /** * RecipeBook interface to ElasticSearch recipe service. * Currently not implemented, comments document expected * implementation. */ public class CloudRecipeBook implements RecipeBook{ private final String RECIPE_INDEX_URL = "http://cmput301.softwareprocess.es:8080/cmput301w13t10/recipe/"; private HttpClient httpClient = new DefaultHttpClient(); private Gson gson = new Gson(); @Override public Recipe[] query(String searchTerms) { String searchUrlParam; try { searchUrlParam = URLEncoder.encode(new QueryRequest(searchTerms).toJSON(gson), "UTF-8"); } catch (UnsupportedEncodingException e1) { return null; } HttpGet getRequest = new HttpGet(RECIPE_INDEX_URL + "_search?source=" + searchUrlParam); HttpResponse response; String resultBody; try { response = httpClient.execute(getRequest); resultBody = readInputStreamToString(response.getEntity().getContent()); } catch (ClientProtocolException e) { return null; } catch (IOException e) { return null; } // TODO: what if response is not 200 OK? return gson.fromJson(resultBody, QueryResult.class).getResults(); } /** * Create an ElasticSearch update or create command object, * serialize to JSON and use HTTP to send to server. * * Alternatively, cache the update commands and send them * when save() is called. */ @Override public void addRecipe(Recipe recipe) { HttpResponse response = null; try { String url = buildRecipeURL(recipe) + "/_update"; HttpPost postRequest = new HttpPost(url); String postBody = gson.toJson(new UpdateInsertRequest(recipe)); postRequest.setHeader("Accept", "application/json"); postRequest.setEntity(new StringEntity(postBody)); response = httpClient.execute(postRequest); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // status 200 = ok if (response != null && response.getStatusLine().getStatusCode() != 200) { // TODO } } /** * Check whether a connection can be made to the server. * @return true if ElasticSearch server can be reached. */ public boolean isAvailable() { return false; } /** * Flush any cached update/insert commands to server. */ @Override public void save() { // TODO Auto-generated method stub } /** * Public for testing purposes. * @param recipe the recipe for which to build the URL * @return a URL for the recipe's entry in ElasticSearch * @throws UnsupportedEncodingException */ public String buildRecipeURL(Recipe recipe) throws UnsupportedEncodingException { return RECIPE_INDEX_URL + URLEncoder.encode(recipe.showAuthor() + "/" + recipe.getRecipeName(), "UTF-8"); } /* * Class to be serialized into an ElasticSearch update request. * * Since we regard update/insert as basically the same thing, we * use a bit of a hack to achieve this with ElasticSearch. * * If the record already exists, ES will update it with fields from * the doc member. If it does not exist, it will first create the * record using the upsert member. */ private static class UpdateInsertRequest { public Recipe doc; public Recipe upsert; UpdateInsertRequest(Recipe recipe) { doc = recipe; upsert = recipe; } public String toJSON(Gson gson) { return gson.toJson(this); } } private static class QueryRequest { private static class Query { Map<String, String> query_string; Query(String query) { query_string = new HashMap<String, String>(); query_string.put("query", query); } } Query query; public QueryRequest(String query) { this.query = new Query(query); } public String toJSON(Gson gson) { return gson.toJson(this); } } /* * Class for reading query results. */ private static class QueryResult { public static class QueryHitData { int total; double max_score; QueryHit[] hits; } public static class QueryHit { Recipe _source; } public QueryHitData hits; public Recipe[] getResults() { if (hits == null) { return null; } ArrayList<Recipe> results = new ArrayList<Recipe>(); for (QueryHit hit: hits.hits) { results.add(hit._source); } Recipe asArray[] = new Recipe[results.size()]; results.toArray(asArray); // TODO: set is published return asArray; } } private String readInputStreamToString(InputStream input) { java.util.Scanner s = new java.util.Scanner(input).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } }
package org.bouncycastle.crypto.ec; import org.bouncycastle.math.ec.ECPoint; public class ECPair { private final ECPoint x; private final ECPoint y; public ECPair(ECPoint x, ECPoint y) { this.x = x; this.y = y; } public ECPoint getX() { return x; } public ECPoint getY() { return y; } public boolean equals(ECPair other) { return other.getX().equals(getX()) && other.getY().equals(getY()); } public boolean equals(Object other) { return other instanceof ECPair ? equals((ECPair)other) : false; } public int hashCode() { return x.hashCode() + 37 * y.hashCode(); } }
package org.jivesoftware.gui; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.AffineTransform; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Principal; import java.security.UnrecoverableKeyException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.net.ssl.SSLContext; import javax.security.auth.Subject; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.login.Configuration; import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JPopupMenu; import javax.swing.JSplitPane; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.text.JTextComponent; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.jivesoftware.AccountCreationWizard; import org.jivesoftware.MainWindow; import org.jivesoftware.Spark; import org.jivesoftware.resource.Default; import org.jivesoftware.resource.Res; import org.jivesoftware.resource.SparkRes; import org.jivesoftware.smack.AbstractXMPPConnection; import org.jivesoftware.smack.ConnectionConfiguration; import org.jivesoftware.smack.ReconnectionManager; import org.jivesoftware.smack.SASLAuthentication; import org.jivesoftware.smack.SmackConfiguration; import org.jivesoftware.smack.SmackException; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.parsing.ExceptionLoggingCallback; import org.jivesoftware.smack.proxy.ProxyInfo; import org.jivesoftware.smack.sasl.javax.SASLExternalMechanism; import org.jivesoftware.smack.sasl.javax.SASLGSSAPIMechanism; import org.jivesoftware.smack.tcp.XMPPTCPConnection; import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration; import org.jivesoftware.smack.util.DNSUtil; import org.jivesoftware.smack.util.TLSUtils; import org.jivesoftware.smackx.carbons.CarbonManager; import org.jivesoftware.smackx.chatstates.ChatStateManager; import org.jivesoftware.spark.PluginManager; import org.jivesoftware.spark.SessionManager; import org.jivesoftware.spark.SparkManager; import org.jivesoftware.spark.Workspace; import org.jivesoftware.spark.component.MessageDialog; import org.jivesoftware.spark.component.RolloverButton; import org.jivesoftware.spark.sasl.SASLGSSAPIv3CompatMechanism; import org.jivesoftware.spark.ui.login.GSSAPIConfiguration; import org.jivesoftware.spark.ui.login.LoginSettingDialog; import org.jivesoftware.spark.util.BrowserLauncher; import org.jivesoftware.spark.util.GraphicUtils; import org.jivesoftware.spark.util.ModelUtil; import org.jivesoftware.spark.util.ResourceUtils; import static org.jivesoftware.spark.util.StringUtils.modifyWildcards; import org.jivesoftware.spark.util.SwingWorker; import org.jivesoftware.spark.util.log.Log; import org.jivesoftware.sparkimpl.certificates.CertificateModel; import org.jivesoftware.sparkimpl.certificates.SparkSSLContextCreator; import org.jivesoftware.sparkimpl.certificates.SparkSSLSocketFactory; import org.jivesoftware.sparkimpl.certificates.SparkTrustManager; import org.jivesoftware.sparkimpl.certificates.UnrecognizedServerCertificatePanel; import org.jivesoftware.sparkimpl.plugin.layout.LayoutSettings; import org.jivesoftware.sparkimpl.plugin.layout.LayoutSettingsManager; import org.jivesoftware.sparkimpl.plugin.manager.Enterprise; import org.jivesoftware.sparkimpl.settings.JiveInfo; import org.jivesoftware.sparkimpl.settings.local.LocalPreferences; import org.jivesoftware.sparkimpl.settings.local.SettingsManager; import org.jxmpp.jid.DomainBareJid; import org.jxmpp.jid.impl.JidCreate; import org.jxmpp.jid.parts.Resourcepart; import org.jxmpp.stringprep.XmppStringprepException; import org.jxmpp.util.XmppStringUtils; import org.minidns.dnsname.DnsName; /** * * @author KeepToo */ public class LoginUIPanel extends javax.swing.JPanel implements KeyListener, ActionListener, FocusListener, CallbackHandler { private JFrame loginDialog; private static final String BUTTON_PANEL = "buttonpanel"; // NOTRANS private static final String PROGRESS_BAR = "progressbar"; // NOTRANS private LocalPreferences localPref; private ArrayList<String> _usernames = new ArrayList<>(); private String loginUsername; private String loginPassword; private String loginServer; private static final long serialVersionUID = 2445523786538863459L; // Panel used to hold buttons private final CardLayout cardLayout = new CardLayout(0, 5); final JPanel cardPanel = new JPanel(cardLayout); final JPanel buttonPanel = new JPanel(new GridBagLayout()); private AbstractXMPPConnection connection = null; private RolloverButton otherUsers = new RolloverButton(SparkRes.getImageIcon(SparkRes.PANE_UP_ARROW_IMAGE)); /** * Creates new form LoginWindow */ public LoginUIPanel() { initComponents(); localPref = SettingsManager.getLocalPreferences(); init(); // Check if upgraded needed. try { checkForOldSettings(); } catch (Exception e) { Log.error(e); } } private void init() { ResourceUtils.resButton(cbSavePassword, Res.getString("checkbox.save.password")); ResourceUtils.resButton(cbAutoLogin, Res.getString("checkbox.auto.login")); ResourceUtils.resButton(btnCreateAccount, Res.getString("label.accounts")); ResourceUtils.resButton(cbLoginInvisible, Res.getString("checkbox.login.as.invisible")); ResourceUtils.resButton(cbAnonymous, Res.getString("checkbox.login.anonymously")); ResourceUtils.resButton(btnReset, Res.getString("label.passwordreset")); configureVisibility(); lblProgress.setVisible(false); cbSavePassword.setOpaque(false); cbAutoLogin.setOpaque(false); cbLoginInvisible.setOpaque(false); cbAnonymous.setOpaque(false); // btnReset.setVisible(false); // Add button but disable the login button initially cbSavePassword.addActionListener(this); cbAutoLogin.addActionListener(this); cbLoginInvisible.addActionListener(this); cbAnonymous.addActionListener(this); // Add KeyListener tfUsername.addKeyListener(this); tfPassword.addKeyListener(this); tfDomain.addKeyListener(this); tfPassword.addFocusListener(this); tfUsername.addFocusListener(this); tfDomain.addFocusListener(this); // Add ActionListener btnLogin.addActionListener(this); btnAdvanced.addActionListener(this); otherUsers.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { getPopup().show(otherUsers, e.getX(), e.getY()); } }); // Make same size GraphicUtils.makeSameSize(tfUsername, tfPassword); // Set progress bar description lblProgress.setText(Res.getString("message.authenticating")); lblProgress.setVerticalTextPosition(JLabel.BOTTOM); lblProgress.setHorizontalTextPosition(JLabel.CENTER); lblProgress.setHorizontalAlignment(JLabel.CENTER); // Set Resources // ResourceUtils.resLabel(usernameLabel, tfUsername, Res.getString("label.username")); //ResourceUtils.resLabel(passwordLabel, passwordField, Res.getString("label.password")); ResourceUtils.resButton(btnLogin, Res.getString("button.login")); ResourceUtils.resButton(btnAdvanced, Res.getString("button.advanced")); // Load previous instances String userProp = localPref.getLastUsername(); String serverProp = localPref.getServer(); File file = new File(Spark.getSparkUserHome(), "/user/"); File[] userprofiles = file.listFiles(); for (File f : userprofiles) { if (f.getName().contains("@")) { _usernames.add(f.getName()); } else { Log.error("Profile contains wrong format: \"" + f.getName() + "\" located at: " + f.getAbsolutePath()); } } if (userProp != null) { tfUsername.setText(XmppStringUtils.unescapeLocalpart(userProp)); } if (serverProp != null) { tfDomain.setText(serverProp); } // Check Settings if (localPref.isSavePassword()) { String encryptedPassword = localPref.getPasswordForUser(getBareJid()); if (encryptedPassword != null) { tfPassword.setText(encryptedPassword); } cbSavePassword.setSelected(true); btnLogin.setEnabled(true); } cbAutoLogin.setSelected(localPref.isAutoLogin()); cbLoginInvisible.setSelected(localPref.isLoginAsInvisible()); cbAnonymous.setSelected(localPref.isLoginAnonymously()); tfUsername.setEnabled(!cbAnonymous.isSelected()); tfPassword.setEnabled(!cbAnonymous.isSelected()); useSSO(localPref.isSSOEnabled()); if (cbAutoLogin.isSelected()) { validateLogin(); return; } // Handle arguments String username = Spark.getArgumentValue("username"); String password = Spark.getArgumentValue("password"); String server = Spark.getArgumentValue("server"); if (username != null) { tfUsername.setText(username); } if (password != null) { tfPassword.setText(password); } if (server != null) { tfDomain.setText(server); } if (username != null && server != null && password != null) { validateLogin(); } btnCreateAccount.addActionListener(this); final String lockedDownURL = Default.getString(Default.HOST_NAME); if (ModelUtil.hasLength(lockedDownURL)) { tfDomain.setText(lockedDownURL); } //reset ui //btnAdvanced.setUI(new BasicButtonUI()); //btnCreateAccount.setUI(new BasicButtonUI()); tfDomain.putClientProperty("JTextField.placeholderText", "Enter Domain(e.g igniterealtime.org)"); tfPassword.putClientProperty("JTextField.placeholderText", "Enter Password"); tfUsername.putClientProperty("JTextField.placeholderText", "Enter Username"); setComponentsAvailable(true); } private void configureVisibility() { int height = filler3.getPreferredSize().height; if (Default.getBoolean(Default.HIDE_SAVE_PASSWORD_AND_AUTO_LOGIN) || !localPref.getPswdAutologin()) { pnlCheckboxes.remove(cbAutoLogin); pnlCheckboxes.remove(cbSavePassword); height = height + 20; } // Add option to hide "Login as invisible" selection on the login screen if (Default.getBoolean(Default.HIDE_LOGIN_AS_INVISIBLE) || !localPref.getInvisibleLogin()) { pnlCheckboxes.remove(cbLoginInvisible); height = height + 10; } // Add option to hide "Login anonymously" selection on the login screen if (Default.getBoolean(Default.HIDE_LOGIN_ANONYMOUSLY) || !localPref.getAnonymousLogin()) { pnlCheckboxes.remove(cbAnonymous); height = height + 10; } if (Default.getBoolean(Default.ACCOUNT_DISABLED) || !localPref.getAccountsReg()) { pnlBtns.remove(btnCreateAccount); height = height + 15; } if (!Default.getBoolean(Default.PASSWORD_RESET_ENABLED)) { pnlBtns.remove(btnReset); } if (Default.getBoolean(Default.ADVANCED_DISABLED) || !localPref.getAdvancedConfig()) { pnlBtns.remove(btnAdvanced); height = height + 15; } filler3.setPreferredSize(new Dimension(220, height)); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { pnlLeft = new javax.swing.JPanel(); filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 50), new java.awt.Dimension(250, 50), new java.awt.Dimension(32767, 50)); lblLogo = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); pnlCenter = new javax.swing.JPanel(); filler3 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(220, 20), new java.awt.Dimension(0, 32767)); pnlInputs = new javax.swing.JPanel(); tfUsername = new javax.swing.JTextField(); tfDomain = new javax.swing.JTextField(); tfPassword = new javax.swing.JPasswordField(); pnlCheckboxes = new javax.swing.JPanel(); cbSavePassword = new javax.swing.JCheckBox(); cbAutoLogin = new javax.swing.JCheckBox(); cbLoginInvisible = new javax.swing.JCheckBox(); cbAnonymous = new javax.swing.JCheckBox(); pnlBtns = new javax.swing.JPanel(); btnLogin = new javax.swing.JButton(); btnCreateAccount = new javax.swing.JButton(); btnAdvanced = new javax.swing.JButton(); btnReset = new javax.swing.JButton(); setLayout(new java.awt.BorderLayout()); pnlLeft.setPreferredSize(new java.awt.Dimension(260, 0)); pnlLeft.add(filler1); lblLogo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblLogo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/spark-64x64.png"))); // NOI18N lblLogo.setPreferredSize(new java.awt.Dimension(250, 80)); lblLogo.setRequestFocusEnabled(false); pnlLeft.add(lblLogo); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("Spark"); jLabel1.setPreferredSize(new java.awt.Dimension(250, 22)); pnlLeft.add(jLabel1); jLabel2.setText("Instant Messenger"); pnlLeft.add(jLabel2); lblProgress.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblProgress.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ripple.gif"))); // NOI18N lblProgress.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); lblProgress.setPreferredSize(new java.awt.Dimension(250, 90)); lblProgress.setRequestFocusEnabled(false); lblProgress.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); pnlLeft.add(lblProgress); add(pnlLeft, java.awt.BorderLayout.WEST); pnlCenter.setBackground(new java.awt.Color(255, 255, 255)); pnlCenter.setMinimumSize(new java.awt.Dimension(0, 0)); pnlCenter.setPreferredSize(new java.awt.Dimension(250, 0)); java.awt.FlowLayout flowLayout1 = new java.awt.FlowLayout(); flowLayout1.setAlignOnBaseline(true); pnlCenter.setLayout(flowLayout1); pnlCenter.add(filler3); pnlInputs.setBackground(new java.awt.Color(255, 255, 255)); pnlInputs.setPreferredSize(new java.awt.Dimension(220, 110)); tfUsername.setPreferredSize(new java.awt.Dimension(200, 30)); tfUsername.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { tfUsernameMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { tfUsernameMouseExited(evt); } public void mousePressed(java.awt.event.MouseEvent evt) { tfUsernameMousePressed(evt); } }); pnlInputs.add(tfUsername); tfDomain.setPreferredSize(new java.awt.Dimension(200, 30)); pnlInputs.add(tfDomain); tfPassword.setPreferredSize(new java.awt.Dimension(200, 30)); pnlInputs.add(tfPassword); pnlCenter.add(pnlInputs); pnlCheckboxes.setBackground(new java.awt.Color(255, 255, 255)); pnlCheckboxes.setPreferredSize(null); pnlCheckboxes.setLayout(new javax.swing.BoxLayout(pnlCheckboxes, javax.swing.BoxLayout.Y_AXIS)); cbSavePassword.setBackground(new java.awt.Color(255, 255, 255)); cbSavePassword.setText("Save Password"); cbSavePassword.setPreferredSize(new java.awt.Dimension(200, 20)); pnlCheckboxes.add(cbSavePassword); cbAutoLogin.setBackground(new java.awt.Color(255, 255, 255)); cbAutoLogin.setText("Auto login"); cbAutoLogin.setPreferredSize(new java.awt.Dimension(200, 20)); pnlCheckboxes.add(cbAutoLogin); cbLoginInvisible.setBackground(new java.awt.Color(255, 255, 255)); cbLoginInvisible.setText("Login as invisible"); cbLoginInvisible.setPreferredSize(new java.awt.Dimension(200, 20)); pnlCheckboxes.add(cbLoginInvisible); cbAnonymous.setBackground(new java.awt.Color(255, 255, 255)); cbAnonymous.setText("Login anonymously"); cbAnonymous.setPreferredSize(new java.awt.Dimension(200, 20)); pnlCheckboxes.add(cbAnonymous); pnlCenter.add(pnlCheckboxes); pnlBtns.setBackground(new java.awt.Color(255, 255, 255)); pnlBtns.setPreferredSize(new java.awt.Dimension(220, 120)); btnLogin.setBackground(new java.awt.Color(241, 100, 34)); btnLogin.setForeground(new java.awt.Color(255, 255, 255)); btnLogin.setText("Login"); btnLogin.setPreferredSize(new java.awt.Dimension(205, 30)); btnLogin.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnLoginActionPerformed(evt); } }); pnlBtns.add(btnLogin); btnCreateAccount.setBackground(new java.awt.Color(255, 255, 255)); btnCreateAccount.setText("Create Account"); btnCreateAccount.setBorderPainted(false); btnCreateAccount.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING); btnCreateAccount.setOpaque(false); btnCreateAccount.setPreferredSize(new java.awt.Dimension(110, 28)); pnlBtns.add(btnCreateAccount); btnAdvanced.setBackground(new java.awt.Color(255, 255, 255)); btnAdvanced.setText("Advanced"); btnAdvanced.setBorderPainted(false); btnAdvanced.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING); btnAdvanced.setOpaque(false); btnAdvanced.setPreferredSize(new java.awt.Dimension(90, 28)); pnlBtns.add(btnAdvanced); btnReset.setBackground(new java.awt.Color(255, 255, 255)); btnReset.setText("Reset Password"); btnReset.setBorderPainted(false); btnReset.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING); btnReset.setOpaque(false); btnReset.setPreferredSize(new java.awt.Dimension(205, 28)); btnReset.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnResetActionPerformed(evt); } }); pnlBtns.add(btnReset); pnlCenter.add(pnlBtns); add(pnlCenter, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoginActionPerformed // TODO add your handling code here: }//GEN-LAST:event_btnLoginActionPerformed private void tfUsernameMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tfUsernameMousePressed if (SwingUtilities.isRightMouseButton(evt)) { getPopup().show(tfUsername, evt.getX(), evt.getY()); } }//GEN-LAST:event_tfUsernameMousePressed private void tfUsernameMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tfUsernameMouseEntered // getPopup().show(tfUsername, evt.getX(), evt.getY()); }//GEN-LAST:event_tfUsernameMouseEntered private void tfUsernameMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tfUsernameMouseExited // getPopup().setVisible(false); }//GEN-LAST:event_tfUsernameMouseExited private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResetActionPerformed final String url = Default.getString(Default.PASSWORD_RESET_URL); try { BrowserLauncher.openURL(url); } catch (Exception e) { Log.error("Unable to load password " + "reset.", e); } }//GEN-LAST:event_btnResetActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAdvanced; private javax.swing.JButton btnCreateAccount; private javax.swing.JButton btnLogin; private javax.swing.JButton btnReset; private javax.swing.JCheckBox cbAnonymous; private javax.swing.JCheckBox cbAutoLogin; private javax.swing.JCheckBox cbLoginInvisible; private javax.swing.JCheckBox cbSavePassword; private javax.swing.Box.Filler filler1; private javax.swing.Box.Filler filler3; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel lblLogo; public final javax.swing.JLabel lblProgress = new javax.swing.JLabel(); private javax.swing.JPanel pnlBtns; private javax.swing.JPanel pnlCenter; private javax.swing.JPanel pnlCheckboxes; private javax.swing.JPanel pnlInputs; private javax.swing.JPanel pnlLeft; private javax.swing.JTextField tfDomain; private javax.swing.JPasswordField tfPassword; private javax.swing.JTextField tfUsername; // End of variables declaration//GEN-END:variables public JTextField getUsernameField() { return tfUsername; } public JPasswordField getPasswordField() { return tfPassword; } public JButton getBtnLogin() { return btnLogin; } public JCheckBox getCbAutoLogin() { return cbAutoLogin; } /** * Invokes the LoginDialog to be visible. * * @param parentFrame the parentFrame of the Login Dialog. This is used for * correct parenting. */ public void invoke(final JFrame parentFrame) { // Before creating any connections. Update proxy if needed. try { updateProxyConfig(); } catch (Exception e) { Log.error(e); } loginDialog = new JFrame(Default.getString(Default.APPLICATION_NAME)); // Construct Dialog EventQueue.invokeLater(() -> { loginDialog.setIconImage(SparkManager.getApplicationImage().getImage()); loginDialog.setContentPane(this); loginDialog.setLocationRelativeTo(parentFrame); loginDialog.setResizable(false); loginDialog.pack(); loginDialog.setSize(550, 390); // Center dialog on screen GraphicUtils.centerWindowOnScreen(loginDialog); // Show dialog loginDialog.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { quitLogin(); } }); if (getUsernameField().getText().trim().length() > 0) { getPasswordField().requestFocus(); } if (!localPref.isStartedHidden() || !localPref.isAutoLogin()) { // Make dialog top most. loginDialog.setVisible(true); } }); } //This method can be overwritten by subclasses to provide additional validations //(such as certificate download functionality when connecting) protected boolean beforeLoginValidations() { return true; } protected void afterLogin() { // Make certain Enterprise features persist across future logins persistEnterprise(); // Load plugins before Workspace initialization to avoid any UI delays during plugin rendering, but after // Enterprise initialization, which can pull in additional plugin configuration (eg: blacklist). PluginManager.getInstance().loadPlugins(); // Initialize and write default values from "Advanced Connection Preferences" to disk initAdvancedDefaults(); } protected XMPPTCPConnectionConfiguration retrieveConnectionConfiguration() { int port = localPref.getXmppPort(); int checkForPort = loginServer.indexOf(":"); if (checkForPort != -1) { String portString = loginServer.substring(checkForPort + 1); if (ModelUtil.hasLength(portString)) { // Set new port. port = Integer.valueOf(portString); } } ConnectionConfiguration.SecurityMode securityMode = localPref.getSecurityMode(); boolean useOldSSL = localPref.isSSL(); boolean hostPortConfigured = localPref.isHostAndPortConfigured(); ProxyInfo proxyInfo = null; if (localPref.isProxyEnabled()) { ProxyInfo.ProxyType pType = localPref.getProtocol().equals("SOCKS") ? ProxyInfo.ProxyType.SOCKS5 : ProxyInfo.ProxyType.HTTP; String pHost = ModelUtil.hasLength(localPref.getHost()) ? localPref.getHost() : null; int pPort = ModelUtil.hasLength(localPref.getPort()) ? Integer.parseInt(localPref.getPort()) : 0; String pUser = ModelUtil.hasLength(localPref.getProxyUsername()) ? localPref.getProxyUsername() : null; String pPass = ModelUtil.hasLength(localPref.getProxyPassword()) ? localPref.getProxyPassword() : null; if (pHost != null && pPort != 0) { if (pUser == null || pPass == null) { proxyInfo = new ProxyInfo(pType, pHost, pPort, null, null); } else { proxyInfo = new ProxyInfo(pType, pHost, pPort, pUser, pPass); } } else { Log.error("No proxy info found but proxy type is enabled!"); } } DomainBareJid xmppDomain; try { xmppDomain = JidCreate.domainBareFrom(loginServer); } catch (XmppStringprepException e) { throw new IllegalStateException(e); } final XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder() .setUsernameAndPassword(loginUsername, loginPassword) .setXmppDomain(xmppDomain) .setPort(port) .setSendPresence(false) .setCompressionEnabled(localPref.isCompressionEnabled()) .setSecurityMode(securityMode); if (securityMode != ConnectionConfiguration.SecurityMode.disabled && localPref.isDisableHostnameVerification()) { TLSUtils.disableHostnameVerificationForTlsCertificates(builder); } if (localPref.isDebuggerEnabled()) { builder.enableDefaultDebugger(); } if (hostPortConfigured) { builder.setHost(localPref.getXmppHost()); } if (localPref.isProxyEnabled()) { builder.setProxyInfo(proxyInfo); } if (securityMode != ConnectionConfiguration.SecurityMode.disabled && !useOldSSL) { // This use STARTTLS which starts initially plain connection to upgrade it to TLS, it use the same port as // plain connections which is 5222. SparkSSLContextCreator.Options options; if (localPref.isAllowClientSideAuthentication()) { options = SparkSSLContextCreator.Options.BOTH; } else { options = SparkSSLContextCreator.Options.ONLY_SERVER_SIDE; } try { SSLContext context = SparkSSLContextCreator.setUpContext(options); builder.setCustomSSLContext(context); builder.setSecurityMode(securityMode); } catch (NoSuchAlgorithmException | KeyManagementException | UnrecoverableKeyException | KeyStoreException | NoSuchProviderException e) { Log.warning("Couldnt establish secured connection", e); } } if (securityMode != ConnectionConfiguration.SecurityMode.disabled && useOldSSL) { if (!hostPortConfigured) { // SMACK 4.1.9 does not support XEP-0368, and does not apply a port change, if the host is not changed too. // Here, we force the host to be set (by doing a DNS lookup), and force the port to 5223 (which is the // default 'old-style' SSL port). DnsName serverNameDnsName = DnsName.from(loginServer); builder.setHost(DNSUtil.resolveXMPPServiceDomain(serverNameDnsName, null, ConnectionConfiguration.DnssecMode.disabled).get(0).getFQDN()); builder.setPort(5223); } SparkSSLContextCreator.Options options; if (localPref.isAllowClientSideAuthentication()) { options = SparkSSLContextCreator.Options.BOTH; } else { options = SparkSSLContextCreator.Options.ONLY_SERVER_SIDE; } builder.setSocketFactory(new SparkSSLSocketFactory(options)); // SMACK 4.1.9 does not recognize an 'old-style' SSL socket as being secure, which will cause a failure when // the 'required' Security Mode is defined. Here, we work around this by replacing that security mode with an // 'if-possible' setting. builder.setSecurityMode(ConnectionConfiguration.SecurityMode.ifpossible); } if (securityMode != ConnectionConfiguration.SecurityMode.disabled) { SASLAuthentication.registerSASLMechanism(new SASLExternalMechanism()); } // SPARK-1747: Don't use the GSS-API SASL mechanism when SSO is disabled. SASLAuthentication.unregisterSASLMechanism(SASLGSSAPIMechanism.class.getName()); SASLAuthentication.unregisterSASLMechanism(SASLGSSAPIv3CompatMechanism.class.getName()); // Add the mechanism only when SSO is enabled (which allows us to register the correct one). if (localPref.isSSOEnabled()) { // SPARK-1740: Register a mechanism that's compatible with Smack 3, when requested. if (localPref.isSaslGssapiSmack3Compatible()) { // SPARK-1747: Don't use the GSSAPI mechanism when SSO is disabled. SASLAuthentication.registerSASLMechanism(new SASLGSSAPIv3CompatMechanism()); } else { SASLAuthentication.registerSASLMechanism(new SASLGSSAPIMechanism()); } } if (localPref.isLoginAnonymously() && !localPref.isSSOEnabled()) { //later login() is called without arguments builder.performSaslAnonymousAuthentication(); } // TODO These were used in Smack 3. Find Smack 4 alternative. // config.setRosterLoadedAtLogin(true); // if(ModelUtil.hasLength(localPref.getTrustStorePath())) { // config.setTruststorePath(localPref.getTrustStorePath()); // config.setTruststorePassword(localPref.getTrustStorePassword()); return builder.build(); } /** * Returns the username the user defined. * * @return the username. */ private String getUsername() { return XmppStringUtils.escapeLocalpart(tfUsername.getText().trim()); } /** * Returns the resulting bareJID from username and server * * @return */ private String getBareJid() { return tfUsername.getText() + "@" + tfDomain.getText(); } /** * Returns the password specified by the user. * * @return the password. */ private String getPassword() { return new String(tfPassword.getPassword()); } /** * Returns the server name specified by the user. * * @return the server name. */ private String getServerName() { return tfDomain.getText().trim(); } /** * Return whether user wants to login as invisible or not. * * @return the true if user wants to login as invisible. */ boolean isLoginAsInvisible() { return cbLoginInvisible.isSelected(); } /** * ActionListener implementation. * * @param e the ActionEvent */ @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == btnCreateAccount) { AccountCreationWizard createAccountPanel = new AccountCreationWizard(); createAccountPanel.invoke(loginDialog); if (createAccountPanel.isRegistered()) { tfUsername.setText(createAccountPanel.getUsernameWithoutEscape()); tfPassword.setText(createAccountPanel.getPassword()); tfDomain.setText(createAccountPanel.getServer()); btnLogin.setEnabled(true); } } else if (e.getSource() == btnLogin) { validateLogin(); } else if (e.getSource() == btnAdvanced) { final LoginSettingDialog loginSettingsDialog = new LoginSettingDialog(); loginSettingsDialog.invoke(loginDialog); useSSO(localPref.isSSOEnabled()); } else if (e.getSource() == cbSavePassword) { cbAutoLogin.setEnabled(cbSavePassword.isSelected()); if (!cbSavePassword.isSelected()) { cbAutoLogin.setSelected(false); } } else if (e.getSource() == cbAutoLogin) { if ((cbAutoLogin.isSelected() && (!localPref.isSSOEnabled()))) { cbSavePassword.setSelected(true); } } else if (e.getSource() == cbAnonymous) { tfUsername.setEnabled(!cbAnonymous.isSelected()); tfPassword.setEnabled(!cbAnonymous.isSelected()); validateDialog(); } } private JPopupMenu getPopup() { JPopupMenu popup = new JPopupMenu(); for (final String key : _usernames) { JMenuItem menu = new JMenuItem(key); final String username = key.split("@")[0]; final String host = key.split("@")[1]; menu.addActionListener(e -> { tfUsername.setText(username); tfDomain.setText(host); try { tfPassword.setText(localPref.getPasswordForUser(getBareJid())); if (tfPassword.getPassword().length < 1) { btnLogin.setEnabled(cbAnonymous.isSelected()); } else { btnLogin.setEnabled(true); } } catch (Exception e1) { } }); popup.add(menu); } return popup; } /** * KeyListener implementation. * * @param e the KeyEvent to process. */ @Override public void keyTyped(KeyEvent e) { validate(e); } @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_RIGHT && ((JTextField) e.getSource()).getCaretPosition() == ((JTextField) e.getSource()).getText().length()) { getPopup().show(otherUsers, 0, 0); } } @Override public void keyReleased(KeyEvent e) { validateDialog(); } /** * Checks the users input and enables/disables the login button depending on * state. */ private void validateDialog() { btnLogin.setEnabled(cbAnonymous.isSelected() || ModelUtil.hasLength(getUsername()) && (ModelUtil.hasLength(getPassword()) || localPref.isSSOEnabled()) && ModelUtil.hasLength(getServerName())); } /** * Validates key input. * * @param e the keyEvent. */ private void validate(KeyEvent e) { if (btnLogin.isEnabled() && e.getKeyChar() == KeyEvent.VK_ENTER) { validateLogin(); } } @Override public void focusGained(FocusEvent e) { Object o = e.getSource(); if (o instanceof JTextComponent) { ((JTextComponent) o).selectAll(); } } @Override public void focusLost(FocusEvent e) { } /** * Enables/Disables the editable components in the login screen. * * @param available true to enable components, otherwise false to disable. */ private void setComponentsAvailable(boolean available) { cbSavePassword.setEnabled(available); cbAutoLogin.setEnabled(available); cbLoginInvisible.setEnabled(available); cbAnonymous.setEnabled(available); // Need to set both editable and enabled for best behavior. tfUsername.setEditable(available); tfUsername.setEnabled(available && !cbAnonymous.isSelected()); tfPassword.setEditable(available); tfPassword.setEnabled(available && !cbAnonymous.isSelected()); if (Default.getBoolean(Default.HOST_NAME_CHANGE_DISABLED) || !localPref.getHostNameChange()) { tfDomain.setEditable(false); tfDomain.setEnabled(false); } else { tfDomain.setEditable(available); tfDomain.setEnabled(available); } if (available) { // Reapply focus to password field tfPassword.requestFocus(); } } /** * Displays the progress bar. * * @param visible true to display progress bar, false to hide it. */ private void setProgressBarVisible(boolean visible) { lblProgress.setVisible(visible); } /** * Validates the users login information. */ private void validateLogin() { final SwingWorker loginValidationThread = new SwingWorker() { @Override public Object construct() { setLoginUsername(getUsername()); setLoginPassword(getPassword()); setLoginServer(getServerName()); boolean loginSuccessfull = beforeLoginValidations() && login(); if (loginSuccessfull) { afterLogin(); lblProgress.setText(Res.getString("message.connecting.please.wait")); // Startup Spark startSpark(); // dispose login dialog loginDialog.dispose(); // Show ChangeLog if we need to. // new ChangeLogDialog().showDialog(); } else { EventQueue.invokeLater(() -> { setComponentsAvailable(true); setProgressBarVisible(false); }); } return loginSuccessfull; } }; // Start the login process in separate thread. // Disable text fields setComponentsAvailable(false); // Show progressbar setProgressBarVisible(true); loginValidationThread.start(); } @Override public Dimension getPreferredSize() { final Dimension dim = super.getPreferredSize(); dim.height = 230; return dim; } public void useSSO(boolean use) { if (use) { //usernameLabel.setVisible(true); tfUsername.setVisible(true); //passwordLabel.setVisible(false); tfPassword.setVisible(false); cbSavePassword.setVisible(false); cbSavePassword.setSelected(false); tfDomain.setVisible(true); cbAutoLogin.setVisible(true); //serverLabel.setVisible(true); cbLoginInvisible.setVisible(true); cbAnonymous.setVisible(false); if (localPref.getDebug()) { System.setProperty("java.security.krb5.debug", "true"); System.setProperty("sun.security.krb5.debug", "true"); } else { System.setProperty("java.security.krb5.debug", "false"); System.setProperty("sun.security.krb5.debug", "false"); } String ssoMethod = localPref.getSSOMethod(); if (!ModelUtil.hasLength(ssoMethod)) { ssoMethod = "file"; } System.setProperty("javax.security.auth.useSubjectCredsOnly", "false"); GSSAPIConfiguration config = new GSSAPIConfiguration(ssoMethod.equals("file")); Configuration.setConfiguration(config); LoginContext lc; String princName = localPref.getLastUsername(); String princRealm = null; try { lc = new LoginContext("com.sun.security.jgss.krb5.initiate"); lc.login(); Subject mySubject = lc.getSubject(); for (Principal p : mySubject.getPrincipals()) { //TODO: check if principal is a kerberos principal first... String name = p.getName(); int indexOne = name.indexOf("@"); if (indexOne != -1) { princName = name.substring(0, indexOne); princRealm = name.substring(indexOne + 1); } btnLogin.setEnabled(true); } } catch (LoginException le) { Log.debug(le.getMessage()); //useSSO(false); } String ssoKdc; if (ssoMethod.equals("dns")) { if (princRealm != null) { //princRealm is null if we got a LoginException above. ssoKdc = getDnsKdc(princRealm); System.setProperty("java.security.krb5.realm", princRealm); System.setProperty("java.security.krb5.kdc", ssoKdc); } } else if (ssoMethod.equals("manual")) { princRealm = localPref.getSSORealm(); ssoKdc = localPref.getSSOKDC(); System.setProperty("java.security.krb5.realm", princRealm); System.setProperty("java.security.krb5.kdc", ssoKdc); } else { //Assume "file" method. We don't have to do anything special, //java takes care of it for us. Unset the props if they are set System.clearProperty("java.security.krb5.realm"); System.clearProperty("java.security.krb5.kdc"); } String userName = localPref.getLastUsername(); if (ModelUtil.hasLength(userName)) { tfUsername.setText(userName); } else { tfUsername.setText(princName); } } else { cbAutoLogin.setVisible(true); tfUsername.setVisible(true); tfPassword.setVisible(true); cbSavePassword.setVisible(true); // usernameLabel.setVisible(true); // passwordLabel.setVisible(true); // serverLabel.setVisible(true); tfDomain.setVisible(true); cbLoginInvisible.setVisible(true); cbAnonymous.setVisible(true); Configuration.setConfiguration(null); validateDialog(); } } /** * Login to the specified server using username, password, and workgroup. * Handles error representation as well as logging. * * @return true if login was successful, false otherwise */ private boolean login() { localPref = SettingsManager.getLocalPreferences(); localPref.setLoginAsInvisible(cbLoginInvisible.isSelected()); localPref.setLoginAnonymously(cbAnonymous.isSelected()); if (localPref.isDebuggerEnabled()) { SmackConfiguration.DEBUG = true; } SmackConfiguration.setDefaultReplyTimeout(localPref.getTimeOut() * 1000); try { // TODO: SPARK-2140 - add support to Spark for stream management. Challenges expected around reconnection logic! XMPPTCPConnection.setUseStreamManagementDefault(false); connection = new XMPPTCPConnection(retrieveConnectionConfiguration()); connection.setParsingExceptionCallback(new ExceptionLoggingCallback()); // If we want to launch the Smack debugger, we have to check if we are on the dispatch thread, because Smack will create an UI. if (localPref.isDebuggerEnabled() && !EventQueue.isDispatchThread()) { // Exception handling should be no different from the regular flow. final Exception[] exception = new Exception[1]; EventQueue.invokeAndWait(() -> { try { connection.connect(); } catch (IOException | SmackException | XMPPException | InterruptedException e) { exception[0] = e; } }); if (exception[0] != null) { throw exception[0]; } } else { connection.connect(); } if (localPref.isLoginAnonymously() && !localPref.isSSOEnabled()) { // ConnectionConfiguration.performSaslAnonymousAuthentication() used earlier in connection configuration builder, // so now we can just login() connection.login(); } else { String resource = localPref.getResource(); if (Default.getBoolean(Default.HOSTNAME_AS_RESOURCE) || localPref.isUseHostnameAsResource()) { try { resource = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { Log.warning("Cannot set hostname as resource - unable to retrieve hostname.", e); } } else if (Default.getBoolean(Default.VERSION_AS_RESOURCE) || localPref.isUseVersionAsResource()) { resource = JiveInfo.getName() + " " + JiveInfo.getVersion(); } Resourcepart resourcepart = Resourcepart.from(modifyWildcards(resource).trim()); connection.login(getLoginUsername(), getLoginPassword(), resourcepart); } final SessionManager sessionManager = SparkManager.getSessionManager(); sessionManager.setServerAddress(connection.getXMPPServiceDomain()); sessionManager.initializeSession(connection, getLoginUsername(), getLoginPassword()); sessionManager.setJID(connection.getUser()); final ReconnectionManager reconnectionManager = ReconnectionManager.getInstanceFor(connection); reconnectionManager.setFixedDelay(localPref.getReconnectDelay()); reconnectionManager.setReconnectionPolicy(ReconnectionManager.ReconnectionPolicy.FIXED_DELAY); reconnectionManager.enableAutomaticReconnection(); final CarbonManager carbonManager = CarbonManager.getInstanceFor(connection); if (carbonManager.isSupportedByServer()) { carbonManager.enableCarbons(); } } catch (Exception xee) { Log.error("Exception in Login:", xee); final String errorMessage; if (localPref.isSSOEnabled()) { errorMessage = Res.getString("title.advanced.connection.sso.unable"); } else if (xee.getMessage() != null && xee.getMessage().contains("not-authorized")) { errorMessage = Res.getString("message.invalid.username.password"); } else if (xee.getMessage() != null && (xee.getMessage().contains("java.net.UnknownHostException:") || xee.getMessage().contains("Network is unreachable") || xee.getMessage().contains("java.net.ConnectException: Connection refused:"))) { errorMessage = Res.getString("message.server.unavailable"); } else if (xee.getMessage() != null && xee.getMessage().contains("Hostname verification of certificate failed")) { errorMessage = Res.getString("message.cert.hostname.verification.failed"); } else if (xee.getMessage() != null && xee.getMessage().contains("unable to find valid certification path to requested target")) { errorMessage = Res.getString("message.cert.verification.failed"); } else if (xee.getMessage() != null && xee.getMessage().contains("StanzaError: conflict")) { errorMessage = Res.getString("label.conflict.error"); } else if (xee instanceof SmackException) { errorMessage = xee.getLocalizedMessage(); } else { errorMessage = Res.getString("message.unrecoverable.error"); } EventQueue.invokeLater(() -> { lblProgress.setVisible(false); // Show error dialog UIManager.put("OptionPane.okButtonText", Res.getString("ok")); if (!loginDialog.isVisible()) { loginDialog.setVisible(true); } if (loginDialog.isVisible()) { if (xee.getMessage() != null && xee.getMessage().contains("Self Signed certificate")) { // Handle specific case: if server certificate is self-signed, but self-signed certs are not allowed, show a popup allowing the user to override. // Prompt user if they'd like to add the failed chain to the trust store. final Object[] options = { Res.getString("yes"), Res.getString("no") }; final int userChoice = JOptionPane.showOptionDialog(this, Res.getString("dialog.certificate.ask.allow.self-signed"), Res.getString("title.certificate"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1]); if (userChoice == JOptionPane.YES_OPTION) { // Toggle the preference. localPref.setAcceptSelfSigned(true); SettingsManager.saveSettings(); // Attempt to login again. validateLogin(); } } else { final X509Certificate[] lastFailedChain = SparkTrustManager.getLastFailedChain(); final SparkTrustManager sparkTrustManager = (SparkTrustManager) SparkTrustManager.getTrustManagerList()[0]; // Handle specific case: if path validation failed because of an unrecognized CA, show popup allowing the user to add the certificate. if (lastFailedChain != null && ((xee.getMessage() != null && xee.getMessage().contains("Certificate not in the TrustStore")) || !sparkTrustManager.containsTrustAnchorFor(lastFailedChain))) { // Prompt user if they'd like to add the failed chain to the trust store. final CertificateModel certModel = new CertificateModel(lastFailedChain[0]); final Object[] options = { Res.getString("yes"), Res.getString("no") }; final int userChoice = JOptionPane.showOptionDialog(this, new UnrecognizedServerCertificatePanel(certModel), Res.getString("title.certificate"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1]); if (userChoice == JOptionPane.YES_OPTION) { // Add the certificate chain to the truststore. sparkTrustManager.addChain(lastFailedChain); // Attempt to login again. validateLogin(); } } else { // For anything else, show a generic error dialog. MessageDialog.showErrorDialog(loginDialog, errorMessage, xee); } } } }); setEnabled(true); return false; } // Since the connection and workgroup are valid. Add a ConnectionListener connection.addConnectionListener(SparkManager.getSessionManager()); // Initialize chat state notification mechanism in smack ChatStateManager.getInstance(SparkManager.getConnection()); // Persist information localPref.setLastUsername(getLoginUsername()); // Check to see if the password should be saved or cleared from file. if (cbSavePassword.isSelected()) { try { localPref.setPasswordForUser(getBareJid(), getPassword()); } catch (Exception e) { Log.error("Error encrypting password.", e); } } else { try { localPref.clearPasswordForAllUsers();//clearPasswordForUser(getBareJid()); } catch (Exception e) { Log.debug("Unable to clear saved password..." + e); } } localPref.setSavePassword(cbSavePassword.isSelected()); localPref.setAutoLogin(cbAutoLogin.isSelected()); localPref.setServer(tfDomain.getText()); SettingsManager.saveSettings(); return true; } @Override public void handle(Callback[] callbacks) throws IOException { for (Callback callback : callbacks) { if (callback instanceof NameCallback) { NameCallback ncb = (NameCallback) callback; ncb.setName(getLoginUsername()); } else if (callback instanceof PasswordCallback) { PasswordCallback pcb = (PasswordCallback) callback; pcb.setPassword(getPassword().toCharArray()); } else { Log.error("Unknown callback requested: " + callback.getClass().getSimpleName()); } } } /** * If the user quits, just shut down the application. */ private void quitLogin() { System.exit(1); } /** * Initializes Spark and initializes all plugins. */ private void startSpark() { // Invoke the MainWindow. try { EventQueue.invokeLater(() -> { final MainWindow mainWindow = MainWindow.getInstance(); /* if (tray != null) { // Remove trayIcon tray.removeTrayIcon(trayIcon); } */ // Creates the Spark Workspace and add to MainWindow Workspace workspace = Workspace.getInstance(); LayoutSettings settings = LayoutSettingsManager.getLayoutSettings(); LocalPreferences pref = SettingsManager.getLocalPreferences(); if (pref.isDockingEnabled()) { JSplitPane splitPane = mainWindow.getSplitPane(); workspace.getCardPanel().setMinimumSize(null); splitPane.setLeftComponent(workspace.getCardPanel()); SparkManager.getChatManager().getChatContainer().setMinimumSize(null); splitPane.setRightComponent(SparkManager.getChatManager().getChatContainer()); int dividerLoc = settings.getSplitPaneDividerLocation(); if (dividerLoc != -1) { mainWindow.getSplitPane().setDividerLocation(dividerLoc); } else { mainWindow.getSplitPane().setDividerLocation(240); } mainWindow.getContentPane().add(splitPane, BorderLayout.CENTER); } else { mainWindow.getContentPane().add(workspace.getCardPanel(), BorderLayout.CENTER); } final Rectangle mainWindowBounds = settings.getMainWindowBounds(); if (mainWindowBounds == null || mainWindowBounds.width <= 0 || mainWindowBounds.height <= 0) { // Use Default size mainWindow.setSize(500, 520); // Center Window on Screen GraphicUtils.centerWindowOnScreen(mainWindow); } else { mainWindow.setBounds(mainWindowBounds); } if (loginDialog != null) { if (loginDialog.isVisible()) { mainWindow.setVisible(true); } loginDialog.dispose(); } // Build the layout in the workspace workspace.buildLayout(); }); } catch (Exception e) { e.printStackTrace(); } } /** * Updates System properties with Proxy configuration. * * @throws Exception thrown if an exception occurs. */ private void updateProxyConfig() throws Exception { if (ModelUtil.hasLength(Default.getString(Default.PROXY_PORT)) && ModelUtil.hasLength(Default.getString(Default.PROXY_HOST))) { String port = Default.getString(Default.PROXY_PORT); String host = Default.getString(Default.PROXY_HOST); System.setProperty("socksProxyHost", host); System.setProperty("socksProxyPort", port); return; } boolean proxyEnabled = localPref.isProxyEnabled(); if (proxyEnabled) { String host = localPref.getHost(); String port = localPref.getPort(); String username = localPref.getProxyUsername(); String password = localPref.getProxyPassword(); String protocol = localPref.getProtocol(); if (protocol.equals("SOCKS")) { System.setProperty("socksProxyHost", host); System.setProperty("socksProxyPort", port); if (ModelUtil.hasLength(username) && ModelUtil.hasLength(password)) { System.setProperty("java.net.socks.username", username); System.setProperty("java.net.socks.password", password); } } else { System.setProperty("http.proxyHost", host); System.setProperty("http.proxyPort", port); System.setProperty("https.proxyHost", host); System.setProperty("https.proxyPort", port); if (ModelUtil.hasLength(username) && ModelUtil.hasLength(password)) { System.setProperty("http.proxyUser", username); System.setProperty("http.proxyPassword", password); } } } } /** * Checks for historic Spark settings and upgrades the user. * * @throws Exception thrown if an error occurs. */ private void checkForOldSettings() throws Exception { // Check for old settings.xml File settingsXML = new File(Spark.getSparkUserHome(), "/settings.xml"); if (settingsXML.exists()) { SAXReader saxReader = new SAXReader(); Document pluginXML; try { // SPARK-2147: Disable certain features for security purposes (CVE-2020-10683) saxReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); saxReader.setFeature("http://xml.org/sax/features/external-general-entities", false); saxReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); pluginXML = saxReader.read(settingsXML); } catch (DocumentException e) { Log.error(e); return; } List<?> plugins = pluginXML.selectNodes("/settings"); for (Object plugin1 : plugins) { Element plugin = (Element) plugin1; String username = plugin.selectSingleNode("username").getText(); localPref.setLastUsername(username); String server = plugin.selectSingleNode("server").getText(); localPref.setServer(server); String autoLogin = plugin.selectSingleNode("autoLogin").getText(); localPref.setAutoLogin(Boolean.parseBoolean(autoLogin)); String savePassword = plugin.selectSingleNode("savePassword").getText(); localPref.setSavePassword(Boolean.parseBoolean(savePassword)); String password = plugin.selectSingleNode("password").getText(); localPref.setPasswordForUser(username + "@" + server, password); SettingsManager.saveSettings(); } // Delete settings File settingsXML.delete(); } } /** * Use DNS to lookup a KDC * * @param realm The realm to look up * @return the KDC hostname */ private String getDnsKdc(String realm) { //Assumption: the KDC will be found with the SRV record // _kerberos._udp.$realm try { Hashtable<String, String> env = new Hashtable<>(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); DirContext context = new InitialDirContext(env); Attributes dnsLookup = context.getAttributes("_kerberos._udp." + realm, new String[]{"SRV"}); ArrayList<Integer> priorities = new ArrayList<>(); HashMap<Integer, List<String>> records = new HashMap<>(); for (Enumeration<?> e = dnsLookup.getAll(); e.hasMoreElements();) { Attribute record = (Attribute) e.nextElement(); for (Enumeration<?> e2 = record.getAll(); e2.hasMoreElements();) { String sRecord = (String) e2.nextElement(); String[] sRecParts = sRecord.split(" "); Integer pri = Integer.valueOf(sRecParts[0]); if (priorities.contains(pri)) { List<String> recs = records.get(pri); if (recs == null) { recs = new ArrayList<>(); } recs.add(sRecord); } else { priorities.add(pri); List<String> recs = new ArrayList<>(); recs.add(sRecord); records.put(pri, recs); } } } Collections.sort(priorities); List<String> l = records.get(priorities.get(0)); String toprec = l.get(0); String[] sRecParts = toprec.split(" "); return sRecParts[3]; } catch (NamingException e) { return ""; } } protected String getLoginUsername() { return loginUsername; } protected void setLoginUsername(String loginUsername) { this.loginUsername = loginUsername; } protected String getLoginPassword() { return loginPassword; } protected void setLoginPassword(String loginPassword) { this.loginPassword = loginPassword; } protected String getLoginServer() { return loginServer; } protected void setLoginServer(String loginServer) { this.loginServer = loginServer; } protected ArrayList<String> getUsernames() { return _usernames; } private void persistEnterprise() { new Enterprise(); localPref.setAccountsReg(Enterprise.containsFeature(Enterprise.ACCOUNTS_REG_FEATURE)); localPref.setAdvancedConfig(Enterprise.containsFeature(Enterprise.ADVANCED_CONFIG_FEATURE)); localPref.setHostNameChange(Enterprise.containsFeature(Enterprise.HOST_NAME_FEATURE)); localPref.setInvisibleLogin(Enterprise.containsFeature(Enterprise.INVISIBLE_LOGIN_FEATURE)); localPref.setAnonymousLogin(Enterprise.containsFeature(Enterprise.ANONYMOUS_LOGIN_FEATURE)); localPref.setPswdAutologin(Enterprise.containsFeature(Enterprise.SAVE_PASSWORD_FEATURE)); localPref.setUseHostnameAsResource(Enterprise.containsFeature(Enterprise.HOSTNAME_AS_RESOURCE_FEATURE)); localPref.setUseVersionAsResource(Enterprise.containsFeature(Enterprise.VERSION_AS_RESOURCE_FEATURE)); } private void initAdvancedDefaults() { localPref.setCompressionEnabled(localPref.isCompressionEnabled()); localPref.setDebuggerEnabled(localPref.isDebuggerEnabled()); localPref.setDisableHostnameVerification(localPref.isDisableHostnameVerification()); localPref.setHostAndPortConfigured(localPref.isHostAndPortConfigured()); localPref.setProtocol("SOCKS"); localPref.setProxyEnabled(localPref.isProxyEnabled()); // localPref.setProxyPassword(""); // localPref.setProxyUsername(""); localPref.setResource("Spark"); localPref.setSaslGssapiSmack3Compatible(localPref.isSaslGssapiSmack3Compatible()); localPref.setSSL(localPref.isSSL()); localPref.setSecurityMode(localPref.getSecurityMode()); localPref.setSSOEnabled(localPref.isSSOEnabled()); localPref.setSSOMethod("file"); localPref.setTimeOut(localPref.getTimeOut()); // localPref.setTrustStorePassword(""); // localPref.setTrustStorePath(""); localPref.setUseHostnameAsResource(localPref.isUseHostnameAsResource()); localPref.setUseVersionAsResource(localPref.isUseVersionAsResource()); // localPref.setXmppHost(""); localPref.setXmppPort(localPref.getXmppPort()); SettingsManager.saveSettings(); } }
package ch.unizh.ini.jaer.chip.retina; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.Serializable; import java.util.Observable; import java.util.Observer; import javax.swing.AbstractButton; import javax.swing.ButtonGroup; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JRadioButtonMenuItem; import javax.swing.JTabbedPane; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.aemonitor.AEPacketRaw; import net.sf.jaer.biasgen.BiasgenHardwareInterface; import net.sf.jaer.biasgen.ChipControlPanel; import net.sf.jaer.biasgen.IPot; import net.sf.jaer.biasgen.IPotArray; import net.sf.jaer.biasgen.PotTweakerUtilities; import net.sf.jaer.chip.AEChip; import net.sf.jaer.chip.Chip; import net.sf.jaer.chip.RetinaExtractor; import net.sf.jaer.event.BasicEvent; import net.sf.jaer.event.EventPacket; import net.sf.jaer.event.OutputEventIterator; import net.sf.jaer.event.PolarityEvent; import net.sf.jaer.event.TypedEvent; import net.sf.jaer.graphics.DavisRenderer; import net.sf.jaer.graphics.ChipRendererDisplayMethodRGBA; import net.sf.jaer.hardwareinterface.HardwareInterface; import net.sf.jaer.hardwareinterface.usb.cypressfx2.CypressFX2DVS128HardwareInterface; import net.sf.jaer.hardwareinterface.usb.cypressfx2.HasLEDControl; import net.sf.jaer.hardwareinterface.usb.cypressfx2.HasLEDControl.LEDState; import net.sf.jaer.hardwareinterface.usb.cypressfx2.HasResettablePixelArray; import net.sf.jaer.hardwareinterface.usb.cypressfx2.HasSyncEventOutput; import net.sf.jaer.util.HexString; import net.sf.jaer.util.RemoteControlCommand; import net.sf.jaer.util.RemoteControlled; import net.sf.jaer.util.WarningDialogWithDontShowPreference; /** * Describes DVS128 retina and its event extractor and bias generator. This * camera is the Tmpdiff128 chip with certain biases tied to the rails to * enhance AE bus bandwidth and it achieves about 2 Meps, as opposed to the * approx 500 keps using the on-chip Tmpdiff128 biases. * <p> * Two constructors ara available, the vanilla constructor is used for event * playback and the one with a HardwareInterface parameter is useful for live * capture. {@link #setHardwareInterface} is used when the hardware interface is * constructed after the retina object. The constructor that takes a hardware * interface also constructs the biasgen interface. * * @author tobi */ @Description("DVS128 Dynamic Vision Sensor") @DevelopmentStatus(DevelopmentStatus.Status.Stable) public class DVS640 extends AETemporalConstastRetina implements Serializable { private DavisRenderer dvsRenderer; private ChipRendererDisplayMethodRGBA dvsDisplayMethod = null; /** * Creates a new instance of DVS640. No biasgen is constructed. */ public DVS640() { setName("DVS640"); setSizeX(640); setSizeY(480); setNumCellTypes(2); setPixelHeightUm(9); setPixelWidthUm(9); setEventExtractor(new Extractor(this)); setBiasgen(null); // only for viewing data // ChipCanvas c = getCanvas(); dvsRenderer = new DVS640.DvsRenderer(this); setRenderer(dvsRenderer); dvsDisplayMethod = new ChipRendererDisplayMethodRGBA(this.getCanvas()); getCanvas().addDisplayMethod(dvsDisplayMethod); getCanvas().setDisplayMethod(dvsDisplayMethod); } /** * Creates a new instance of DVS128 * * @param hardwareInterface an existing hardware interface. This constructor * is preferred. It makes a new Biasgen object to talk to the on-chip * biasgen. */ public DVS640(HardwareInterface hardwareInterface) { this(); setHardwareInterface(hardwareInterface); } @Override public void onDeregistration() { super.onDeregistration(); if (getAeViewer() == null) { return; } } @Override public void onRegistration() { super.onRegistration(); if (getAeViewer() == null) { return; } } /** * the event extractor for DVS128. DVS128 has two polarities 0 and 1. Here * the polarity is flipped by the extractor so that the raw polarity 0 * becomes 1 in the extracted event. The ON events have raw polarity 0. 1 is * an ON event after event extraction, which flips the type. Raw polarity 1 * is OFF event, which becomes 0 after extraction. */ public class Extractor extends RetinaExtractor { final int XSHIFT = 1, XMASK = 0b11_1111_1111<<XSHIFT , YSHIFT = 11, YMASK = 0b11_1111_1111<<YSHIFT; public Extractor(DVS640 chip) { super(chip); setXmask(XMASK); // 10 bits for 640 setXshift((byte) XSHIFT); setYmask(YMASK); // also 10 bits for 480 setYshift((byte) YSHIFT); setTypemask(1); setTypeshift((byte) 0); setFlipx(true); // flip x to match rosbags from ev-imo dataset (tobi) setFlipy(false); setFliptype(false); } @Override public int reconstructRawAddressFromEvent(TypedEvent e) { return reconstructDefaultRawAddressFromEvent(e); } /** * extracts the meaning of the raw events. * * @param in the raw events, can be null * @return out the processed events. these are partially processed * in-place. empty packet is returned if null is supplied as in. This * event packet is reused and should only be used by a single thread of * execution or for a single input stream, or mysterious results may * occur! */ @Override synchronized public EventPacket extractPacket(AEPacketRaw in) { if (out == null) { out = new EventPacket<PolarityEvent>(getChip().getEventClass()); } else { out.clear(); } extractPacket(in, out); return out; } private int printedSyncBitWarningCount = 3; /** * Extracts the meaning of the raw events. This form is used to supply * an output packet. This method is used for real time event filtering * using a buffer of output events local to data acquisition. An * AEPacketRaw may contain multiple events, not all of them have to sent * out as EventPackets. An AEPacketRaw is a set(!) of addresses and * corresponding timing moments. * * A first filter (independent from the other ones) is implemented by * subSamplingEnabled and getSubsampleThresholdEventCount. The latter * may limit the amount of samples in one package to say 50,000. If * there are 160,000 events and there is a sub sample threshold of * 50,000, a "skip parameter" set to 3. Every so now and then the * routine skips with 4, so we end up with 50,000. It's an * approximation, the amount of events may be less than 50,000. The * events are extracted uniform from the input. * * @param in the raw events, can be null * @param out the processed events. these are partially processed * in-place. empty packet is returned if null is supplied as input. */ @Override synchronized public void extractPacket(AEPacketRaw in, EventPacket out) { if (in == null) { return; } int n = in.getNumEvents(); //addresses.length; out.systemModificationTimeNs = in.systemModificationTimeNs; int skipBy = 1; if (isSubSamplingEnabled()) { while ((n / skipBy) > getSubsampleThresholdEventCount()) { skipBy++; } } int sxm = sizeX - 1; int[] a = in.getAddresses(); int[] timestamps = in.getTimestamps(); OutputEventIterator outItr = out.outputIterator(); for (int i = 0; i < n; i += skipBy) { // TODO bug here? int addr = a[i]; PolarityEvent e = (PolarityEvent) outItr.nextOutput(); e.address = addr; e.timestamp = (timestamps[i]); e.setSpecial(false); e.type = (byte) (addr & 1); e.polarity = e.type == 0 ? PolarityEvent.Polarity.Off : PolarityEvent.Polarity.On; e.x = (short) (sxm - (((addr & XMASK) >>> XSHIFT))); e.y = (short) ((addr & YMASK) >>> YSHIFT); } } } private class DvsRenderer extends DavisRenderer { public DvsRenderer(AEChip chip) { super(chip); } @Override public boolean isDisplayEvents() { return true; } @Override public boolean isDisplayFrames() { return false; } } }
package org.radargun.stages.test; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.LockSupport; import org.radargun.Operation; import org.radargun.logging.Log; import org.radargun.logging.LogFactory; import org.radargun.stats.Request; import org.radargun.stats.RequestSet; import org.radargun.stats.Statistics; import org.radargun.traits.Transactional; import org.radargun.utils.TimeService; /** * Each stressor operates according to its {@link OperationLogic logic} - the instance is private to each thread. * After finishing the {@linkplain OperationLogic#init(Stressor) init phase}, all stressors synchronously * execute logic's {@link OperationLogic#run(org.radargun.Operation) run} method until * the {@link Completion#moreToRun()} returns false. * * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ public class Stressor extends Thread { private static Log log = LogFactory.getLog(Stressor.class); private final TestStage stage; private final int threadIndex; private final int globalThreadIndex; private final OperationLogic logic; private final Random random; private final OperationSelector operationSelector; private final Completion completion; private final boolean logTransactionExceptions; private long thinkTime; private boolean useTransactions; private int txRemainingOperations = 0; private RequestSet requests; private Transactional.Transaction ongoingTx; private Statistics stats; private boolean started = false; private CountDownLatch threadCountDown; // uniform rate limiter final long uniformRateLimiterOpsPerNano; long uniformRateLimiterOpIndex = 0; long uniformRateLimiterStart = Long.MIN_VALUE; public Stressor(TestStage stage, OperationLogic logic, int globalThreadIndex, int threadIndex, CountDownLatch threadCountDown) { super("Stressor-" + threadIndex); this.stage = stage; this.threadIndex = threadIndex; this.globalThreadIndex = globalThreadIndex; this.logic = logic; this.random = ThreadLocalRandom.current(); this.completion = stage.getCompletion(); this.operationSelector = stage.getOperationSelector(); this.logTransactionExceptions = stage.logTransactionExceptions; this.threadCountDown = threadCountDown; this.thinkTime = stage.thinkTime; this.uniformRateLimiterOpsPerNano = TimeUnit.MILLISECONDS.toNanos(stage.cycleTime); } private boolean recording() { return this.started && !stage.isFinished(); } @Override public void run() { try { logic.init(this); stats = stage.createStatistics(); runInternal(); } catch (Exception e) { log.error("Unexpected error in stressor!", e); stage.setTerminated(); } finally { if (stats != null) { stats.end(); } logic.destroy(); } } private void runInternal() { boolean counted = false; try { // the operation selector needs to be started before any #next() call operationSelector.start(); while (!stage.isTerminated()) { boolean started = stage.isStarted(); if (started) { txRemainingOperations = 0; if (ongoingTx != null) { endTransactionAndRegisterStats(null); } break; } else { if (!counted) { threadCountDown.countDown(); counted = true; } Operation operation = operationSelector.next(random); try { logic.run(operation); if (thinkTime > 0) sleep(thinkTime); } catch (OperationLogic.RequestException e) { // the exception was already logged in makeRequest } catch (InterruptedException e) { log.trace("Stressor interrupted.", e); interrupt(); } } } uniformRateLimiterStart = TimeService.nanoTime(); stats.begin(); this.started = true; completion.start(); int i = 0; while (!stage.isTerminated()) { Operation operation = operationSelector.next(random); if (!completion.moreToRun()) break; try { logic.run(operation); if (thinkTime > 0) sleep(thinkTime); } catch (OperationLogic.RequestException e) { // the exception was already logged in makeRequest } catch (InterruptedException e) { log.trace("Stressor interrupted.", e); interrupt(); } i++; completion.logProgress(i); } } finally { if (txRemainingOperations > 0) { endTransactionAndRegisterStats(null); } } } public <T> T wrap(T resource) { return ongoingTx.wrap(resource); } public <T> T makeRequest(Invocation<T> invocation) throws OperationLogic.RequestException { return makeRequest(invocation, true); } public <T> T makeRequest(Invocation<T> invocation, boolean countForTx) throws OperationLogic.RequestException { if (useTransactions && txRemainingOperations <= 0) { try { ongoingTx = stage.transactional.getTransaction(); logic.transactionStarted(); if (recording()) { requests = stats.requestSet(); } Request beginRequest = startTransaction(); if (requests != null && beginRequest != null) { requests.add(beginRequest); } txRemainingOperations = stage.transactionSize; } catch (TransactionException e) { throw new OperationLogic.RequestException(e); } } T result = null; Exception exception = null; Request request = nextRequest(); try { result = invocation.invoke(); succeeded(request, invocation.operation()); // make sure that the return value cannot be optimized away // however, we can't be 100% sure about reordering without // volatile writes/reads here Blackhole.consume(result); if (countForTx) { txRemainingOperations } } catch (Exception e) { failed(request, invocation.operation()); log.warn("Error in request", e); txRemainingOperations = 0; exception = e; } if (requests != null && request != null && recording()) { requests.add(request); } if (useTransactions && txRemainingOperations <= 0) { endTransactionAndRegisterStats(stage.isSingleTxType() ? invocation.txOperation() : null); } if (exception != null) { throw new OperationLogic.RequestException(exception); } return result; } public <T> void succeeded(Request request, Operation operation) { if (request != null) { if (recording()) { request.succeeded(operation); } else { request.discard(); } } } public <T> void failed(Request request, Operation operation) { if (request != null) { if (recording()) { request.failed(operation); } else { request.discard(); } } } private void endTransactionAndRegisterStats(Operation singleTxOperation) { Request commitRequest = recording() ? stats.startRequest() : null; try { if (stage.commitTransactions) { ongoingTx.commit(); } else { ongoingTx.rollback(); } succeeded(commitRequest, stage.commitTransactions ? Transactional.COMMIT : Transactional.ROLLBACK); } catch (Exception e) { failed(commitRequest, stage.commitTransactions ? Transactional.COMMIT : Transactional.ROLLBACK); if (logTransactionExceptions) { log.error("Failed to end transaction", e); } } finally { if (requests != null) { if (recording()) { requests.add(commitRequest); requests.finished(commitRequest.isSuccessful(), Transactional.DURATION); if (singleTxOperation != null) { requests.finished(commitRequest.isSuccessful(), singleTxOperation); } } else { requests.discard(); } requests = null; } clearTransaction(); } } public void setUseTransactions(boolean useTransactions) { this.useTransactions = useTransactions; } private void clearTransaction() { logic.transactionEnded(); ongoingTx = null; } public int getThreadIndex() { return threadIndex; } public int getGlobalThreadIndex() { return globalThreadIndex; } public Statistics getStats() { return stats; } public OperationLogic getLogic() { return logic; } public Random getRandom() { return random; } public boolean isUseTransactions() { return useTransactions; } private Request startTransaction() throws TransactionException { Request request = recording() ? stats.startRequest() : null; try { ongoingTx.begin(); if (request != null) { request.succeeded(Transactional.BEGIN); } return request; } catch (Exception e) { if (request != null) { request.failed(Transactional.BEGIN); } log.error("Failed to start transaction", e); throw new TransactionException(request, e); } } private class TransactionException extends Exception { private final Request request; public TransactionException(Request request, Exception cause) { super(cause); this.request = request; } public Request getRequest() { return request; } } private Request nextRequest() { Request request = null; if (recording()) { if (uniformRateLimiterOpsPerNano > 0) { request = stats.startRequest(uniformRateLimiterStart + (++uniformRateLimiterOpIndex) * uniformRateLimiterOpsPerNano); long intendedTime = request.getRequestStartTime(); long now; while ((now = System.nanoTime()) < intendedTime) LockSupport.parkNanos(intendedTime - now); } else { request = stats.startRequest(); } } return request; } }
package com.veaer.glass; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Color; import android.os.Build; import android.support.annotation.ColorInt; import android.support.annotation.NonNull; import android.support.v4.view.ViewPager; import android.support.v7.graphics.Palette; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.FrameLayout; import android.widget.TextView; import com.veaer.glass.setter.Setter; import com.veaer.glass.setter.SetterFactory; import com.veaer.glass.util.LocalDisplay; import com.veaer.glass.viewpager.ColorProvider; import com.veaer.glass.viewpager.PagerTrigger; import java.util.ArrayList; import java.util.List; public class Glass extends Setter { private final List<Setter> setters; private PagerTrigger pagerTrigger; public enum paletteType {VIBRANT, VIBRANT_DARK, VIBRANT_LIGHT, MUTED , MUTED_DARK, MUTED_LIGHT} private Glass.paletteType mPaletteType = paletteType.MUTED_DARK; private Glass(List<Setter> setters) { this.setters = setters; } private Glass(List<Setter> setters, ViewPager viewPager, ColorProvider colorProvider) { this.setters = setters; this.pagerTrigger = PagerTrigger.addTrigger(viewPager, colorProvider, this); } @Override protected void onSetColor(@ColorInt int color) { for (Setter setter : setters) { setter.setColor(color); } } public void setPaletteBmp(Bitmap bitmap) { new Palette.Builder(bitmap).generate(listener); } public void setPaletteBmp(Bitmap bitmap, Glass.paletteType type) { this.mPaletteType = type; setPaletteBmp(bitmap); } public void onDestroy() { this.setters.clear(); pagerTrigger.destroy(); } private Palette.PaletteAsyncListener listener = new Palette.PaletteAsyncListener() { @Override public void onGenerated(Palette newPalette) { switch (mPaletteType) { case VIBRANT : setColor(newPalette.getVibrantColor(0)); break; case VIBRANT_DARK : setColor(newPalette.getDarkVibrantColor(0)); break; case VIBRANT_LIGHT : setColor(newPalette.getLightVibrantColor(0)); break; case MUTED : setColor(newPalette.getMutedColor(0)); break; case MUTED_DARK : setColor(newPalette.getDarkMutedColor(0)); break; case MUTED_LIGHT : setColor(newPalette.getLightMutedColor(0)); break; } } }; public static final class Builder { private int defaultColor = Color.parseColor("#3F51B5"); private boolean changeColor = false; private List<Setter> setters; private ViewPager viewPager; private ColorProvider colorProvider; public static Builder newInstance() { return new Builder(new ArrayList<Setter>()); } private Builder(List<Setter> setters) { this.setters = setters; } public Builder add(Setter setter) { if(null != setter) { setters.add(setter); } return this; } public Builder background(@NonNull View view) { return add(SetterFactory.getBackgroundSetter(view)); } public Builder text(@NonNull TextView view) { return add(SetterFactory.getTextSetter(view)); } public Builder statusBar(Window window) { return statusBarWithLower(window, null); } public Builder setViewPager(ViewPager viewPager, ColorProvider colorProvider) { this.viewPager = viewPager; this.colorProvider = colorProvider; return this; } public Builder defaultColor(@ColorInt int defaultColor) { this.defaultColor = defaultColor; changeColor = true; return this; } public Builder statusBarWithLower(Window window, Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { LocalDisplay.init(context); WindowManager.LayoutParams localLayoutParams = window.getAttributes(); localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags); ViewGroup contentView = (ViewGroup)window.getDecorView().findViewById(android.R.id.content); View mStatusBarView = new View(context); int height = LocalDisplay.getStatusHeight(context.getResources()); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, height); params.gravity = Gravity.TOP; mStatusBarView.setLayoutParams(params); contentView.addView(mStatusBarView); background(mStatusBarView); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Setter windowSetter = SetterFactory.getSystemSetter(window); add(windowSetter); } return this; } public Glass build() { Glass mGlass; if(viewPager != null && colorProvider != null) { mGlass = new Glass(setters, viewPager, colorProvider); } else { mGlass = new Glass(setters); } if(changeColor) { mGlass.setColor(defaultColor); } return mGlass; } } }
package org.realityforge.arez; import java.util.Objects; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.realityforge.anodoc.TestOnly; import org.realityforge.arez.spy.ActionCompletedEvent; import org.realityforge.arez.spy.ActionStartedEvent; import org.realityforge.arez.spy.ComputedValueCreatedEvent; import org.realityforge.arez.spy.ObservableCreatedEvent; import org.realityforge.arez.spy.ObserverCreatedEvent; import org.realityforge.arez.spy.ObserverErrorEvent; import org.realityforge.arez.spy.PropertyAccessor; import org.realityforge.arez.spy.PropertyMutator; import org.realityforge.arez.spy.ReactionScheduledEvent; import static org.realityforge.braincheck.Guards.*; /** * The ArezContext defines the top level container of interconnected observables and observers. * The context also provides the mechanism for creating transactions to read and write state * within the system. */ @SuppressWarnings( "Duplicates" ) public final class ArezContext { /** * Id of next node to be created. * This is only used if {@link Arez#areNamesEnabled()} returns true but no name has been supplied. */ private int _nextNodeId = 1; /** * Id of next transaction to be created. * * This needs to start at 1 as {@link Observable#NOT_IN_CURRENT_TRACKING} is used * to optimize dependency tracking in transactions. */ private int _nextTransactionId = 1; /** * Reaction Scheduler. * Currently hard-coded, in the future potentially configurable. */ private final ReactionScheduler _scheduler = new ReactionScheduler( this ); /** * Support infrastructure for propagating observer errors. */ @Nonnull private final ObserverErrorHandlerSupport _observerErrorHandlerSupport = new ObserverErrorHandlerSupport(); /** * Support infrastructure for supporting spy events. */ @Nullable private final SpyImpl _spy = Arez.areSpiesEnabled() ? new SpyImpl( this ) : null; /** * Flag indicating whether the scheduler should run next time it is triggered. * This should be active only when there is no uncommitted transaction for context. */ private boolean _schedulerEnabled = true; /** * Arez context should not be created directly but only accessed via Arez. */ ArezContext() { } /** * Create a ComputedValue with specified parameters. * * @param <T> the type of the computed value. * @param function the function that computes the value. * @return the ComputedValue instance. */ @Nonnull public <T> ComputedValue<T> createComputedValue( @Nonnull final SafeFunction<T> function ) { return createComputedValue( null, function ); } /** * Create a ComputedValue with specified parameters. * * @param <T> the type of the computed value. * @param name the name of the ComputedValue. Should be non-null if {@link Arez#areNamesEnabled()} returns true, null otherwise. * @param function the function that computes the value. * @return the ComputedValue instance. */ @Nonnull public <T> ComputedValue<T> createComputedValue( @Nullable final String name, @Nonnull final SafeFunction<T> function ) { return createComputedValue( name, function, Objects::equals ); } /** * Create a ComputedValue with specified parameters. * * @param <T> the type of the computed value. * @param name the name of the ComputedValue. Should be non-null if {@link Arez#areNamesEnabled()} returns true, null otherwise. * @param function the function that computes the value. * @param equalityComparator the comparator that determines whether the newly computed value differs from existing value. * @return the ComputedValue instance. */ @Nonnull public <T> ComputedValue<T> createComputedValue( @Nullable final String name, @Nonnull final SafeFunction<T> function, @Nonnull final EqualityComparator<T> equalityComparator ) { return createComputedValue( name, function, equalityComparator, null, null, null, null ); } /** * Create a ComputedValue with specified parameters. * * @param <T> the type of the computed value. * @param name the name of the ComputedValue. * @param function the function that computes the value. * @param equalityComparator the comparator that determines whether the newly computed value differs from existing value. * @param onActivate the procedure to invoke when the ComputedValue changes from the INACTIVE state to any other state. This will be invoked when the transition occurs and will occur in the context of the transaction that made the change. * @param onDeactivate the procedure to invoke when the ComputedValue changes to the INACTIVE state to any other state. This will be invoked when the transition occurs and will occur in the context of the transaction that made the change. * @param onStale the procedure to invoke when the ComputedValue changes changes from the UP_TO_DATE state to STALE or POSSIBLY_STALE. This will be invoked when the transition occurs and will occur in the context of the transaction that made the change. * @param onDispose the procedure to invoke when the ComputedValue id disposed. * @return the ComputedValue instance. */ @Nonnull public <T> ComputedValue<T> createComputedValue( @Nullable final String name, @Nonnull final SafeFunction<T> function, @Nonnull final EqualityComparator<T> equalityComparator, @Nullable final Procedure onActivate, @Nullable final Procedure onDeactivate, @Nullable final Procedure onStale, @Nullable final Procedure onDispose ) { final ComputedValue<T> computedValue = new ComputedValue<>( this, generateNodeName( "ComputedValue", name ), function, equalityComparator ); final Observer observer = computedValue.getObserver(); observer.setOnActivate( onActivate ); observer.setOnDeactivate( onDeactivate ); observer.setOnStale( onStale ); observer.setOnDispose( onDispose ); if ( willPropagateSpyEvents() ) { getSpy().reportSpyEvent( new ComputedValueCreatedEvent( computedValue ) ); } return computedValue; } /** * Build name for node. * If {@link Arez#areNamesEnabled()} returns false then this method will return null, otherwise the specified * name will be returned or a name synthesized from the prefix and a running number if no name is specified. * * @param prefix the prefix used if this method needs to generate name. * @param name the name specified by the user. * @return the name. */ @Nullable public String generateNodeName( @Nonnull final String prefix, @Nullable final String name ) { return Arez.areNamesEnabled() ? null != name ? name : prefix + "@" + _nextNodeId++ : null; } /** * Create a read-only autorun observer and run immediately. * * @param action the action defining the observer. * @return the new Observer. */ @Nonnull public Observer autorun( @Nonnull final Procedure action ) { return autorun( null, action ); } /** * Create a read-only autorun observer and run immediately. * * @param name the name of the observer. * @param action the action defining the observer. * @return the new Observer. */ @Nonnull public Observer autorun( @Nullable final String name, @Nonnull final Procedure action ) { return autorun( name, false, action ); } /** * Create an autorun observer and run immediately. * * @param mutation true if the action may modify state, false otherwise. * @param action the action defining the observer. * @return the new Observer. */ @Nonnull public Observer autorun( final boolean mutation, @Nonnull final Procedure action ) { return autorun( null, mutation, action ); } /** * Create an autorun observer and run immediately. * * @param name the name of the observer. * @param mutation true if the action may modify state, false otherwise. * @param action the action defining the observer. * @return the new Observer. */ @Nonnull public Observer autorun( @Nullable final String name, final boolean mutation, @Nonnull final Procedure action ) { return autorun( name, mutation, action, true ); } /** * Create an autorun observer. * * @param name the name of the observer. * @param mutation true if the action may modify state, false otherwise. * @param action the action defining the observer. * @param runImmediately true to invoke action immediately, false to schedule reaction for next reaction cycle. * @return the new Observer. */ @Nonnull public Observer autorun( @Nullable final String name, final boolean mutation, @Nonnull final Procedure action, final boolean runImmediately ) { final Observer observer = createObserver( name, mutation, o -> action( name, ArezConfig.enforceTransactionType() ? o.getMode() : null, action, true, o ), false ); if ( runImmediately ) { observer.invokeReaction(); } else { scheduleReaction( observer ); } return observer; } /** * Create a "tracker" observer that tracks code using a read-only transaction. * The "tracker" observer triggers the specified action any time any of the observers dependencies are updated. * To track dependencies, this returned observer must be passed as the tracker to an action method like {@link #track(Observer, Function, Object...)}. * * @param action the action invoked as the reaction. * @return the new Observer. */ @Nonnull public Observer tracker( @Nonnull final Procedure action ) { return tracker( false, action ); } /** * Create a "tracker" observer. * The "tracker" observer triggers the specified action any time any of the observers dependencies are updated. * To track dependencies, this returned observer must be passed as the tracker to an action method like {@link #track(Observer, Function, Object...)}. * * @param mutation true if the observer may modify state during tracking, false otherwise. * @param action the action invoked as the reaction. * @return the new Observer. */ @Nonnull public Observer tracker( final boolean mutation, @Nonnull final Procedure action ) { return tracker( null, mutation, action ); } /** * Create a "tracker" observer. * The "tracker" observer triggers the specified action any time any of the observers dependencies are updated. * To track dependencies, this returned observer must be passed as the tracker to an action method like {@link #track(Observer, Function, Object...)}. * * @param name the name of the observer. * @param mutation true if the observer may modify state during tracking, false otherwise. * @param action the action invoked as the reaction. * @return the new Observer. */ @Nonnull public Observer tracker( @Nullable final String name, final boolean mutation, @Nonnull final Procedure action ) { return createObserver( name, mutation, o -> action.call(), true ); } /** * Create an observer with specified parameters. * * @param name the name of the observer. * @param mutation true if the reaction may modify state, false otherwise. * @param reaction the reaction defining observer. * @return the new Observer. */ @Nonnull Observer createObserver( @Nullable final String name, final boolean mutation, @Nonnull final Reaction reaction, final boolean canTrackExplicitly ) { final TransactionMode mode = mutationToTransactionMode( mutation ); final Observer observer = new Observer( this, generateNodeName( "Observer", name ), null, mode, reaction, canTrackExplicitly ); if ( willPropagateSpyEvents() ) { getSpy().reportSpyEvent( new ObserverCreatedEvent( observer ) ); } return observer; } /** * Create an Observable with the specified name. * * @param name the name of the Observable. Should be non null if {@link Arez#areNamesEnabled()} returns true, null otherwise. * @return the new Observable. */ @Nonnull public Observable createObservable( @Nullable final String name ) { return createObservable( name, null, null ); } /** * Create an Observable. * * @param name the name of the observable. Should be non null if {@link Arez#areNamesEnabled()} returns true, null otherwise. * @param accessor the accessor for observable. Should be null if {@link Arez#arePropertyIntrospectorsEnabled()} returns false, may be non-null otherwise. * @param mutator the mutator for observable. Should be null if {@link Arez#arePropertyIntrospectorsEnabled()} returns false, may be non-null otherwise. * @return the new Observable. */ @Nonnull public <T> Observable<T> createObservable( @Nullable final String name, @Nullable final PropertyAccessor<T> accessor, @Nullable final PropertyMutator<T> mutator ) { final Observable<T> observable = new Observable<>( this, Arez.areNamesEnabled() ? name : null, null, accessor, mutator ); if ( willPropagateSpyEvents() ) { getSpy().reportSpyEvent( new ObservableCreatedEvent( observable ) ); } return observable; } /** * Pass the supplied observer to the scheduler. * The observer should NOT be already pending execution. * * @param observer the reaction to schedule. */ void scheduleReaction( @Nonnull final Observer observer ) { if ( willPropagateSpyEvents() ) { getSpy().reportSpyEvent( new ReactionScheduledEvent( observer ) ); } _scheduler.scheduleReaction( observer ); } /** * Return true if there is a transaction in progress. * * @return true if there is a transaction in progress. */ boolean isTransactionActive() { return Transaction.isTransactionActive() && ( !Arez.areZonesEnabled() || Transaction.current().getContext() == this ); } /** * Return the current transaction. * This method should not be invoked unless a transaction active and will throw an * exception if invariant checks are enabled. * * @return the current transaction. */ @Nonnull Transaction getTransaction() { final Transaction current = Transaction.current(); invariant( () -> !Arez.areZonesEnabled() || current.getContext() == this, () -> "Attempting to get current transaction but current transaction is for different context." ); return current; } /** * Enable scheduler so that it will run pending observers next time it is triggered. */ void enableScheduler() { _schedulerEnabled = true; } /** * Disable scheduler so that it will not run pending observers next time it is triggered. */ void disableScheduler() { _schedulerEnabled = false; } /** * Method invoked to trigger the scheduler to run any pending reactions. The scheduler will only be * triggered if there is no transaction active. This method is typically used after one or more Observers * have been created outside a transaction with the runImmediately flag set to false and the caller wants * to force the observers to react. Otherwise the Observers will not be schedule until the next top-level * transaction completes. */ public void triggerScheduler() { if ( _schedulerEnabled ) { _scheduler.runPendingObservers(); } } /** * Execute the supplied action in a read-write transaction. * The name is synthesized if {@link Arez#areNamesEnabled()} returns true. * The action may throw an exception. * * @param <T> the type of return value. * @param action the action to execute. * @param parameters the action parameters if any. * @return the value returned from the action. * @throws Exception if the action throws an an exception. */ public <T> T action( @Nonnull final Function<T> action, @Nonnull final Object... parameters ) throws Throwable { return action( true, action, parameters ); } /** * Execute the supplied action in a transaction. * The name is synthesized if {@link Arez#areNamesEnabled()} returns true. * The action may throw an exception. * * @param <T> the type of return value. * @param mutation true if the action may modify state, false otherwise. * @param action the action to execute. * @param parameters the action parameters if any. * @return the value returned from the action. * @throws Exception if the action throws an an exception. */ public <T> T action( final boolean mutation, @Nonnull final Function<T> action, @Nonnull final Object... parameters ) throws Throwable { return action( null, mutation, action, parameters ); } /** * Execute the supplied action in a transaction. * The action may throw an exception. * * @param <T> the type of return value. * @param name the name of the transaction. * @param action the action to execute. * @param parameters the action parameters if any. * @return the value returned from the action. * @throws Exception if the action throws an an exception. */ public <T> T action( @Nullable final String name, @Nonnull final Function<T> action, @Nonnull final Object... parameters ) throws Throwable { return action( name, true, action, parameters ); } /** * Execute the supplied action in a transaction. * The action may throw an exception. * * @param <T> the type of return value. * @param name the name of the transaction. * @param mutation true if the action may modify state, false otherwise. * @param action the action to execute. * @param parameters the action parameters if any. * @return the value returned from the action. * @throws Exception if the action throws an an exception. */ public <T> T action( @Nullable final String name, final boolean mutation, @Nonnull final Function<T> action, @Nonnull final Object... parameters ) throws Throwable { return action( generateNodeName( "Transaction", name ), mutationToTransactionMode( mutation ), action, null, parameters ); } public <T> T track( @Nonnull final Observer tracker, @Nonnull final Function<T> action, @Nonnull final Object... parameters ) throws Throwable { apiInvariant( tracker::canTrackExplicitly, () -> "Attempted to track Observer named '" + tracker.getName() + "' but " + "observer is not a tracker." ); return action( generateNodeName( tracker ), ArezConfig.enforceTransactionType() ? tracker.getMode() : null, action, tracker, parameters ); } private <T> T action( @Nullable final String name, @Nullable final TransactionMode mode, @Nonnull final Function<T> action, @Nullable final Observer tracker, @Nonnull final Object... parameters ) throws Throwable { final boolean tracked = null != tracker; Throwable t = null; boolean completed = false; long startedAt = 0L; T result; try { if ( Arez.areSpiesEnabled() && getSpy().willPropagateSpyEvents() ) { startedAt = System.currentTimeMillis(); assert null != name; getSpy().reportSpyEvent( new ActionStartedEvent( name, tracked, parameters ) ); } final Transaction transaction = Transaction.begin( this, generateNodeName( "Transaction", name ), mode, tracker ); try { result = action.call(); } finally { Transaction.commit( transaction ); } if ( Arez.areSpiesEnabled() && getSpy().willPropagateSpyEvents() ) { completed = true; final long duration = System.currentTimeMillis() - startedAt; assert null != name; getSpy().reportSpyEvent( new ActionCompletedEvent( name, tracked, parameters, true, result, null, duration ) ); } return result; } catch ( final Throwable e ) { t = e; throw e; } finally { if ( Arez.areSpiesEnabled() && getSpy().willPropagateSpyEvents() ) { if ( !completed ) { final long duration = System.currentTimeMillis() - startedAt; assert null != name; getSpy().reportSpyEvent( new ActionCompletedEvent( name, tracked, parameters, true, null, t, duration ) ); } } triggerScheduler(); } } /** * Execute the supplied action in a read-write transaction. * The action is expected to not throw an exception. * * @param <T> the type of return value. * @param action the action to execute. * @param parameters the action parameters if any. * @return the value returned from the action. */ public <T> T safeAction( @Nonnull final SafeFunction<T> action, @Nonnull final Object... parameters ) { return safeAction( true, action, parameters ); } /** * Execute the supplied function in a transaction. * The action is expected to not throw an exception. * * @param <T> the type of return value. * @param mutation true if the action may modify state, false otherwise. * @param action the action to execute. * @param parameters the action parameters if any. * @return the value returned from the action. */ public <T> T safeAction( final boolean mutation, @Nonnull final SafeFunction<T> action, @Nonnull final Object... parameters ) { return safeAction( null, mutation, action, parameters ); } /** * Execute the supplied action in a read-write transaction. * The action is expected to not throw an exception. * * @param <T> the type of return value. * @param name the name of the transaction. * @param action the action to execute. * @param parameters the action parameters if any. * @return the value returned from the action. */ public <T> T safeAction( @Nullable final String name, @Nonnull final SafeFunction<T> action, @Nonnull final Object... parameters ) { return safeAction( name, true, action, parameters ); } /** * Execute the supplied action. * The action is expected to not throw an exception. * * @param <T> the type of return value. * @param name the name of the transaction. * @param mutation true if the action may modify state, false otherwise. * @param action the action to execute. * @param parameters the action parameters if any. * @return the value returned from the action. */ public <T> T safeAction( @Nullable final String name, final boolean mutation, @Nonnull final SafeFunction<T> action, @Nonnull final Object... parameters ) { return safeAction( generateNodeName( "Transaction", name ), mutationToTransactionMode( mutation ), action, null, parameters ); } public <T> T safeTrack( @Nonnull final Observer tracker, @Nonnull final SafeFunction<T> action, @Nonnull final Object... parameters ) { apiInvariant( tracker::canTrackExplicitly, () -> "Attempted to track Observer named '" + tracker.getName() + "' but " + "observer is not a tracker." ); return safeAction( generateNodeName( tracker ), ArezConfig.enforceTransactionType() ? tracker.getMode() : null, action, tracker, parameters ); } private <T> T safeAction( @Nullable final String name, @Nullable final TransactionMode mode, @Nonnull final SafeFunction<T> action, @Nullable final Observer tracker, @Nonnull final Object... parameters ) { final boolean tracked = null != tracker; Throwable t = null; boolean completed = false; long startedAt = 0L; T result; try { if ( Arez.areSpiesEnabled() && getSpy().willPropagateSpyEvents() ) { startedAt = System.currentTimeMillis(); assert null != name; getSpy().reportSpyEvent( new ActionStartedEvent( name, tracked, parameters ) ); } final Transaction transaction = Transaction.begin( this, generateNodeName( "Transaction", name ), mode, tracker ); try { result = action.call(); } finally { Transaction.commit( transaction ); } if ( Arez.areSpiesEnabled() && getSpy().willPropagateSpyEvents() ) { completed = true; final long duration = System.currentTimeMillis() - startedAt; assert null != name; getSpy().reportSpyEvent( new ActionCompletedEvent( name, tracked, parameters, true, result, null, duration ) ); } return result; } catch ( final Throwable e ) { t = e; throw e; } finally { if ( Arez.areSpiesEnabled() && getSpy().willPropagateSpyEvents() ) { if ( !completed ) { final long duration = System.currentTimeMillis() - startedAt; assert null != name; getSpy().reportSpyEvent( new ActionCompletedEvent( name, tracked, parameters, true, null, t, duration ) ); } } triggerScheduler(); } } /** * Execute the supplied action in a read-write transaction. * The procedure may throw an exception. * * @param action the action to execute. * @param parameters the action parameters if any. * @throws Throwable if the procedure throws an an exception. */ public void action( @Nonnull final Procedure action, @Nonnull final Object... parameters ) throws Throwable { action( true, action, parameters ); } /** * Execute the supplied action in a transaction. * The action may throw an exception. * * @param mutation true if the action may modify state, false otherwise. * @param action the action to execute. * @param parameters the action parameters if any. * @throws Throwable if the procedure throws an an exception. */ public void action( final boolean mutation, @Nonnull final Procedure action, @Nonnull final Object... parameters ) throws Throwable { action( null, mutation, action, parameters ); } /** * Execute the supplied action in a read-write transaction. * The action may throw an exception. * * @param name the name of the transaction. * @param action the action to execute. * @param parameters the action parameters if any. * @throws Throwable if the procedure throws an an exception. */ public void action( @Nullable final String name, @Nonnull final Procedure action, @Nonnull final Object... parameters ) throws Throwable { action( name, true, action, true, parameters ); } /** * Execute the supplied action in a transaction. * The action may throw an exception. * * @param name the name of the transaction. * @param mutation true if the action may modify state, false otherwise. * @param action the action to execute. * @param parameters the action parameters if any. * @throws Throwable if the procedure throws an an exception. */ public void action( @Nullable final String name, final boolean mutation, @Nonnull final Procedure action, @Nonnull final Object... parameters ) throws Throwable { action( generateNodeName( "Transaction", name ), mutationToTransactionMode( mutation ), action, true, null, parameters ); } public void track( @Nonnull final Observer tracker, @Nonnull final Procedure action, @Nonnull final Object... parameters ) throws Throwable { apiInvariant( tracker::canTrackExplicitly, () -> "Attempted to track Observer named '" + tracker.getName() + "' but " + "observer is not a tracker." ); action( generateNodeName( tracker ), ArezConfig.enforceTransactionType() ? tracker.getMode() : null, action, true, tracker, parameters ); } @Nullable private String generateNodeName( @Nonnull final Observer tracker ) { return Arez.areNamesEnabled() ? tracker.getName() : null; } void action( @Nullable final String name, @Nullable final TransactionMode mode, @Nonnull final Procedure action, final boolean reportAction, @Nullable final Observer tracker, @Nonnull final Object... parameters ) throws Throwable { final boolean tracked = null != tracker; Throwable t = null; boolean completed = false; long startedAt = 0L; try { if ( reportAction && Arez.areSpiesEnabled() && getSpy().willPropagateSpyEvents() ) { startedAt = System.currentTimeMillis(); assert null != name; getSpy().reportSpyEvent( new ActionStartedEvent( name, tracked, parameters ) ); } final Transaction transaction = Transaction.begin( this, generateNodeName( "Transaction", name ), mode, tracker ); try { action.call(); } finally { Transaction.commit( transaction ); } if ( reportAction && Arez.areSpiesEnabled() && getSpy().willPropagateSpyEvents() ) { completed = true; final long duration = System.currentTimeMillis() - startedAt; assert null != name; getSpy().reportSpyEvent( new ActionCompletedEvent( name, tracked, parameters, false, null, null, duration ) ); } } catch ( final Throwable e ) { t = e; throw e; } finally { if ( reportAction && Arez.areSpiesEnabled() && getSpy().willPropagateSpyEvents() ) { if ( !completed ) { final long duration = System.currentTimeMillis() - startedAt; assert null != name; getSpy().reportSpyEvent( new ActionCompletedEvent( name, tracked, parameters, false, null, t, duration ) ); } } triggerScheduler(); } } /** * Execute the supplied action in a read-write transaction. * The action is expected to not throw an exception. * * @param action the action to execute. * @param parameters the action parameters if any. */ public void safeAction( @Nonnull final SafeProcedure action, @Nonnull final Object... parameters ) { safeAction( true, action, parameters ); } /** * Execute the supplied action in a transaction. * The action is expected to not throw an exception. * * @param mutation true if the action may modify state, false otherwise. * @param action the action to execute. * @param parameters the action parameters if any. */ public void safeAction( final boolean mutation, @Nonnull final SafeProcedure action, @Nonnull final Object... parameters ) { safeAction( null, mutation, action, parameters ); } /** * Execute the supplied action in a read-write transaction. * The action is expected to not throw an exception. * * @param name the name of the transaction. * @param action the action to execute. * @param parameters the action parameters if any. */ public void safeAction( @Nullable final String name, @Nonnull final SafeProcedure action, @Nonnull final Object... parameters ) { safeAction( name, true, action, parameters ); } /** * Execute the supplied action in a transaction. * The action is expected to not throw an exception. * * @param name the name of the transaction. * @param mutation true if the action may modify state, false otherwise. * @param action the action to execute. * @param parameters the action parameters if any. */ public void safeAction( @Nullable final String name, final boolean mutation, @Nonnull final SafeProcedure action, @Nonnull final Object... parameters ) { safeAction( generateNodeName( "Transaction", name ), mutationToTransactionMode( mutation ), action, null, parameters ); } public void safeTrack( @Nonnull final Observer tracker, @Nonnull final SafeProcedure action, @Nonnull final Object... parameters ) { apiInvariant( tracker::canTrackExplicitly, () -> "Attempted to track Observer named '" + tracker.getName() + "' but " + "observer is not a tracker." ); safeAction( generateNodeName( tracker ), ArezConfig.enforceTransactionType() ? tracker.getMode() : null, action, tracker, parameters ); } void safeAction( @Nullable final String name, @Nullable final TransactionMode mode, @Nonnull final SafeProcedure action, @Nullable final Observer tracker, @Nonnull final Object... parameters ) { final boolean tracked = null != tracker; Throwable t = null; boolean completed = false; long startedAt = 0L; try { if ( Arez.areSpiesEnabled() && getSpy().willPropagateSpyEvents() ) { startedAt = System.currentTimeMillis(); assert null != name; getSpy().reportSpyEvent( new ActionStartedEvent( name, tracked, parameters ) ); } final Transaction transaction = Transaction.begin( this, generateNodeName( "Transaction", name ), mode, tracker ); try { action.call(); } finally { Transaction.commit( transaction ); } if ( Arez.areSpiesEnabled() && getSpy().willPropagateSpyEvents() ) { completed = true; final long duration = System.currentTimeMillis() - startedAt; assert null != name; getSpy().reportSpyEvent( new ActionCompletedEvent( name, tracked, parameters, false, null, null, duration ) ); } } catch ( final Throwable e ) { t = e; throw e; } finally { if ( Arez.areSpiesEnabled() && getSpy().willPropagateSpyEvents() ) { if ( !completed ) { final long duration = System.currentTimeMillis() - startedAt; assert null != name; getSpy().reportSpyEvent( new ActionCompletedEvent( name, tracked, parameters, false, null, t, duration ) ); } } triggerScheduler(); } } /** * Return next transaction id and increment internal counter. * The id is a monotonically increasing number starting at 1. * * @return the next transaction id. */ int nextTransactionId() { return _nextTransactionId++; } /** * Add error handler to the list of error handlers called. * The handler should not already be in the list. * * @param handler the error handler. */ public void addObserverErrorHandler( @Nonnull final ObserverErrorHandler handler ) { _observerErrorHandlerSupport.addObserverErrorHandler( handler ); } /** * Remove error handler from list of existing error handlers. * The handler should already be in the list. * * @param handler the error handler. */ public void removeObserverErrorHandler( @Nonnull final ObserverErrorHandler handler ) { _observerErrorHandlerSupport.removeObserverErrorHandler( handler ); } /** * Report an error in observer. * * @param observer the observer that generated error. * @param error the type of the error. * @param throwable the exception that caused error if any. */ void reportObserverError( @Nonnull final Observer observer, @Nonnull final ObserverError error, @Nullable final Throwable throwable ) { if ( willPropagateSpyEvents() ) { getSpy().reportSpyEvent( new ObserverErrorEvent( observer, error, throwable ) ); } _observerErrorHandlerSupport.onObserverError( observer, error, throwable ); } /** * Return true if spy events will be propagated. * This means spies are enabled and there is at least one spy event handler present. * * @return true if spy events will be propagated, false otherwise. */ boolean willPropagateSpyEvents() { return Arez.areSpiesEnabled() && getSpy().willPropagateSpyEvents(); } /** * Return the spy associated with context. * This method should not be invoked unless {@link Arez#areSpiesEnabled()} returns true. * * @return the spy associated with context. */ @Nonnull public Spy getSpy() { apiInvariant( Arez::areSpiesEnabled, () -> "Attempting to get Spy but spies are not enabled." ); assert null != _spy; return _spy; } /** * Convert flag to appropriate transaction mode. * * @param mutation true if the transaction may modify state, false otherwise. * @return the READ_WRITE transaction mode if mutation is true else READ_ONLY. */ @Nullable private TransactionMode mutationToTransactionMode( final boolean mutation ) { return ArezConfig.enforceTransactionType() ? ( mutation ? TransactionMode.READ_WRITE : TransactionMode.READ_ONLY ) : null; } @TestOnly @Nonnull ObserverErrorHandlerSupport getObserverErrorHandlerSupport() { return _observerErrorHandlerSupport; } @TestOnly int currentNextTransactionId() { return _nextTransactionId; } @TestOnly @Nonnull ReactionScheduler getScheduler() { return _scheduler; } @TestOnly void setNextNodeId( final int nextNodeId ) { _nextNodeId = nextNodeId; } @TestOnly int getNextNodeId() { return _nextNodeId; } @TestOnly boolean isSchedulerEnabled() { return _schedulerEnabled; } }
package com.apigee.proxywriter; /** * * The GenerateProxy program generates a Apigee API Proxy from a WSDL Document. The generated proxy can be * passthru or converted to an API (REST/JSON over HTTP). * * How does it work? * At a high level, here is the logic implemented for SOAP-to-API: * Step 1: Parse the WSDL * Step 2: Build a HashMap with * Step 2a: Generate SOAP Request template for each operation * Step 2b: Convert SOAP Request to JSON Request template without the SOAP Envelope * Step 3: Create the API Proxy folder structure * Step 4: Copy policies from the standard template * Step 5: Create the Extract Variables and Assign Message Policies * Step 5a: If the operation is interpreted as a POST (create), then obtain JSON Paths from JSON request template * Step 5b: Use JSONPaths in the Extract Variables * * At a high level, here is the logic implemented for SOAP-passthru: * Step 1: Parse the WSDL * Step 2: Copy policies from the standard template * * * @author Nandan Sridhar * @version 0.1 * @since 2016-05-20 */ import java.io.*; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.*; import java.util.logging.ConsoleHandler; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import com.apigee.proxywriter.exception.*; import com.apigee.utils.*; import org.apache.commons.lang3.StringEscapeUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import com.apigee.utils.Options.Multiplicity; import com.apigee.utils.Options.Separator; import com.apigee.xsltgen.Rule; import com.apigee.xsltgen.RuleSet; import com.predic8.schema.All; import com.predic8.schema.Choice; import com.predic8.schema.ComplexContent; import com.predic8.schema.ComplexType; import com.predic8.schema.Derivation; import com.predic8.schema.ModelGroup; import com.predic8.schema.Schema; import com.predic8.schema.SchemaComponent; import com.predic8.schema.Sequence; import com.predic8.schema.SimpleContent; import com.predic8.schema.TypeDefinition; import com.predic8.soamodel.XMLElement; import com.predic8.wsdl.AbstractSOAPBinding; import com.predic8.wsdl.Binding; import com.predic8.wsdl.BindingOperation; import com.predic8.wsdl.Definitions; import com.predic8.wsdl.Operation; import com.predic8.wsdl.PortType; import com.predic8.wsdl.Service; import com.predic8.wsdl.WSDLParser; import com.predic8.wstool.creator.RequestTemplateCreator; import com.predic8.wstool.creator.SOARequestCreator; import groovy.xml.MarkupBuilder; import groovy.xml.QName; public class GenerateProxy { private static final Logger LOGGER = Logger.getLogger(GenerateProxy.class.getName()); private static final ConsoleHandler handler = new ConsoleHandler(); public static String OPSMAPPING_TEMPLATE = "/templates/opsmap/opsmapping.xml"; private static String SOAP2API_XSL = ""; private static final String SOAP2API_APIPROXY_TEMPLATE = "/templates/soap2api/apiProxyTemplate.xml"; private static final String SOAP2API_PROXY_TEMPLATE = "/templates/soap2api/proxyDefault.xml"; private static final String SOAP2API_TARGET_TEMPLATE = "/templates/soap2api/targetDefault.xml"; private static final String SOAP2API_EXTRACT_TEMPLATE = "/templates/soap2api/ExtractPolicy.xml"; private static final String SOAP2API_ASSIGN_TEMPLATE = "/templates/soap2api/AssignMessagePolicy.xml"; private static final String SOAP2API_XSLT11POLICY_TEMPLATE = "/templates/soap2api/add-namespace11.xml"; private static final String SOAP2API_XSLT11_TEMPLATE = "/templates/soap2api/add-namespace11.xslt"; private static final String SOAP2API_XSLT12POLICY_TEMPLATE = "/templates/soap2api/add-namespace12.xml"; private static final String SOAP2API_XSLT12_TEMPLATE = "/templates/soap2api/add-namespace12.xslt"; private static final String SOAP2API_JSON_TO_XML_TEMPLATE = "/templates/soap2api/json-to-xml.xml"; private static final String SOAP2API_ADD_SOAPACTION_TEMPLATE = "/templates/soap2api/add-soapaction.xml"; private static final String SOAP2API_JSPOLICY_TEMPLATE = "/templates/soap2api/root-wrapper.xml"; private static final String SOAPPASSTHRU_APIPROXY_TEMPLATE = "/templates/soappassthru/apiProxyTemplate.xml"; private static final String SOAPPASSTHRU_PROXY_TEMPLATE = "/templates/soappassthru/proxyDefault.xml"; private static final String SOAPPASSTHRU_TARGET_TEMPLATE = "/templates/soappassthru/targetDefault.xml"; private static final String SOAP11_CONTENT_TYPE = "text/xml; charset=utf-8";// "text&#x2F;xml; // charset=utf-8"; private static final String SOAP12_CONTENT_TYPE = "application/soap+xml"; private static final String SOAP11_PAYLOAD_TYPE = "text/xml";// "text&#x2F;xml"; private static final String SOAP12_PAYLOAD_TYPE = "application/soap+xml"; private static final String SOAP11 = "http://schemas.xmlsoap.org/soap/envelope/"; private static final String SOAP12 = "http: // set this to true if SOAP passthru is needed private boolean PASSTHRU; // set this to true if all operations are to be consumed via POST verb private boolean ALLPOST; // set this to true if oauth should be added to the proxy private boolean OAUTH; // set this to true if apikey should be added to the proxy private boolean APIKEY; // enable this flag if api key based quota is enabled private boolean QUOTAAPIKEY; // enable this flag if oauth based quota is enabled private boolean QUOTAOAUTH; // enable this flag is cors is enabled private boolean CORS; // enable this flag if wsdl is of rpc style private boolean RPCSTYLE; // enable this flag if user sets desc private boolean DESCSET; private String targetEndpoint; private String soapVersion; private String serviceName; private String portName; private String basePath; private String proxyName; private String opsMap; private String selectedOperationsJson; private List<String> vHosts; private SelectedOperations selectedOperations; private OpsMap operationsMap; // default build folder is ./build private String buildFolder; // Each row in this Map has the key as the operation name. The operation // name has SOAP Request // and JSON Equivalent of SOAP (without the SOAP Envelope) as values. // private Map<String, KeyValue<String, String>> messageTemplates; private Map<String, APIMap> messageTemplates; // tree to hold elements to build an xpath private HashMap<Integer, String> xpathElement; // xpath tree element level private int level; // List of rules to generate XSLT private ArrayList<Rule> ruleList = new ArrayList<Rule>(); public Map<String, String> namespace = new LinkedHashMap<String, String>(); // initialize the logger static { LOGGER.setUseParentHandlers(false); Handler[] handlers = LOGGER.getHandlers(); for (Handler handler : handlers) { if (handler.getClass() == ConsoleHandler.class) LOGGER.removeHandler(handler); } handler.setFormatter(new SimpleFormatter()); LOGGER.addHandler(handler); } public GenerateProxy() { // initialize hashmap messageTemplates = new HashMap<String, APIMap>(); xpathElement = new HashMap<Integer, String>(); operationsMap = new OpsMap(); selectedOperations = new SelectedOperations(); vHosts = new ArrayList<String>(); vHosts.add("default"); buildFolder = null; soapVersion = "SOAP12"; ALLPOST = false; PASSTHRU = false; OAUTH = false; APIKEY = false; QUOTAAPIKEY = false; QUOTAOAUTH = false; CORS = false; RPCSTYLE = false; DESCSET = false; basePath = null; level = 0; } public void setSelectedOperationsJson (String json) throws Exception { selectedOperations.parseSelectedOperations(json); } public void setDesc(boolean descset) { DESCSET = descset; } public void setCORS(boolean cors) { CORS = cors; } public void setBasePath(String bp) { basePath = bp; } public void setQuotaAPIKey(boolean quotaAPIKey) { QUOTAAPIKEY = quotaAPIKey; } public void setQuotaOAuth(boolean quotaOAuth) { QUOTAOAUTH = quotaOAuth; } public void setAPIKey(boolean apikey) { APIKEY = apikey; } public void setOpsMap(String oMap) { opsMap = oMap; } public void setVHost(String vhosts) { if (vhosts.indexOf(",") != -1) { // contains > 1 vhosts vHosts = Arrays.asList(vhosts.split(",")); } else { vHosts.remove(0);// remove default vHosts.add(vhosts); } } public void setAllPost(boolean allPost) { ALLPOST = allPost; } public void setBuildFolder(String folder) { buildFolder = folder; } public void setPassThru(boolean pass) { PASSTHRU = pass; } public void setService(String serv) { serviceName = serv; } public void setPort(String prt) { portName = prt; } public void setOAuth(boolean oauth) { OAUTH = oauth; } private void writeAPIProxy(String proxyDescription) throws Exception { LOGGER.entering(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); XMLUtils xmlUtils = new XMLUtils(); Document apiTemplateDocument; if (PASSTHRU) { apiTemplateDocument = xmlUtils.readXML(SOAPPASSTHRU_APIPROXY_TEMPLATE); } else { apiTemplateDocument = xmlUtils.readXML(SOAP2API_APIPROXY_TEMPLATE); } LOGGER.finest("Read API Proxy template file"); Node rootElement = apiTemplateDocument.getFirstChild(); NamedNodeMap attr = rootElement.getAttributes(); Node nodeAttr = attr.getNamedItem("name"); nodeAttr.setNodeValue(proxyName); LOGGER.fine("Set proxy name: " + proxyName); Node displayName = apiTemplateDocument.getElementsByTagName("DisplayName").item(0); displayName.setTextContent(proxyName); LOGGER.fine("Set proxy display name: " + proxyName); Node description = apiTemplateDocument.getElementsByTagName("Description").item(0); description.setTextContent(proxyDescription); LOGGER.fine("Set proxy description: " + proxyDescription); Node createdAt = apiTemplateDocument.getElementsByTagName("CreatedAt").item(0); createdAt.setTextContent(Long.toString(java.lang.System.currentTimeMillis())); Node LastModifiedAt = apiTemplateDocument.getElementsByTagName("LastModifiedAt").item(0); LastModifiedAt.setTextContent(Long.toString(java.lang.System.currentTimeMillis())); xmlUtils.writeXML(apiTemplateDocument, buildFolder + File.separator + "apiproxy" + File.separator + proxyName + ".xml"); LOGGER.fine( "Generated file: " + buildFolder + File.separator + "apiproxy" + File.separator + proxyName + ".xml"); LOGGER.exiting(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); } private void writeSOAP2APIProxyEndpoint(String proxyDescription) throws Exception { LOGGER.entering(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); XMLUtils xmlUtils = new XMLUtils(); Document proxyDefault = xmlUtils.readXML(SOAP2API_PROXY_TEMPLATE); Node basePathNode = proxyDefault.getElementsByTagName("BasePath").item(0); if (basePath != null && basePath.equalsIgnoreCase("") != true) { basePathNode.setTextContent(basePath); } Node httpProxyConnection = proxyDefault.getElementsByTagName("HTTPProxyConnection").item(0); Node virtualHost = null; for (String vHost : vHosts) { virtualHost = proxyDefault.createElement("VirtualHost"); virtualHost.setTextContent(vHost); httpProxyConnection.appendChild(virtualHost); } Document apiTemplateDocument = xmlUtils .readXML(buildFolder + File.separator + "apiproxy" + File.separator + proxyName + ".xml"); Document extractTemplate = xmlUtils.readXML(SOAP2API_EXTRACT_TEMPLATE); Document assignTemplate = xmlUtils.readXML(SOAP2API_ASSIGN_TEMPLATE); Document jsPolicyTemplate = xmlUtils.readXML(SOAP2API_JSPOLICY_TEMPLATE); Document addNamespaceTemplate = null; if (soapVersion.equalsIgnoreCase("SOAP11")) { addNamespaceTemplate = xmlUtils.readXML(SOAP2API_XSLT11POLICY_TEMPLATE); } else { addNamespaceTemplate = xmlUtils.readXML(SOAP2API_XSLT12POLICY_TEMPLATE); } Document jsonXMLTemplate = xmlUtils.readXML(SOAP2API_JSON_TO_XML_TEMPLATE); Document addSoapActionTemplate = xmlUtils.readXML(SOAP2API_ADD_SOAPACTION_TEMPLATE); Node description = proxyDefault.getElementsByTagName("Description").item(0); description.setTextContent(proxyDescription); Node policies = apiTemplateDocument.getElementsByTagName("Policies").item(0); Node resources = apiTemplateDocument.getElementsByTagName("Resources").item(0); Node flows = proxyDefault.getElementsByTagName("Flows").item(0); Node flow; Node flowDescription; Node request; Node response; Node condition, condition2; Node step1, step2, step3, step4, step5; Node name1, name2, name3, name4, name5; boolean once = false; // add oauth policies if set if (OAUTH) { String oauthPolicy = "verify-oauth-v2-access-token"; String remoOAuthPolicy = "remove-header-authorization"; String quota = "impose-quota-oauth"; // Add policy to proxy.xml Node policy1 = apiTemplateDocument.createElement("Policy"); policy1.setTextContent(oauthPolicy); Node policy2 = apiTemplateDocument.createElement("Policy"); policy2.setTextContent(remoOAuthPolicy); policies.appendChild(policy1); policies.appendChild(policy2); Node preFlowRequest = proxyDefault.getElementsByTagName("PreFlow").item(0).getChildNodes().item(1); step1 = proxyDefault.createElement("Step"); name1 = proxyDefault.createElement("Name"); name1.setTextContent(oauthPolicy); step1.appendChild(name1); step2 = proxyDefault.createElement("Step"); name2 = proxyDefault.createElement("Name"); name2.setTextContent(remoOAuthPolicy); step2.appendChild(name2); preFlowRequest.appendChild(step1); preFlowRequest.appendChild(step2); if (QUOTAOAUTH) { Node policy3 = apiTemplateDocument.createElement("Policy"); policy2.setTextContent(quota); policies.appendChild(policy3); step3 = proxyDefault.createElement("Step"); name3 = proxyDefault.createElement("Name"); name3.setTextContent(quota); step3.appendChild(name3); preFlowRequest.appendChild(step3); } } if (APIKEY) { String apiKeyPolicy = "verify-api-key"; String remoAPIKeyPolicy = "remove-query-param-apikey"; String quota = "impose-quota-apikey"; // Add policy to proxy.xml Node policy1 = apiTemplateDocument.createElement("Policy"); policy1.setTextContent(apiKeyPolicy); Node policy2 = apiTemplateDocument.createElement("Policy"); policy2.setTextContent(remoAPIKeyPolicy); policies.appendChild(policy1); policies.appendChild(policy2); Node preFlowRequest = proxyDefault.getElementsByTagName("PreFlow").item(0).getChildNodes().item(1); step1 = proxyDefault.createElement("Step"); name1 = proxyDefault.createElement("Name"); name1.setTextContent(apiKeyPolicy); step1.appendChild(name1); step2 = proxyDefault.createElement("Step"); name2 = proxyDefault.createElement("Name"); name2.setTextContent(remoAPIKeyPolicy); step2.appendChild(name2); preFlowRequest.appendChild(step1); preFlowRequest.appendChild(step2); if (QUOTAAPIKEY) { Node policy3 = apiTemplateDocument.createElement("Policy"); policy2.setTextContent(quota); policies.appendChild(policy3); step3 = proxyDefault.createElement("Step"); name3 = proxyDefault.createElement("Name"); name3.setTextContent(quota); step3.appendChild(name3); preFlowRequest.appendChild(step3); } } if (CORS) { Node proxyEndpoint = proxyDefault.getElementsByTagName("ProxyEndpoint").item(0); Node routeRule = proxyDefault.createElement("RouteRule"); ((Element) routeRule).setAttribute("name", "NoRoute"); Node routeCondition = proxyDefault.createElement("Condition"); routeCondition.setTextContent("request.verb == \"OPTIONS\""); routeRule.appendChild(routeCondition); proxyEndpoint.appendChild(routeRule); String cors = "add-cors"; String corsCondition = "request.verb == \"OPTIONS\""; // Add policy to proxy.xml Node policy1 = apiTemplateDocument.createElement("Policy"); policy1.setTextContent(cors); policies.appendChild(policy1); flow = proxyDefault.createElement("Flow"); ((Element) flow).setAttribute("name", "OptionsPreFlight"); flowDescription = proxyDefault.createElement("Description"); flowDescription.setTextContent("OptionsPreFlight"); flow.appendChild(flowDescription); request = proxyDefault.createElement("Request"); response = proxyDefault.createElement("Response"); condition = proxyDefault.createElement("Condition"); step1 = proxyDefault.createElement("Step"); name1 = proxyDefault.createElement("Name"); name1.setTextContent(cors); step1.appendChild(name1); response.appendChild(step1); condition.setTextContent(corsCondition); flow.appendChild(request); flow.appendChild(response); flow.appendChild(condition); flows.appendChild(flow); } for (Map.Entry<String, APIMap> entry : messageTemplates.entrySet()) { String operationName = entry.getKey(); APIMap apiMap = entry.getValue(); String buildSOAPPolicy = operationName + "-build-soap"; String extractPolicyName = operationName + "-extract-query-param"; String jsonToXML = operationName + "-json-to-xml"; String jsPolicyName = operationName + "-root-wrapper"; String jsonToXMLCondition = "(request.header.Content-Type == \"application/json\")"; String httpVerb = apiMap.getVerb(); String resourcePath = apiMap.getResourcePath(); String Condition = "(proxy.pathsuffix MatchesPath \"" + resourcePath + "\") and (request.verb = \"" + httpVerb + "\")"; String addSoapAction = operationName + "-add-soapaction"; flow = proxyDefault.createElement("Flow"); ((Element) flow).setAttribute("name", operationName); flowDescription = proxyDefault.createElement("Description"); flowDescription.setTextContent(operationName); flow.appendChild(flowDescription); request = proxyDefault.createElement("Request"); response = proxyDefault.createElement("Response"); condition = proxyDefault.createElement("Condition"); condition2 = proxyDefault.createElement("Condition"); condition2.setTextContent(jsonToXMLCondition); step1 = proxyDefault.createElement("Step"); name1 = proxyDefault.createElement("Name"); step2 = proxyDefault.createElement("Step"); name2 = proxyDefault.createElement("Name"); step3 = proxyDefault.createElement("Step"); name3 = proxyDefault.createElement("Name"); step4 = proxyDefault.createElement("Step"); name4 = proxyDefault.createElement("Name"); step5 = proxyDefault.createElement("Step"); name5 = proxyDefault.createElement("Name"); if (httpVerb.equalsIgnoreCase("get")) { name1.setTextContent(extractPolicyName); step1.appendChild(name1); request.appendChild(step1); step2 = proxyDefault.createElement("Step"); name2 = proxyDefault.createElement("Name"); name2.setTextContent(buildSOAPPolicy); step2.appendChild(name2); request.appendChild(step2); LOGGER.fine("Assign Message: " + buildSOAPPolicy); LOGGER.fine("Extract Variable: " + extractPolicyName); } else { // add root wrapper policy name3.setTextContent(jsPolicyName); step3.appendChild(name3); step3.appendChild(condition2.cloneNode(true)); request.appendChild(step3); //add the root wrapper only once if (!once) { Node resourceRootWrapper = apiTemplateDocument.createElement("Resource"); resourceRootWrapper.setTextContent("jsc://root-wrapper.js"); resources.appendChild(resourceRootWrapper); once = true; } name1.setTextContent(jsonToXML); step1.appendChild(name1); step1.appendChild(condition2); request.appendChild(step1); // TODO: add condition here to convert to XML only if // Content-Type is json; name2.setTextContent(operationName + "-add-namespace"); step2.appendChild(name2); request.appendChild(step2); if (apiMap.getOthernamespaces()) { name4.setTextContent(operationName + "-add-other-namespaces"); step4.appendChild(name4); request.appendChild(step4); } // for soap 1.1 add soap action if (soapVersion.equalsIgnoreCase("SOAP11")) { step5 = proxyDefault.createElement("Step"); name5 = proxyDefault.createElement("Name"); name5.setTextContent(addSoapAction); step5.appendChild(name5); request.appendChild(step5); } } LOGGER.fine("Condition: " + Condition); condition.setTextContent(Condition); flow.appendChild(request); flow.appendChild(response); flow.appendChild(condition); flows.appendChild(flow); if (httpVerb.equalsIgnoreCase("get")) { // Add policy to proxy.xml Node policy1 = apiTemplateDocument.createElement("Policy"); policy1.setTextContent(extractPolicyName); Node policy2 = apiTemplateDocument.createElement("Policy"); policy2.setTextContent(buildSOAPPolicy); policies.appendChild(policy1); policies.appendChild(policy2); // write Assign Message Policy writeSOAP2APIAssignMessagePolicies(assignTemplate, operationName, buildSOAPPolicy, apiMap.getSoapAction()); // write Extract Variable Policy writeSOAP2APIExtractPolicy(extractTemplate, operationName, extractPolicyName); } else { Node policy2 = apiTemplateDocument.createElement("Policy"); policy2.setTextContent(jsPolicyName); policies.appendChild(policy2); writeRootWrapper(jsPolicyTemplate, operationName, apiMap.getRootElement()); Node policy1 = apiTemplateDocument.createElement("Policy"); policy1.setTextContent(jsonToXML); policies.appendChild(policy1); writeJsonToXMLPolicy(jsonXMLTemplate, operationName, apiMap.getRootElement()); Node policy3 = apiTemplateDocument.createElement("Policy"); policy3.setTextContent(operationName + "add-namespace"); policies.appendChild(policy3); Node resourceAddNamespaces = apiTemplateDocument.createElement("Resource"); resourceAddNamespaces.setTextContent("xsl://"+operationName + "add-namespace.xslt"); resources.appendChild(resourceAddNamespaces); if (apiMap.getOthernamespaces()) { Node policy4 = apiTemplateDocument.createElement("Policy"); policy4.setTextContent(operationName + "add-other-namespaces"); policies.appendChild(policy4); Node resourceAddOtherNamespaces = apiTemplateDocument.createElement("Resource"); resourceAddOtherNamespaces.setTextContent("xsl://"+operationName + "add-other-namespaces.xslt"); resources.appendChild(resourceAddOtherNamespaces); writeAddNamespace(addNamespaceTemplate, operationName, true); } else { writeAddNamespace(addNamespaceTemplate, operationName, false); } // for soap 1.1 add soap action if (soapVersion.equalsIgnoreCase("SOAP11")) { // Add policy to proxy.xml Node policy5 = apiTemplateDocument.createElement("Policy"); policy5.setTextContent(addSoapAction); policies.appendChild(policy5); writeAddSoapAction(addSoapActionTemplate, operationName, apiMap.getSoapAction()); } } } // Add unknown resource flow = proxyDefault.createElement("Flow"); ((Element) flow).setAttribute("name", "unknown-resource"); flowDescription = proxyDefault.createElement("Description"); flowDescription.setTextContent("Unknown Resource"); flow.appendChild(flowDescription); request = proxyDefault.createElement("Request"); response = proxyDefault.createElement("Response"); condition = proxyDefault.createElement("Condition"); Node conditionA = proxyDefault.createElement("Condition"); conditionA.setTextContent( "(verb != \"GET\" AND contentformat == \"application/json\") OR (verb == \"GET\" AND acceptformat !~ \"*/xml\")"); Node conditionB = proxyDefault.createElement("Condition"); conditionB.setTextContent( "(verb != \"GET\" AND contentformat != \"application/json\") OR (verb == \"GET\" AND acceptformat ~ \"*/xml\")"); step1 = proxyDefault.createElement("Step"); name1 = proxyDefault.createElement("Name"); name1.setTextContent("unknown-resource"); step1.appendChild(name1); step1.appendChild(conditionA);// added request.appendChild(step1); step2 = proxyDefault.createElement("Step"); name2 = proxyDefault.createElement("Name"); name2.setTextContent("unknown-resource-xml"); step2.appendChild(name2); step2.appendChild(conditionB); request.appendChild(step2); flow.appendChild(request); flow.appendChild(response); flow.appendChild(condition); flows.appendChild(flow); LOGGER.fine( "Edited proxy xml: " + buildFolder + File.separator + "apiproxy" + File.separator + proxyName + ".xml"); xmlUtils.writeXML(apiTemplateDocument, buildFolder + File.separator + "apiproxy" + File.separator + proxyName + ".xml"); xmlUtils.writeXML(proxyDefault, buildFolder + File.separator + "apiproxy" + File.separator + "proxies" + File.separator + "default.xml"); LOGGER.fine("Edited target xml: " + buildFolder + File.separator + "apiproxy" + File.separator + "proxies" + File.separator + "default.xml"); LOGGER.exiting(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); } private void writeRootWrapper(Document rootWrapperTemplate, String operationName, String rootElement) throws Exception { LOGGER.entering(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); String targetPath = buildFolder + File.separator + "apiproxy" + File.separator + "policies" + File.separator; XMLUtils xmlUtils = new XMLUtils(); Document jsPolicyXML = xmlUtils.cloneDocument(rootWrapperTemplate); Node root = jsPolicyXML.getFirstChild(); NamedNodeMap attr = root.getAttributes(); Node nodeAttr = attr.getNamedItem("name"); nodeAttr.setNodeValue(operationName + "-root-wrapper"); Node displayName = jsPolicyXML.getElementsByTagName("DisplayName").item(0); displayName.setTextContent(operationName + " Root Wrapper"); Node propertyElement = jsPolicyXML.getElementsByTagName("Property").item(0); propertyElement.setTextContent(rootElement); xmlUtils.writeXML(jsPolicyXML, targetPath + operationName + "-root-wrapper.xml"); LOGGER.exiting(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); } private void writeAddSoapAction(Document addSoapActionTemplate, String operationName, String soapAction) throws Exception { LOGGER.entering(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); try { XMLUtils xmlUtils = new XMLUtils(); String policyName = operationName + "-add-soapaction"; Document soapActionPolicyXML = xmlUtils.cloneDocument(addSoapActionTemplate); Node rootElement = soapActionPolicyXML.getFirstChild(); NamedNodeMap attr = rootElement.getAttributes(); Node nodeAttr = attr.getNamedItem("name"); nodeAttr.setNodeValue(policyName); Node displayName = soapActionPolicyXML.getElementsByTagName("DisplayName").item(0); displayName.setTextContent(operationName + " Add SOAPAction"); Node header = soapActionPolicyXML.getElementsByTagName("Header").item(0); header.setTextContent(soapAction); xmlUtils.writeXML(soapActionPolicyXML, buildFolder + File.separator + "apiproxy" + File.separator + "policies" + File.separator + policyName + ".xml"); } catch (Exception e) { e.printStackTrace(); throw e; } LOGGER.exiting(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); } private void writeAddNamespace(Document namespaceTemplate, String operationName, boolean addOtherNamespaces) throws Exception { LOGGER.entering(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); try { XMLUtils xmlUtils = new XMLUtils(); String policyName = operationName + "-add-namespace"; Document xslPolicyXML = xmlUtils.cloneDocument(namespaceTemplate); Node rootElement = xslPolicyXML.getFirstChild(); NamedNodeMap attr = rootElement.getAttributes(); Node nodeAttr = attr.getNamedItem("name"); nodeAttr.setNodeValue(policyName); Node displayName = xslPolicyXML.getElementsByTagName("DisplayName").item(0); displayName.setTextContent(operationName + " Add Namespace"); Node resourceURL = xslPolicyXML.getElementsByTagName("ResourceURL").item(0); resourceURL.setTextContent("xsl://" + policyName + ".xslt"); xmlUtils.writeXML(xslPolicyXML, buildFolder + File.separator + "apiproxy" + File.separator + "policies" + File.separator + policyName + ".xml"); if (addOtherNamespaces) { String policyNameOther = operationName + "-add-other-namespaces"; Document xslPolicyXMLOther = xmlUtils.cloneDocument(namespaceTemplate); Node rootElementOther = xslPolicyXMLOther.getFirstChild(); NamedNodeMap attrOther = rootElementOther.getAttributes(); Node nodeAttrOther = attrOther.getNamedItem("name"); nodeAttrOther.setNodeValue(policyNameOther); Node displayNameOther = xslPolicyXMLOther.getElementsByTagName("DisplayName").item(0); displayNameOther.setTextContent(operationName + " Add Other Namespaces"); Node resourceURLOther = xslPolicyXMLOther.getElementsByTagName("ResourceURL").item(0); resourceURLOther.setTextContent("xsl://" + policyNameOther + ".xslt"); xmlUtils.writeXML(xslPolicyXMLOther, buildFolder + File.separator + "apiproxy" + File.separator + "policies" + File.separator + policyNameOther + ".xml"); } } catch (Exception e) { e.printStackTrace(); throw e; } LOGGER.exiting(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); } private void writeSOAP2APIExtractPolicy(Document extractTemplate, String operationName, String policyName) throws Exception { LOGGER.entering(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); XMLUtils xmlUtils = new XMLUtils(); Element queryParam; Element pattern; Document extractPolicyXML = xmlUtils.cloneDocument(extractTemplate); Node rootElement = extractPolicyXML.getFirstChild(); NamedNodeMap attr = rootElement.getAttributes(); Node nodeAttr = attr.getNamedItem("name"); nodeAttr.setNodeValue(policyName); Node displayName = extractPolicyXML.getElementsByTagName("DisplayName").item(0); displayName.setTextContent(operationName + " Extract Query Param"); APIMap apiMap = messageTemplates.get(operationName); List<String> elementList = xmlUtils.getElementList(apiMap.getSoapBody()); for (String elementName : elementList) { queryParam = extractPolicyXML.createElement("QueryParam"); queryParam.setAttribute("name", elementName); pattern = extractPolicyXML.createElement("Pattern"); pattern.setAttribute("ignoreCase", "true"); pattern.setTextContent("{" + elementName + "}"); queryParam.appendChild(pattern); rootElement.appendChild(queryParam); } xmlUtils.writeXML(extractPolicyXML, buildFolder + File.separator + "apiproxy" + File.separator + "policies" + File.separator + policyName + ".xml"); LOGGER.exiting(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); } private void writeSOAP2APIAssignMessagePolicies(Document assignTemplate, String operationName, String policyName, String soapAction) throws Exception { LOGGER.entering(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); XMLUtils xmlUtils = new XMLUtils(); Document assignPolicyXML = xmlUtils.cloneDocument(assignTemplate); Node rootElement = assignPolicyXML.getFirstChild(); NamedNodeMap attr = rootElement.getAttributes(); Node nodeAttr = attr.getNamedItem("name"); nodeAttr.setNodeValue(policyName); Node displayName = assignPolicyXML.getElementsByTagName("DisplayName").item(0); displayName.setTextContent(operationName + " Build SOAP"); Node payload = assignPolicyXML.getElementsByTagName("Payload").item(0); NamedNodeMap payloadNodeMap = payload.getAttributes(); Node payloadAttr = payloadNodeMap.getNamedItem("contentType"); if (soapVersion.equalsIgnoreCase("SOAP12")) { payloadAttr.setNodeValue(StringEscapeUtils.escapeXml10(SOAP12_PAYLOAD_TYPE)); assignPolicyXML.getElementsByTagName("Header").item(1) .setTextContent(StringEscapeUtils.escapeXml10(SOAP12_CONTENT_TYPE)); } else { payloadAttr.setNodeValue(StringEscapeUtils.escapeXml10(SOAP11_PAYLOAD_TYPE)); assignPolicyXML.getElementsByTagName("Header").item(1) .setTextContent(StringEscapeUtils.escapeXml10(SOAP11_CONTENT_TYPE)); Node header = assignPolicyXML.getElementsByTagName("Header").item(0); header.setTextContent(soapAction); } APIMap apiMap = messageTemplates.get(operationName); Document operationPayload = xmlUtils.getXMLFromString(apiMap.getSoapBody()); Node importedNode = assignPolicyXML.importNode(operationPayload.getDocumentElement(), true); payload.appendChild(importedNode); Node value = assignPolicyXML.getElementsByTagName("Value").item(0); value.setTextContent(targetEndpoint); LOGGER.fine("Generated resource xml: " + buildFolder + File.separator + "apiproxy" + File.separator + "policies" + File.separator + policyName + ".xml"); xmlUtils.writeXML(assignPolicyXML, buildFolder + File.separator + "apiproxy" + File.separator + "policies" + File.separator + policyName + ".xml"); LOGGER.exiting(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); } private void writeTargetEndpoint() throws Exception { LOGGER.entering(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); XMLUtils xmlUtils = new XMLUtils(); Document targetDefault; if (PASSTHRU) { targetDefault = xmlUtils.readXML(SOAPPASSTHRU_TARGET_TEMPLATE); } else { targetDefault = xmlUtils.readXML(SOAP2API_TARGET_TEMPLATE); if (CORS) { Node response = targetDefault.getElementsByTagName("Response").item(0); Node step = targetDefault.createElement("Step"); Node name = targetDefault.createElement("Name"); name.setTextContent("add-cors"); step.appendChild(name); response.appendChild(step); } } Node urlNode = targetDefault.getElementsByTagName("URL").item(0); if (targetEndpoint != null && targetEndpoint.equalsIgnoreCase("") != true) { urlNode.setTextContent(targetEndpoint); } else { LOGGER.warning("No target URL set"); } xmlUtils.writeXML(targetDefault, buildFolder + File.separator + "apiproxy" + File.separator + "targets" + File.separator + "default.xml"); LOGGER.info("Generated Target xml: " + buildFolder + File.separator + "apiproxy" + File.separator + "targets" + File.separator + "default.xml"); LOGGER.exiting(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); } private void writeJsonToXMLPolicy(Document jsonXMLTemplate, String operationName, String rootElement) throws Exception { LOGGER.entering(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); String targetPath = buildFolder + File.separator + "apiproxy" + File.separator + "policies" + File.separator; XMLUtils xmlUtils = new XMLUtils(); Document jsonxmlPolicyXML = xmlUtils.cloneDocument(jsonXMLTemplate); Node root = jsonxmlPolicyXML.getFirstChild(); NamedNodeMap attr = root.getAttributes(); Node nodeAttr = attr.getNamedItem("name"); nodeAttr.setNodeValue(operationName + "-json-to-xml"); Node displayName = jsonxmlPolicyXML.getElementsByTagName("DisplayName").item(0); displayName.setTextContent(operationName + " JSON TO XML"); Node objectRootElement = jsonxmlPolicyXML.getElementsByTagName("ObjectRootElementName").item(0); objectRootElement.setTextContent(rootElement); Node arrayRootElement = jsonxmlPolicyXML.getElementsByTagName("ArrayRootElementName").item(0); arrayRootElement.setTextContent(rootElement); xmlUtils.writeXML(jsonxmlPolicyXML, targetPath + operationName + "-json-to-xml.xml"); LOGGER.exiting(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); } private void writeStdPolicies() throws Exception { LOGGER.entering(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); try { String sourcePath = "/templates/"; String targetPath = buildFolder + File.separator + "apiproxy" + File.separator + "policies" + File.separator; String xslResourcePath = buildFolder + File.separator + "apiproxy" + File.separator + "resources" + File.separator + "xsl" + File.separator; String jsResourcePath = buildFolder + File.separator + "apiproxy" + File.separator + "resources" + File.separator + "jsc" + File.separator; LOGGER.fine("Source Path: " + sourcePath); LOGGER.fine("Target Path: " + targetPath); if (PASSTHRU) { sourcePath += "soappassthru/"; Files.copy(getClass().getResourceAsStream(sourcePath + "Extract-Operation-Name.xml"), Paths.get(targetPath + "Extract-Operation-Name.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); Files.copy(getClass().getResourceAsStream(sourcePath + "Invalid-SOAP.xml"), Paths.get(targetPath + "Invalid-SOAP.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); } else { sourcePath += "soap2api/"; Files.copy(getClass().getResourceAsStream(sourcePath + "xml-to-json.xml"), Paths.get(targetPath + "xml-to-json.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); Files.copy(getClass().getResourceAsStream(sourcePath + "set-response-soap-body.xml"), Paths.get(targetPath + "set-response-soap-body.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); Files.copy(getClass().getResourceAsStream(sourcePath + "set-response-soap-body-accept.xml"), Paths.get(targetPath + "set-response-soap-body-accept.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); Files.copy(getClass().getResourceAsStream(sourcePath + "get-response-soap-body.xml"), Paths.get(targetPath + "get-response-soap-body.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); Files.copy(getClass().getResourceAsStream(sourcePath + "get-response-soap-body-xml.xml"), Paths.get(targetPath + "get-response-soap-body-xml.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); Files.copy(getClass().getResourceAsStream(sourcePath + "set-target-url.xml"), Paths.get(targetPath + "set-target-url.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); Files.copy(getClass().getResourceAsStream(sourcePath + "extract-format.xml"), Paths.get(targetPath + "extract-format.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); Files.copy(getClass().getResourceAsStream(sourcePath + "unknown-resource.xml"), Paths.get(targetPath + "unknown-resource.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); Files.copy(getClass().getResourceAsStream(sourcePath + "unknown-resource-xml.xml"), Paths.get(targetPath + "unknown-resource-xml.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); Files.copy(getClass().getResourceAsStream(sourcePath + "remove-empty-nodes.xml"), Paths.get(targetPath + "remove-empty-nodes.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); Files.copy(getClass().getResourceAsStream(sourcePath + "remove-empty-nodes.xslt"), Paths.get(xslResourcePath + "remove-empty-nodes.xslt"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); Files.copy(getClass().getResourceAsStream(sourcePath + "return-generic-error.xml"), Paths.get(targetPath + "return-generic-error.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); Files.copy(getClass().getResourceAsStream(sourcePath + "return-generic-error-accept.xml"), Paths.get(targetPath + "return-generic-error-accept.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); Files.copy(getClass().getResourceAsStream(sourcePath + "remove-namespaces.xml"), Paths.get(targetPath + "remove-namespaces.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); Files.copy(getClass().getResourceAsStream(sourcePath + "remove-namespaces.xslt"), Paths.get(xslResourcePath + "remove-namespaces.xslt"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); Files.copy(getClass().getResourceAsStream(sourcePath + "root-wrapper.js"), Paths.get(jsResourcePath + "root-wrapper.js"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); if (OAUTH) { Files.copy(getClass().getResourceAsStream(sourcePath + "verify-oauth-v2-access-token.xml"), Paths.get(targetPath + "verify-oauth-v2-access-token.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); Files.copy(getClass().getResourceAsStream(sourcePath + "remove-header-authorization.xml"), Paths.get(targetPath + "remove-header-authorization.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); if (QUOTAOAUTH) { Files.copy(getClass().getResourceAsStream(sourcePath + "impose-quota-oauth.xml"), Paths.get(targetPath + "impose-quota-oauth.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); } } if (APIKEY) { Files.copy(getClass().getResourceAsStream(sourcePath + "verify-api-key.xml"), Paths.get(targetPath + "verify-api-key.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); Files.copy(getClass().getResourceAsStream(sourcePath + "remove-query-param-apikey.xml"), Paths.get(targetPath + "remove-query-param-apikey.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); if (QUOTAAPIKEY) { Files.copy(getClass().getResourceAsStream(sourcePath + "impose-quota-apikey.xml"), Paths.get(targetPath + "impose-quota-apikey.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); } } if (CORS) { Files.copy(getClass().getResourceAsStream(sourcePath + "add-cors.xml"), Paths.get(targetPath + "add-cors.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); } } } catch (Exception e) { LOGGER.severe(e.getMessage()); e.printStackTrace(); throw e; } LOGGER.exiting(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); } private void writeSOAPPassThruProxyEndpointConditions(String proxyDescription) throws Exception { LOGGER.entering(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); String soapConditionText = "(envelope != \"Envelope\") or (body != \"Body\") or (envelopeNamespace !=\""; XMLUtils xmlUtils = new XMLUtils(); Document proxyDefault = xmlUtils.readXML(SOAPPASSTHRU_PROXY_TEMPLATE); Node basePathNode = proxyDefault.getElementsByTagName("BasePath").item(0); if (basePath != null && basePath.equalsIgnoreCase("") != true) { basePathNode.setTextContent(basePath); } Node httpProxyConnection = proxyDefault.getElementsByTagName("HTTPProxyConnection").item(0); Node virtualHost = null; for (String vHost : vHosts) { virtualHost = proxyDefault.createElement("VirtualHost"); virtualHost.setTextContent(vHost); httpProxyConnection.appendChild(virtualHost); } Node description = proxyDefault.getElementsByTagName("Description").item(0); description.setTextContent(proxyDescription); Node soapCondition = proxyDefault.getElementsByTagName("Condition").item(1); if (soapVersion.equalsIgnoreCase("SOAP11")) { soapCondition.setTextContent(soapConditionText + SOAP11 + "\")"); } else { soapCondition.setTextContent(soapConditionText + SOAP12 + "\")"); } String conditionText = "(proxy.pathsuffix MatchesPath \"/\") and (request.verb = \"POST\") and (operation = \""; Node flows = proxyDefault.getElementsByTagName("Flows").item(0); Node flow; Node flowDescription; Node request; Node response; Node condition; Node step1; Node name1; for (Map.Entry<String, APIMap> entry : messageTemplates.entrySet()) { String operationName = entry.getKey(); APIMap apiMap = entry.getValue(); flow = proxyDefault.createElement("Flow"); ((Element) flow).setAttribute("name", operationName); flowDescription = proxyDefault.createElement("Description"); flowDescription.setTextContent(operationName); flow.appendChild(flowDescription); request = proxyDefault.createElement("Request"); response = proxyDefault.createElement("Response"); condition = proxyDefault.createElement("Condition"); condition.setTextContent(conditionText + apiMap.getRootElement() + "\")"); flow.appendChild(request); flow.appendChild(response); flow.appendChild(condition); flows.appendChild(flow); } // Add unknown resource flow = proxyDefault.createElement("Flow"); ((Element) flow).setAttribute("name", "unknown-resource"); flowDescription = proxyDefault.createElement("Description"); flowDescription.setTextContent("Unknown Resource"); flow.appendChild(flowDescription); request = proxyDefault.createElement("Request"); response = proxyDefault.createElement("Response"); condition = proxyDefault.createElement("Condition"); step1 = proxyDefault.createElement("Step"); name1 = proxyDefault.createElement("Name"); name1.setTextContent("Invalid-SOAP"); step1.appendChild(name1); request.appendChild(step1); flow.appendChild(request); flow.appendChild(response); flow.appendChild(condition); flows.appendChild(flow); xmlUtils.writeXML(proxyDefault, buildFolder + File.separator + "apiproxy" + File.separator + "proxies" + File.separator + "default.xml"); LOGGER.fine("Edited target xml: " + buildFolder + File.separator + "apiproxy" + File.separator + "proxies" + File.separator + "default.xml"); LOGGER.exiting(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); } public String getPrefix(String namespaceUri) { LOGGER.entering(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); for (Map.Entry<String, String> entry : namespace.entrySet()) { if (entry.getValue().equalsIgnoreCase(namespaceUri)) { if (entry.getKey().length() == 0) { return "ns"; } else { return entry.getKey(); } } } LOGGER.exiting(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); return "ns"; } private void parseElement(com.predic8.schema.Element e, List<Schema> schemas, String rootElement, String rootNamespace, String rootPrefix) { if (e.getName() == null) { if (e.getRef() != null) { final String localPart = e.getRef().getLocalPart(); final com.predic8.schema.Element element = elementFromSchema(localPart, schemas); parseSchema(element, schemas, rootElement, rootNamespace, rootPrefix); } else { // fail silently LOGGER.warning("unhandled conditions getRef() = null"); } } else { if (!e.getName().equalsIgnoreCase(rootElement)) { if (e.getEmbeddedType() instanceof ComplexType) { ComplexType ct = (ComplexType) e.getEmbeddedType(); if (!e.getNamespaceUri().equalsIgnoreCase(rootNamespace)) { buildXPath(e, rootElement, rootNamespace, rootPrefix); } parseSchema(ct.getModel(), schemas, rootElement, rootNamespace, rootPrefix); } else { if (e.getType() != null) { if (!getParentNamepace(e).equalsIgnoreCase(rootNamespace) && !e.getType().getNamespaceURI().equalsIgnoreCase(rootNamespace)) { buildXPath(e, rootElement, rootNamespace, rootPrefix); } TypeDefinition typeDefinition = getTypeFromSchema(e.getType(), schemas); if (typeDefinition instanceof ComplexType) { parseSchema(((ComplexType) typeDefinition).getModel(), schemas, rootElement, rootNamespace, rootPrefix); } } else { // handle this as anyType buildXPath(e, rootElement, rootNamespace, rootPrefix, true); if (!getParentNamepace(e).equalsIgnoreCase(rootNamespace)) { buildXPath(e, rootElement, rootNamespace, rootPrefix); } LOGGER.warning("Found element " + e.getName() + " with no type. Handling as xsd:anyType"); } } } } } private com.predic8.schema.Element elementFromSchema(String name, List<Schema> schemas) { if (name != null) { for (Schema schema : schemas) { try { final com.predic8.schema.Element element = schema.getElement(name); if (element != null) { return element; } } catch (Exception e) { LOGGER.warning("unhandled conditions: " + e.getMessage()); } } } return null; } private void parseSchema(SchemaComponent sc, List<Schema> schemas, String rootElement, String rootNamespace, String rootPrefix) { LOGGER.entering(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); if (sc instanceof Sequence) { Sequence seq = (Sequence) sc; level++; for (com.predic8.schema.Element e : seq.getElements()) { // System.out.println(e.getName() + " - " + " " + e.getType()); if (e.getName() == null) level if (e.getName() != null) { xpathElement.put(level, e.getName()); if (e.getType() != null) { if (e.getType().getLocalPart().equalsIgnoreCase("anyType")) { // found a anyType. remove namespaces for // descendents buildXPath(e, rootElement, rootNamespace, rootPrefix, true); } } } parseElement(e, schemas, rootElement, rootNamespace, rootPrefix); } level cleanUpXPath(); } else if (sc instanceof Choice) { Choice ch = (Choice) sc; level++; for (com.predic8.schema.Element e : ch.getElements()) { if (!e.getName().equalsIgnoreCase(rootElement)) { if (e.getEmbeddedType() instanceof ComplexType) { ComplexType ct = (ComplexType) e.getEmbeddedType(); xpathElement.put(level, e.getName()); parseSchema(ct.getModel(), schemas, rootElement, rootNamespace, rootPrefix); } else { final TypeDefinition typeDefinition = getTypeFromSchema(e.getType(), schemas); if (typeDefinition instanceof ComplexType) { xpathElement.put(level, e.getName()); parseSchema(((ComplexType) typeDefinition).getModel(), schemas, rootElement, rootNamespace, rootPrefix); } if (e.getType() == null) { // handle this any anyType buildXPath(e, rootElement, rootNamespace, rootPrefix, true); LOGGER.warning("Element " + e.getName() + " type was null; treating as anyType"); } else if (!getParentNamepace(e).equalsIgnoreCase(rootNamespace) && !e.getType().getNamespaceURI().equalsIgnoreCase(rootNamespace)) { buildXPath(e, rootElement, rootNamespace, rootPrefix); } else if (e.getType().getLocalPart().equalsIgnoreCase("anyType")) { // if you find a anyType, remove namespace for the // descendents. buildXPath(e, rootElement, rootNamespace, rootPrefix, true); } } } } level cleanUpXPath(); } else if (sc instanceof ComplexContent) { ComplexContent complexContent = (ComplexContent) sc; Derivation derivation = complexContent.getDerivation(); if (derivation != null) { TypeDefinition typeDefinition = getTypeFromSchema(derivation.getBase(), schemas); if (typeDefinition instanceof ComplexType) { parseSchema(((ComplexType) typeDefinition).getModel(), schemas, rootElement, rootNamespace, rootPrefix); } if (derivation.getModel() instanceof Sequence) { parseSchema(derivation.getModel(), schemas, rootElement, rootNamespace, rootPrefix); } else if (derivation.getModel() instanceof ModelGroup) { parseSchema(derivation.getModel(), schemas, rootElement, rootNamespace, rootPrefix); } } } else if (sc instanceof SimpleContent) { SimpleContent simpleContent = (SimpleContent) sc; Derivation derivation = (Derivation) simpleContent.getDerivation(); if (derivation.getAllAttributes().size() > 0) { // has attributes buildXPath(derivation.getNamespaceUri(), rootElement, rootNamespace, rootPrefix); } } else if (sc instanceof com.predic8.schema.Element) { level++; xpathElement.put(level, ((com.predic8.schema.Element) sc).getName()); parseElement((com.predic8.schema.Element) sc, schemas, rootElement, rootNamespace, rootPrefix); } else if (sc instanceof All) { All all = (All) sc; level++; for (com.predic8.schema.Element e : all.getElements()) { if (e.getName() == null) level if (e.getName() != null) xpathElement.put(level, e.getName()); parseElement(e, schemas, rootElement, rootNamespace, rootPrefix); } level cleanUpXPath(); } else if (sc != null) { // fail silently LOGGER.warning("unhandled conditions - " + sc.getClass().getName()); } LOGGER.exiting(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); } private TypeDefinition getTypeFromSchema(QName qName, List<Schema> schemas) { LOGGER.entering(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); if (qName != null) { for (Schema schema : schemas) { try { final TypeDefinition type = schema.getType(qName); if (type != null) { return type; } } catch (Exception e) { // Fail silently LOGGER.warning("unhandle conditions: " + e.getMessage()); } } } return null; } private void cleanUpXPath() { LOGGER.entering(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); for (Integer key : xpathElement.keySet()) { if (key > level) xpathElement.remove(key); } LOGGER.exiting(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); } private void buildXPath(com.predic8.schema.Element e, String rootElement, String rootNamespace, String rootPrefix, boolean removeNamespace) { LOGGER.entering(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); Rule r = null; String xpathString = ""; String prefix = "NULL"; String namespaceUri = "NULL"; String soapElements = "/soapenv:Envelope/soapenv:Body"; String lastElement = ""; for (Map.Entry<Integer, String> entry : xpathElement.entrySet()) { xpathString = xpathString + "/" + rootPrefix + ":" + entry.getValue(); lastElement = entry.getValue(); } // add the last element to xpath if (!lastElement.equalsIgnoreCase(e.getName())) xpathString = xpathString + "/" + rootPrefix + ":" + e.getName(); r = new Rule(soapElements + xpathString, prefix, namespaceUri, "descendant"); ruleList.add(r); LOGGER.exiting(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); } private void buildXPath(com.predic8.schema.Element e, String rootElement, String rootNamespace, String rootPrefix) { LOGGER.entering(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); Rule r = null; String xpathString = ""; String soapElements = "/soapenv:Envelope/soapenv:Body"; String prefix = getPrefix(e.getNamespaceUri()); String namespaceUri = e.getNamespaceUri(); for (Map.Entry<Integer, String> entry : xpathElement.entrySet()) { xpathString = xpathString + "/" + rootPrefix + ":" + entry.getValue(); } r = new Rule(soapElements + xpathString, prefix, namespaceUri); ruleList.add(r); LOGGER.exiting(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); } private void buildXPath(String namespaceUri, String rootElement, String rootNamespace, String rootPrefix) { LOGGER.entering(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); Rule r = null; String prefix = getPrefix(namespaceUri); String soapElements = "/soapenv:Envelope/soapenv:Body"; String xpathString = ""; for (Map.Entry<Integer, String> entry : xpathElement.entrySet()) { xpathString = xpathString + "/" + rootPrefix + ":" + entry.getValue(); } r = new Rule(soapElements + xpathString + "/@*", prefix, namespaceUri); ruleList.add(r); cleanUpXPath(); LOGGER.exiting(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); } private String getParentNamepace(com.predic8.schema.Element e) { XMLElement parent = e.getParent(); try { return parent.getNamespaceUri(); } catch (NullPointerException npe) { if (e.getNamespaceUri() != null) return e.getNamespaceUri(); else return null; } } @SuppressWarnings("unchecked") private void parseWSDL(String wsdlPath) throws Exception { LOGGER.entering(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); XMLUtils xmlUtils = new XMLUtils(); StringWriter writer = new StringWriter(); Definitions wsdl = null; SOARequestCreator creator = null; Service service = null; com.predic8.wsdl.Port port = null; String bindingName; try { WSDLParser parser = new WSDLParser(); wsdl = parser.parse(wsdlPath); if (wsdl.getServices().size() == 0) { LOGGER.severe("No services were found in the WSDL"); throw new NoServicesFoundException("No services were found in the WSDL"); } creator = new SOARequestCreator(wsdl, new RequestTemplateCreator(), new MarkupBuilder(writer)); } catch (Exception e) { e.printStackTrace(); LOGGER.severe(e.getLocalizedMessage()); throw e; } KeyValue<String, String> map = StringUtils.proxyNameAndBasePath(wsdlPath); if (serviceName != null) { for (Service svc : wsdl.getServices()) { if (svc.getName().equalsIgnoreCase(serviceName)) { service = svc; LOGGER.fine("Found Service: " + service.getName()); break; } } if (service == null) { // didn't find any service matching name LOGGER.severe("No matching services were found in the WSDL"); throw new NoServicesFoundException("No matching services were found in the WSDL"); } else { proxyName = serviceName; } } else { service = wsdl.getServices().get(0); // get the first service LOGGER.fine("Found Service: " + service.getName()); serviceName = service.getName(); proxyName = serviceName; } if (basePath == null) { if (serviceName != null) { basePath = "/" + serviceName.toLowerCase(); } else { basePath = map.getValue(); } } if (portName != null) { for (com.predic8.wsdl.Port prt : service.getPorts()) { if (prt.getName().equalsIgnoreCase(portName)) { port = prt; } } if (port == null) { // didn't find any port matching name LOGGER.severe("No matching port was found in the WSDL"); throw new NoServicesFoundException("No matching port found in the WSDL"); } } else { port = service.getPorts().get(0); // get first port } LOGGER.fine("Found Port: " + port.getName()); Binding binding = port.getBinding(); bindingName = binding.getName(); soapVersion = binding.getProtocol().toString(); if (!binding.getStyle().toLowerCase().contains("document/literal")) { RPCSTYLE = true; } if (!PASSTHRU && RPCSTYLE == true) { throw new UnSupportedWSDLException("Only Document/Literal is supported for SOAP to REST"); } LOGGER.fine("Found Binding: " + bindingName + " Binding Protocol: " + soapVersion + " Prefix: " + binding.getPrefix() + " NamespaceURI: " + binding.getNamespaceUri()); targetEndpoint = port.getAddress().getLocation(); LOGGER.info("Retrieved WSDL endpoint: " + targetEndpoint); PortType portType = binding.getPortType(); APIMap apiMap = null; HashMap<String, SelectedOperation> selectedOperationList = selectedOperations.getSelectedOperations(); for (Operation op : portType.getOperations()) { LOGGER.fine("Found Operation Name: " + op.getName() + " Prefix: " + op.getPrefix() + " NamespaceURI: " + op.getNamespaceUri()); try { if (selectedOperationList.size() > 0 && !selectedOperationList.containsKey(op.getName())) { //the current operations is not in the list; skip. continue; } if (RPCSTYLE) { apiMap = new APIMap(null, null, null, "POST", op.getName(), false); messageTemplates.put(op.getName(), apiMap); } else { if (op.getInput().getMessage().getParts().size() < 1) { LOGGER.warning("wsdl operation " + op.getName() + " has no parts."); } else if (op.getInput().getMessage().getParts().size() > 1) { LOGGER.warning( "wsdl operation " + op.getName() + " has > 1 part. This is not currently supported"); } else { com.predic8.schema.Element requestElement = op.getInput().getMessage().getParts().get(0) .getElement(); namespace = (Map<String, String>) requestElement.getNamespaceContext(); if (PASSTHRU) { apiMap = new APIMap(null, null, null, "POST", requestElement.getName(), false); messageTemplates.put(op.getName(), apiMap); } else { String resourcePath = operationsMap.getResourcePath(op.getName(), selectedOperationList); String verb = ""; if (!ALLPOST) { verb = operationsMap.getVerb(op.getName(), selectedOperationList); } else { verb = "POST"; } if (verb.equalsIgnoreCase("GET")) { creator.setCreator(new RequestTemplateCreator()); // use membrane SOAP to generate a SOAP Request creator.createRequest(port.getName(), op.getName(), binding.getName()); // store the operation name, SOAP Request and // the // expected JSON Body in the map KeyValue<String, String> kv = xmlUtils.replacePlaceHolders(writer.toString()); apiMap = new APIMap(kv.getValue(), kv.getKey(), resourcePath, verb, requestElement.getName(), false); writer.getBuffer().setLength(0); } else { String namespaceUri = null; if (requestElement.getType() != null) { namespaceUri = requestElement.getType().getNamespaceURI(); } else { namespaceUri = requestElement.getEmbeddedType().getNamespaceUri(); } String prefix = getPrefix(namespaceUri); if (soapVersion.equalsIgnoreCase("SOAP11")) { xmlUtils.generateRootNamespaceXSLT(SOAP2API_XSLT11_TEMPLATE, SOAP2API_XSL, op.getName(), prefix, namespaceUri, namespace); } else { xmlUtils.generateRootNamespaceXSLT(SOAP2API_XSLT12_TEMPLATE, SOAP2API_XSL, op.getName(), prefix, namespaceUri, namespace); } TypeDefinition typeDefinition = null; if (requestElement.getEmbeddedType() != null) { typeDefinition = requestElement.getEmbeddedType(); } else { typeDefinition = getTypeFromSchema(requestElement.getType(), wsdl.getSchemas()); } if (typeDefinition instanceof ComplexType) { ComplexType ct = (ComplexType) typeDefinition; xpathElement.put(level, requestElement.getName()); parseSchema(ct.getModel(), wsdl.getSchemas(), requestElement.getName(), namespaceUri, prefix); } if (ruleList.size() > 0) { RuleSet rs = new RuleSet(); rs.addRuleList(ruleList); xmlUtils.generateOtherNamespacesXSLT(SOAP2API_XSL, op.getName(), rs.getTransform(soapVersion), namespace); ruleList.clear(); apiMap = new APIMap("", "", resourcePath, verb, requestElement.getName(), true); } else { apiMap = new APIMap("", "", resourcePath, verb, requestElement.getName(), false); } } messageTemplates.put(op.getName(), apiMap); } } } } catch (Exception e) { LOGGER.severe(e.getMessage()); e.printStackTrace(); throw e; } } if (messageTemplates.size() == 0) { LOGGER.exiting(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); throw new BindingNotFoundException("Soap version provided did not match any binding in WSDL"); } if (!PASSTHRU) { for (Binding bnd : wsdl.getBindings()) { if (bindingName.equalsIgnoreCase(bnd.getName())) { for (BindingOperation bop : bnd.getOperations()) { if (selectedOperationList.size() > 0 && !selectedOperationList.containsKey(bop.getName())) { //the current operations is not in the list; skip. continue; } if (bnd.getBinding() instanceof AbstractSOAPBinding) { LOGGER.fine("Found Operation Name: " + bop.getName() + " SOAPAction: " + bop.getOperation().getSoapAction()); APIMap apiM = messageTemplates.get(bop.getName()); apiM.setSoapAction(bop.getOperation().getSoapAction()); messageTemplates.put(bop.getName(), apiM); } } } } } LOGGER.exiting(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); } private boolean prepareTargetFolder() { LOGGER.entering(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); File f = new File(buildFolder); if (f.isDirectory()) { // ensure target is a folder LOGGER.fine("Target is a folder"); File apiproxy = new File(f.getAbsolutePath() + File.separator + "apiproxy"); if (apiproxy.exists()) { LOGGER.severe("Folder called apiproxy already exists"); LOGGER.exiting(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); return false; } else { apiproxy.mkdir(); LOGGER.fine("created apiproxy folder"); new File(apiproxy.getAbsolutePath() + File.separator + "policies").mkdirs(); LOGGER.fine("created policies folder"); new File(apiproxy.getAbsolutePath() + File.separator + "proxies").mkdirs(); LOGGER.fine("created proxies folder"); new File(apiproxy.getAbsolutePath() + File.separator + "targets").mkdirs(); LOGGER.fine("created targets folder"); if (!PASSTHRU) { File xsltFolder = new File( apiproxy.getAbsolutePath() + File.separator + "resources" + File.separator + "xsl"); xsltFolder.mkdirs(); SOAP2API_XSL = xsltFolder.getAbsolutePath() + File.separator; File jsFolder = new File( apiproxy.getAbsolutePath() + File.separator + "resources" + File.separator + "jsc"); jsFolder.mkdirs(); LOGGER.fine("created resources folder"); } LOGGER.info("Target proxy folder setup complete"); LOGGER.exiting(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); return true; } } else { LOGGER.severe("Target folder is not a directory"); LOGGER.exiting(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); return false; } } public InputStream begin(String proxyDescription, String wsdlPath) throws Exception { LOGGER.entering(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); LOGGER.fine("Preparing target folder"); String zipFolder = null; Path tempDirectory = null; InputStream is = null; GenerateBundle generateBundle = new GenerateBundle(); try { if (buildFolder == null) { tempDirectory = Files.createTempDirectory(null); buildFolder = tempDirectory.toAbsolutePath().toString(); } zipFolder = buildFolder + File.separator + "apiproxy"; // prepare the target folder (create apiproxy folder and sub-folders if (prepareTargetFolder()) { // if not passthru read conf file to interpret soap operations // to resources if (!PASSTHRU) { operationsMap.readOperationsMap(opsMap); LOGGER.info("Read operations map"); } // parse the wsdl parseWSDL(wsdlPath); LOGGER.info("Parsed WSDL Successfully."); if (!DESCSET) { proxyDescription += serviceName; } LOGGER.info("Base Path: " + basePath + "\nWSDL Path: " + wsdlPath); LOGGER.info("Build Folder: " + buildFolder + "\nSOAP Version: " + soapVersion); LOGGER.info("Proxy Name: " + proxyName + "\nProxy Description: " + proxyDescription); // create the basic proxy structure from templates writeAPIProxy(proxyDescription); LOGGER.info("Generated Apigee proxy file."); if (!PASSTHRU) { LOGGER.info("Generated SOAP Message Templates."); writeSOAP2APIProxyEndpoint(proxyDescription); LOGGER.info("Generated proxies XML."); writeStdPolicies(); LOGGER.info("Copied standard policies."); writeTargetEndpoint(); LOGGER.info("Generated target XML."); } else { writeStdPolicies(); LOGGER.info("Copied standard policies."); writeTargetEndpoint(); LOGGER.info("Generated target XML."); writeSOAPPassThruProxyEndpointConditions(proxyDescription); } File file = generateBundle.build(zipFolder, proxyName); LOGGER.info("Generated Apigee Edge API Bundle file: " + proxyName + ".zip"); LOGGER.exiting(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); return new ByteArrayInputStream(Files.readAllBytes(file.toPath())); } else { LOGGER.exiting(GenerateProxy.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); throw new TargetFolderException("Erorr is preparing target folder; target folder not empty " + buildFolder); } } catch (Exception e) { LOGGER.severe(e.getMessage()); throw e; } finally { if (tempDirectory != null) { try { Files.walkFileTree(tempDirectory, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return FileVisitResult.CONTINUE; } }); } catch (IOException e) { LOGGER.severe(e.getMessage()); } } } } public static void usage() { System.out.println(""); System.out.println("Usage: java -jar wsdl2apigee.jar -wsdl={url or path to wsdl} <options>"); System.out.println(""); System.out.println("Options:"); System.out.println("-passthru=<true|false> default is false;"); System.out.println("-desc=\"description for proxy\""); System.out.println("-service=servicename if wsdl has > 1 service, enter service name"); System.out.println("-port=portname if service has > 1 port, enter port name"); System.out.println("-opsmap=opsmapping.xml mapping file that to map wsdl operation to http verb"); System.out.println("-allpost=<true|false> set to true if all operations are http verb; default is false"); System.out.println("-vhosts=<comma separated values for virtuals hosts>"); System.out.println("-build=specify build folder default is temp/tmp"); System.out.println("-oauth=<true|false> default is false"); System.out.println("-apikey=<true|false> default is false"); System.out.println("-quota=<true|false> default is false; works only if apikey or oauth is set"); System.out.println("-basepath=specify base path"); System.out.println("-cors=<true|false> default is false"); System.out.println("-debug=<true|false> default is false"); System.out.println(""); System.out.println(""); System.out.println("Examples:"); System.out.println("$ java -jar wsdl2apigee.jar -wsdl=\"https://paypalobjects.com/wsdl/PayPalSvc.wsdl\""); System.out.println( "$ java -jar wsdl2apigee.jar -wsdl=\"https://paypalobjects.com/wsdl/PayPalSvc.wsdl\" -passthru=true"); System.out.println( "$ java -jar wsdl2apigee.jar -wsdl=\"https://paypalobjects.com/wsdl/PayPalSvc.wsdl\" -vhosts=secure"); System.out.println(""); System.out.println("OpsMap:"); System.out.println("A file that maps WSDL operations to HTTP Verbs. A Sample Ops Mapping file looks like:"); System.out.println(""); System.out.println("\t<proxywriter>"); System.out.println("\t\t<get>"); System.out.println("\t\t\t<name location=\"beginsWith\">get</name>"); System.out.println("\t\t\t<name location=\"beginsWith\">list</name>"); System.out.println("\t\t\t<name location=\"beginsWith\">inq</name>"); System.out.println("\t\t\t<name location=\"beginsWith\">search</name>"); System.out.println("\t\t\t<name location=\"beginsWith\">retrieve</name>"); System.out.println("\t\t</get>"); System.out.println("\t\t<post>"); System.out.println("\t\t\t<name location=\"contains\">create</name>"); System.out.println("\t\t\t<name location=\"beginsWith\">add</name>"); System.out.println("\t\t\t<name location=\"beginsWith\">process</name>"); System.out.println("\t\t</post>"); System.out.println("\t\t<put>"); System.out.println("\t\t\t<name location=\"contains\">update</name>"); System.out.println("\t\t\t<name location=\"contains\">change</name>"); System.out.println("\t\t\t<name location=\"beginsWith\">modify</name>"); System.out.println("\t\t\t<name location=\"beginsWith\">set</name>"); System.out.println("\t\t</put>"); System.out.println("\t\t<delete>"); System.out.println("\t\t\t<name location=\"beginsWith\">delete</name>"); System.out.println("\t\t\t<name location=\"beginsWith\">remove</name>"); System.out.println("\t\t\t<name location=\"beginsWith\">del</name>"); System.out.println("\t\t</delete>"); System.out.println("\t</proxywriter>"); } private static List<WsdlDefinitions.Port> convertPorts(List<com.predic8.wsdl.Port> ports, List<PortType> portTypes) { List<WsdlDefinitions.Port> list = new ArrayList<>(ports.size()); for (com.predic8.wsdl.Port port : ports) { list.add(new WsdlDefinitions.Port(port.getName(), convertOperations(port.getBinding(), portTypes))); } return list; } private static List<WsdlDefinitions.Operation> convertOperations(Binding binding, List<PortType> portTypes) { List<WsdlDefinitions.Operation> list = new ArrayList<>(); //TODO: ops map should be passed as a param OpsMap opsMap = null; try { opsMap = new OpsMap(OPSMAPPING_TEMPLATE); } catch (Exception e) { } binding.getOperations(); for (BindingOperation bindingOperation : binding.getOperations()) { final String operationName = bindingOperation.getName(); final WsdlDefinitions.Operation operation = new WsdlDefinitions.Operation(operationName, findDocForOperation(operationName, portTypes), opsMap.getVerb(operationName, null), opsMap.getResourcePath(operationName, null), null); list.add(operation); } return list; } private static String findDocForOperation(String operationName, List<PortType> portTypes) { for (PortType portType : portTypes) { final Operation operation = portType.getOperation(operationName); if (operation != null) { return operation.getDocumentation() != null ? operation.getDocumentation().getContent() : ""; } } return ""; } private static WsdlDefinitions definitionsToWsdlDefinitions(Definitions definitions) { List<WsdlDefinitions.Service> services = new ArrayList<>(); definitions.getServices(); for (Service service : definitions.getServices()) { final WsdlDefinitions.Service service1 = new WsdlDefinitions.Service(service.getName(), convertPorts(service.getPorts(), definitions.getPortTypes())); services.add(service1); } return new WsdlDefinitions(services); } public static void main(String[] args) throws Exception { GenerateProxy genProxy = new GenerateProxy(); String wsdlPath = ""; String proxyDescription = ""; Options opt = new Options(args, 1); // the wsdl param contains the URL or FilePath to a WSDL document opt.getSet().addOption("wsdl", Separator.EQUALS, Multiplicity.ONCE); // if this flag it set, the generate a passthru proxy opt.getSet().addOption("passthru", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); // set this flag to pass proxy description opt.getSet().addOption("desc", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); // set this flag to specify service name opt.getSet().addOption("service", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); // set this flag to specify port name opt.getSet().addOption("port", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); // set this flag to specify operations map opt.getSet().addOption("opsmap", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); // set this flag to handle all operations via post verb opt.getSet().addOption("allpost", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); // set virtual hosts opt.getSet().addOption("vhosts", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); // set build path opt.getSet().addOption("build", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); // add verify oauth policy opt.getSet().addOption("oauth", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); // add verify apikey policy opt.getSet().addOption("apikey", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); // add impose quota policy opt.getSet().addOption("quota", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); // set basepath opt.getSet().addOption("basepath", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); // add enable cors conditions opt.getSet().addOption("cors", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); // set this flag to enable debug opt.getSet().addOption("debug", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); opt.check(); if (opt.getSet().isSet("wsdl")) { // React to option -wsdl wsdlPath = opt.getSet().getOption("wsdl").getResultValue(0); } else { System.out.println("-wsdl is a madatory parameter"); usage(); System.exit(1); } if (opt.getSet().isSet("passthru")) { // React to option -passthru genProxy.setPassThru(Boolean.parseBoolean(opt.getSet().getOption("passthru").getResultValue(0))); if (opt.getSet().isSet("cors")) { LOGGER.warning("WARNING: cors can only be enabled for SOAP to REST. This flag will be ignored."); } if (opt.getSet().isSet("desc")) { // React to option -des proxyDescription = opt.getSet().getOption("desc").getResultValue(0); genProxy.setDesc(true); } else { proxyDescription = "Generated SOAP proxy from "; } } else { genProxy.setPassThru(false); if (opt.getSet().isSet("desc")) { // React to option -des proxyDescription = opt.getSet().getOption("desc").getResultValue(0); genProxy.setDesc(true); } else { proxyDescription = "Generated SOAP to API proxy from "; } } if (opt.getSet().isSet("service")) { // React to option -service genProxy.setService(opt.getSet().getOption("service").getResultValue(0)); if (opt.getSet().isSet("port")) { // React to option -port genProxy.setPort(opt.getSet().getOption("port").getResultValue(0)); } } if (opt.getSet().isSet("opsmap")) { genProxy.setOpsMap(opt.getSet().getOption("opsmap").getResultValue(0)); } else { genProxy.setOpsMap(GenerateProxy.OPSMAPPING_TEMPLATE); } if (opt.getSet().isSet("allpost")) { genProxy.setAllPost(new Boolean(opt.getSet().getOption("allpost").getResultValue(0))); } if (opt.getSet().isSet("vhosts")) { genProxy.setVHost(opt.getSet().getOption("vhosts").getResultValue(0)); } if (opt.getSet().isSet("build")) { genProxy.setBuildFolder(opt.getSet().getOption("build").getResultValue(0)); } if (opt.getSet().isSet("basepath")) { genProxy.setBasePath(opt.getSet().getOption("basepath").getResultValue(0)); } if (opt.getSet().isSet("cors")) { genProxy.setCORS(new Boolean(opt.getSet().getOption("cors").getResultValue(0))); } if (opt.getSet().isSet("oauth")) { genProxy.setOAuth(new Boolean(opt.getSet().getOption("oauth").getResultValue(0))); if (opt.getSet().isSet("quota")) { genProxy.setQuotaOAuth(new Boolean(opt.getSet().getOption("quota").getResultValue(0))); } } if (opt.getSet().isSet("apikey")) { genProxy.setAPIKey(new Boolean(opt.getSet().getOption("apikey").getResultValue(0))); if (opt.getSet().isSet("quota")) { genProxy.setQuotaAPIKey(new Boolean(opt.getSet().getOption("quota").getResultValue(0))); } } if (!opt.getSet().isSet("apikey") && !opt.getSet().isSet("oauth") && opt.getSet().isSet("quota")) { LOGGER.warning("WARNING: Quota is applicable with apikey or oauth flags. This flag will be ignored"); } if (opt.getSet().isSet("debug")) { // enable debug LOGGER.setLevel(Level.FINEST); handler.setLevel(Level.FINEST); } else { LOGGER.setLevel(Level.INFO); handler.setLevel(Level.INFO); } final InputStream begin = genProxy.begin(proxyDescription, wsdlPath); if (begin != null) { Files.copy(begin, new File(genProxy.proxyName + ".zip").toPath(), StandardCopyOption.REPLACE_EXISTING); } } public static InputStream generateProxy(GenerateProxyOptions generateProxyOptions) throws Exception { GenerateProxy genProxy = new GenerateProxy(); genProxy.setOpsMap(OPSMAPPING_TEMPLATE); genProxy.setPassThru(generateProxyOptions.isPassthrough()); genProxy.setBasePath(generateProxyOptions.getBasepath()); genProxy.setVHost(generateProxyOptions.getvHosts()); genProxy.setPort(generateProxyOptions.getPort()); genProxy.setCORS(generateProxyOptions.isCors()); genProxy.setAPIKey(generateProxyOptions.isApiKey()); genProxy.setOAuth(generateProxyOptions.isOauth()); genProxy.setQuotaAPIKey(generateProxyOptions.isApiKey() && generateProxyOptions.isQuota()); genProxy.setQuotaOAuth(generateProxyOptions.isOauth() && generateProxyOptions.isQuota()); if (generateProxyOptions.getOperationsFilter() != null && generateProxyOptions.getOperationsFilter().length() > 0) { genProxy.setSelectedOperationsJson(generateProxyOptions.getOperationsFilter()); } return genProxy.begin(generateProxyOptions.getDescription() != null ? generateProxyOptions.getDescription() : "Generated SOAP to API proxy", generateProxyOptions.getWsdl()); } public static WsdlDefinitions parseWsdl(String wsdl) throws ErrorParsingWsdlException { final WSDLParser wsdlParser = new WSDLParser(); try { final Definitions definitions = wsdlParser.parse(wsdl); return definitionsToWsdlDefinitions(definitions); } catch (com.predic8.xml.util.ResourceDownloadException e) { String message = formatResourceError(e); throw new ErrorParsingWsdlException(message, e); } catch (Throwable t) { String message = t.getLocalizedMessage(); if (message == null) { message = t.getMessage(); } if (message == null) { message = "Error processing WSDL."; } throw new ErrorParsingWsdlException(message, t); } } private static String formatResourceError(com.predic8.xml.util.ResourceDownloadException e) { StringBuffer errorMessage = new StringBuffer("Could not download resource."); String rootCause = e.getRootCause().getLocalizedMessage(); if (!rootCause.isEmpty()) { int pos = rootCause.indexOf("status for class:"); if (pos == -1) { errorMessage.append(" " + rootCause + "."); } } return (errorMessage.toString()); } }
package com.ecyrd.jspwiki.filters; import java.io.*; import java.util.*; import javax.servlet.http.HttpServletRequest; import net.sf.akismet.Akismet; import org.apache.commons.jrcs.diff.*; import org.apache.commons.jrcs.diff.myers.MyersDiff; import org.apache.commons.lang.time.StopWatch; import org.apache.log4j.Logger; import org.apache.oro.text.regex.*; import com.ecyrd.jspwiki.*; import com.ecyrd.jspwiki.attachment.Attachment; import com.ecyrd.jspwiki.providers.ProviderException; /** * This is Herb, the JSPWiki spamfilter that can also do choke modifications. * * Parameters: * <ul> * <li>wordlist - Page name where the regexps are found. Use [{SET spamwords='regexp list separated with spaces'}] on * that page. Default is "SpamFilterWordList". * <li>blacklist - The name of an attachment containing the list of spam patterns, one per line. Default is * "SpamFilterWordList/blacklist.txt"</li> * <li>errorpage - The page to which the user is redirected. Has a special variable $msg which states the reason. Default is "RejectedMessage". * <li>pagechangesinminute - How many page changes are allowed/minute. Default is 5.</li> * <li>similarchanges - How many similar page changes are allowed before the host is banned. Default is 2. (since 2.4.72)</li> * <li>bantime - How long an IP address stays on the temporary ban list (default is 60 for 60 minutes).</li> * <li>maxurls - How many URLs can be added to the page before it is considered spam (default is 5)</li> * </ul> * * <p>Changes by admin users are ignored.</p> * * @since 2.1.112 * @author Janne Jalkanen */ public class SpamFilter extends BasicPageFilter { private String URL_REGEXP = "(http://|https://|mailto:)([A-Za-z0-9_/\\.\\+\\?\\ private String m_forbiddenWordsPage = "SpamFilterWordList"; private String m_errorPage = "RejectedMessage"; private String m_blacklist = "SpamFilterWordList/blacklist.txt"; private static final String LISTVAR = "spamwords"; private PatternMatcher m_matcher = new Perl5Matcher(); private PatternCompiler m_compiler = new Perl5Compiler(); private Collection m_spamPatterns = null; private Date m_lastRebuild = new Date( 0L ); static Logger log = Logger.getLogger( SpamFilter.class ); public static final String PROP_WORDLIST = "wordlist"; public static final String PROP_ERRORPAGE = "errorpage"; public static final String PROP_PAGECHANGES = "pagechangesinminute"; public static final String PROP_SIMILARCHANGES = "similarchanges"; public static final String PROP_BANTIME = "bantime"; public static final String PROP_BLACKLIST = "blacklist"; public static final String PROP_MAXURLS = "maxurls"; public static final String PROP_AKISMET_API_KEY = "akismet-apikey"; private Vector m_temporaryBanList = new Vector(); private int m_banTime = 60; // minutes private Vector m_lastModifications = new Vector(); /** * How many times a single IP address can change a page per minute? */ private int m_limitSinglePageChanges = 5; private int m_limitSimilarChanges = 2; /** * How many URLs can be added at maximum. */ private int m_maxUrls = 5; private Pattern m_UrlPattern; private Akismet m_akismet; private String m_akismetAPIKey = null; public void initialize( Properties properties ) { m_forbiddenWordsPage = properties.getProperty( PROP_WORDLIST, m_forbiddenWordsPage ); m_errorPage = properties.getProperty( PROP_ERRORPAGE, m_errorPage ); m_limitSinglePageChanges = TextUtil.getIntegerProperty( properties, PROP_PAGECHANGES, m_limitSinglePageChanges ); m_limitSimilarChanges = TextUtil.getIntegerProperty( properties, PROP_SIMILARCHANGES, m_limitSimilarChanges ); m_maxUrls = TextUtil.getIntegerProperty( properties, PROP_MAXURLS, m_maxUrls ); m_banTime = TextUtil.getIntegerProperty( properties, PROP_BANTIME, m_banTime ); m_blacklist = properties.getProperty( PROP_BLACKLIST, m_blacklist ); try { m_UrlPattern = m_compiler.compile( URL_REGEXP ); } catch( MalformedPatternException e ) { log.fatal("Internal error: Someone put in a faulty pattern.",e); throw new InternalWikiException("Faulty pattern."); } m_akismetAPIKey = TextUtil.getStringProperty( properties, PROP_AKISMET_API_KEY, m_akismetAPIKey ); log.info("Spam filter initialized. Temporary ban time "+m_banTime+ " mins, max page changes/minute: "+m_limitSinglePageChanges ); } /** * Parses a list of patterns and returns a Collection of compiled Pattern * objects. * * @param source * @param list * @return */ private Collection parseWordList( WikiPage source, String list ) { ArrayList compiledpatterns = new ArrayList(); if( list != null ) { StringTokenizer tok = new StringTokenizer( list, " \t\n" ); while( tok.hasMoreTokens() ) { String pattern = tok.nextToken(); try { compiledpatterns.add( m_compiler.compile( pattern ) ); } catch( MalformedPatternException e ) { log.debug( "Malformed spam filter pattern "+pattern ); source.setAttribute("error", "Malformed spam filter pattern "+pattern); } } } return compiledpatterns; } /** * Takes a MT-Blacklist -formatted blacklist and returns a list of compiled * Pattern objects. * * @param list * @return */ private Collection parseBlacklist( String list ) { ArrayList compiledpatterns = new ArrayList(); if( list != null ) { try { BufferedReader in = new BufferedReader( new StringReader(list) ); String line; while( (line = in.readLine()) != null ) { line = line.trim(); if( line.length() == 0 ) continue; // Empty line if( line.startsWith("#") ) continue; // It's a comment int ws = line.indexOf(' '); if( ws == -1 ) ws = line.indexOf('\t'); if( ws != -1 ) line = line.substring(0,ws); try { compiledpatterns.add( m_compiler.compile( line ) ); } catch( MalformedPatternException e ) { log.debug( "Malformed spam filter pattern "+line ); } } } catch( IOException e ) { log.info("Could not read patterns; returning what I got",e); } } return compiledpatterns; } /** * Takes a single page change and performs a load of tests on the content change. * An admin can modify anything. * * @param context * @param content * @throws RedirectException */ private synchronized void checkSinglePageChange( WikiContext context, String content ) throws RedirectException { HttpServletRequest req = context.getHttpRequest(); if( context.hasAdminPermissions() ) { return; } if( req != null ) { String addr = req.getRemoteAddr(); int hostCounter = 0; int changeCounter = 0; String change = getChange( context, content ); log.debug("Change is"+change); long time = System.currentTimeMillis()-60*1000L; // 1 minute for( Iterator i = m_lastModifications.iterator(); i.hasNext(); ) { Host host = (Host)i.next(); // Check if this item is invalid if( host.getAddedTime() < time ) { log.debug("Removed host "+host.getAddress()+" from modification queue (expired)"); i.remove(); continue; } // Check if this IP address has been seen before if( host.getAddress().equals(addr) ) { hostCounter++; } // Check, if this change has been seen before if( host.getChange() != null && host.getChange().equals(change) ) { changeCounter++; } } // Now, let's check against the limits. if( hostCounter >= m_limitSinglePageChanges ) { Host host = new Host( addr, null ); m_temporaryBanList.add( host ); log.info("SPAM:TooManyModifications. Added host "+addr+" to temporary ban list for doing too many modifications/minute" ); throw new RedirectException( "Herb says you look like a spammer, and I trust Herb!", context.getViewURL( m_errorPage ) ); } if( changeCounter >= m_limitSimilarChanges ) { Host host = new Host( addr, null ); m_temporaryBanList.add( host ); log.info("SPAM:SimilarModifications. Added host "+addr+" to temporary ban list for doing too many similar modifications" ); throw new RedirectException( "Herb says you look like a spammer, and I trust Herb!", context.getViewURL( m_errorPage ) ); } // Calculate the number of links in the addition. String tstChange = change; int urlCounter = 0; while( m_matcher.contains(tstChange,m_UrlPattern) ) { MatchResult m = m_matcher.getMatch(); tstChange = tstChange.substring( m.end(0) ); urlCounter++; } if( urlCounter > m_maxUrls ) { Host host = new Host( addr, null ); m_temporaryBanList.add( host ); log.info("SPAM:TooManyUrls. Added host "+addr+" to temporary ban list for adding too many URLs" ); throw new RedirectException( "Herb says you look like a spammer, and I trust Herb!", context.getViewURL( m_errorPage ) ); } // Do Akismet check checkAkismet( context, change ); m_lastModifications.add( new Host( addr, change ) ); } } /** * Checks against the akismet system. * * @param context * @param change * @throws RedirectException */ private void checkAkismet( WikiContext context, String change ) throws RedirectException { if( m_akismetAPIKey != null ) { if( m_akismet == null ) { log.info("Initializing Akismet spam protection."); m_akismet = new Akismet( m_akismetAPIKey, context.getEngine().getBaseURL() ); if( !m_akismet.verifyAPIKey() ) { log.error("Akismet API key cannot be verified. Please check your config."); m_akismetAPIKey = null; m_akismet = null; } } HttpServletRequest req = context.getHttpRequest(); if( req != null && m_akismet != null ) { log.debug("Calling Akismet to check for spam..."); StopWatch sw = new StopWatch(); sw.start(); String ipAddress = req.getRemoteAddr(); String userAgent = req.getHeader("User-Agent"); String referrer = req.getHeader( "Referer"); String permalink = context.getViewURL( context.getPage().getName() ); String commentType = (context.getRequestContext().equals(WikiContext.COMMENT) ? "comment" : "edit" ); String commentAuthor = context.getCurrentUser().getName(); String commentAuthorEmail = null; String commentAuthorURL = null; boolean isSpam = m_akismet.commentCheck( ipAddress, userAgent, referrer, permalink, commentType, commentAuthor, commentAuthorEmail, commentAuthorURL, change, null ); sw.stop(); log.debug("Akismet request done in: "+sw); if( isSpam ) { Host host = new Host( ipAddress, null ); m_temporaryBanList.add( host ); log.info("SPAM:Akismet. Akismet thinks this change is spam; added host to temporary ban list."); throw new RedirectException("Akismet tells Herb you're a spammer, Herb trusts Akismet, and I trust Herb!", context.getViewURL( m_errorPage ) ); } } } } /** * Goes through the ban list and cleans away any host which has expired from it. */ private synchronized void cleanBanList() { long now = System.currentTimeMillis(); for( Iterator i = m_temporaryBanList.iterator(); i.hasNext(); ) { Host host = (Host)i.next(); if( host.getReleaseTime() < now ) { log.debug("Removed host "+host.getAddress()+" from temporary ban list (expired)"); i.remove(); } } } /** * Checks the ban list if the IP address of the changer is already on it. * * @param context * @throws RedirectException */ private void checkBanList( WikiContext context ) throws RedirectException { HttpServletRequest req = context.getHttpRequest(); if( req != null ) { String remote = req.getRemoteAddr(); long now = System.currentTimeMillis(); for( Iterator i = m_temporaryBanList.iterator(); i.hasNext(); ) { Host host = (Host)i.next(); if( host.getAddress().equals(remote) ) { long timeleft = (host.getReleaseTime() - now) / 1000L; throw new RedirectException( "You have been temporarily banned from modifying this wiki. ("+timeleft+" seconds of ban left)", context.getViewURL( m_errorPage ) ); } } } } /** * If the spam filter notices changes in the black list page, it will refresh * them automatically. * * @param context */ private void refreshBlacklists( WikiContext context ) { try { WikiPage source = context.getEngine().getPage( m_forbiddenWordsPage ); Attachment att = context.getEngine().getAttachmentManager().getAttachmentInfo( context, m_blacklist ); boolean rebuild = false; // Rebuild, if the page or the attachment has changed since. if( source != null ) { if( m_spamPatterns == null || m_spamPatterns.isEmpty() || source.getLastModified().after(m_lastRebuild) ) { rebuild = true; } } if( att != null ) { if( m_spamPatterns == null || m_spamPatterns.isEmpty() || att.getLastModified().after(m_lastRebuild) ) { rebuild = true; } } // Do the actual rebuilding. For simplicity's sake, we always rebuild the complete // filter list regardless of what changed. if( rebuild ) { m_lastRebuild = new Date(); m_spamPatterns = parseWordList( source, (String)source.getAttribute( LISTVAR ) ); log.info("Spam filter reloaded - recognizing "+m_spamPatterns.size()+" patterns from page "+m_forbiddenWordsPage); if( att != null ) { InputStream in = context.getEngine().getAttachmentManager().getAttachmentStream(att); StringWriter out = new StringWriter(); FileUtil.copyContents( new InputStreamReader(in,"UTF-8"), out ); Collection blackList = parseBlacklist( out.toString() ); log.info("...recognizing additional "+blackList.size()+" patterns from blacklist "+m_blacklist); m_spamPatterns.addAll( blackList ); } } } catch( IOException ex ) { log.info("Unable to read attachment data, continuing...",ex); } catch( ProviderException ex ) { log.info("Failed to read spam filter attachment, continuing...",ex); } } public String preSave( WikiContext context, String content ) throws RedirectException { cleanBanList(); checkBanList( context ); checkSinglePageChange( context, content ); refreshBlacklists(context); String changeNote = (String)context.getPage().getAttribute( WikiPage.CHANGENOTE ); // If we have no spam patterns defined, or we're trying to save // the page containing the patterns, just return. if( m_spamPatterns == null || context.getPage().getName().equals( m_forbiddenWordsPage ) ) { return content; } for( Iterator i = m_spamPatterns.iterator(); i.hasNext(); ) { Pattern p = (Pattern) i.next(); log.debug("Attempting to match page contents with "+p.getPattern()); if( m_matcher.contains( content, p ) ) { // Spam filter has a match. log.info("SPAM:Regexp. Content matches the spam filter '"+p.getPattern()+"'"); throw new RedirectException( "Herb says '"+p.getPattern()+"' is a bad spam word and I trust Herb!", context.getURL(WikiContext.VIEW,m_errorPage) ); } if( changeNote != null && m_matcher.contains( changeNote, p ) ) { log.info("SPAM:Regexp. Content matches the spam filter '"+p.getPattern()+"'"); throw new RedirectException( "Herb says '"+p.getPattern()+"' is a bad spam word and I trust Herb!", context.getURL(WikiContext.VIEW,m_errorPage) ); } } return content; } /** * Creates a simple text string describing the added content. * * @param context * @param newText */ private String getChange( WikiContext context, String newText ) { StringBuffer change = new StringBuffer(); WikiEngine engine = context.getEngine(); // Get current page version try { String oldText = engine.getPureText(context.getPage().getName(), WikiProvider.LATEST_VERSION); String[] first = Diff.stringToArray(oldText); String[] second = Diff.stringToArray(newText); Revision rev = Diff.diff(first, second, new MyersDiff()); if( rev == null || rev.size() == 0 ) { return null; } for( int i = 0; i < rev.size(); i++ ) { Delta d = rev.getDelta(i); if( d instanceof AddDelta ) { change.append( d.getRevised().toString() ); } } } catch (DifferentiationFailedException e) { log.error( "Diff failed", e ); } return change.toString(); } /** * A local class for storing host information. * * @author jalkanen * * @since */ private class Host { private long m_addedTime = System.currentTimeMillis(); private long m_releaseTime; private String m_address; private String m_change; public String getAddress() { return m_address; } public long getReleaseTime() { return m_releaseTime; } public long getAddedTime() { return m_addedTime; } public String getChange() { return m_change; } public Host( String ipaddress, String change ) { m_address = ipaddress; m_change = change; m_releaseTime = System.currentTimeMillis() + m_banTime * 60 * 1000L; } } }
package com.fedorvlasov.lazylist; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import android.graphics.Bitmap; import android.util.Log; public class MemoryCache { private static final String TAG = "MemoryCache"; private Map<String, Bitmap> cache=Collections.synchronizedMap( new LinkedHashMap<String, Bitmap>(10,1.5f,true));//Last argument true for LRU ordering private long size=0;//current allocated size private long limit=1000000;//max memory in bytes public MemoryCache(){ //use 25% of available heap size setLimit(Runtime.getRuntime().maxMemory()/4); } public void setLimit(long new_limit){ limit=new_limit; Log.i(TAG, "MemoryCache will use up to "+limit/1024./1024.+"MB"); } public Bitmap get(String id){ if(!cache.containsKey(id)) return null; return cache.get(id); } public void put(String id, Bitmap bitmap){ try{ if(cache.containsKey(id)) size-=getSizeInBytes(cache.get(id)); cache.put(id, bitmap); size+=getSizeInBytes(bitmap); checkSize(); }catch(Throwable th){ th.printStackTrace(); } } private void checkSize() { Log.i(TAG, "cache size="+size+" length="+cache.size()); if(size>limit){ Iterator<Entry<String, Bitmap>> iter=cache.entrySet().iterator();//least recently accessed item will be the first one iterated while(iter.hasNext()){ Entry<String, Bitmap> entry=iter.next(); size-=getSizeInBytes(entry.getValue()); iter.remove(); if(size<=limit) break; } Log.i(TAG, "Clean cache. New size "+cache.size()); } } public void clear() { cache.clear(); } long getSizeInBytes(Bitmap bitmap) { if(bitmap==null) return 0; return bitmap.getRowBytes() * bitmap.getHeight(); } }
package com.github.triplesolitaire; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.Random; import java.util.Stack; import java.util.StringTokenizer; import android.os.Bundle; import android.util.Log; import com.github.triplesolitaire.TripleSolitaireActivity.AutoPlayPreference; public class GameState { private class GameTimerIncrement implements Runnable { @Override public void run() { timeInSeconds++; activity.updateTime(timeInSeconds); if (gameInProgress) activity.findViewById(R.id.base).postDelayed( new GameTimerIncrement(), 1000); } } /** * Logging tag */ private static final String TAG = "TripleSolitaireActivity"; private final TripleSolitaireActivity activity; private boolean[] autoplayLaneIndexLocked = new boolean[13]; private String[] foundation; private long gameId = 0; private boolean gameInProgress = false; private LaneData[] lane; private int moveCount = 0; private Stack<String> stock; private int timeInSeconds = 0; private LinkedList<String> waste; public GameState(final TripleSolitaireActivity activity) { this.activity = activity; } public boolean acceptCascadeDrop(final int laneIndex, final String topNewCard) { final String cascadeCard = lane[laneIndex].getCascade().getLast(); final String cascadeSuit = getSuit(cascadeCard); final int cascadeNum = getNumber(cascadeCard); final String topNewCardSuit = getSuit(topNewCard); final int topNewCardNum = getNumber(topNewCard); boolean acceptDrop = false; if (topNewCardNum != cascadeNum - 1) acceptDrop = false; else if (cascadeSuit.equals("clubs") && topNewCardSuit.equals("diamonds")) acceptDrop = true; else if (cascadeSuit.equals("clubs") && topNewCardSuit.equals("hearts")) acceptDrop = true; else if (cascadeSuit.equals("clubs") && topNewCardSuit.equals("spades")) acceptDrop = false; else if (cascadeSuit.equals("diamonds") && topNewCardSuit.equals("clubs")) acceptDrop = true; else if (cascadeSuit.equals("diamonds") && topNewCardSuit.equals("hearts")) acceptDrop = false; else if (cascadeSuit.equals("diamonds") && topNewCardSuit.equals("spades")) acceptDrop = true; else if (cascadeSuit.equals("hearts") && topNewCardSuit.equals("clubs")) acceptDrop = true; else if (cascadeSuit.equals("hearts") && topNewCardSuit.equals("diamonds")) acceptDrop = false; else if (cascadeSuit.equals("hearts") && topNewCardSuit.equals("spades")) acceptDrop = true; else if (cascadeSuit.equals("spades") && topNewCardSuit.equals("clubs")) acceptDrop = false; else if (cascadeSuit.equals("spades") && topNewCardSuit.equals("diamonds")) acceptDrop = true; else if (cascadeSuit.equals("spades") && topNewCardSuit.equals("hearts")) acceptDrop = true; else // same suit acceptDrop = false; if (acceptDrop) Log.d(TAG, "Drag -> " + (laneIndex + 1) + ": Acceptable drag of " + topNewCard + " onto " + cascadeCard); return acceptDrop; } public boolean acceptFoundationDrop(final int foundationIndex, final String newCard) { if (newCard.startsWith("MULTI")) // Foundations don't accept multiple cards return false; final String existingFoundationCard = foundation[foundationIndex]; boolean acceptDrop = false; if (existingFoundationCard == null) acceptDrop = newCard.endsWith("s1"); else acceptDrop = newCard.equals(nextInSuit(existingFoundationCard)); if (acceptDrop) { final String foundationDisplayCard = existingFoundationCard == null ? "empty foundation" : existingFoundationCard; Log.d(TAG, "Drag -> " + -1 * (foundationIndex + 1) + ": Acceptable drag of " + newCard + " onto " + foundationDisplayCard); } return acceptDrop; } public boolean acceptLaneDrop(final int laneIndex, final String topNewCard) { final boolean acceptDrop = topNewCard.endsWith("s13"); if (acceptDrop) Log.d(TAG, "Drag -> " + (laneIndex + 1) + ": Acceptable drag of " + topNewCard + " onto empty lane"); return acceptDrop; } public boolean attemptAutoMoveFromCascadeToFoundation(final int laneIndex) { if (lane[laneIndex].getCascade().isEmpty()) return false; final String card = lane[laneIndex].getCascade().getLast(); for (int foundationIndex = 0; foundationIndex < 12; foundationIndex++) if (acceptFoundationDrop(foundationIndex, card)) { Log.d(TAG, "Auto Move " + (laneIndex + 1) + " -> " + -1 * (foundationIndex + 1) + ": " + card); dropFromCascadeToFoundation(foundationIndex, laneIndex); return true; } return false; } public boolean attemptAutoMoveFromWasteToFoundation() { if (waste.isEmpty()) return false; final String card = waste.getFirst(); for (int foundationIndex = 0; foundationIndex < 12; foundationIndex++) if (acceptFoundationDrop(foundationIndex, card)) { Log.d(TAG, "Auto Move W -> " + -1 * (foundationIndex + 1) + ": " + card); dropFromWasteToFoundation(foundationIndex); return true; } return false; } private void autoPlay() { final AutoPlayPreference autoPlayPreference = activity .getAutoPlayPreference(); if (autoPlayPreference == AutoPlayPreference.AUTOPLAY_NEVER) return; else if (autoPlayPreference == AutoPlayPreference.AUTOPLAY_WHEN_WON) { int totalStackSize = 0; for (int laneIndex = 0; laneIndex < 13; laneIndex++) totalStackSize += lane[laneIndex].getStack().size(); if (totalStackSize > 0 || !stock.isEmpty() || waste.size() > 1) return; } boolean foundAutoPlay; do { foundAutoPlay = false; for (int laneIndex = 0; laneIndex < 13; laneIndex++) if (!autoplayLaneIndexLocked[laneIndex] && attemptAutoMoveFromCascadeToFoundation(laneIndex)) { foundAutoPlay = true; break; } } while (foundAutoPlay); do { } while (attemptAutoMoveFromWasteToFoundation()); } public String buildCascadeString(final int laneIndex, final int numCardsToInclude) { final LinkedList<String> cascade = lane[laneIndex].getCascade(); final StringBuilder cascadeData = new StringBuilder(cascade.get(cascade .size() - numCardsToInclude)); for (int cascadeIndex = cascade.size() - numCardsToInclude + 1; cascadeIndex < cascade .size(); cascadeIndex++) { cascadeData.append(";"); cascadeData.append(cascade.get(cascadeIndex)); } return cascadeData.toString(); } private void checkForWin() { for (int foundationIndex = 0; foundationIndex < 12; foundationIndex++) if (!foundation[foundationIndex].endsWith("s13")) return; Log.d(TAG, "Game win detected"); pauseGame(); activity.showDialog(TripleSolitaireActivity.DIALOG_ID_WINNING); } public void clickStock() { if (stock.isEmpty() && waste.isEmpty()) return; Log.d(TAG, "Clicked Stock"); if (stock.isEmpty()) { stock.addAll(waste); waste.clear(); } else for (int wasteIndex = 0; wasteIndex < 3 && !stock.isEmpty(); wasteIndex++) waste.addFirst(stock.pop()); activity.updateStockUI(); activity.updateWasteUI(); incrementMoveCount(true); } public void dropFromCascadeToCascade(final int laneIndex, final int from, final String card) { Log.d(TAG, "Drop " + (from + 1) + " -> " + (laneIndex + 1) + ": " + card); final ArrayList<String> cascadeToAdd = new ArrayList<String>(); final StringTokenizer st = new StringTokenizer(card, ";"); while (st.hasMoreTokens()) cascadeToAdd.add(st.nextToken()); for (int cascadeIndex = 0; cascadeIndex < cascadeToAdd.size(); cascadeIndex++) lane[from].getCascade().removeLast(); final Lane fromLaneLayout = activity.getLane(from); fromLaneLayout.decrementCascadeSize(cascadeToAdd.size()); lane[laneIndex].getCascade().addAll(cascadeToAdd); final Lane laneLayout = activity.getLane(laneIndex); laneLayout.addCascade(cascadeToAdd); incrementMoveCount(true); } public void dropFromCascadeToFoundation(final int foundationIndex, final int from) { final String cascadeCard = lane[from].getCascade().removeLast(); Log.d(TAG, "Drop " + (from + 1) + " -> " + -1 * (foundationIndex + 1) + ": " + cascadeCard); foundation[foundationIndex] = cascadeCard; activity.updateFoundationUI(foundationIndex); activity.getLane(from).decrementCascadeSize(1); incrementMoveCount(true); checkForWin(); } public void dropFromFoundationToCascade(final int laneIndex, final int foundationIndex) { final String foundationCard = foundation[foundationIndex]; Log.d(TAG, "Drop " + -1 * (foundationIndex + 1) + " -> " + (laneIndex + 1) + ": " + foundationCard); foundation[foundationIndex] = prevInSuit(foundationCard); activity.updateFoundationUI(foundationIndex); lane[laneIndex].getCascade().add(foundationCard); final Lane laneLayout = activity.getLane(laneIndex); final ArrayList<String> cascadeToAdd = new ArrayList<String>(); cascadeToAdd.add(foundationCard); laneLayout.addCascade(cascadeToAdd); autoplayLaneIndexLocked[laneIndex] = true; incrementMoveCount(false); } public void dropFromFoundationToFoundation(final int foundationIndex, final int from) { final String foundationCard = foundation[from]; Log.d(TAG, "Drop " + -1 * (from + 1) + " -> " + -1 * (foundationIndex + 1) + ": " + foundationCard); foundation[foundationIndex] = foundationCard; foundation[from] = prevInSuit(foundationCard); activity.updateFoundationUI(foundationIndex); activity.updateFoundationUI(from); incrementMoveCount(true); } public void dropFromWasteToCascade(final int laneIndex) { final String card = waste.removeFirst(); Log.d(TAG, "Drop " + "W -> " + (laneIndex + 1) + ": " + card); activity.updateWasteUI(); lane[laneIndex].getCascade().add(card); final Lane laneLayout = activity.getLane(laneIndex); final ArrayList<String> cascadeToAdd = new ArrayList<String>(); cascadeToAdd.add(card); laneLayout.addCascade(cascadeToAdd); incrementMoveCount(true); } public void dropFromWasteToFoundation(final int foundationIndex) { final String card = waste.removeFirst(); Log.d(TAG, "Drop " + "W -> " + -1 * (foundationIndex + 1) + ": " + card); foundation[foundationIndex] = card; activity.updateFoundationUI(foundationIndex); activity.updateWasteUI(); incrementMoveCount(true); checkForWin(); } public void flipCard(final int laneIndex) { final String card = lane[laneIndex].getStack().pop(); Log.d(TAG, "Flip " + (laneIndex + 1) + ": " + card); lane[laneIndex].getCascade().add(card); activity.getLane(laneIndex).flipOverTopStack(card); autoPlay(); } public String getFoundationCard(final int foundationIndex) { return foundation[foundationIndex]; } public long getGameId() { return gameId; } private int getNumber(final String card) { int firstNumber; for (firstNumber = 0; firstNumber < card.length(); firstNumber++) if (Character.isDigit(card.charAt(firstNumber))) break; return Integer.parseInt(card.substring(firstNumber)); } private String getSuit(final String card) { int firstNumber; for (firstNumber = 0; firstNumber < card.length(); firstNumber++) if (Character.isDigit(card.charAt(firstNumber))) break; return card.substring(0, firstNumber); } public String getWasteCard(final int wasteIndex) { if (wasteIndex < waste.size()) return waste.get(wasteIndex); return null; } private void incrementMoveCount(final boolean resetAutoplayLaneIndexLocked) { activity.updateMoveCount(++moveCount); if (moveCount == 1) { gameInProgress = true; activity.findViewById(R.id.base).postDelayed( new GameTimerIncrement(), 1000); } if (resetAutoplayLaneIndexLocked) for (int laneIndex = 0; laneIndex < 13; laneIndex++) autoplayLaneIndexLocked[laneIndex] = false; autoPlay(); } public boolean isStockEmpty() { return stock.isEmpty(); } public boolean isWasteEmpty() { return waste.isEmpty(); } public void newGame() { final ArrayList<String> fullDeck = new ArrayList<String>(); for (int deckNum = 0; deckNum < 3; deckNum++) { fullDeck.add("clubs1"); fullDeck.add("clubs2"); fullDeck.add("clubs3"); fullDeck.add("clubs4"); fullDeck.add("clubs5"); fullDeck.add("clubs6"); fullDeck.add("clubs7"); fullDeck.add("clubs8"); fullDeck.add("clubs9"); fullDeck.add("clubs10"); fullDeck.add("clubs11"); fullDeck.add("clubs12"); fullDeck.add("clubs13"); fullDeck.add("diamonds1"); fullDeck.add("diamonds2"); fullDeck.add("diamonds3"); fullDeck.add("diamonds4"); fullDeck.add("diamonds5"); fullDeck.add("diamonds6"); fullDeck.add("diamonds7"); fullDeck.add("diamonds8"); fullDeck.add("diamonds9"); fullDeck.add("diamonds10"); fullDeck.add("diamonds11"); fullDeck.add("diamonds12"); fullDeck.add("diamonds13"); fullDeck.add("hearts1"); fullDeck.add("hearts2"); fullDeck.add("hearts3"); fullDeck.add("hearts4"); fullDeck.add("hearts5"); fullDeck.add("hearts6"); fullDeck.add("hearts7"); fullDeck.add("hearts8"); fullDeck.add("hearts9"); fullDeck.add("hearts10"); fullDeck.add("hearts11"); fullDeck.add("hearts12"); fullDeck.add("hearts13"); fullDeck.add("spades1"); fullDeck.add("spades2"); fullDeck.add("spades3"); fullDeck.add("spades4"); fullDeck.add("spades5"); fullDeck.add("spades6"); fullDeck.add("spades7"); fullDeck.add("spades8"); fullDeck.add("spades9"); fullDeck.add("spades10"); fullDeck.add("spades11"); fullDeck.add("spades12"); fullDeck.add("spades13"); } final Random random = new Random(); gameId = random.nextLong(); random.setSeed(gameId); timeInSeconds = 0; activity.updateTime(timeInSeconds); moveCount = 0; activity.updateMoveCount(moveCount); for (int h = 0; h < 13; h++) autoplayLaneIndexLocked[h] = false; Collections.shuffle(fullDeck, random); int currentIndex = 0; stock = new Stack<String>(); for (int stockIndex = 0; stockIndex < 65; stockIndex++) stock.push(fullDeck.get(currentIndex++)); activity.updateStockUI(); waste = new LinkedList<String>(); activity.updateWasteUI(); foundation = new String[12]; for (int foundationIndex = 0; foundationIndex < 12; foundationIndex++) activity.updateFoundationUI(foundationIndex); lane = new LaneData[13]; for (int laneIndex = 0; laneIndex < 13; laneIndex++) { lane[laneIndex] = new LaneData(); for (int i = 0; i < laneIndex; i++) lane[laneIndex].getStack().push(fullDeck.get(currentIndex++)); lane[laneIndex].getCascade().add(fullDeck.get(currentIndex++)); final Lane laneLayout = activity.getLane(laneIndex); laneLayout.setStackSize(lane[laneIndex].getStack().size()); laneLayout.addCascade(lane[laneIndex].getCascade()); } Log.d(TAG, "Game Started: " + gameId); } private String nextInSuit(final String card) { return getSuit(card) + (getNumber(card) + 1); } public void onRestoreInstanceState(final Bundle savedInstanceState) { // Restore the current game information gameId = savedInstanceState.getLong("gameId"); timeInSeconds = savedInstanceState.getInt("timeInSeconds"); activity.updateTime(timeInSeconds); moveCount = savedInstanceState.getInt("moveCount"); activity.updateMoveCount(moveCount); autoplayLaneIndexLocked = savedInstanceState .getBooleanArray("autoplayLaneIndexLocked"); // Restore the stack final ArrayList<String> arrayCardStock = savedInstanceState .getStringArrayList("stock"); stock = new Stack<String>(); for (final String card : arrayCardStock) stock.push(card); activity.updateStockUI(); // Restore the waste data waste = new LinkedList<String>( savedInstanceState.getStringArrayList("waste")); activity.updateWasteUI(); // Restore the foundation data foundation = savedInstanceState.getStringArray("foundation"); for (int foundationIndex = 0; foundationIndex < 12; foundationIndex++) activity.updateFoundationUI(foundationIndex); lane = new LaneData[13]; for (int laneIndex = 0; laneIndex < 13; laneIndex++) { lane[laneIndex] = new LaneData( savedInstanceState.getStringArrayList("laneStack" + laneIndex), savedInstanceState.getStringArrayList("laneCascade" + laneIndex)); final Lane laneLayout = activity.getLane(laneIndex); laneLayout.setStackSize(lane[laneIndex].getStack().size()); laneLayout.addCascade(lane[laneIndex].getCascade()); } } public void onSaveInstanceState(final Bundle outState) { outState.putLong("gameId", gameId); outState.putInt("timeInSeconds", timeInSeconds); outState.putInt("moveCount", moveCount); outState.putBooleanArray("autoplayLaneIndexLocked", autoplayLaneIndexLocked); outState.putStringArrayList("stock", new ArrayList<String>(stock)); outState.putStringArrayList("waste", new ArrayList<String>(waste)); outState.putStringArray("foundation", foundation); for (int laneIndex = 0; laneIndex < 13; laneIndex++) { outState.putStringArrayList("laneStack" + laneIndex, new ArrayList<String>(lane[laneIndex].getStack())); outState.putStringArrayList("laneCascade" + laneIndex, new ArrayList<String>(lane[laneIndex].getCascade())); } } public void pauseGame() { gameInProgress = false; } private String prevInSuit(final String card) { if (card.endsWith("s1")) return null; return getSuit(card) + (getNumber(card) - 1); } public void resumeGame() { gameInProgress = moveCount > 0; if (gameInProgress) activity.findViewById(R.id.base).postDelayed( new GameTimerIncrement(), 1000); } }
package com.interview.recursion; public class OneEditApart { public boolean matchRecurisve(char[] str1, char[] str2){ return match(str1,str2,0,0,true); } private boolean match(char[] str1, char[] str2, int pos1,int pos2, boolean areSame){ if(pos1 == str1.length && pos2 == str2.length){ return true; } if(areSame){ if((pos1 == str1.length && pos2 == str2.length-1) || (pos1 == str1.length -1 && pos2 == str2.length)){ return true; } } if(pos1 == str1.length || pos2 == str2.length){ return false; } if(areSame){ return match(str1,str2,pos1+1,pos2+1, str1[pos1] == str2[pos2]) || match(str1,str2,pos1,pos2+1,false) || match(str1,str2,pos1+1,pos2,false); }else{ return str1[pos1] == str2[pos2] && match(str1,str2,pos1+1,pos2+1,areSame); } } public boolean matchIterative(char str1[], char str2[]){ if(str1.length < str2.length){ char temp[] = str1; str1 = str2; str2 = temp; } if(str1.length - str2.length > 1){ return false; } int k = 1; if(str1.length == str2.length){ int i =0; int j =0; while(k >= 0 && i < str1.length){ if(str1[i] != str2[j]){ k } i++; j++; } if(k < 0){ return false; } }else{ int i=0; int j =0; while(k >= 0 && i < str1.length && j < str2.length){ if(str1[i] != str2[j]){ i++; k continue; } i++; j++; } if(k == -1){ return false; } } return true; } public static void main(String args[]){ OneEditApart oea = new OneEditApart(); System.out.println(oea.matchRecurisve("cat".toCharArray(), "dog".toCharArray())); System.out.println(oea.matchRecurisve("cat".toCharArray(), "cats".toCharArray())); System.out.println(oea.matchRecurisve("cat".toCharArray(), "cut".toCharArray())); System.out.println(oea.matchRecurisve("cats".toCharArray(), "casts".toCharArray())); System.out.println(oea.matchRecurisve("catsts".toCharArray(), "casts".toCharArray())); System.out.println(oea.matchIterative("cat".toCharArray(), "dog".toCharArray())); System.out.println(oea.matchIterative("cat".toCharArray(), "cats".toCharArray())); System.out.println(oea.matchIterative("cat".toCharArray(), "cut".toCharArray())); System.out.println(oea.matchIterative("cats".toCharArray(), "casts".toCharArray())); System.out.println(oea.matchIterative("catsts".toCharArray(), "casts".toCharArray())); } }
package com.irccloud.android; import java.util.ArrayList; import java.util.HashMap; import org.json.JSONException; import org.json.JSONObject; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.google.android.gcm.GCMRegistrar; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.PowerManager; import android.preference.PreferenceManager; import android.text.Editable; import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.text.TextWatcher; import android.text.method.LinkMovementMethod; import android.text.style.BackgroundColorSpan; import android.text.style.ForegroundColorSpan; import android.text.style.StyleSpan; import android.text.style.UnderlineSpan; import android.text.util.Linkify; import android.util.Log; import android.view.ContextThemeWrapper; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnFocusChangeListener; import android.view.View.OnKeyListener; import android.view.WindowManager; import android.view.View.OnClickListener; import android.view.animation.AlphaAnimation; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.HorizontalScrollView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; public class MessageActivity extends BaseActivity implements UsersListFragment.OnUserSelectedListener, BuffersListFragment.OnBufferSelectedListener, MessageViewFragment.MessageViewListener { int cid = -1; int bid = -1; String name; String type; EditText messageTxt; View sendBtn; int joined; int archived; String status; UsersDataSource.User selected_user; View userListView; View buffersListView; TextView title; TextView subtitle; LinearLayout messageContainer; HorizontalScrollView scrollView; NetworkConnection conn; private boolean shouldFadeIn = false; ImageView upView; private RefreshUpIndicatorTask refreshUpIndicatorTask = null; private ShowNotificationsTask showNotificationsTask = null; private ArrayList<Integer> backStack = new ArrayList<Integer>(); PowerManager.WakeLock screenLock = null; private int launchBid = -1; private Uri launchURI = null; private AlertDialog channelsListDialog; private HashMap<Integer, EventsDataSource.Event> pendingEvents = new HashMap<Integer, EventsDataSource.Event>(); @SuppressLint("NewApi") @SuppressWarnings({ "deprecation", "unchecked" }) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_message); buffersListView = findViewById(R.id.BuffersList); messageContainer = (LinearLayout)findViewById(R.id.messageContainer); scrollView = (HorizontalScrollView)findViewById(R.id.scroll); if(scrollView != null) { LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)messageContainer.getLayoutParams(); params.width = getWindowManager().getDefaultDisplay().getWidth(); messageContainer.setLayoutParams(params); } messageTxt = (EditText)findViewById(R.id.messageTxt); messageTxt.setEnabled(false); messageTxt.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if(event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER && messageTxt.getText() != null && messageTxt.getText().length() > 0) { new SendTask().execute((Void)null); } return false; } }); messageTxt.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(scrollView != null && v == messageTxt && hasFocus) scrollView.scrollTo((int)getResources().getDimension(R.dimen.drawer_width), 0); } }); messageTxt.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(scrollView != null) scrollView.scrollTo((int)getResources().getDimension(R.dimen.drawer_width), 0); } }); messageTxt.setOnEditorActionListener(new OnEditorActionListener() { public boolean onEditorAction(TextView view, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEND && messageTxt.getText() != null && messageTxt.getText().length() > 0) { new SendTask().execute((Void)null); } return true; } }); messageTxt.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { Object[] spans = s.getSpans(0, s.length(), Object.class); for(Object o : spans) { if(((s.getSpanFlags(o) & Spanned.SPAN_COMPOSING) != Spanned.SPAN_COMPOSING) && (o.getClass() == StyleSpan.class || o.getClass() == ForegroundColorSpan.class || o.getClass() == BackgroundColorSpan.class || o.getClass() == UnderlineSpan.class)) { s.removeSpan(o); } } if(s.length() > 0) { sendBtn.setEnabled(true); if(Build.VERSION.SDK_INT >= 11) sendBtn.setAlpha(1); } else { sendBtn.setEnabled(false); if(Build.VERSION.SDK_INT >= 11) sendBtn.setAlpha(0.5f); } } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } }); sendBtn = findViewById(R.id.sendBtn); sendBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new SendTask().execute((Void)null); } }); userListView = findViewById(R.id.usersListFragment); getSupportActionBar().setLogo(R.drawable.logo); getSupportActionBar().setHomeButtonEnabled(false); getSupportActionBar().setDisplayHomeAsUpEnabled(false); getSupportActionBar().setDisplayShowTitleEnabled(false); View v = getLayoutInflater().inflate(R.layout.actionbar_messageview, null); v.findViewById(R.id.actionTitleArea).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(bid); if(c != null) { AlertDialog.Builder builder = new AlertDialog.Builder(MessageActivity.this); builder.setTitle("Channel Topic"); if(c.topic_text.length() > 0) { builder.setMessage(ColorFormatter.html_to_spanned(TextUtils.htmlEncode(c.topic_text), true, ServersDataSource.getInstance().getServer(cid))); } else builder.setMessage("No topic set."); builder.setPositiveButton("Close", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setNeutralButton("Edit", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); editTopic(); } }); final AlertDialog dialog = builder.create(); dialog.setOwnerActivity(MessageActivity.this); dialog.show(); ((TextView)dialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance()); ((TextView)dialog.findViewById(android.R.id.message)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); } else if(archived == 0 && subtitle.getText().length() > 0){ AlertDialog.Builder builder = new AlertDialog.Builder(MessageActivity.this); builder.setTitle(title.getText().toString()); final SpannableString s = new SpannableString(subtitle.getText().toString()); Linkify.addLinks(s, Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES); builder.setMessage(s); builder.setPositiveButton("Close", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog dialog = builder.create(); dialog.setOwnerActivity(MessageActivity.this); dialog.show(); ((TextView)dialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance()); } } }); upView = (ImageView)v.findViewById(R.id.upIndicator); if(scrollView != null) { upView.setVisibility(View.VISIBLE); upView.setOnClickListener(upClickListener); ImageView icon = (ImageView)v.findViewById(R.id.upIcon); icon.setOnClickListener(upClickListener); if(refreshUpIndicatorTask != null) refreshUpIndicatorTask.cancel(true); refreshUpIndicatorTask = new RefreshUpIndicatorTask(); refreshUpIndicatorTask.execute((Void)null); } else { upView.setVisibility(View.INVISIBLE); } title = (TextView)v.findViewById(R.id.title); subtitle = (TextView)v.findViewById(R.id.subtitle); getSupportActionBar().setCustomView(v); if(savedInstanceState != null && savedInstanceState.containsKey("cid")) { cid = savedInstanceState.getInt("cid"); bid = savedInstanceState.getInt("bid"); name = savedInstanceState.getString("name"); type = savedInstanceState.getString("type"); joined = savedInstanceState.getInt("joined"); archived = savedInstanceState.getInt("archived"); status = savedInstanceState.getString("status"); backStack = (ArrayList<Integer>) savedInstanceState.getSerializable("backStack"); } try { if(getSharedPreferences("prefs", 0).contains("session_key")) { GCMRegistrar.checkDevice(this); GCMRegistrar.checkManifest(this); final String regId = GCMRegistrar.getRegistrationId(this); if (regId.equals("")) { GCMRegistrar.register(this, GCMIntentService.GCM_ID); } else { if(!getSharedPreferences("prefs", 0).contains("gcm_registered")) GCMIntentService.scheduleRegisterTimer(30000); } } } catch (Exception e) { //GCM might not be available on the device } } @Override public void onSaveInstanceState(Bundle state) { super.onSaveInstanceState(state); state.putInt("cid", cid); state.putInt("bid", bid); state.putString("name", name); state.putString("type", type); state.putInt("joined", joined); state.putInt("archived", archived); state.putString("status", status); state.putSerializable("backStack", backStack); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK)) { //Back key pressed if(backStack != null && backStack.size() > 0) { Integer bid = backStack.get(0); backStack.remove(0); BuffersDataSource.Buffer buffer = BuffersDataSource.getInstance().getBuffer(bid); if(buffer != null) { ServersDataSource.Server s = ServersDataSource.getInstance().getServer(buffer.cid); if(s != null) status = s.status; String name = buffer.name; if(buffer.type.equalsIgnoreCase("console")) { if(s != null) { if(s.name != null && s.name.length() > 0) name = s.name; else name = s.hostname; } } onBufferSelected(buffer.cid, buffer.bid, name, buffer.last_seen_eid, buffer.min_eid, buffer.type, 1, buffer.archived, status); if(backStack.size() > 0) backStack.remove(0); } else { return super.onKeyDown(keyCode, event); } return true; } } return super.onKeyDown(keyCode, event); } private class SendTask extends AsyncTaskEx<Void, Void, Void> { EventsDataSource.Event e = null; @Override protected void onPreExecute() { MessageViewFragment mvf = (MessageViewFragment)getSupportFragmentManager().findFragmentById(R.id.messageViewFragment); if(mvf != null && mvf.bid != bid) { Log.w("IRCCloud", "MessageViewFragment's bid differs from MessageActivity's, switching buffers again"); open_bid(mvf.bid); } if(conn.getState() == NetworkConnection.STATE_CONNECTED && messageTxt.getText() != null && messageTxt.getText().length() > 0) { sendBtn.setEnabled(false); ServersDataSource.Server s = ServersDataSource.getInstance().getServer(cid); UsersDataSource.User u = UsersDataSource.getInstance().getUser(cid, name, s.nick); e = EventsDataSource.getInstance().new Event(); e.cid = cid; e.bid = bid; e.eid = (System.currentTimeMillis() + conn.clockOffset + 5000) * 1000L; e.self = true; e.from = s.nick; e.nick = s.nick; if(u != null) e.from_mode = u.mode; String msg = messageTxt.getText().toString(); if(msg.startsWith(" msg = msg.substring(1); else if(msg.startsWith("/") && !msg.startsWith("/me ")) msg = null; e.msg = msg; if(msg != null && msg.toLowerCase().startsWith("/me ")) { e.type = "buffer_me_msg"; e.msg = msg.substring(4); } else { e.type = "buffer_msg"; } e.color = R.color.timestamp; if(name.equals(s.nick)) e.bg_color = R.color.message_bg; else e.bg_color = R.color.self; e.row_type = 0; e.html = null; e.group_msg = null; e.linkify = true; e.target_mode = null; e.highlight = false; e.reqid = -1; e.pending = true; if(e.msg != null) { e.msg = TextUtils.htmlEncode(e.msg); EventsDataSource.getInstance().addEvent(e); conn.notifyHandlers(NetworkConnection.EVENT_BUFFERMSG, e, mHandler); } } } @Override protected Void doInBackground(Void... arg0) { if(conn.getState() == NetworkConnection.STATE_CONNECTED && messageTxt.getText() != null && messageTxt.getText().length() > 0) { e.reqid = conn.say(cid, name, messageTxt.getText().toString()); Log.d("IRCCloud", "Inserted pending message, EID: " + e.eid + " reqid: " + e.reqid); if(e.msg != null) pendingEvents.put(e.reqid, e); } return null; } @Override protected void onPostExecute(Void result) { messageTxt.setText(""); sendBtn.setEnabled(true); } } private class RefreshUpIndicatorTask extends AsyncTaskEx<Void, Void, Void> { int unread = 0; int highlights = 0; @Override protected Void doInBackground(Void... arg0) { ArrayList<ServersDataSource.Server> servers = ServersDataSource.getInstance().getServers(); JSONObject channelDisabledMap = null; JSONObject bufferDisabledMap = null; if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) { try { if(conn.getUserInfo().prefs.has("channel-disableTrackUnread")) channelDisabledMap = conn.getUserInfo().prefs.getJSONObject("channel-disableTrackUnread"); if(conn.getUserInfo().prefs.has("buffer-disableTrackUnread")) bufferDisabledMap = conn.getUserInfo().prefs.getJSONObject("buffer-disableTrackUnread"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } for(int i = 0; i < servers.size(); i++) { ServersDataSource.Server s = servers.get(i); ArrayList<BuffersDataSource.Buffer> buffers = BuffersDataSource.getInstance().getBuffersForServer(s.cid); for(int j = 0; j < buffers.size(); j++) { BuffersDataSource.Buffer b = buffers.get(j); if(b.type == null) Log.w("IRCCloud", "Buffer with null type: " + b.bid + " name: " + b.name); if(b.bid != bid) { if(unread == 0) { int u = 0; try { u = EventsDataSource.getInstance().getUnreadCountForBuffer(b.bid, b.last_seen_eid, b.type); if(b.type.equalsIgnoreCase("channel") && channelDisabledMap != null && channelDisabledMap.has(String.valueOf(b.bid)) && channelDisabledMap.getBoolean(String.valueOf(b.bid))) u = 0; else if(bufferDisabledMap != null && bufferDisabledMap.has(String.valueOf(b.bid)) && bufferDisabledMap.getBoolean(String.valueOf(b.bid))) u = 0; } catch (JSONException e) { e.printStackTrace(); } unread += u; } if(highlights == 0) { try { if(!b.type.equalsIgnoreCase("conversation") || bufferDisabledMap == null || !bufferDisabledMap.has(String.valueOf(b.bid)) || !bufferDisabledMap.getBoolean(String.valueOf(b.bid))) highlights += EventsDataSource.getInstance().getHighlightCountForBuffer(b.bid, b.last_seen_eid, b.type); } catch (JSONException e) { } } } } } return null; } @Override protected void onPostExecute(Void result) { if(!isCancelled()) { if(highlights > 0) { upView.setImageResource(R.drawable.up_highlight); } else if(unread > 0) { upView.setImageResource(R.drawable.up_unread); } else { upView.setImageResource(R.drawable.up); } refreshUpIndicatorTask = null; } } } private class ShowNotificationsTask extends AsyncTaskEx<Integer, Void, Void> { @Override protected Void doInBackground(Integer... params) { Notifications.getInstance().excludeBid(params[0]); if(params[0] > 0) Notifications.getInstance().showNotifications(null); showNotificationsTask = null; return null; } } private void setFromIntent(Intent intent) { long min_eid = 0; long last_seen_eid = 0; launchBid = -1; launchURI = null; if(intent.hasExtra("bid")) { int new_bid = intent.getIntExtra("bid", 0); if(NetworkConnection.getInstance().ready && BuffersDataSource.getInstance().getBuffer(new_bid) == null) { Log.w("IRCCloud", "Invalid bid requested by launch intent: " + new_bid); Notifications.getInstance().deleteNotificationsForBid(new_bid); if(showNotificationsTask != null) showNotificationsTask.cancel(true); showNotificationsTask = new ShowNotificationsTask(); showNotificationsTask.execute(bid); return; } else { if(bid >= 0) backStack.add(0, bid); bid = new_bid; Log.d("IRCCloud", "BID set by launch intent: " + bid); } } if(intent.getData() != null && intent.getData().getScheme().startsWith("irc")) { if(open_uri(intent.getData())) return; launchURI = intent.getData(); } else if(intent.hasExtra("cid")) { cid = intent.getIntExtra("cid", 0); name = intent.getStringExtra("name"); type = intent.getStringExtra("type"); joined = intent.getIntExtra("joined", 0); archived = intent.getIntExtra("archived", 0); status = intent.getStringExtra("status"); min_eid = intent.getLongExtra("min_eid", 0); last_seen_eid = intent.getLongExtra("last_seen_eid", 0); if(bid == -1) { BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(cid, name); if(b != null) { bid = b.bid; last_seen_eid = b.last_seen_eid; min_eid = b.min_eid; archived = b.archived; } } Log.d("IRCCloud", "CID set by launch intent: " + cid); } else if(bid != -1) { BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBuffer(bid); if(b != null) { ServersDataSource.Server s = ServersDataSource.getInstance().getServer(b.cid); joined = 1; if(b.type.equalsIgnoreCase("channel")) { ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(b.bid); if(c == null) joined = 0; } if(b.type.equalsIgnoreCase("console")) b.name = s.name; cid = b.cid; name = b.name; type = b.type; archived = b.archived; min_eid = b.min_eid; last_seen_eid = b.last_seen_eid; status = s.status; } else { cid = -1; } } if(cid == -1) { launchBid = bid; Log.d("IRCCloud", "Buffer not available yet, assigned to launchBid: " + launchBid); } else { UsersListFragment ulf = (UsersListFragment)getSupportFragmentManager().findFragmentById(R.id.usersListFragment); MessageViewFragment mvf = (MessageViewFragment)getSupportFragmentManager().findFragmentById(R.id.messageViewFragment); Bundle b = new Bundle(); b.putInt("cid", cid); b.putInt("bid", bid); b.putLong("last_seen_eid", last_seen_eid); b.putLong("min_eid", min_eid); b.putString("name", name); b.putString("type", type); ulf.setArguments(b); mvf.setArguments(b); messageTxt.setEnabled(true); } } @Override protected void onNewIntent(Intent intent) { if(intent != null) { setFromIntent(intent); } } @SuppressLint("NewApi") @Override public void onResume() { conn = NetworkConnection.getInstance(); if(!conn.ready) { super.onResume(); Intent i = new Intent(this, MainActivity.class); if(getIntent() != null) { if(getIntent().getData() != null) i.setData(getIntent().getData()); if(getIntent().getExtras() != null) i.putExtras(getIntent().getExtras()); } startActivity(i); finish(); return; } conn.addHandler(mHandler); super.onResume(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()); if(prefs.getBoolean("screenlock", false)) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } else { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } if(conn.getState() != NetworkConnection.STATE_CONNECTED) { if(scrollView != null && !NetworkConnection.getInstance().ready) scrollView.setEnabled(false); messageTxt.setEnabled(false); } else { if(scrollView != null) { scrollView.setEnabled(true); scrollView.scrollTo((int)getResources().getDimension(R.dimen.drawer_width), 0); upView.setVisibility(View.VISIBLE); } messageTxt.setEnabled(true); } if(cid == -1) { if(getIntent() != null && (getIntent().hasExtra("bid") || getIntent().getData() != null)) { setFromIntent(getIntent()); } else if(conn.getState() == NetworkConnection.STATE_CONNECTED && conn.getUserInfo() != null && NetworkConnection.getInstance().ready) { if(!open_bid(conn.getUserInfo().last_selected_bid)) { if(!open_bid(BuffersDataSource.getInstance().firstBid())) { if(scrollView != null && NetworkConnection.getInstance().ready) scrollView.scrollTo(0,0); } } } } updateUsersListFragmentVisibility(); title.setText(name); getSupportActionBar().setTitle(name); update_subtitle(); if(getSupportFragmentManager().findFragmentById(R.id.BuffersList) != null) ((BuffersListFragment)getSupportFragmentManager().findFragmentById(R.id.BuffersList)).setSelectedBid(bid); if(refreshUpIndicatorTask != null) refreshUpIndicatorTask.cancel(true); refreshUpIndicatorTask = new RefreshUpIndicatorTask(); refreshUpIndicatorTask.execute((Void)null); invalidateOptionsMenu(); if(NetworkConnection.getInstance().ready) { if(showNotificationsTask != null) showNotificationsTask.cancel(true); showNotificationsTask = new ShowNotificationsTask(); showNotificationsTask.execute(bid); } sendBtn.setEnabled(messageTxt.getText().length() > 0); if(Build.VERSION.SDK_INT >= 11 && messageTxt.getText().length() == 0) sendBtn.setAlpha(0.5f); } @Override public void onPause() { super.onPause(); if(showNotificationsTask != null) showNotificationsTask.cancel(true); showNotificationsTask = new ShowNotificationsTask(); showNotificationsTask.execute(-1); if(channelsListDialog != null) channelsListDialog.dismiss(); if(conn != null) conn.removeHandler(mHandler); } private boolean open_uri(Uri uri) { Log.i("IRCCloud", "Launch URI: " + uri); if(uri != null && NetworkConnection.getInstance().ready) { ServersDataSource.Server s = null; if(uri.getPort() > 0) s = ServersDataSource.getInstance().getServer(uri.getHost(), uri.getPort()); else if(uri.getScheme().equalsIgnoreCase("ircs")) s = ServersDataSource.getInstance().getServer(uri.getHost(), true); else s = ServersDataSource.getInstance().getServer(uri.getHost()); if(s != null) { if(uri.getPath().length() > 1) { String key = null; String channel = uri.getPath().substring(1); if(channel.contains(",")) { key = channel.substring(channel.indexOf(",") + 1); channel = channel.substring(0, channel.indexOf(",")); } BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(s.cid, channel); if(b != null) return open_bid(b.bid); else conn.join(s.cid, channel, key); return true; } else { BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(s.cid, "*"); if(b != null) return open_bid(b.bid); } } else { EditConnectionFragment connFragment = new EditConnectionFragment(); connFragment.default_hostname = uri.getHost(); if(uri.getPort() > 0) connFragment.default_port = uri.getPort(); else if(uri.getScheme().equalsIgnoreCase("ircs")) connFragment.default_port = 6697; if(uri.getPath().length() > 1) connFragment.default_channels = uri.getPath().substring(1).replace(",", " "); connFragment.show(getSupportFragmentManager(), "addnetwork"); return true; } } return false; } private boolean open_bid(int bid) { Log.d("IRCCloud", "Attempting to open bid: " + bid); BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBuffer(bid); if(b != null) { ServersDataSource.Server s = ServersDataSource.getInstance().getServer(b.cid); int joined = 1; if(b.type.equalsIgnoreCase("channel")) { ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(b.bid); if(c == null) joined = 0; } String name = b.name; if(b.type.equalsIgnoreCase("console")) { if(s.name != null && s.name.length() > 0) name = s.name; else name = s.hostname; } onBufferSelected(b.cid, b.bid, name, b.last_seen_eid, b.min_eid, b.type, joined, b.archived, s.status); return true; } Log.w("IRCCloud", "Requested BID not found"); return false; } private void update_subtitle() { if(cid == -1 || !NetworkConnection.getInstance().ready) { getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setDisplayShowCustomEnabled(false); } else { getSupportActionBar().setDisplayShowHomeEnabled(false); getSupportActionBar().setDisplayShowCustomEnabled(true); if(archived > 0 && !type.equalsIgnoreCase("console")) { subtitle.setVisibility(View.VISIBLE); subtitle.setText("(archived)"); } else { if(type == null) { subtitle.setVisibility(View.GONE); } else if(type.equalsIgnoreCase("conversation")) { UsersDataSource.User user = UsersDataSource.getInstance().getUser(cid, name); BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBuffer(bid); if(user != null && user.away > 0) { subtitle.setVisibility(View.VISIBLE); if(user.away_msg != null && user.away_msg.length() > 0) { subtitle.setText("Away: " + user.away_msg); } else if(b != null && b.away_msg != null && b.away_msg.length() > 0) { subtitle.setText("Away: " + b.away_msg); } else { subtitle.setText("Away"); } } else { subtitle.setVisibility(View.GONE); } } else if(type.equalsIgnoreCase("channel")) { ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(bid); if(c != null && c.topic_text.length() > 0) { subtitle.setVisibility(View.VISIBLE); subtitle.setText(c.topic_text); } else { subtitle.setVisibility(View.GONE); } } else if(type.equalsIgnoreCase("console")) { ServersDataSource.Server s = ServersDataSource.getInstance().getServer(cid); if(s != null) { subtitle.setVisibility(View.VISIBLE); subtitle.setText(s.hostname + ":" + s.port); } else { subtitle.setVisibility(View.GONE); } } } } invalidateOptionsMenu(); } private void updateUsersListFragmentVisibility() { boolean hide = false; if(userListView != null) { try { if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) { JSONObject hiddenMap = conn.getUserInfo().prefs.getJSONObject("channel-hiddenMembers"); if(hiddenMap.has(String.valueOf(bid)) && hiddenMap.getBoolean(String.valueOf(bid))) hide = true; } } catch (Exception e) { e.printStackTrace(); } if(hide || type == null || !type.equalsIgnoreCase("channel") || joined == 0) userListView.setVisibility(View.GONE); else userListView.setVisibility(View.VISIBLE); } } @SuppressLint("HandlerLeak") private final Handler mHandler = new Handler() { String bufferToOpen = null; int cidToOpen = -1; public void handleMessage(Message msg) { Integer event_bid = 0; IRCCloudJSONObject event = null; Bundle args = null; switch (msg.what) { case NetworkConnection.EVENT_LINKCHANNEL: event = (IRCCloudJSONObject)msg.obj; if(cidToOpen == event.cid() && event.getString("invalid_chan").equalsIgnoreCase(bufferToOpen)) { Log.d("IRCCloud", "Linked channel"); bufferToOpen = event.getString("valid_chan"); msg.obj = BuffersDataSource.getInstance().getBuffer(event.bid()); } case NetworkConnection.EVENT_MAKEBUFFER: BuffersDataSource.Buffer b = (BuffersDataSource.Buffer)msg.obj; if(cidToOpen == b.cid && b.name.equalsIgnoreCase(bufferToOpen) && !bufferToOpen.equalsIgnoreCase(name)) { onBufferSelected(b.cid, b.bid, b.name, b.last_seen_eid, b.min_eid, b.type, 1, 0, "connected_ready"); bufferToOpen = null; cidToOpen = -1; } else if(bid == -1 && b.cid == cid && b.name.equalsIgnoreCase(name)) { Log.i("IRCCloud", "Got my new buffer id: " + b.bid); bid = b.bid; if(getSupportFragmentManager().findFragmentById(R.id.BuffersList) != null) ((BuffersListFragment)getSupportFragmentManager().findFragmentById(R.id.BuffersList)).setSelectedBid(bid); if(showNotificationsTask != null) showNotificationsTask.cancel(true); showNotificationsTask = new ShowNotificationsTask(); showNotificationsTask.execute(bid); } break; case NetworkConnection.EVENT_OPENBUFFER: event = (IRCCloudJSONObject)msg.obj; try { bufferToOpen = event.getString("name"); cidToOpen = event.cid(); b = BuffersDataSource.getInstance().getBufferByName(cidToOpen, bufferToOpen); if(b != null && !bufferToOpen.equalsIgnoreCase(name)) { onBufferSelected(b.cid, b.bid, b.name, b.last_seen_eid, b.min_eid, b.type, 1, 0, "connected_ready"); bufferToOpen = null; cidToOpen = -1; } } catch (Exception e2) { // TODO Auto-generated catch block e2.printStackTrace(); } break; case NetworkConnection.EVENT_CONNECTIVITY: if(conn.getState() == NetworkConnection.STATE_CONNECTED) { for(EventsDataSource.Event e : pendingEvents.values()) { EventsDataSource.getInstance().deleteEvent(e.eid, e.bid); } pendingEvents.clear(); if(scrollView != null && NetworkConnection.getInstance().ready) scrollView.setEnabled(true); if(cid != -1) messageTxt.setEnabled(true); } else { if(scrollView != null && NetworkConnection.getInstance().ready) { scrollView.setEnabled(false); scrollView.smoothScrollTo((int)getResources().getDimension(R.dimen.drawer_width), 0); upView.setVisibility(View.VISIBLE); } messageTxt.setEnabled(false); } break; case NetworkConnection.EVENT_BANLIST: event = (IRCCloudJSONObject)msg.obj; if(event.getString("channel").equalsIgnoreCase(name)) { args = new Bundle(); args.putInt("cid", cid); args.putInt("bid", bid); args.putString("event", event.toString()); BanListFragment banList = (BanListFragment)getSupportFragmentManager().findFragmentByTag("banlist"); if(banList == null) { banList = new BanListFragment(); banList.setArguments(args); banList.show(getSupportFragmentManager(), "banlist"); } else { banList.setArguments(args); } } break; case NetworkConnection.EVENT_WHOLIST: event = (IRCCloudJSONObject)msg.obj; args = new Bundle(); args.putString("event", event.toString()); WhoListFragment whoList = (WhoListFragment)getSupportFragmentManager().findFragmentByTag("wholist"); if(whoList == null) { whoList = new WhoListFragment(); whoList.setArguments(args); whoList.show(getSupportFragmentManager(), "wholist"); } else { whoList.setArguments(args); } break; case NetworkConnection.EVENT_WHOIS: event = (IRCCloudJSONObject)msg.obj; args = new Bundle(); args.putString("event", event.toString()); WhoisFragment whois = (WhoisFragment)getSupportFragmentManager().findFragmentByTag("whois"); if(whois == null) { whois = new WhoisFragment(); whois.setArguments(args); whois.show(getSupportFragmentManager(), "whois"); } else { whois.setArguments(args); } break; case NetworkConnection.EVENT_LISTRESPONSEFETCHING: event = (IRCCloudJSONObject)msg.obj; String dialogtitle = "List of channels on " + ServersDataSource.getInstance().getServer(event.cid()).hostname; if(channelsListDialog == null) { Log.d("IRCCloud", "Created new dialog"); Context ctx = MessageActivity.this; if(Build.VERSION.SDK_INT < 11) ctx = new ContextThemeWrapper(ctx, android.R.style.Theme_Dialog); AlertDialog.Builder builder = new AlertDialog.Builder(ctx); builder.setView(getLayoutInflater().inflate(R.layout.dialog_channelslist, null)); builder.setTitle(dialogtitle); builder.setNegativeButton("Close", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); channelsListDialog = builder.create(); channelsListDialog.setOwnerActivity(MessageActivity.this); } else { channelsListDialog.setTitle(dialogtitle); Log.d("IRCCloud", "Re-used dialog"); } channelsListDialog.show(); ChannelListFragment channels = (ChannelListFragment)getSupportFragmentManager().findFragmentById(R.id.channelListFragment); args = new Bundle(); args.putInt("cid", event.cid()); channels.setArguments(args); break; case NetworkConnection.EVENT_BACKLOG_END: Log.d("IRCCloud", "Backlog processing ended, cid: " + cid + " bid: " + bid); if(scrollView != null) { scrollView.setEnabled(true); } if(cid == -1) { if(launchURI == null || !open_uri(launchURI)) { if(launchBid == -1 || !open_bid(launchBid)) { if(conn.getUserInfo() == null || !open_bid(conn.getUserInfo().last_selected_bid)) { if(!open_bid(BuffersDataSource.getInstance().firstBid())) { if(scrollView != null && NetworkConnection.getInstance().ready) { scrollView.scrollTo(0, 0); } } } } } } update_subtitle(); if(refreshUpIndicatorTask != null) refreshUpIndicatorTask.cancel(true); refreshUpIndicatorTask = new RefreshUpIndicatorTask(); refreshUpIndicatorTask.execute((Void)null); break; case NetworkConnection.EVENT_USERINFO: updateUsersListFragmentVisibility(); invalidateOptionsMenu(); if(refreshUpIndicatorTask != null) refreshUpIndicatorTask.cancel(true); refreshUpIndicatorTask = new RefreshUpIndicatorTask(); refreshUpIndicatorTask.execute((Void)null); if(launchBid == -1 && cid == -1) launchBid = conn.getUserInfo().last_selected_bid; break; case NetworkConnection.EVENT_STATUSCHANGED: try { event = (IRCCloudJSONObject)msg.obj; if(event.cid() == cid) { status = event.getString("new_status"); invalidateOptionsMenu(); } } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } break; case NetworkConnection.EVENT_MAKESERVER: ServersDataSource.Server server = (ServersDataSource.Server)msg.obj; if(server.cid == cid) { status = server.status; invalidateOptionsMenu(); } break; case NetworkConnection.EVENT_BUFFERARCHIVED: event_bid = (Integer)msg.obj; if(event_bid == bid) { archived = 1; invalidateOptionsMenu(); subtitle.setVisibility(View.VISIBLE); subtitle.setText("(archived)"); } break; case NetworkConnection.EVENT_BUFFERUNARCHIVED: event_bid = (Integer)msg.obj; if(event_bid == bid) { archived = 0; invalidateOptionsMenu(); subtitle.setVisibility(View.GONE); } break; case NetworkConnection.EVENT_JOIN: event = (IRCCloudJSONObject)msg.obj; if(event.bid() == bid && event.type().equalsIgnoreCase("you_joined_channel")) { joined = 1; invalidateOptionsMenu(); updateUsersListFragmentVisibility(); } break; case NetworkConnection.EVENT_PART: event = (IRCCloudJSONObject)msg.obj; if(event.bid() == bid && event.type().equalsIgnoreCase("you_parted_channel")) { joined = 0; invalidateOptionsMenu(); updateUsersListFragmentVisibility(); } break; case NetworkConnection.EVENT_CHANNELINIT: ChannelsDataSource.Channel channel = (ChannelsDataSource.Channel)msg.obj; if(channel.bid == bid) { joined = 1; archived = 0; update_subtitle(); invalidateOptionsMenu(); } break; case NetworkConnection.EVENT_CONNECTIONDELETED: case NetworkConnection.EVENT_DELETEBUFFER: Integer id = (Integer)msg.obj; if(msg.what==NetworkConnection.EVENT_DELETEBUFFER) { for(int i = 0; i < backStack.size(); i++) { if(backStack.get(i).equals(id)) { backStack.remove(i); i } } } if(id == ((msg.what==NetworkConnection.EVENT_CONNECTIONDELETED)?cid:bid)) { if(backStack != null && backStack.size() > 0) { Integer bid = backStack.get(0); backStack.remove(0); BuffersDataSource.Buffer buffer = BuffersDataSource.getInstance().getBuffer(bid); if(buffer != null) { ServersDataSource.Server s = ServersDataSource.getInstance().getServer(buffer.cid); if(s != null) status = s.status; String name = buffer.name; if(buffer.type.equalsIgnoreCase("console")) { if(s != null) { if(s.name != null && s.name.length() > 0) name = s.name; else name = s.hostname; } } onBufferSelected(buffer.cid, buffer.bid, name, buffer.last_seen_eid, buffer.min_eid, buffer.type, 1, buffer.archived, status); backStack.remove(0); } else { finish(); } } else { if(!open_bid(BuffersDataSource.getInstance().firstBid())) finish(); } } break; case NetworkConnection.EVENT_CHANNELTOPIC: event = (IRCCloudJSONObject)msg.obj; if(event.bid() == bid) { try { if(event.getString("topic").length() > 0) { subtitle.setVisibility(View.VISIBLE); subtitle.setText(event.getString("topic")); } else { subtitle.setVisibility(View.GONE); } } catch (Exception e1) { subtitle.setVisibility(View.GONE); e1.printStackTrace(); } } break; case NetworkConnection.EVENT_SELFBACK: try { event = (IRCCloudJSONObject)msg.obj; if(event.cid() == cid && event.getString("nick").equalsIgnoreCase(name)) { subtitle.setVisibility(View.GONE); subtitle.setText(""); } } catch (Exception e1) { e1.printStackTrace(); } break; case NetworkConnection.EVENT_AWAY: try { event = (IRCCloudJSONObject)msg.obj; if((event.bid() == bid || (event.type().equalsIgnoreCase("self_away") && event.cid() == cid)) && event.getString("nick").equalsIgnoreCase(name)) { subtitle.setVisibility(View.VISIBLE); if(event.has("away_msg")) subtitle.setText("Away: " + event.getString("away_msg")); else subtitle.setText("Away: " + event.getString("msg")); } } catch (Exception e1) { e1.printStackTrace(); } break; case NetworkConnection.EVENT_HEARTBEATECHO: if(refreshUpIndicatorTask != null) refreshUpIndicatorTask.cancel(true); refreshUpIndicatorTask = new RefreshUpIndicatorTask(); refreshUpIndicatorTask.execute((Void)null); break; case NetworkConnection.EVENT_FAILURE_MSG: event = (IRCCloudJSONObject)msg.obj; if(event.has("_reqid")) { int reqid = event.getInt("_reqid"); if(pendingEvents.containsKey(reqid)) { EventsDataSource.Event e = pendingEvents.get(reqid); EventsDataSource.getInstance().deleteEvent(e.eid, e.bid); pendingEvents.remove(event.getInt("_reqid")); e.msg = ColorFormatter.irc_to_html(e.msg + " \u00034(FAILED)\u000f"); conn.notifyHandlers(NetworkConnection.EVENT_BUFFERMSG, e); } } break; case NetworkConnection.EVENT_BUFFERMSG: try { EventsDataSource.Event e = (EventsDataSource.Event)msg.obj; if(e.bid != bid && upView != null) { if(refreshUpIndicatorTask != null) refreshUpIndicatorTask.cancel(true); refreshUpIndicatorTask = new RefreshUpIndicatorTask(); refreshUpIndicatorTask.execute((Void)null); } if(e.from.equalsIgnoreCase(name)) { for(EventsDataSource.Event e1 : pendingEvents.values()) { EventsDataSource.getInstance().deleteEvent(e1.eid, e1.bid); } pendingEvents.clear(); Log.d("IRCCloud", "Cleared pending events for this PM buffer"); } else if(pendingEvents.containsKey(e.reqid)) { Log.d("IRCCloud", "Removed pending event for reqid: " + e.reqid); e = pendingEvents.get(e.reqid); EventsDataSource.getInstance().deleteEvent(e.eid, e.bid); pendingEvents.remove(e.reqid); } if(pendingEvents.size() > 0) { Log.d("IRCCloud", "pendingEvents reqids: " + pendingEvents.keySet().toString()); } } catch (Exception e1) { } break; } } }; @Override public boolean onCreateOptionsMenu(Menu menu) { if(type != null && NetworkConnection.getInstance().ready) { if(type.equalsIgnoreCase("channel")) { getSupportMenuInflater().inflate(R.menu.activity_message_channel_userlist, menu); getSupportMenuInflater().inflate(R.menu.activity_message_channel, menu); } else if(type.equalsIgnoreCase("conversation")) getSupportMenuInflater().inflate(R.menu.activity_message_conversation, menu); else if(type.equalsIgnoreCase("console")) getSupportMenuInflater().inflate(R.menu.activity_message_console, menu); getSupportMenuInflater().inflate(R.menu.activity_message_archive, menu); } getSupportMenuInflater().inflate(R.menu.activity_main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onPrepareOptionsMenu (Menu menu) { if(type != null && NetworkConnection.getInstance().ready) { if(archived == 0) { menu.findItem(R.id.menu_archive).setTitle(R.string.menu_archive); } else { menu.findItem(R.id.menu_archive).setTitle(R.string.menu_unarchive); } if(type.equalsIgnoreCase("channel")) { if(joined == 0) { menu.findItem(R.id.menu_leave).setTitle(R.string.menu_rejoin); menu.findItem(R.id.menu_archive).setVisible(true); menu.findItem(R.id.menu_archive).setEnabled(true); menu.findItem(R.id.menu_delete).setVisible(true); menu.findItem(R.id.menu_delete).setEnabled(true); if(menu.findItem(R.id.menu_userlist) != null) { menu.findItem(R.id.menu_userlist).setEnabled(false); menu.findItem(R.id.menu_userlist).setVisible(false); } } else { menu.findItem(R.id.menu_leave).setTitle(R.string.menu_leave); menu.findItem(R.id.menu_archive).setVisible(false); menu.findItem(R.id.menu_archive).setEnabled(false); menu.findItem(R.id.menu_delete).setVisible(false); menu.findItem(R.id.menu_delete).setEnabled(false); if(menu.findItem(R.id.menu_userlist) != null) { boolean hide = false; try { if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) { JSONObject hiddenMap = conn.getUserInfo().prefs.getJSONObject("channel-hiddenMembers"); if(hiddenMap.has(String.valueOf(bid)) && hiddenMap.getBoolean(String.valueOf(bid))) hide = true; } } catch (JSONException e) { } if(hide) { menu.findItem(R.id.menu_userlist).setEnabled(false); menu.findItem(R.id.menu_userlist).setVisible(false); } else { menu.findItem(R.id.menu_userlist).setEnabled(true); menu.findItem(R.id.menu_userlist).setVisible(true); } } } } else if(type.equalsIgnoreCase("console")) { menu.findItem(R.id.menu_archive).setVisible(false); menu.findItem(R.id.menu_archive).setEnabled(false); if(status != null && status.contains("connected") && !status.startsWith("dis")) { menu.findItem(R.id.menu_disconnect).setTitle(R.string.menu_disconnect); menu.findItem(R.id.menu_delete).setVisible(false); menu.findItem(R.id.menu_delete).setEnabled(false); } else { menu.findItem(R.id.menu_disconnect).setTitle(R.string.menu_reconnect); menu.findItem(R.id.menu_delete).setVisible(true); menu.findItem(R.id.menu_delete).setEnabled(true); } } } return super.onPrepareOptionsMenu(menu); } private OnClickListener upClickListener = new OnClickListener() { @Override public void onClick(View arg0) { if(scrollView != null) { if(scrollView.getScrollX() < buffersListView.getWidth() / 4) { scrollView.smoothScrollTo(buffersListView.getWidth(), 0); upView.setVisibility(View.VISIBLE); } else { scrollView.smoothScrollTo(0, 0); upView.setVisibility(View.INVISIBLE); } } } }; @Override public boolean onOptionsItemSelected(MenuItem item) { AlertDialog.Builder builder; AlertDialog dialog; switch (item.getItemId()) { case R.id.menu_whois: conn.whois(cid, name, null); break; case R.id.menu_identify: NickservFragment nsFragment = new NickservFragment(); nsFragment.setCid(cid); nsFragment.show(getSupportFragmentManager(), "nickserv"); break; case R.id.menu_add_network: if(getWindowManager().getDefaultDisplay().getWidth() < 800) { Intent i = new Intent(this, EditConnectionActivity.class); startActivity(i); } else { EditConnectionFragment connFragment = new EditConnectionFragment(); connFragment.show(getSupportFragmentManager(), "addnetwork"); } break; case R.id.menu_channel_options: ChannelOptionsFragment newFragment = new ChannelOptionsFragment(cid, bid); newFragment.show(getSupportFragmentManager(), "channeloptions"); break; case R.id.menu_buffer_options: BufferOptionsFragment bufferFragment = new BufferOptionsFragment(cid, bid, type); bufferFragment.show(getSupportFragmentManager(), "bufferoptions"); break; case R.id.menu_userlist: if(scrollView != null) { if(scrollView.getScrollX() > buffersListView.getWidth()) { scrollView.smoothScrollTo(buffersListView.getWidth(), 0); } else { scrollView.smoothScrollTo(buffersListView.getWidth() + userListView.getWidth(), 0); } upView.setVisibility(View.VISIBLE); } return true; case R.id.menu_ignore_list: Bundle args = new Bundle(); args.putInt("cid", cid); IgnoreListFragment ignoreList = new IgnoreListFragment(); ignoreList.setArguments(args); ignoreList.show(getSupportFragmentManager(), "ignorelist"); return true; case R.id.menu_ban_list: conn.mode(cid, name, "b"); return true; case R.id.menu_leave: if(joined == 0) conn.join(cid, name, null); else conn.part(cid, name, null); return true; case R.id.menu_archive: if(archived == 0) conn.archiveBuffer(cid, bid); else conn.unarchiveBuffer(cid, bid); return true; case R.id.menu_delete: builder = new AlertDialog.Builder(MessageActivity.this); if(type.equalsIgnoreCase("console")) builder.setTitle("Delete Connection"); else builder.setTitle("Delete History"); if(type.equalsIgnoreCase("console")) builder.setMessage("Are you sure you want to remove this connection?"); else if(type.equalsIgnoreCase("channel")) builder.setMessage("Are you sure you want to clear your history in " + name + "?"); else builder.setMessage("Are you sure you want to clear your history with " + name + "?"); builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setNeutralButton("Delete", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(type.equalsIgnoreCase("console")) { conn.deleteServer(cid); } else { conn.deleteBuffer(cid, bid); } dialog.dismiss(); } }); dialog = builder.create(); dialog.setOwnerActivity(MessageActivity.this); dialog.show(); return true; case R.id.menu_editconnection: if(getWindowManager().getDefaultDisplay().getWidth() < 800) { Intent i = new Intent(this, EditConnectionActivity.class); i.putExtra("cid", cid); startActivity(i); } else { EditConnectionFragment editFragment = new EditConnectionFragment(); editFragment.setCid(cid); editFragment.show(getSupportFragmentManager(), "editconnection"); } return true; case R.id.menu_disconnect: if(status != null && status.contains("connected") && !status.startsWith("dis")) { conn.disconnect(cid, null); } else { conn.reconnect(cid); } return true; } return super.onOptionsItemSelected(item); } void editTopic() { ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(bid); AlertDialog.Builder builder = new AlertDialog.Builder(this); LayoutInflater inflater = getLayoutInflater(); View view = inflater.inflate(R.layout.dialog_textprompt,null); TextView prompt = (TextView)view.findViewById(R.id.prompt); final EditText input = (EditText)view.findViewById(R.id.textInput); input.setText(c.topic_text); prompt.setVisibility(View.GONE); builder.setTitle("Channel Topic"); builder.setView(view); builder.setPositiveButton("Set Topic", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { conn.topic(cid, name, input.getText().toString()); dialog.dismiss(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog dialog = builder.create(); dialog.setOwnerActivity(this); dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); dialog.show(); } @Override public void onMessageDoubleClicked(EventsDataSource.Event event) { if(event == null) return; String from = event.from; if(from == null || from.length() == 0) from = event.nick; onUserDoubleClicked(from); } @Override public void onUserDoubleClicked(String from) { if(messageTxt == null || from == null || from.length() == 0) return; if(scrollView != null) scrollView.scrollTo((int)getResources().getDimension(R.dimen.drawer_width), 0); if(messageTxt.getText().length() == 0) { messageTxt.append(from + ": "); } else { int oldPosition = messageTxt.getSelectionStart(); String text = messageTxt.getText().toString(); int start = oldPosition - 1; if(start > 0 && text.charAt(start) == ' ') start while(start > 0 && text.charAt(start) != ' ') start int match = text.indexOf(from, start); int end = oldPosition + from.length(); if(end > text.length() - 1) end = text.length() - 1; if(match >= 0 && match < end) { String newtext = ""; if(match > 1 && text.charAt(match - 1) == ' ') newtext = text.substring(0, match - 1); else newtext = text.substring(0, match); if(match+from.length() < text.length() && text.charAt(match+from.length()) == ':' && match+from.length()+1 < text.length() && text.charAt(match+from.length()+1) == ' ') { if(match+from.length()+2 < text.length()) newtext += text.substring(match+from.length()+2, text.length()); } else if(match+from.length() < text.length()) { newtext += text.substring(match+from.length(), text.length()); } if(newtext.endsWith(" ")) newtext = newtext.substring(0, newtext.length() - 1); if(newtext.equals(":")) newtext = ""; messageTxt.setText(newtext); if(match < newtext.length()) messageTxt.setSelection(match); else messageTxt.setSelection(newtext.length()); } else { if(oldPosition == text.length() - 1) { text += " " + from; } else { String newtext = text.substring(0, oldPosition); if(!newtext.endsWith(" ")) from = " " + from; if(!text.substring(oldPosition, text.length()).startsWith(" ")) from += " "; newtext += from; newtext += text.substring(oldPosition, text.length()); if(newtext.endsWith(" ")) newtext = newtext.substring(0, newtext.length() - 1); text = newtext; } messageTxt.setText(text); if(text.length() > 0) { if(oldPosition + from.length() + 2 < text.length()) messageTxt.setSelection(oldPosition + from.length()); else messageTxt.setSelection(text.length()); } } } messageTxt.requestFocus(); InputMethodManager keyboard = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); keyboard.showSoftInput(messageTxt, 0); } @Override public boolean onBufferLongClicked(BuffersDataSource.Buffer b) { if(b == null) return false; ArrayList<String> itemList = new ArrayList<String>(); final String[] items; final BuffersDataSource.Buffer buffer = b; ServersDataSource.Server s = ServersDataSource.getInstance().getServer(buffer.cid); if(buffer.bid != bid) itemList.add("Open"); if(ChannelsDataSource.getInstance().getChannelForBuffer(b.bid) != null) { itemList.add("Leave"); itemList.add("Channel Options"); } else { if(b.type.equalsIgnoreCase("channel")) itemList.add("Join"); else if(b.type.equalsIgnoreCase("console")) { if(s.status.contains("connected") && !s.status.startsWith("dis")) { itemList.add("Disconnect"); } else { itemList.add("Connect"); itemList.add("Delete"); } itemList.add("Edit Connection"); } if(!b.type.equalsIgnoreCase("console")) { if(b.archived == 0) itemList.add("Archive"); else itemList.add("Unarchive"); itemList.add("Delete"); } if(!b.type.equalsIgnoreCase("channel")) { itemList.add("Buffer Options"); } } AlertDialog.Builder builder = new AlertDialog.Builder(this); if(b.type.equalsIgnoreCase("console")) builder.setTitle(s.name); else builder.setTitle(b.name); items = itemList.toArray(new String[itemList.size()]); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int item) { AlertDialog.Builder builder = new AlertDialog.Builder(MessageActivity.this); AlertDialog dialog; if(items[item].equals("Open")) { ServersDataSource.Server s = ServersDataSource.getInstance().getServer(buffer.cid); if(buffer.type.equalsIgnoreCase("console")) { onBufferSelected(buffer.cid, buffer.bid, s.name, buffer.last_seen_eid, buffer.min_eid, buffer.type, 1, buffer.archived, s.status); } else { onBufferSelected(buffer.cid, buffer.bid, buffer.name, buffer.last_seen_eid, buffer.min_eid, buffer.type, 1, buffer.archived, s.status); } } else if(items[item].equals("Join")) { conn.join(buffer.cid, buffer.name, null); } else if(items[item].equals("Leave")) { conn.part(buffer.cid, buffer.name, null); } else if(items[item].equals("Archive")) { conn.archiveBuffer(buffer.cid, buffer.bid); } else if(items[item].equals("Unarchive")) { conn.unarchiveBuffer(buffer.cid, buffer.bid); } else if(items[item].equals("Connect")) { conn.reconnect(buffer.cid); } else if(items[item].equals("Disconnect")) { conn.disconnect(buffer.cid, null); } else if(items[item].equals("Channel Options")) { ChannelOptionsFragment newFragment = new ChannelOptionsFragment(buffer.cid, buffer.bid); newFragment.show(getSupportFragmentManager(), "channeloptions"); } else if(items[item].equals("Buffer Options")) { BufferOptionsFragment newFragment = new BufferOptionsFragment(buffer.cid, buffer.bid, buffer.type); newFragment.show(getSupportFragmentManager(), "bufferoptions"); } else if(items[item].equals("Edit Connection")) { EditConnectionFragment editFragment = new EditConnectionFragment(); editFragment.setCid(buffer.cid); editFragment.show(getSupportFragmentManager(), "editconnection"); } else if(items[item].equals("Delete")) { builder = new AlertDialog.Builder(MessageActivity.this); if(buffer.type.equalsIgnoreCase("console")) builder.setTitle("Delete Connection"); else builder.setTitle("Delete History"); if(buffer.type.equalsIgnoreCase("console")) builder.setMessage("Are you sure you want to remove this connection?"); else if(buffer.type.equalsIgnoreCase("channel")) builder.setMessage("Are you sure you want to clear your history in " + buffer.name + "?"); else builder.setMessage("Are you sure you want to clear your history with " + buffer.name + "?"); builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setNeutralButton("Delete", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(type.equalsIgnoreCase("console")) { conn.deleteServer(buffer.cid); } else { conn.deleteBuffer(buffer.cid, buffer.bid); } dialog.dismiss(); } }); dialog = builder.create(); dialog.setOwnerActivity(MessageActivity.this); dialog.show(); } } }); AlertDialog dialog = builder.create(); dialog.setOwnerActivity(this); dialog.show(); return true; } @Override public boolean onMessageLongClicked(EventsDataSource.Event event) { String from = event.from; if(from == null || from.length() == 0) from = event.nick; UsersDataSource.User user; if(type.equals("channel")) user = UsersDataSource.getInstance().getUser(cid, name, from); else user = UsersDataSource.getInstance().getUser(cid, from); if(user == null && from != null && event.hostmask != null) { user = UsersDataSource.getInstance().new User(); user.nick = from; user.hostmask = event.hostmask; user.mode = ""; } if(user == null && event.html == null) return false; if(event.html != null) showUserPopup(user, ColorFormatter.html_to_spanned(event.html)); else showUserPopup(user, null); return true; } @Override public void onUserSelected(int c, String chan, String nick) { UsersDataSource u = UsersDataSource.getInstance(); if(type.equals("channel")) showUserPopup(u.getUser(cid, name, nick), null); else showUserPopup(u.getUser(cid, nick), null); } @SuppressLint("NewApi") @SuppressWarnings("deprecation") private void showUserPopup(UsersDataSource.User user, Spanned message) { ArrayList<String> itemList = new ArrayList<String>(); final String[] items; final Spanned text_to_copy = message; selected_user = user; AlertDialog.Builder builder = new AlertDialog.Builder(this); if(message != null) itemList.add("Copy Message"); if(selected_user != null) { itemList.add("Whois"); itemList.add("Open"); itemList.add("Mention (double tap)"); itemList.add("Invite to a channel"); itemList.add("Ignore"); if(type.equalsIgnoreCase("channel")) { UsersDataSource.User self_user = UsersDataSource.getInstance().getUser(cid, name, ServersDataSource.getInstance().getServer(cid).nick); if(self_user.mode.contains("q") || self_user.mode.contains("a") || self_user.mode.contains("o")) { if(selected_user.mode.contains("o")) itemList.add("Deop"); else itemList.add("Op"); } if(self_user.mode.contains("q") || self_user.mode.contains("a") || self_user.mode.contains("o") || self_user.mode.contains("h")) { itemList.add("Kick"); itemList.add("Ban"); } } } items = itemList.toArray(new String[itemList.size()]); if(selected_user != null) builder.setTitle(selected_user.nick + "\n(" + selected_user.hostmask + ")"); else builder.setTitle("Message"); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int item) { AlertDialog.Builder builder = new AlertDialog.Builder(MessageActivity.this); LayoutInflater inflater = getLayoutInflater(); ServersDataSource s = ServersDataSource.getInstance(); ServersDataSource.Server server = s.getServer(cid); View view; final TextView prompt; final EditText input; AlertDialog dialog; if(items[item].equals("Copy Message")) { if(Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(text_to_copy); } else { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData.newPlainText("IRCCloud Message",text_to_copy); clipboard.setPrimaryClip(clip); } } else if(items[item].equals("Whois")) { conn.whois(cid, selected_user.nick, null); } else if(items[item].equals("Open")) { BuffersDataSource b = BuffersDataSource.getInstance(); BuffersDataSource.Buffer buffer = b.getBufferByName(cid, selected_user.nick); if(getSupportFragmentManager().findFragmentById(R.id.BuffersList) != null) { if(buffer != null) { onBufferSelected(buffer.cid, buffer.bid, buffer.name, buffer.last_seen_eid, buffer.min_eid, buffer.type, 1, buffer.archived, status); } else { onBufferSelected(cid, -1, selected_user.nick, 0, 0, "conversation", 1, 0, status); } } else { Intent i = new Intent(MessageActivity.this, MessageActivity.class); if(buffer != null) { i.putExtra("cid", buffer.cid); i.putExtra("bid", buffer.bid); i.putExtra("name", buffer.name); i.putExtra("last_seen_eid", buffer.last_seen_eid); i.putExtra("min_eid", buffer.min_eid); i.putExtra("type", buffer.type); i.putExtra("joined", 1); i.putExtra("archived", buffer.archived); i.putExtra("status", status); } else { i.putExtra("cid", cid); i.putExtra("bid", -1); i.putExtra("name", selected_user.nick); i.putExtra("last_seen_eid", 0L); i.putExtra("min_eid", 0L); i.putExtra("type", "conversation"); i.putExtra("joined", 1); i.putExtra("archived", 0); i.putExtra("status", status); } startActivity(i); } } else if(items[item].equals("Mention (double tap)")) { onUserDoubleClicked(selected_user.nick); } else if(items[item].equals("Invite to a channel")) { view = inflater.inflate(R.layout.dialog_textprompt,null); prompt = (TextView)view.findViewById(R.id.prompt); input = (EditText)view.findViewById(R.id.textInput); prompt.setText("Invite " + selected_user.nick + " to a channel"); builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")"); builder.setView(view); builder.setPositiveButton("Invite", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { conn.invite(cid, input.getText().toString(), selected_user.nick); dialog.dismiss(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog = builder.create(); dialog.setOwnerActivity(MessageActivity.this); dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); dialog.show(); } else if(items[item].equals("Ignore")) { view = inflater.inflate(R.layout.dialog_textprompt,null); prompt = (TextView)view.findViewById(R.id.prompt); input = (EditText)view.findViewById(R.id.textInput); input.setText("*!"+selected_user.hostmask); prompt.setText("Ignore messages for " + selected_user.nick + " at this hostmask"); builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")"); builder.setView(view); builder.setPositiveButton("Ignore", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { conn.ignore(cid, input.getText().toString()); dialog.dismiss(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog = builder.create(); dialog.setOwnerActivity(MessageActivity.this); dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); dialog.show(); } else if(items[item].equals("Op")) { conn.mode(cid, name, "+o " + selected_user.nick); } else if(items[item].equals("Deop")) { conn.mode(cid, name, "-o " + selected_user.nick); } else if(items[item].equals("Kick")) { view = inflater.inflate(R.layout.dialog_textprompt,null); prompt = (TextView)view.findViewById(R.id.prompt); input = (EditText)view.findViewById(R.id.textInput); prompt.setText("Give a reason for kicking"); builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")"); builder.setView(view); builder.setPositiveButton("Kick", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { conn.kick(cid, name, selected_user.nick, input.getText().toString()); dialog.dismiss(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog = builder.create(); dialog.setOwnerActivity(MessageActivity.this); dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); dialog.show(); } else if(items[item].equals("Ban")) { view = inflater.inflate(R.layout.dialog_textprompt,null); prompt = (TextView)view.findViewById(R.id.prompt); input = (EditText)view.findViewById(R.id.textInput); input.setText("*!"+selected_user.hostmask); prompt.setText("Add a banmask for " + selected_user.nick); builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")"); builder.setView(view); builder.setPositiveButton("Ban", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { conn.mode(cid, name, "+b " + input.getText().toString()); dialog.dismiss(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog = builder.create(); dialog.setOwnerActivity(MessageActivity.this); dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); dialog.show(); } dialogInterface.dismiss(); } }); AlertDialog dialog = builder.create(); dialog.setOwnerActivity(this); dialog.show(); } @Override public void onBufferSelected(int cid, int bid, String name, long last_seen_eid, long min_eid, String type, int joined, int archived, String status) { if(scrollView != null) { if(buffersListView.getWidth() > 0) scrollView.smoothScrollTo(buffersListView.getWidth(), 0); upView.setVisibility(View.VISIBLE); } if(bid != this.bid || this.cid == -1) { if(bid != -1 && conn != null && conn.getUserInfo() != null) conn.getUserInfo().last_selected_bid = bid; for(int i = 0; i < backStack.size(); i++) { if(backStack.get(i) == this.bid) backStack.remove(i); } if(this.bid >= 0) backStack.add(0, this.bid); this.cid = cid; this.bid = bid; this.name = name; this.type = type; this.joined = joined; this.archived = archived; this.status = status; title.setText(name); getSupportActionBar().setTitle(name); update_subtitle(); Bundle b = new Bundle(); b.putInt("cid", cid); b.putInt("bid", bid); b.putLong("last_seen_eid", last_seen_eid); b.putLong("min_eid", min_eid); b.putString("name", name); b.putString("type", type); BuffersListFragment blf = (BuffersListFragment)getSupportFragmentManager().findFragmentById(R.id.BuffersList); MessageViewFragment mvf = (MessageViewFragment)getSupportFragmentManager().findFragmentById(R.id.messageViewFragment); UsersListFragment ulf = (UsersListFragment)getSupportFragmentManager().findFragmentById(R.id.usersListFragment); if(blf != null) blf.setSelectedBid(bid); if(mvf != null) mvf.setArguments(b); if(ulf != null) ulf.setArguments(b); AlphaAnimation anim = new AlphaAnimation(1, 0); anim.setDuration(200); anim.setFillAfter(true); mvf.getListView().startAnimation(anim); ulf.getListView().startAnimation(anim); shouldFadeIn = true; updateUsersListFragmentVisibility(); invalidateOptionsMenu(); if(showNotificationsTask != null) showNotificationsTask.cancel(true); showNotificationsTask = new ShowNotificationsTask(); showNotificationsTask.execute(bid); if(upView != null) new RefreshUpIndicatorTask().execute((Void)null); } if(cid != -1) { if(scrollView != null) scrollView.setEnabled(true); messageTxt.setEnabled(true); } } public void showUpButton(boolean show) { if(upView != null) { if(show) { upView.setVisibility(View.VISIBLE); } else { upView.setVisibility(View.INVISIBLE); } } } @Override public void onMessageViewReady() { if(shouldFadeIn) { MessageViewFragment mvf = (MessageViewFragment)getSupportFragmentManager().findFragmentById(R.id.messageViewFragment); UsersListFragment ulf = (UsersListFragment)getSupportFragmentManager().findFragmentById(R.id.usersListFragment); AlphaAnimation anim = new AlphaAnimation(0, 1); anim.setDuration(200); anim.setFillAfter(true); mvf.getListView().startAnimation(anim); ulf.getListView().startAnimation(anim); shouldFadeIn = false; } } @Override public void addButtonPressed(int cid) { if(scrollView != null) scrollView.scrollTo(0,0); } }
package gov.nih.nci.eagle.util; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumSet; import java.util.List; import java.util.Set; import gov.nih.nci.caintegrator.application.lists.ListSubType; import gov.nih.nci.caintegrator.application.lists.ListType; /** * TARGETListFilter "filters" the kind of lists expected in this * project by type and pertaining subtypes. * @author rossok * */ public class EAGLEListFilter{ public static ListType[] values() { ListType[] lsa = {ListType.PatientDID}; //no duplicates here return lsa; } public static List<ListSubType> getSubTypesForType(ListType lt) { //control the mapping between which subtypes are associated with a primary type //for example: when adding a new "Reporter List", the app needs to know //which subtypes "Reporter" has so we can add a "IMAGE CLONE REPORTER" list ArrayList<ListSubType> lsta = new ArrayList(); if(lt == ListType.Reporter){ //list the reporter subtypes here and return them //lsta.add(ListSubType.PROBE_SET); lsta.add(ListSubType.IMAGE_CLONE); lsta.add(ListSubType.DBSNP); //lsta.add(ListSubType.SNP_PROBESET); } else if(lt == ListType.Gene){ //ListSubType[] lsta = {ListSubType.GENBANK_ACCESSION_NUMBER, ListSubType.GENESYMBOL, ListSubType.LOCUS_LINK}; //lsta.add(ListSubType.GENBANK_ACCESSION_NUMBER); lsta.add(ListSubType.GENESYMBOL); // lsta.add(ListSubType.LOCUS_LINK); } // Default, Custom, IMAGE_CLONE, PROBE_SET, SNPProbeSet, DBSNP, GENBANK_ACCESSION_NUMBER, GENESYMBOL, LOCUS_LINK; return lsta; } }
package com.jakewharton.snakewallpaper; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import android.app.Activity; import android.net.Uri; import android.os.Bundle; import android.webkit.WebView; /** * Activity which displays a web view with the contents loaded from an asset. * * @author Jake Wharton */ public class About extends Activity { /** * Filename of the asset to load. */ public static final String EXTRA_FILENAME = "filename"; /** * Title of the activity. */ public static final String EXTRA_TITLE = "title"; /** * Newline character to use between asset lines. */ private static final char NEWLINE = '\n'; /** * Error message displayed when the asset fails to load. */ private static final String ERROR = "Failed to load the file from assets."; /** * Encoding of the assets. */ private static final String MIME_TYPE = "text/html"; /** * Character set of the assets. */ private static final String ENCODING = "utf-8"; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final StringBuffer content = new StringBuffer(); try { //Load entire about plain text from asset final BufferedReader about = new BufferedReader(new InputStreamReader(this.getAssets().open(this.getIntent().getStringExtra(About.EXTRA_FILENAME)))); String data; while ((data = about.readLine()) != null) { content.append(data); content.append(About.NEWLINE); } } catch (IOException e) { e.printStackTrace(); content.append(About.ERROR); } this.setTitle(this.getIntent().getStringExtra(About.EXTRA_TITLE)); //Put text into layout final WebView view = new WebView(this); view.loadData(Uri.encode(content.toString()), About.MIME_TYPE, About.ENCODING); this.setContentView(view); } }
package com.jensdriller.libs.undobar; import android.app.Activity; import android.os.Handler; import android.os.Parcelable; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import com.nineoldandroids.animation.Animator; import com.nineoldandroids.animation.AnimatorListenerAdapter; import com.nineoldandroids.view.ViewPropertyAnimator; import static com.nineoldandroids.view.ViewHelper.setAlpha; import static com.nineoldandroids.view.ViewPropertyAnimator.animate; public final class UndoBar { /** * Listener for actions of the undo bar. */ public static interface Listener { /** * Will be fired when the undo bar disappears without being actioned. */ void onHide(); /** * Will be fired when the undo button is pressed. */ void onUndo(Parcelable token); } /** * Default duration in milliseconds the undo bar will be displayed. */ public static final int DEFAULT_DURATION = 5000; /** * Default duration in milliseconds of the undo bar show and hide animation. */ public static final int DEFAULT_ANIMATION_DURATION = 300; private final Activity mActivity; private final UndoBarView mView; private final ViewPropertyAnimator mViewAnimator; private final Handler mHandler = new Handler(); private final Runnable mHideRunnable = new Runnable() { @Override public void run() { hide(true); safelyNotifyOnHide(); } }; private final OnClickListener mOnUndoClickListener = new OnClickListener() { @Override public void onClick(View v) { hide(true); safelyNotifyOnUndo(); } }; private Listener mUndoListener; private Parcelable mUndoToken; private CharSequence mUndoMessage; private int mDuration = DEFAULT_DURATION; private int mAnimationDuration = DEFAULT_ANIMATION_DURATION; public UndoBar(Activity activity) { mActivity = activity; mView = getView(activity); mView.setOnUndoClickListener(mOnUndoClickListener); mViewAnimator = animate(mView); hide(false); } /** * Sets the message to be displayed on the left of the undo bar. */ public void setMessage(CharSequence message) { mUndoMessage = message; } /** * Sets the message to be displayed on the left of the undo bar. */ public void setMessage(int messageResId) { mUndoMessage = mActivity.getString(messageResId); } /** * Sets the {@link Listener UndoBar.Listener}. */ public void setListener(Listener undoListener) { mUndoListener = undoListener; } /** * Sets a {@link Parcelable} token to the undo bar which will be returned in * the {@link Listener UndoBar.Listener}. */ public void setUndoToken(Parcelable undoToken) { mUndoToken = undoToken; } /** * Sets the duration the undo bar will be shown.<br> * Default is {@link #DEFAULT_DURATION}. * * @param duration * in milliseconds */ public void setDuration(int duration) { mDuration = duration; } /** * Sets the duration of the animation for showing and hiding the undo bar.<br> * Default is {@link #DEFAULT_ANIMATION_DURATION}. * * @param animationDuration * in milliseconds */ public void setAnimationDuration(int animationDuration) { mAnimationDuration = animationDuration; } /** * Calls {@link #show(boolean)} with {@code shouldAnimate = true}. */ public void show() { show(true); } /** * Shows the {@link UndoBar}. * * @param shouldAnimate * whether the {@link UndoBar} should animate in */ public void show(boolean shouldAnimate) { mView.setMessage(mUndoMessage); mHandler.removeCallbacks(mHideRunnable); mHandler.postDelayed(mHideRunnable, mDuration); mView.setVisibility(View.VISIBLE); if (shouldAnimate) { animateIn(); } else { setAlpha(mView, 1); } } /** * Calls {@link #hide(boolean)} with {@code shouldAnimate = true}. */ public void hide() { hide(true); } /** * Hides the {@link UndoBar}. * * @param shouldAnimate * whether the {@link UndoBar} should animate out */ public void hide(boolean shouldAnimate) { mHandler.removeCallbacks(mHideRunnable); if (shouldAnimate) { animateOut(); } else { setAlpha(mView, 0); mView.setVisibility(View.GONE); mUndoMessage = null; mUndoToken = null; } } /** * Performs the actual show animation. */ private void animateIn() { mViewAnimator.cancel(); mViewAnimator.alpha(1) .setDuration(mAnimationDuration) .setListener(null); } /** * Performs the actual hide animation. */ private void animateOut() { mViewAnimator.cancel(); mViewAnimator.alpha(0) .setDuration(mAnimationDuration) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mView.setVisibility(View.GONE); mUndoMessage = null; mUndoToken = null; } }); } /** * Checks if the undo bar is currently visible. * * @return {@code true} if visible, {@code false} otherwise */ public boolean isVisible() { return mView.getVisibility() == View.VISIBLE; } /** * Notifies listener if available. */ private void safelyNotifyOnHide() { if (mUndoListener != null) { mUndoListener.onHide(); } } /** * Notifies listener if available. */ private void safelyNotifyOnUndo() { if (mUndoListener != null) { mUndoListener.onUndo(mUndoToken); } } /** * Checks if there is already an {@link UndoBarView} instance added to the * given {@link Activity}.<br> * If {@code true}, returns that instance.<br> * If {@code false}, inflates a new {@link UndoBarView} and returns it. */ private UndoBarView getView(Activity activity) { ViewGroup rootView = (ViewGroup) activity.findViewById(android.R.id.content); UndoBarView undoBarView = (UndoBarView) rootView.findViewById(R.id.undoBar); if (undoBarView == null) { undoBarView = (UndoBarView) LayoutInflater.from(activity).inflate(R.layout.undo_bar, rootView, false); rootView.addView(undoBarView); } return undoBarView; } public static class Builder { private final Activity mActivity; private CharSequence mUndoMessage; private Listener mUndoListener; private Parcelable mUndoToken; private int mDuration = DEFAULT_DURATION; private int mAnimationDuration = DEFAULT_ANIMATION_DURATION; /** * Constructor using the {@link Activity} in which the undo bar will be * displayed */ public Builder(Activity activity) { mActivity = activity; } /** * Sets the message to be displayed on the left of the undo bar. */ public Builder setMessage(int messageResId) { mUndoMessage = mActivity.getString(messageResId); return this; } /** * Sets the message to be displayed on the left of the undo bar. */ public Builder setMessage(CharSequence message) { mUndoMessage = message; return this; } /** * Sets the {@link Listener UndoBar.Listener}. */ public Builder setListener(Listener undoListener) { mUndoListener = undoListener; return this; } /** * Sets a {@link Parcelable} token to the undo bar which will be * returned in the {@link Listener UndoBar.Listener}. */ public Builder setUndoToken(Parcelable undoToken) { mUndoToken = undoToken; return this; } /** * Sets the duration the undo bar will be shown.<br> * Default is {@link #DEFAULT_DURATION}. * * @param duration * in milliseconds */ public Builder setDuration(int duration) { mDuration = duration; return this; } /** * Sets the duration of the animation for showing and hiding the undo * bar.<br> * Default is {@link #DEFAULT_ANIMATION_DURATION}. * * @param animationDuration * in milliseconds */ public Builder setAnimationDuration(int animationDuration) { mAnimationDuration = animationDuration; return this; } /** * Creates an {@link UndoBar} instance with this Builder's * configuration. */ public UndoBar create() { UndoBar undoBarController = new UndoBar(mActivity); undoBarController.setListener(mUndoListener); undoBarController.setUndoToken(mUndoToken); undoBarController.setMessage(mUndoMessage); undoBarController.setDuration(mDuration); undoBarController.setAnimationDuration(mAnimationDuration); return undoBarController; } /** * Calls {@link #show(boolean)} with {@code shouldAnimate = true}. */ public void show() { show(true); } /** * Shows the {@link UndoBar} with this Builder's configuration. * * @param shouldAnimate * whether the {@link UndoBar} should animate in and out. */ public void show(boolean shouldAnimate) { create().show(shouldAnimate); } } }
package com.jetbrains.crucible.ui; import com.intellij.ide.util.treeView.AbstractTreeBuilder; import com.intellij.openapi.project.Project; import com.intellij.ui.treeStructure.SimpleNode; import com.intellij.ui.treeStructure.SimpleTreeStructure; import com.jetbrains.crucible.model.Comment; import com.jetbrains.crucible.ui.toolWindow.CrucibleTreeStructure; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import java.awt.*; import java.util.ArrayList; import java.util.List; /** * User: ktisha */ public class ReviewForm extends JTree { private static final int ourBalloonWidth = 400; private static final int ourBalloonHeight = 400; public ReviewForm(final Comment comment, final Project project, boolean editable) { final CommentNode root = new CommentNode(comment); SimpleTreeStructure structure = new CrucibleTreeStructure(project, root); final DefaultTreeModel model = new DefaultTreeModel(new DefaultMutableTreeNode()); AbstractTreeBuilder reviewTreeBuilder = new AbstractTreeBuilder(this, model, structure, null); invalidate(); setPreferredSize(new Dimension(ourBalloonWidth, ourBalloonHeight)); } class CommentNode extends SimpleNode { private final Comment myComment; CommentNode(Comment comment) { myComment = comment; } @Override public String getName() { return myComment.getAuthor() + " : " + myComment.getMessage(); } @Override public SimpleNode[] getChildren() { final List<Comment> replies = myComment.getReplies(); final List<SimpleNode> children = new ArrayList<SimpleNode>(); for (Comment reply : replies) { children.add(new CommentNode(reply)); } return children.toArray(new SimpleNode[children.size()]); } } }
package com.hubspot.singularity.mesos; import com.google.common.collect.HashMultiset; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.common.collect.Multiset; import com.google.inject.Inject; import com.google.inject.name.Named; import com.hubspot.mesos.json.MesosMasterAgentObject; import com.hubspot.mesos.json.MesosMasterStateObject; import com.hubspot.singularity.AgentMatchState; import com.hubspot.singularity.AgentPlacement; import com.hubspot.singularity.MachineState; import com.hubspot.singularity.RequestUtilization; import com.hubspot.singularity.SingularityAgent; import com.hubspot.singularity.SingularityMachineAbstraction; import com.hubspot.singularity.SingularityPendingRequest.PendingType; import com.hubspot.singularity.SingularityPendingTask; import com.hubspot.singularity.SingularityPendingTaskId; import com.hubspot.singularity.SingularityRack; import com.hubspot.singularity.SingularityRequest; import com.hubspot.singularity.SingularityTask; import com.hubspot.singularity.SingularityTaskId; import com.hubspot.singularity.SingularityTaskRequest; import com.hubspot.singularity.config.OverrideConfiguration; import com.hubspot.singularity.config.SingularityConfiguration; import com.hubspot.singularity.data.AbstractMachineManager; import com.hubspot.singularity.data.AgentManager; import com.hubspot.singularity.data.InactiveAgentManager; import com.hubspot.singularity.data.RackManager; import com.hubspot.singularity.data.TaskManager; import com.hubspot.singularity.mesos.SingularityAgentAndRackHelper.CpuMemoryPreference; import com.hubspot.singularity.scheduler.SingularityLeaderCache; import com.hubspot.singularity.sentry.SingularityExceptionNotifier; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import javax.inject.Singleton; import org.apache.mesos.v1.Protos.AgentID; import org.apache.mesos.v1.Protos.Offer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public class SingularityAgentAndRackManager { private static final Logger LOG = LoggerFactory.getLogger( SingularityAgentAndRackManager.class ); private final SingularityConfiguration configuration; private final SingularityExceptionNotifier exceptionNotifier; private final RackManager rackManager; private final AgentManager agentManager; private final TaskManager taskManager; private final InactiveAgentManager inactiveAgentManager; private final SingularityAgentAndRackHelper agentAndRackHelper; private final AtomicInteger activeAgentsLost; private final SingularityLeaderCache leaderCache; private final OverrideConfiguration overrides; @Inject SingularityAgentAndRackManager( SingularityAgentAndRackHelper agentAndRackHelper, SingularityConfiguration configuration, OverrideConfiguration overrides, SingularityExceptionNotifier exceptionNotifier, RackManager rackManager, AgentManager agentManager, TaskManager taskManager, InactiveAgentManager inactiveAgentManager, @Named( SingularityMesosModule.ACTIVE_AGENTS_LOST_COUNTER ) AtomicInteger activeAgentsLost, SingularityLeaderCache leaderCache ) { this.configuration = configuration; this.overrides = overrides; this.exceptionNotifier = exceptionNotifier; this.agentAndRackHelper = agentAndRackHelper; this.rackManager = rackManager; this.agentManager = agentManager; this.taskManager = taskManager; this.inactiveAgentManager = inactiveAgentManager; this.activeAgentsLost = activeAgentsLost; this.leaderCache = leaderCache; } AgentMatchState doesOfferMatch( SingularityOfferHolder offerHolder, SingularityTaskRequest taskRequest, List<SingularityTaskId> activeTaskIdsForRequest, boolean isPreemptibleTask, RequestUtilization requestUtilization ) { final String host = offerHolder.getHostname(); final String rackId = offerHolder.getRackId(); final String agentId = offerHolder.getAgentId(); Optional<SingularityAgent> maybeAgent = agentManager.getObject(agentId); if (!maybeAgent.isPresent()) { return AgentMatchState.RESOURCES_DO_NOT_MATCH; } final MachineState currentState = maybeAgent.get().getCurrentState().getState(); if (currentState == MachineState.FROZEN) { return AgentMatchState.AGENT_FROZEN; } if (currentState.isDecommissioning()) { return AgentMatchState.AGENT_DECOMMISSIONING; } final MachineState currentRackState = rackManager .getObject(rackId) .get() .getCurrentState() .getState(); if (currentRackState == MachineState.FROZEN) { return AgentMatchState.RACK_FROZEN; } if (currentRackState.isDecommissioning()) { return AgentMatchState.RACK_DECOMMISSIONING; } if ( !taskRequest .getRequest() .getRackAffinity() .orElse(Collections.emptyList()) .isEmpty() ) { if (!taskRequest.getRequest().getRackAffinity().get().contains(rackId)) { LOG.trace( "Task {} requires a rack in {} (current rack {})", taskRequest.getPendingTask().getPendingTaskId(), taskRequest.getRequest().getRackAffinity().get(), rackId ); return AgentMatchState.RACK_AFFINITY_NOT_MATCHING; } } if (!isAttributesMatch(offerHolder, taskRequest, isPreemptibleTask)) { return AgentMatchState.AGENT_ATTRIBUTES_DO_NOT_MATCH; } else if ( !areAttributeMinimumsFeasible(offerHolder, taskRequest, activeTaskIdsForRequest) ) { return AgentMatchState.AGENT_ATTRIBUTES_DO_NOT_MATCH; } final AgentPlacement agentPlacement = maybeOverrideAgentPlacement( taskRequest .getRequest() .getAgentPlacement() .orElse(configuration.getDefaultAgentPlacement()) ); if ( !taskRequest.getRequest().isRackSensitive() && agentPlacement == AgentPlacement.GREEDY ) { // todo: account for this or let this behavior continue? return AgentMatchState.NOT_RACK_OR_AGENT_PARTICULAR; } final int numDesiredInstances = taskRequest.getRequest().getInstancesSafe(); boolean allowBounceToSameHost = isAllowBounceToSameHost(taskRequest.getRequest()); int activeRacksWithCapacityCount = getActiveRacksWithCapacityCount(); Multiset<String> countPerRack = HashMultiset.create(activeRacksWithCapacityCount); double numOnAgent = 0; double numCleaningOnAgent = 0; double numFromSameBounceOnAgent = 0; double numOtherDeploysOnAgent = 0; boolean taskLaunchedFromBounceWithActionId = taskRequest.getPendingTask().getPendingTaskId().getPendingType() == PendingType.BOUNCE && taskRequest.getPendingTask().getActionId().isPresent(); final String sanitizedHost = offerHolder.getSanitizedHost(); final String sanitizedRackId = offerHolder.getSanitizedRackId(); Collection<SingularityTaskId> cleaningTasks = leaderCache.getCleanupTaskIds(); for (SingularityTaskId taskId : activeTaskIdsForRequest) { if ( !cleaningTasks.contains(taskId) && !taskManager.isKilledTask(taskId) && taskRequest.getDeploy().getId().equals(taskId.getDeployId()) ) { countPerRack.add(taskId.getSanitizedRackId()); } if (!taskId.getSanitizedHost().equals(sanitizedHost)) { continue; } if (taskRequest.getDeploy().getId().equals(taskId.getDeployId())) { if (cleaningTasks.contains(taskId)) { numCleaningOnAgent++; } else { numOnAgent++; } if (taskLaunchedFromBounceWithActionId) { Optional<SingularityTask> maybeTask = taskManager.getTask(taskId); boolean errorInTaskData = false; if (maybeTask.isPresent()) { SingularityPendingTask pendingTask = maybeTask .get() .getTaskRequest() .getPendingTask(); if (pendingTask.getPendingTaskId().getPendingType() == PendingType.BOUNCE) { if (pendingTask.getActionId().isPresent()) { if ( pendingTask .getActionId() .get() .equals(taskRequest.getPendingTask().getActionId().get()) ) { numFromSameBounceOnAgent++; } } else { // No actionId present on bounce, fall back to more restrictive placement strategy errorInTaskData = true; } } } else { // Could not find appropriate task data, fall back to more restrictive placement strategy errorInTaskData = true; } if (errorInTaskData) { allowBounceToSameHost = false; } } } else { numOtherDeploysOnAgent++; } } if ( overrides.isAllowRackSensitivity() && taskRequest.getRequest().isRackSensitive() ) { final boolean isRackOk = isRackOk( countPerRack, sanitizedRackId, numDesiredInstances, taskRequest.getRequest().getId(), agentId, host, numCleaningOnAgent ); if (!isRackOk) { return AgentMatchState.RACK_SATURATED; } } switch (agentPlacement) { case SEPARATE: case SEPARATE_BY_DEPLOY: case SPREAD_ALL_SLAVES: case SPREAD_ALL_AGENTS: if (allowBounceToSameHost && taskLaunchedFromBounceWithActionId) { if (numFromSameBounceOnAgent > 0) { LOG.trace( "Rejecting SEPARATE task {} from agent {} ({}) due to numFromSameBounceOnAgent {}", taskRequest.getRequest().getId(), agentId, host, numFromSameBounceOnAgent ); return AgentMatchState.AGENT_SATURATED; } } else { if (numOnAgent > 0 || numCleaningOnAgent > 0) { LOG.trace( "Rejecting {} task {} from agent {} ({}) due to numOnAgent {} numCleaningOnAgent {}", agentPlacement.name(), taskRequest.getRequest().getId(), agentId, host, numOnAgent, numCleaningOnAgent ); return AgentMatchState.AGENT_SATURATED; } } break; case SEPARATE_BY_REQUEST: if (numOnAgent > 0 || numCleaningOnAgent > 0 || numOtherDeploysOnAgent > 0) { LOG.trace( "Rejecting SEPARATE_BY_REQUEST task {} from agent {} ({}) due to numOnAgent {} numCleaningOnAgent {} numOtherDeploysOnAgent {}", taskRequest.getRequest().getId(), agentId, host, numOnAgent, numCleaningOnAgent, numOtherDeploysOnAgent ); return AgentMatchState.AGENT_SATURATED; } break; case OPTIMISTIC: // If no tasks are active for this request yet, we can fall back to greedy. if (activeTaskIdsForRequest.size() > 0) { Collection<SingularityPendingTaskId> pendingTasksForRequestClusterwide = leaderCache.getPendingTaskIdsForRequest( taskRequest.getRequest().getId() ); Set<String> currentHostsForRequest = activeTaskIdsForRequest .stream() .map(SingularityTaskId::getSanitizedHost) .collect(Collectors.toSet()); final double numPerAgent = activeTaskIdsForRequest.size() / (double) currentHostsForRequest.size(); final double leniencyCoefficient = configuration.getPlacementLeniency(); final double threshold = numPerAgent * (1 + (pendingTasksForRequestClusterwide.size() * leniencyCoefficient)); final boolean isOk = numOnAgent <= threshold; if (!isOk) { LOG.trace( "Rejecting OPTIMISTIC task {} from agent {} ({}) because numOnAgent {} violates threshold {} (based on active tasks for request {}, current hosts for request {}, pending tasks for request {})", taskRequest.getRequest().getId(), agentId, host, numOnAgent, threshold, activeTaskIdsForRequest.size(), currentHostsForRequest.size(), pendingTasksForRequestClusterwide.size() ); return AgentMatchState.AGENT_SATURATED; } } break; case GREEDY: } if (isPreferred(offerHolder, taskRequest, requestUtilization)) { LOG.debug("Agent {} is preferred", offerHolder.getHostname()); return AgentMatchState.PREFERRED_AGENT; } return AgentMatchState.OK; } private boolean isPreferred( SingularityOfferHolder offerHolder, SingularityTaskRequest taskRequest, RequestUtilization requestUtilization ) { return ( isPreferredByAllowedAttributes(offerHolder, taskRequest) || isPreferredByCpuMemory(offerHolder, requestUtilization) ); } private AgentPlacement maybeOverrideAgentPlacement(AgentPlacement placement) { return overrides.getAgentPlacementOverride().orElse(placement); } private boolean isPreferredByAllowedAttributes( SingularityOfferHolder offerHolder, SingularityTaskRequest taskRequest ) { Map<String, String> allowedAttributes = getAllowedAttributes(taskRequest); Map<String, String> hostAttributes = offerHolder.getTextAttributes(); boolean containsAtLeastOneMatchingAttribute = agentAndRackHelper.containsAtLeastOneMatchingAttribute( hostAttributes, allowedAttributes ); LOG.trace( "is agent {} by allowed attributes? {}", offerHolder.getHostname(), containsAtLeastOneMatchingAttribute ); return containsAtLeastOneMatchingAttribute; } public boolean isPreferredByCpuMemory( SingularityOfferHolder offerHolder, RequestUtilization requestUtilization ) { if (requestUtilization != null) { CpuMemoryPreference cpuMemoryPreference = agentAndRackHelper.getCpuMemoryPreferenceForAgent( offerHolder ); CpuMemoryPreference cpuMemoryPreferenceForRequest = agentAndRackHelper.getCpuMemoryPreferenceForRequest( requestUtilization ); LOG.trace( "CpuMemoryPreference for agent {} is {}, CpuMemoryPreference for request {} is {}", offerHolder.getHostname(), cpuMemoryPreference.toString(), requestUtilization.getRequestId(), cpuMemoryPreferenceForRequest.toString() ); return cpuMemoryPreference == cpuMemoryPreferenceForRequest; } return false; } private boolean isAttributesMatch( SingularityOfferHolder offer, SingularityTaskRequest taskRequest, boolean isPreemptibleTask ) { final Map<String, String> requiredAttributes = getRequiredAttributes(taskRequest); final Map<String, String> allowedAttributes = getAllowedAttributes(taskRequest); if (offer.hasReservedAgentAttributes()) { Map<String, String> reservedAgentAttributes = offer.getReservedAgentAttributes(); Map<String, String> mergedAttributes = new HashMap<>(); mergedAttributes.putAll(requiredAttributes); mergedAttributes.putAll(allowedAttributes); if (!mergedAttributes.isEmpty()) { if ( !agentAndRackHelper.containsAllAttributes( mergedAttributes, reservedAgentAttributes ) ) { LOG.trace( "Agents with attributes {} are reserved for matching tasks. Task with attributes {} does not match", reservedAgentAttributes, mergedAttributes ); return false; } } else { LOG.trace( "Agents with attributes {} are reserved for matching tasks. No attributes specified for task {}", reservedAgentAttributes, taskRequest.getPendingTask().getPendingTaskId().getId() ); return false; } } if (!configuration.getPreemptibleTasksOnlyMachineAttributes().isEmpty()) { if ( agentAndRackHelper.containsAllAttributes( offer.getTextAttributes(), configuration.getPreemptibleTasksOnlyMachineAttributes() ) && !isPreemptibleTask ) { LOG.debug("Host {} is reserved for preemptible tasks", offer.getHostname()); return false; } } if (!requiredAttributes.isEmpty()) { if ( !agentAndRackHelper.containsAllAttributes( offer.getTextAttributes(), requiredAttributes ) ) { LOG.trace( "Task requires agent with attributes {}, (agent attributes are {})", requiredAttributes, offer.getTextAttributes() ); return false; } } return true; } private Map<String, String> getRequiredAttributes(SingularityTaskRequest taskRequest) { if (!taskRequest.getPendingTask().getRequiredAgentAttributeOverrides().isEmpty()) { return taskRequest.getPendingTask().getRequiredAgentAttributeOverrides(); } else if ( ( taskRequest.getRequest().getRequiredAgentAttributes().isPresent() && !taskRequest.getRequest().getRequiredAgentAttributes().get().isEmpty() ) ) { return taskRequest.getRequest().getRequiredAgentAttributes().get(); } return new HashMap<>(); } private Map<String, String> getAllowedAttributes(SingularityTaskRequest taskRequest) { if (!taskRequest.getPendingTask().getAllowedAgentAttributeOverrides().isEmpty()) { return taskRequest.getPendingTask().getAllowedAgentAttributeOverrides(); } else if ( ( taskRequest.getRequest().getAllowedAgentAttributes().isPresent() && !taskRequest.getRequest().getAllowedAgentAttributes().get().isEmpty() ) ) { return taskRequest.getRequest().getAllowedAgentAttributes().get(); } return new HashMap<>(); } private boolean areAttributeMinimumsFeasible( SingularityOfferHolder offerHolder, SingularityTaskRequest taskRequest, List<SingularityTaskId> activeTaskIdsForRequest ) { if (!taskRequest.getRequest().getAgentAttributeMinimums().isPresent()) { return true; } Map<String, String> offerAttributes = agentManager .getObject(offerHolder.getAgentId()) .get() .getAttributes(); Integer numDesiredInstances = taskRequest.getRequest().getInstancesSafe(); Integer numActiveInstances = activeTaskIdsForRequest.size(); for (Entry<String, Map<String, Integer>> keyEntry : taskRequest .getRequest() .getAgentAttributeMinimums() .get() .entrySet()) { String attrKey = keyEntry.getKey(); for (Entry<String, Integer> valueEntry : keyEntry.getValue().entrySet()) { Integer percentInstancesWithAttr = valueEntry.getValue(); Integer minInstancesWithAttr = Math.max( 1, (int) ((percentInstancesWithAttr / 100.0) * numDesiredInstances) ); if ( offerAttributes.containsKey(attrKey) && offerAttributes.get(attrKey).equals(valueEntry.getKey()) ) { // Accepting this offer would add an instance of the needed attribute, so it's okay. continue; } // Would accepting this offer prevent meeting the necessary attribute in the future? long numInstancesWithAttr = getNumInstancesWithAttribute( activeTaskIdsForRequest, attrKey, valueEntry.getKey() ); long numInstancesWithoutAttr = numActiveInstances - numInstancesWithAttr + 1; long maxPotentialInstancesWithAttr = numDesiredInstances - numInstancesWithoutAttr; if (maxPotentialInstancesWithAttr < minInstancesWithAttr) { return false; } } } return true; } private long getNumInstancesWithAttribute( List<SingularityTaskId> taskIds, String attrKey, String attrValue ) { return taskIds .stream() .map( id -> leaderCache .getAgent( taskManager.getTask(id).get().getMesosTask().getAgentId().getValue() ) .get() .getAttributes() .get(attrKey) ) .filter(Objects::nonNull) .filter(x -> x.equals(attrValue)) .count(); } private boolean isAllowBounceToSameHost(SingularityRequest request) { if (request.getAllowBounceToSameHost().isPresent()) { return request.getAllowBounceToSameHost().get(); } else { return configuration.isAllowBounceToSameHost(); } } private boolean isRackOk( Multiset<String> countPerRack, String sanitizedRackId, int numDesiredInstances, String requestId, String agentId, String host, double numCleaningOnAgent ) { int racksAccountedFor = countPerRack.elementSet().size(); int activeRacksWithCapacityCount = getActiveRacksWithCapacityCount(); double numPerRack = numDesiredInstances / (double) activeRacksWithCapacityCount; if (racksAccountedFor < activeRacksWithCapacityCount) { if (countPerRack.count(sanitizedRackId) < Math.max(numPerRack, 1)) { return true; } } else { Integer rackMin = null; for (String rackId : countPerRack.elementSet()) { if (rackMin == null || countPerRack.count(rackId) < rackMin) { rackMin = countPerRack.count(rackId); } } if (rackMin == null || rackMin < (int) numPerRack) { if (countPerRack.count(sanitizedRackId) < (int) numPerRack) { return true; } } else if (countPerRack.count(sanitizedRackId) < numPerRack) { return true; } } LOG.trace( "Rejecting RackSensitive task {} from agent {} ({}) due to numOnRack {} and cleaningOnAgent {}", requestId, agentId, host, countPerRack.count(sanitizedRackId), numCleaningOnAgent ); return false; } void agentLost(AgentID agentIdObj) { final String agentId = agentIdObj.getValue(); Optional<SingularityAgent> agent = agentManager.getObject(agentId); if (agent.isPresent()) { MachineState previousState = agent.get().getCurrentState().getState(); agentManager.changeState( agent.get(), MachineState.DEAD, Optional.empty(), Optional.empty() ); if (configuration.getDisasterDetection().isEnabled()) { updateDisasterCounter(previousState); } checkRackAfterAgentLoss(agent.get()); } else { LOG.warn("Lost a agent {}, but didn't know about it", agentId); } } private void updateDisasterCounter(MachineState previousState) { if (previousState == MachineState.ACTIVE) { activeAgentsLost.getAndIncrement(); } } private void checkRackAfterAgentLoss(SingularityAgent lostAgent) { List<SingularityAgent> agents = agentManager.getObjectsFiltered(MachineState.ACTIVE); int numInRack = 0; for (SingularityAgent agent : agents) { if (agent.getRackId().equals(lostAgent.getRackId())) { numInRack++; } } LOG.info("Found {} agents left in rack {}", numInRack, lostAgent.getRackId()); if (numInRack == 0) { rackManager.changeState( lostAgent.getRackId(), MachineState.DEAD, Optional.empty(), Optional.empty() ); } } public void loadAgentsAndRacksFromMaster( MesosMasterStateObject state, boolean isStartup ) { Map<String, SingularityAgent> activeAgentsById = agentManager.getObjectsByIdForState( MachineState.ACTIVE ); Map<String, SingularityRack> activeRacksById = rackManager.getObjectsByIdForState( MachineState.ACTIVE ); Map<String, SingularityRack> remainingActiveRacks = Maps.newHashMap(activeRacksById); int agents = 0; int racks = 0; for (MesosMasterAgentObject agentJsonObject : state.getAgents()) { String agentId = agentJsonObject.getId(); String rackId = agentAndRackHelper.getRackId(agentJsonObject.getAttributes()); Map<String, String> textAttributes = agentAndRackHelper.getTextAttributes( agentJsonObject.getAttributes() ); String host = agentAndRackHelper.getMaybeTruncatedHost( agentJsonObject.getHostname() ); if (activeAgentsById.containsKey(agentId)) { SingularityAgent agent = activeAgentsById.get(agentId); if ( agent != null && ( !agent.getResources().isPresent() || !agent.getResources().get().equals(agentJsonObject.getResources()) ) ) { LOG.trace( "Found updated resources ({}) for agent {}", agentJsonObject.getResources(), agent ); agentManager.saveObject(agent.withResources(agentJsonObject.getResources())); } activeAgentsById.remove(agentId); } else { SingularityAgent newAgent = new SingularityAgent( agentId, host, rackId, textAttributes, Optional.of(agentJsonObject.getResources()) ); if (check(newAgent, agentManager) == CheckResult.NEW) { agents++; } } if (activeRacksById.containsKey(rackId)) { remainingActiveRacks.remove(rackId); } else { SingularityRack rack = new SingularityRack(rackId); if (check(rack, rackManager) == CheckResult.NEW) { racks++; } } } for (SingularityAgent leftOverAgent : activeAgentsById.values()) { agentManager.changeState( leftOverAgent, isStartup ? MachineState.MISSING_ON_STARTUP : MachineState.DEAD, Optional.empty(), Optional.empty() ); } for (SingularityRack leftOverRack : remainingActiveRacks.values()) { rackManager.changeState( leftOverRack, isStartup ? MachineState.MISSING_ON_STARTUP : MachineState.DEAD, Optional.empty(), Optional.empty() ); } LOG.info( "Found {} new racks ({} missing) and {} new agents ({} missing)", racks, remainingActiveRacks.size(), agents, activeAgentsById.size() ); } public void checkDecommissionedAgentsFromMaster( MesosMasterStateObject state, boolean isStartup ) { Map<String, SingularityAgent> agentsById = agentManager.getObjectsByIdForState( MachineState.DECOMMISSIONED ); for (MesosMasterAgentObject agentJsonObject : state.getAgents()) { String agentId = agentJsonObject.getId(); if (agentsById.containsKey(agentId)) { SingularityAgent agent = agentsById.get(agentId); if (agent != null) { LOG.info( "Found resources ({}) for decommissioned agent {}", agentJsonObject.getResources(), agent ); agentManager.saveObject(agent.withResources(agentJsonObject.getResources())); } agentsById.remove(agentId); } } for (SingularityAgent leftOverAgent : agentsById.values()) { MachineState newState = isStartup ? MachineState.MISSING_ON_STARTUP : MachineState.DEAD; LOG.info("Marking decommissioned agent without mesos resources as {}", newState); agentManager.changeState( leftOverAgent, newState, Optional.empty(), Optional.empty() ); } } public enum CheckResult { NEW, NOT_ACCEPTING_TASKS, ALREADY_ACTIVE } private <T extends SingularityMachineAbstraction<T>> CheckResult check( T object, AbstractMachineManager<T> manager ) { Optional<T> existingObject = manager.getObject(object.getId()); if (!existingObject.isPresent()) { manager.saveObject(object); return CheckResult.NEW; } MachineState currentState = existingObject.get().getCurrentState().getState(); switch (currentState) { case ACTIVE: return CheckResult.ALREADY_ACTIVE; case DEAD: case MISSING_ON_STARTUP: manager.changeState( object.getId(), MachineState.ACTIVE, Optional.empty(), Optional.empty() ); return CheckResult.NEW; case FROZEN: case DECOMMISSIONED: case DECOMMISSIONING: case STARTING_DECOMMISSION: return CheckResult.NOT_ACCEPTING_TASKS; } throw new IllegalStateException( String.format("Invalid state %s for %s", currentState, object.getId()) ); } public CheckResult checkOffer(Offer offer) { final String agentId = offer.getAgentId().getValue(); final String rackId = agentAndRackHelper.getRackIdOrDefault(offer); final String host = agentAndRackHelper.getMaybeTruncatedHost(offer); final Map<String, String> textAttributes = agentAndRackHelper.getTextAttributes( offer ); final SingularityAgent agent = new SingularityAgent( agentId, host, rackId, textAttributes, Optional.empty() ); CheckResult result = check(agent, agentManager); if (result == CheckResult.NEW) { if (inactiveAgentManager.isInactive(agent.getHost())) { LOG.info( "Agent {} on inactive host {} attempted to rejoin. Marking as decommissioned.", agent, host ); agentManager.changeState( agent, MachineState.STARTING_DECOMMISSION, Optional.of( String.format( "Agent %s on inactive host %s attempted to rejoin cluster.", agentId, host ) ), Optional.empty() ); } else { LOG.info("Offer revealed a new agent {}", agent); } } final SingularityRack rack = new SingularityRack(rackId); if (check(rack, rackManager) == CheckResult.NEW) { LOG.info("Offer revealed a new rack {}", rack); } return result; } void checkStateAfterFinishedTask( SingularityTaskId taskId, String agentId, SingularityLeaderCache leaderCache ) { Optional<SingularityAgent> agent = agentManager.getObject(agentId); if (!agent.isPresent()) { final String message = String.format( "Couldn't find agent with id %s for task %s", agentId, taskId ); LOG.warn(message); exceptionNotifier.notify( message, ImmutableMap.of("agentId", agentId, "taskId", taskId.toString()) ); return; } if (agent.get().getCurrentState().getState() == MachineState.DECOMMISSIONING) { if (!hasTaskLeftOnAgent(taskId, agentId, leaderCache)) { agentManager.changeState( agent.get(), MachineState.DECOMMISSIONED, agent.get().getCurrentState().getMessage(), agent.get().getCurrentState().getUser() ); } } Optional<SingularityRack> rack = rackManager.getObject(agent.get().getRackId()); if (!rack.isPresent()) { final String message = String.format( "Couldn't find rack with id %s for task %s", agent.get().getRackId(), taskId ); LOG.warn(message); exceptionNotifier.notify( message, ImmutableMap.of("rackId", agent.get().getRackId(), "taskId", taskId.toString()) ); return; } if (rack.get().getCurrentState().getState() == MachineState.DECOMMISSIONING) { if (!hasTaskLeftOnRack(taskId, leaderCache)) { rackManager.changeState( rack.get(), MachineState.DECOMMISSIONED, rack.get().getCurrentState().getMessage(), rack.get().getCurrentState().getUser() ); } } } private boolean hasTaskLeftOnRack( SingularityTaskId taskId, SingularityLeaderCache leaderCache ) { for (SingularityTaskId activeTaskId : leaderCache.getActiveTaskIds()) { if ( !activeTaskId.equals(taskId) && activeTaskId.getSanitizedRackId().equals(taskId.getSanitizedRackId()) ) { return true; } } return false; } private boolean hasTaskLeftOnAgent( SingularityTaskId taskId, String agentId, SingularityLeaderCache stateCache ) { for (SingularityTaskId activeTaskId : stateCache.getActiveTaskIds()) { if ( !activeTaskId.equals(taskId) && activeTaskId.getSanitizedHost().equals(taskId.getSanitizedHost()) ) { Optional<SingularityTask> maybeTask = taskManager.getTask(activeTaskId); if ( maybeTask.isPresent() && agentId.equals(maybeTask.get().getAgentId().getValue()) ) { return true; } } } return false; } public int getActiveRacksWithCapacityCount() { return configuration.getExpectedRacksCount().isPresent() ? configuration.getExpectedRacksCount().get() : rackManager.getNumActive(); } }
package com.simsilica.lemur.style; import java.util.*; /** * The attribute settings for a particular style selector. * * @author Paul Speed */ public class Attributes { private Styles parent; private Map<String, Object> values = new HashMap<String, Object>(); public Attributes( Styles parent ) { this.parent = parent; } protected void applyNew( Attributes atts ) { // Note: applyNew is called in highest to lowest priority. // Things that fill the values map now should override // later things. for( Map.Entry<String,Object> e : atts.values.entrySet() ) { Object existing = values.get(e.getKey()); if( existing instanceof Map && e.getValue() instanceof Map ) { // Need to merge the old and the new values.put(e.getKey(), mergeMap((Map)existing, (Map)e.getValue())); } else if( existing == null && !values.containsKey(e.getKey()) ) { // Null check above is not enough because the map might have a // null value that should override subsequent attempts to // set the value. values.put(e.getKey(), e.getValue()); } // Else we ignore it } } protected Map mergeMap( Map high, Map low ) { Map result = new HashMap(); result.putAll(high); for( Object o : low.entrySet() ) { Map.Entry e = (Map.Entry)o; if( !result.containsKey(e.getKey()) ) { result.put(e.getKey(), e.getValue()); } } return result; } /** * Like applyNew except that it returns a new Attributes object * and leaves the original intact if a merge is necessary. * If the specified attributes to merge are empty then this * attributes object is returned. */ protected Attributes merge( Attributes atts ) { if( atts.isEmpty() ) { return this; } Attributes result = new Attributes(parent); result.values.putAll(this.values); result.applyNew(atts); return result; } public boolean isEmpty() { return values.isEmpty(); } public boolean hasAttribute( String key ) { return values.containsKey(key); } public void set( String attribute, Object value ) { set( attribute, value, true ); } public void set( String attribute, Object value, boolean overwrite ) { if( !overwrite && values.containsKey(attribute) ) return; values.put( attribute, value ); } public <T> T get( String attribute ) { return (T)values.get(attribute); } public <T> T get( String attribute, Class<T> type ) { return get(attribute, type, true); } public <T> T get( String attribute, Class<T> type, boolean lookupDefault ) { Object result = values.get(attribute); if( result == null && lookupDefault ) { result = parent.getDefault(type); } return (T)result; } @Override public String toString() { return "Attributes[" + values + "]"; } }
package com.hubspot.singularity.mesos; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import javax.inject.Singleton; import org.apache.mesos.Protos; import org.apache.mesos.Protos.Attribute; import org.apache.mesos.Protos.Offer; import org.apache.mesos.Protos.SlaveID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Optional; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.inject.Inject; import com.hubspot.mesos.json.MesosMasterSlaveObject; import com.hubspot.mesos.json.MesosMasterStateObject; import com.hubspot.singularity.MachineState; import com.hubspot.singularity.SingularityMachineAbstraction; import com.hubspot.singularity.SingularityRack; import com.hubspot.singularity.SingularitySlave; import com.hubspot.singularity.SingularityTask; import com.hubspot.singularity.SingularityTaskId; import com.hubspot.singularity.SingularityTaskRequest; import com.hubspot.singularity.SlavePlacement; import com.hubspot.singularity.config.MesosConfiguration; import com.hubspot.singularity.config.SingularityConfiguration; import com.hubspot.singularity.data.AbstractMachineManager; import com.hubspot.singularity.data.RackManager; import com.hubspot.singularity.data.SlaveManager; import com.hubspot.singularity.data.TaskManager; import com.hubspot.singularity.scheduler.SingularitySchedulerStateCache; import com.hubspot.singularity.sentry.SingularityExceptionNotifier; @Singleton class SingularitySlaveAndRackManager { private static final Logger LOG = LoggerFactory.getLogger(SingularitySlaveAndRackManager.class); private final String rackIdAttributeKey; private final String defaultRackId; private final SingularityConfiguration configuration; private final SingularityExceptionNotifier exceptionNotifier; private final RackManager rackManager; private final SlaveManager slaveManager; private final TaskManager taskManager; @Inject SingularitySlaveAndRackManager(SingularityConfiguration configuration, SingularityExceptionNotifier exceptionNotifier, RackManager rackManager, SlaveManager slaveManager, TaskManager taskManager) { this.configuration = configuration; MesosConfiguration mesosConfiguration = configuration.getMesosConfiguration(); this.exceptionNotifier = exceptionNotifier; this.rackIdAttributeKey = mesosConfiguration.getRackIdAttributeKey(); this.defaultRackId = mesosConfiguration.getDefaultRackId(); this.rackManager = rackManager; this.slaveManager = slaveManager; this.taskManager = taskManager; } public enum SlaveMatchState { OK(true), NOT_RACK_OR_SLAVE_PARTICULAR(true), RACK_SATURATED(false), SLAVE_SATURATED(false), SLAVE_DECOMMISSIONING(false), RACK_DECOMMISSIONING(false), RACK_AFFINITY_NOT_MATCHING(false); private final boolean isMatchAllowed; private SlaveMatchState(boolean isMatchAllowed) { this.isMatchAllowed = isMatchAllowed; } public boolean isMatchAllowed() { return isMatchAllowed; } } private String getHost(String hostname) { if (configuration.getCommonHostnameSuffixToOmit().isPresent()) { if (hostname.endsWith(configuration.getCommonHostnameSuffixToOmit().get())) { hostname = hostname.substring(0, hostname.length() - configuration.getCommonHostnameSuffixToOmit().get().length()); } } return getSafeString(hostname); } public String getSlaveHost(Offer offer) { return getHost(offer.getHostname()); } public SlaveMatchState doesOfferMatch(Protos.Offer offer, SingularityTaskRequest taskRequest, SingularitySchedulerStateCache stateCache) { final String host = getSlaveHost(offer); final String rackId = getRackId(offer); final String slaveId = offer.getSlaveId().getValue(); if (stateCache.getSlave(slaveId).get().getCurrentState().getState().isDecommissioning()) { return SlaveMatchState.SLAVE_DECOMMISSIONING; } if (stateCache.getRack(rackId).get().getCurrentState().getState().isDecommissioning()) { return SlaveMatchState.RACK_DECOMMISSIONING; } if (!taskRequest.getRequest().getRackAffinity().or(Collections.<String> emptyList()).isEmpty()) { if (!taskRequest.getRequest().getRackAffinity().get().contains(rackId)) { LOG.trace("Task {} requires a rack in {} (current rack {})", taskRequest.getPendingTask().getPendingTaskId(), taskRequest.getRequest().getRackAffinity().get(), rackId); return SlaveMatchState.RACK_AFFINITY_NOT_MATCHING; } } final SlavePlacement slavePlacement = taskRequest.getRequest().getSlavePlacement().or(configuration.getDefaultSlavePlacement()); if (!taskRequest.getRequest().isRackSensitive() && slavePlacement == SlavePlacement.GREEDY) { return SlaveMatchState.NOT_RACK_OR_SLAVE_PARTICULAR; } final int numDesiredInstances = taskRequest.getRequest().getInstancesSafe(); double numOnRack = 0; double numOnSlave = 0; double numCleaningOnSlave = 0; double numOtherDeploysOnSlave = 0; Collection<SingularityTaskId> cleaningTasks = stateCache.getCleaningTasks(); for (SingularityTaskId taskId : SingularityTaskId.matchingAndNotIn(stateCache.getActiveTaskIds(), taskRequest.getRequest().getId(), Collections.<SingularityTaskId>emptyList())) { // TODO consider using executorIds if (taskId.getHost().equals(host)) { if (taskRequest.getDeploy().getId().equals(taskId.getDeployId())) { if (cleaningTasks.contains(taskId)) { numCleaningOnSlave++; } else { numOnSlave++; } } else { numOtherDeploysOnSlave++; } } if (taskId.getRackId().equals(rackId) && !cleaningTasks.contains(taskId) && taskRequest.getDeploy().getId().equals(taskId.getDeployId())) { numOnRack++; } } if (taskRequest.getRequest().isRackSensitive()) { final double numPerRack = numDesiredInstances / (double) stateCache.getNumActiveRacks(); final boolean isRackOk = numOnRack < numPerRack; if (!isRackOk) { LOG.trace("Rejecting RackSensitive task {} from slave {} ({}) due to numOnRack {} and cleaningOnSlave {}", taskRequest.getRequest().getId(), slaveId, host, numOnRack, numCleaningOnSlave); return SlaveMatchState.RACK_SATURATED; } } switch (slavePlacement) { case SEPARATE: case SEPARATE_BY_DEPLOY: if (numOnSlave > 0 || numCleaningOnSlave > 0) { LOG.trace("Rejecting SEPARATE task {} from slave {} ({}) due to numOnSlave {} numCleaningOnSlave {}", taskRequest.getRequest().getId(), slaveId, host, numOnSlave, numCleaningOnSlave); return SlaveMatchState.SLAVE_SATURATED; } break; case SEPARATE_BY_REQUEST: if (numOnSlave > 0 || numCleaningOnSlave > 0 || numOtherDeploysOnSlave > 0) { LOG.trace("Rejecting SEPARATE task {} from slave {} ({}) due to numOnSlave {} numCleaningOnSlave {} numOtherDeploysOnSlave {}", taskRequest.getRequest().getId(), slaveId, host, numOnSlave, numCleaningOnSlave, numOtherDeploysOnSlave); return SlaveMatchState.SLAVE_SATURATED; } break; case OPTIMISTIC: final double numPerSlave = numDesiredInstances / (double) stateCache.getNumActiveSlaves(); final boolean isSlaveOk = numOnSlave < numPerSlave; if (!isSlaveOk) { LOG.trace("Rejecting OPTIMISTIC task {} from slave {} ({}) due to numOnSlave {}", taskRequest.getRequest().getId(), slaveId, host, numOnSlave); return SlaveMatchState.SLAVE_SATURATED; } break; case GREEDY: } return SlaveMatchState.OK; } public void slaveLost(SlaveID slaveIdObj) { final String slaveId = slaveIdObj.getValue(); Optional<SingularitySlave> slave = slaveManager.getObject(slaveId); if (slave.isPresent()) { slaveManager.changeState(slave.get(), MachineState.DEAD, Optional.<String> absent()); checkRackAfterSlaveLoss(slave.get()); } else { LOG.warn("Lost a slave {}, but didn't know about it", slaveId); } } private void checkRackAfterSlaveLoss(SingularitySlave lostSlave) { List<SingularitySlave> slaves = slaveManager.getObjectsFiltered(MachineState.ACTIVE); int numInRack = 0; for (SingularitySlave slave : slaves) { if (slave.getRackId().equals(lostSlave.getRackId())) { numInRack++; } } LOG.info("Found {} slaves left in rack {}", numInRack, lostSlave.getRackId()); if (numInRack == 0) { rackManager.changeState(lostSlave.getRackId(), MachineState.DEAD, Optional.<String> absent()); } } public void loadSlavesAndRacksFromMaster(MesosMasterStateObject state) { Map<String, SingularitySlave> activeSlavesById = slaveManager.getObjectsByIdForState(MachineState.ACTIVE); Map<String, SingularityRack> activeRacksById = rackManager.getObjectsByIdForState(MachineState.ACTIVE); Map<String, SingularityRack> remainingActiveRacks = Maps.newHashMap(activeRacksById); int slaves = 0; int racks = 0; for (MesosMasterSlaveObject slaveJsonObject : state.getSlaves()) { Optional<String> maybeRackId = Optional.fromNullable(slaveJsonObject.getAttributes().get(rackIdAttributeKey)); String slaveId = slaveJsonObject.getId(); String rackId = getSafeString(maybeRackId.or(defaultRackId)); String host = getHost(slaveJsonObject.getHostname()); if (activeSlavesById.containsKey(slaveId)) { activeSlavesById.remove(slaveId); } else { SingularitySlave newSlave = new SingularitySlave(slaveId, host, rackId); if (check(newSlave, slaveManager) == CheckResult.NEW) { slaves++; } } if (activeRacksById.containsKey(rackId)) { remainingActiveRacks.remove(rackId); } else { SingularityRack rack = new SingularityRack(rackId); if (check(rack, rackManager) == CheckResult.NEW) { racks++; } } } for (SingularitySlave leftOverSlave : activeSlavesById.values()) { slaveManager.changeState(leftOverSlave, MachineState.MISSING_ON_STARTUP, Optional.<String> absent()); } for (SingularityRack leftOverRack : remainingActiveRacks.values()) { rackManager.changeState(leftOverRack, MachineState.MISSING_ON_STARTUP, Optional.<String> absent()); } LOG.info("Found {} new racks ({} missing) and {} new slaves ({} missing)", racks, remainingActiveRacks.size(), slaves, activeSlavesById.size()); } public String getRackId(Offer offer) { for (Attribute attribute : offer.getAttributesList()) { if (attribute.getName().equals(rackIdAttributeKey)) { return getSafeString(attribute.getText().getValue()); } } return defaultRackId; } private String getSafeString(String string) { return string.replace("-", "_"); } private enum CheckResult { NEW, DECOMMISSIONING, ALREADY_ACTIVE; } private <T extends SingularityMachineAbstraction<T>> CheckResult check(T object, AbstractMachineManager<T> manager) { Optional<T> existingObject = manager.getObject(object.getId()); if (!existingObject.isPresent()) { manager.saveObject(object); return CheckResult.NEW; } MachineState currentState = existingObject.get().getCurrentState().getState(); switch (currentState) { case ACTIVE: return CheckResult.ALREADY_ACTIVE; case DEAD: case MISSING_ON_STARTUP: manager.changeState(object.getId(), MachineState.ACTIVE, Optional.<String> absent()); return CheckResult.NEW; case DECOMMISSIONED: case DECOMMISSIONING: case STARTING_DECOMMISSION: return CheckResult.DECOMMISSIONING; } throw new IllegalStateException(String.format("Invalid state %s for %s", currentState, object.getId())); } public void checkOffer(Offer offer) { final String slaveId = offer.getSlaveId().getValue(); final String rackId = getRackId(offer); final String host = getSlaveHost(offer); final SingularitySlave slave = new SingularitySlave(slaveId, host, rackId); if (check(slave, slaveManager) == CheckResult.NEW) { LOG.info("Offer revealed a new slave {}", slave); } final SingularityRack rack = new SingularityRack(rackId); if (check(rack, rackManager) == CheckResult.NEW) { LOG.info("Offer revealed a new rack {}", rack); } } public void checkStateAfterFinishedTask(SingularityTaskId taskId, String slaveId, SingularitySchedulerStateCache stateCache) { Optional<SingularitySlave> slave = slaveManager.getObject(slaveId); if (!slave.isPresent()) { final String message = String.format("Couldn't find slave with id %s for task %s", slaveId, taskId); LOG.warn(message); exceptionNotifier.notify(message, ImmutableMap.of("slaveId", slaveId, "taskId", taskId.toString())); return; } if (slave.get().getCurrentState().getState() == MachineState.DECOMMISSIONING) { if (!hasTaskLeftOnSlave(taskId, slaveId, stateCache)) { slaveManager.changeState(slave.get(), MachineState.DECOMMISSIONED, slave.get().getCurrentState().getUser()); } } Optional<SingularityRack> rack = rackManager.getObject(taskId.getRackId()); if (!rack.isPresent()) { final String message = String.format("Couldn't find rack with id %s for task %s", taskId.getRackId(), taskId); LOG.warn(message); exceptionNotifier.notify(message, ImmutableMap.of("rackId", taskId.getRackId(), "taskId", taskId.toString())); return; } if (rack.get().getCurrentState().getState() == MachineState.DECOMMISSIONING) { if (!hasTaskLeftOnRack(taskId, stateCache)) { rackManager.changeState(rack.get(), MachineState.DECOMMISSIONED, rack.get().getCurrentState().getUser()); } } } private boolean hasTaskLeftOnRack(SingularityTaskId taskId, SingularitySchedulerStateCache stateCache) { for (SingularityTaskId activeTaskId : stateCache.getActiveTaskIds()) { if (!activeTaskId.equals(taskId) && activeTaskId.getRackId().equals(taskId.getRackId())) { return true; } } return false; } private boolean hasTaskLeftOnSlave(SingularityTaskId taskId, String slaveId, SingularitySchedulerStateCache stateCache) { for (SingularityTaskId activeTaskId : stateCache.getActiveTaskIds()) { if (!activeTaskId.equals(taskId) && activeTaskId.getHost().equals(taskId.getHost())) { Optional<SingularityTask> maybeTask = taskManager.getTask(activeTaskId); if (maybeTask.isPresent() && slaveId.equals(maybeTask.get().getOffer().getSlaveId().getValue())) { return true; } }; } return false; } }
package com.sproutlife.model.step; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map.Entry; import com.sproutlife.Settings; import com.sproutlife.model.GameModel; import com.sproutlife.model.echosystem.Organism; public class ColorsStep extends Step { GameModel gameModel; int COLOR_COUNT = 3; boolean joinMinorColors = false; public ColorsStep(GameModel gameModel) { super(gameModel); } public void perform() { if (getSettings().getBoolean(Settings.AUTO_SPLIT_COLORS)) { splitColors(); } } public void setJoinMinorColors(boolean joinMinorColors) { this.joinMinorColors = joinMinorColors; } private void splitColors() { if (getEchosystem().getOrganisms().size() ==0) { return; } ArrayList<Entry<Integer,Integer>> kindCount = getColorCounts(); int largestPercentOfTotal = kindCount.get(kindCount.size()-1).getValue()*100/getEchosystem().getOrganisms().size(); if (kindCount.get(0).getValue()==0 && largestPercentOfTotal>70) { // if there are only 2 colors left and largest is more than 70% of total, split it splitColor(kindCount.get(kindCount.size()-1).getKey(), kindCount.get(0).getKey()); } else if (joinMinorColors && kindCount.get(1).getValue()>0 && largestPercentOfTotal>80) { // when the 2 smallest colors are less than 20% of total, join them together joinColor(kindCount.get(0).getKey(), kindCount.get(1).getKey()); } } private ArrayList<Entry<Integer,Integer>> getColorCounts() { HashMap<Integer, Integer> kindCountMap = new HashMap<>(); for (int k=0;k<COLOR_COUNT;k++) { kindCountMap.put(k,0); } for (Organism o : getEchosystem().getOrganisms()) { Integer v = kindCountMap.get(o.getAttributes().colorKind); kindCountMap.put(o.getAttributes().colorKind, v == null ? 1 : v+1); } ArrayList<Entry<Integer,Integer>> kindCount = new ArrayList<>(kindCountMap.entrySet()); Collections.sort(kindCount, (e1, e2)->(e1.getValue()-e2.getValue())); return kindCount; } private void joinColor(int fromKind, int toKind) { for (Organism o : getEchosystem().getOrganisms()) { if (o.getAttributes().colorKind == fromKind) { o.getAttributes().colorKind=toKind; } } } private void splitColor(int splitKind, int emptyKind) { int xSum = 0; int sSize = 0; for (Organism o : getEchosystem().getOrganisms()) { if (o.getAttributes().colorKind == splitKind) { xSum += o.x; sSize +=1; } } int avgX = xSum / sSize; for (Organism o : getEchosystem().getOrganisms()) { if (o.getAttributes().colorKind==splitKind) { if ((avgX > getBoard().getWidth()/2 && o.x > avgX) || (avgX <= getBoard().getWidth()/2 && o.x < avgX)) { o.getAttributes().colorKind = emptyKind; } } } } }
package com.hubspot.singularity.scheduler; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.rholder.retry.Retryer; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.hubspot.baragon.models.BaragonRequestState; import com.hubspot.baragon.models.UpstreamInfo; import com.hubspot.singularity.LoadBalancerRequestType; import com.hubspot.singularity.LoadBalancerRequestType.LoadBalancerRequestId; import com.hubspot.singularity.SingularityDeploy; import com.hubspot.singularity.SingularityLoadBalancerUpdate; import com.hubspot.singularity.SingularityLoadBalancerUpdate.LoadBalancerMethod; import com.hubspot.singularity.SingularityRequest; import com.hubspot.singularity.SingularityRequestWithState; import com.hubspot.singularity.SingularityTask; import com.hubspot.singularity.SingularityTaskId; import com.hubspot.singularity.SingularityTaskIdsByStatus; import com.hubspot.singularity.data.DeployManager; import com.hubspot.singularity.data.RequestManager; import com.hubspot.singularity.data.TaskManager; import com.hubspot.singularity.helpers.RequestHelper; import com.hubspot.singularity.hooks.LoadBalancerClient; import com.hubspot.singularity.mesos.SingularitySchedulerLock; import com.github.rholder.retry.RetryerBuilder; import com.github.rholder.retry.WaitStrategies; @Singleton public class SingularityUpstreamChecker { private static final Logger LOG = LoggerFactory.getLogger(SingularityUpstreamChecker.class); private static final Predicate<SingularityLoadBalancerUpdate> IS_WAITING_STATE = singularityLoadBalancerUpdate -> singularityLoadBalancerUpdate.getLoadBalancerState() == BaragonRequestState.WAITING; private final LoadBalancerClient lbClient; private final TaskManager taskManager; private final RequestManager requestManager; private final DeployManager deployManager; private final RequestHelper requestHelper; private final SingularitySchedulerLock lock; @Inject public SingularityUpstreamChecker(LoadBalancerClient lbClient, TaskManager taskManager, RequestManager requestManager, DeployManager deployManager, RequestHelper requestHelper, SingularitySchedulerLock lock) { this.lbClient = lbClient; this.taskManager = taskManager; this.requestManager = requestManager; this.deployManager = deployManager; this.requestHelper = requestHelper; this.lock = lock; } private List<SingularityTask> getActiveHealthyTasksForRequest(String requestId) throws Exception { final Optional<SingularityTaskIdsByStatus> taskIdsByStatusForRequest = requestHelper.getTaskIdsByStatusForRequest(requestId); if (taskIdsByStatusForRequest.isPresent()) { final List<SingularityTaskId> activeHealthyTaskIdsForRequest = taskIdsByStatusForRequest.get().getHealthy(); final Map<SingularityTaskId, SingularityTask> activeTasksForRequest = taskManager.getTasks(activeHealthyTaskIdsForRequest); return new ArrayList<>(activeTasksForRequest.values()); } LOG.error("TaskId not found for requestId: {}.", requestId); throw new Exception("TaskId not found."); } private Collection<UpstreamInfo> getUpstreamsFromActiveTasksForRequest(String singularityRequestId, Optional<String> loadBalancerUpstreamGroup) throws Exception { return lbClient.getUpstreamsForTasks(getActiveHealthyTasksForRequest(singularityRequestId), singularityRequestId, loadBalancerUpstreamGroup); } private boolean isEqualUpstreamGroupRackId(UpstreamInfo upstream1, UpstreamInfo upstream2){ return (upstream1.getUpstream().equals(upstream2.getUpstream())) && (upstream1.getGroup().equals(upstream2.getGroup())) && (upstream1.getRackId().equals(upstream2.getRackId())); } /** * @param upstream * @param upstreams * @return a collection of upstreams in the upstreams param that match with the upstream param on upstream, group and rackId * We expect that the collection will have a maximum of one match, but we will keep it as a collection just in case */ private Collection<UpstreamInfo> getEqualUpstreams(UpstreamInfo upstream, Collection<UpstreamInfo> upstreams) { return upstreams.stream().filter(candidate -> isEqualUpstreamGroupRackId(candidate, upstream)).collect(Collectors.toList()); } private List<UpstreamInfo> getExtraUpstreams(Collection<UpstreamInfo> upstreamsInBaragonForRequest, Collection<UpstreamInfo> upstreamsInSingularityForRequest) { for (UpstreamInfo upstreamInSingularity : upstreamsInSingularityForRequest) { final Collection<UpstreamInfo> matches = getEqualUpstreams(upstreamInSingularity, upstreamsInBaragonForRequest); upstreamsInBaragonForRequest.removeAll(matches); } return new ArrayList<>(upstreamsInBaragonForRequest); } private Collection<UpstreamInfo> getUpstreamsInLoadBalancer (SingularityRequest singularityRequest, SingularityDeploy deploy) { final LoadBalancerRequestId checkUpstreamsId = new LoadBalancerRequestId(String.format("%s-%s-%s", singularityRequest.getId(), deploy.getId(), System.currentTimeMillis()), LoadBalancerRequestType.REMOVE, Optional.absent()); SingularityLoadBalancerUpdate checkUpstreamsState = lbClient.enqueue(checkUpstreamsId, singularityRequest, deploy, Collections.emptyList(), Collections.emptyList()); try { if (checkUpstreamsState.getLoadBalancerState() == BaragonRequestState.WAITING) { Retryer<SingularityLoadBalancerUpdate> getLoadBalancerUpstreamsRetryer = RetryerBuilder.<SingularityLoadBalancerUpdate>newBuilder() .retryIfException() .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS)) .retryIfResult(IS_WAITING_STATE) .build(); checkUpstreamsState = getLoadBalancerUpstreamsRetryer.call(() -> lbClient.getState(checkUpstreamsId)); } if (checkUpstreamsState.getLoadBalancerState() == BaragonRequestState.SUCCESS){ LOG.info("Getting LB upstreams for singularity request {} through LB request {} is {}.", singularityRequest.getId(), checkUpstreamsId, checkUpstreamsState.toString()); return lbClient.getLoadBalancerUpstreamsForLoadBalancerRequest(checkUpstreamsId); } else { LOG.error("Getting LB upstreams for singularity request {} throught LB request {} is {}.", singularityRequest.getId(), checkUpstreamsId, checkUpstreamsState.toString()); } } catch (Exception e) { LOG.error("Could not get LB upstreams for singularity request {} through LB request {}. ", singularityRequest.getId(), checkUpstreamsId, e); } return Collections.emptyList(); //TODO: confirm } private SingularityLoadBalancerUpdate syncUpstreamsForService(SingularityRequest singularityRequest, SingularityDeploy deploy, Optional<String> loadBalancerUpstreamGroup){ final LoadBalancerRequestId loadBalancerRequestId = new LoadBalancerRequestId(String.format("%s-%s-%s", singularityRequest.getId(), deploy.getId(), System.currentTimeMillis()), LoadBalancerRequestType.REMOVE, Optional.absent()); final long start = System.currentTimeMillis(); try { Collection<UpstreamInfo> upstreamsInLoadBalancerForRequest = getUpstreamsInLoadBalancer(singularityRequest, deploy); LOG.info("Upstreams in load balancer for service {} are {}.", singularityRequest.getId(), upstreamsInLoadBalancerForRequest); Collection<UpstreamInfo> upstreamsInSingularityForRequest = getUpstreamsFromActiveTasksForRequest(singularityRequest.getId(), loadBalancerUpstreamGroup); LOG.info("Upstreams in singularity for service {} are {}.", singularityRequest.getId(), upstreamsInSingularityForRequest); final List<UpstreamInfo> extraUpstreams = getExtraUpstreams(upstreamsInLoadBalancerForRequest, upstreamsInSingularityForRequest); LOG.info("Syncing upstreams for service {}. Making and sending load balancer request {} to remove {} extra upstreams. The upstreams removed are: {}.", singularityRequest.getId(), loadBalancerRequestId, extraUpstreams.size(), extraUpstreams); return lbClient.makeAndSendLoadBalancerRequest(loadBalancerRequestId, Collections.emptyList(), extraUpstreams, deploy, singularityRequest); } catch (Exception e) { LOG.error("Could not sync for service {}. Load balancer request {} threw error: ", singularityRequest.getId(), loadBalancerRequestId, e); return new SingularityLoadBalancerUpdate(BaragonRequestState.UNKNOWN, loadBalancerRequestId, Optional.of(String.format("Exception %s - %s", e.getClass().getSimpleName(), e.getMessage())), start, LoadBalancerMethod.CHECK_STATE, Optional.absent()); } } private boolean noPendingDeploy() { return deployManager.getPendingDeploys().size() == 0; } private void doSyncUpstreamsForService(SingularityRequest singularityRequest) { if (singularityRequest.isLoadBalanced() && noPendingDeploy()) { final String singularityRequestId = singularityRequest.getId(); LOG.info("Doing syncing of upstreams for service: {}.", singularityRequestId); final Optional<String> maybeDeployId = deployManager.getInUseDeployId(singularityRequestId); if (maybeDeployId.isPresent()) { final String deployId = maybeDeployId.get(); final Optional<SingularityDeploy> maybeDeploy = deployManager.getDeploy(singularityRequestId, deployId); if (maybeDeploy.isPresent()) { final SingularityDeploy deploy = maybeDeploy.get(); final Optional<String> loadBalancerUpstreamGroup = deploy.getLoadBalancerUpstreamGroup(); final SingularityLoadBalancerUpdate syncUpstreamsUpdate = syncUpstreamsForService(singularityRequest, deploy, loadBalancerUpstreamGroup); checkSyncUpstreamsState(syncUpstreamsUpdate.getLoadBalancerRequestId(), singularityRequestId); } } } } private void checkSyncUpstreamsState(LoadBalancerRequestId loadBalancerRequestId, String singularityRequestId) { Retryer<SingularityLoadBalancerUpdate> syncingRetryer = RetryerBuilder.<SingularityLoadBalancerUpdate>newBuilder() .retryIfException() .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS)) .retryIfResult(IS_WAITING_STATE) .build(); try { SingularityLoadBalancerUpdate syncUpstreamsState = syncingRetryer.call(() -> lbClient.getState(loadBalancerRequestId)); if (syncUpstreamsState.getLoadBalancerState() == BaragonRequestState.SUCCESS){ LOG.info("Syncing upstreams for singularity request {} is {}.", singularityRequestId, syncUpstreamsState.toString()); } else { LOG.error("Syncing upstreams for singularity request {} is {}.", singularityRequestId, syncUpstreamsState.toString()); } } catch (Exception e) { LOG.error("Could not check sync upstream state for singularity request {}. ", singularityRequestId, e); } } public void syncUpstreams() { for (SingularityRequestWithState singularityRequestWithState: requestManager.getActiveRequests()){ final SingularityRequest singularityRequest = singularityRequestWithState.getRequest(); lock.runWithRequestLock(() -> doSyncUpstreamsForService(singularityRequest), singularityRequest.getId(), getClass().getSimpleName()); } } }
package com.stuntddude.polynomial; import processing.core.PApplet; public final class Polynomial extends PApplet { public static final Polynomial polynomial = new Polynomial(); @Override public void settings() { size(1280, 720); smooth(8); } @Override public void setup() { frameRate(60); } @Override public void draw() { background(0xFFFFFFFF); //white //apply grid scaling pushMatrix(); translate(width/2, height/2); float scale = 20.f; //TODO: make scale dependent on window size scale(scale, -scale); //draw grid stroke(0xFF7F7F7F); //grey strokeWeight(1/scale); //TODO: optimize this section for (int i = -100; i <= 100; ++i) { line(i, -100, i, 100); //vertical lines line(-100, i, 100, i); //horizontal lines } //draw axes in bold stroke(0xFF000000); //black strokeWeight(2/scale); line(0, -100, 0, 100); //vertical line(-100, 0, 100, 0); //horizontal //draw an arrow on the ends of each axis fill(0xFF000000); //black float hy = height/scale/2, hx = width/scale/2; float a = 0.25f, b = 0.5f; triangle(0, hy, a, hy - b, -a, hy - b); //top triangle(0, -hy, a, -hy + b, -a, -hy + b); //bottom triangle( hx, 0, hx - b, a, hx - b, -a); //right triangle(-hx, 0, -hx + b, a, -hx + b, -a); //left //un-apply grid scaling popMatrix(); noLoop(); } public static void main(String[] args) { PApplet.runSketch(new String[] { Polynomial.class.getName() }, polynomial); } }
package org.cqframework.cql.poc.translator; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.misc.NotNull; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; import org.cqframework.cql.elm.tracking.TrackBack; import org.cqframework.cql.elm.tracking.Trackable; import org.cqframework.cql.gen.cqlBaseVisitor; import org.cqframework.cql.gen.cqlLexer; import org.cqframework.cql.gen.cqlParser; import org.cqframework.cql.poc.translator.model.*; import org.cqframework.cql.poc.translator.preprocessor.LibraryInfo; import org.hl7.elm.r1.*; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.namespace.QName; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Stack; public class ElmTranslatorVisitor extends cqlBaseVisitor { private final ObjectFactory of = new ObjectFactory(); private LibraryInfo libraryInfo = null; private Library library = null; private String currentContext = "UNKNOWN"; //Put them here for now, but eventually somewhere else? private final HashMap<String, Library> libraries = new HashMap<>(); private final Stack<QueryContext> queries = new Stack<>(); private final Stack<TimingOperatorContext> timingOperators = new Stack<>(); private final List<ClinicalRequest> clinicalRequests = new ArrayList<>(); private final List<Expression> expressions = new ArrayList<>(); private ModelHelper modelHelper = null; public LibraryInfo getLibraryInfo() { return libraryInfo; } public void setLibraryInfo(LibraryInfo value) { libraryInfo = value; } public Library getLibrary() { return library; } public List<ClinicalRequest> getClinicalRequests() { return clinicalRequests; } public List<Expression> getExpressions() { return expressions; } @Override public Object visit(@NotNull ParseTree tree) { Object o = super.visit(tree); if (o instanceof Trackable && tree instanceof ParserRuleContext && !(tree instanceof cqlParser.LogicContext)) { this.track((Trackable) o, (ParserRuleContext) tree); } if (o instanceof Expression) { expressions.add((Expression) o); } return o; } @Override public Object visitLogic(@NotNull cqlParser.LogicContext ctx) { library = of.createLibrary(); Object lastResult = null; // Loop through and call visit on each child (to ensure they are tracked) for (int i=0; i < ctx.getChildCount(); i++) { lastResult = visit(ctx.getChild(i)); } // Return last result (consistent with super implementation and helps w/ testing) return lastResult; } @Override public VersionedIdentifier visitLibraryDefinition(@NotNull cqlParser.LibraryDefinitionContext ctx) { VersionedIdentifier vid = of.createVersionedIdentifier() .withId(parseString(ctx.IDENTIFIER())) .withVersion(parseString(ctx.STRING())); library.setIdentifier(vid); return vid; } @Override public ModelReference visitUsingDefinition(@NotNull cqlParser.UsingDefinitionContext ctx) { String modelIdentifier = parseString(ctx.IDENTIFIER()); // TODO: This should load from a modelinfo file based on the modelIdentifier above. Hard-coding to QUICK for POC purposes. try { modelHelper = new ModelHelper(QuickModelHelper.load()); } catch (ClassNotFoundException e) { // TODO: Should never occur... } // TODO: Needs to write xmlns and schemalocation to the resulting ELM XML document... ModelReference model = of.createModelReference() .withReferencedModel(of.createModelReferenceReferencedModel().withValue(modelHelper.getModelInfo().getUrl())); addToLibrary(model); return model; } @Override public Object visitIncludeDefinition(@NotNull cqlParser.IncludeDefinitionContext ctx) { LibraryReference library = of.createLibraryReference() .withName(ctx.IDENTIFIER(1).getText()) .withPath(ctx.IDENTIFIER(0).getText()) .withVersion(parseString(ctx.STRING())); addToLibrary(library); return library; } @Override public ParameterDef visitParameterDefinition(@NotNull cqlParser.ParameterDefinitionContext ctx) { ParameterDef param = of.createParameterDef() .withName(parseString(ctx.IDENTIFIER())) .withDefault(parseExpression(ctx.expression())) .withParameterTypeSpecifier(parseTypeSpecifier(ctx.typeSpecifier())); addToLibrary(param); return param; } @Override public NamedTypeSpecifier visitAtomicTypeSpecifier(@NotNull cqlParser.AtomicTypeSpecifierContext ctx) { return of.createNamedTypeSpecifier().withName(resolveNamedType(ctx.IDENTIFIER().getText())); } @Override public PropertyTypeSpecifier visitTupleElementDefinition(@NotNull cqlParser.TupleElementDefinitionContext ctx) { return of.createPropertyTypeSpecifier() .withName(ctx.IDENTIFIER().getText()) .withType(parseTypeSpecifier(ctx.typeSpecifier())); } @Override public Object visitTupleTypeSpecifier(@NotNull cqlParser.TupleTypeSpecifierContext ctx) { ObjectTypeSpecifier typeSpecifier = of.createObjectTypeSpecifier(); for (cqlParser.TupleElementDefinitionContext definitionContext : ctx.tupleElementDefinition()) { typeSpecifier.getProperty().add((PropertyTypeSpecifier)visit(definitionContext)); } return typeSpecifier; } @Override public IntervalTypeSpecifier visitIntervalTypeSpecifier(@NotNull cqlParser.IntervalTypeSpecifierContext ctx) { return of.createIntervalTypeSpecifier().withPointType(parseTypeSpecifier(ctx.typeSpecifier())); } @Override public ListTypeSpecifier visitListTypeSpecifier(@NotNull cqlParser.ListTypeSpecifierContext ctx) { return of.createListTypeSpecifier().withElementType(parseTypeSpecifier(ctx.typeSpecifier())); } @Override public ValueSetDef visitValuesetDefinitionByExpression(@NotNull cqlParser.ValuesetDefinitionByExpressionContext ctx) { ValueSetDef vs = of.createValueSetDef() .withName(parseString(ctx.VALUESET())) .withValueSet(parseExpression(ctx.expression())); addToLibrary(vs); return vs; } @Override public ValueSetDef visitValuesetDefinitionByConstructor(@NotNull cqlParser.ValuesetDefinitionByConstructorContext ctx) { ValueSetDef vs = of.createValueSetDef() .withName(parseString(ctx.VALUESET())) .withValueSet(of.createValueSet().withId(parseString(ctx.STRING()))); addToLibrary(vs); return vs; } @Override public String visitContextDefinition(@NotNull cqlParser.ContextDefinitionContext ctx) { currentContext = parseString(ctx.IDENTIFIER()); return currentContext; } @Override public ExpressionDef visitLetStatement(@NotNull cqlParser.LetStatementContext ctx) { ExpressionDef let = of.createExpressionDef() .withName(parseString(ctx.IDENTIFIER())) .withContext(currentContext) .withExpression((Expression) visit(ctx.expression())); addToLibrary(let); return let; } @Override public Literal visitStringLiteral(@NotNull cqlParser.StringLiteralContext ctx) { return createLiteral(parseString(ctx.STRING())); } @Override public Literal visitBooleanLiteral(@NotNull cqlParser.BooleanLiteralContext ctx) { return createLiteral(Boolean.valueOf(parseString(ctx))); } @Override public Object visitIntervalSelector(@NotNull cqlParser.IntervalSelectorContext ctx) { return of.createInterval() .withBegin(parseExpression(ctx.expression(0))) .withBeginOpen(ctx.getChild(1).getText().equals("(")) .withEnd(parseExpression(ctx.expression(1))) .withEndOpen(ctx.getChild(5).getText().equals(")")); } @Override public Object visitTupleElementSelector(@NotNull cqlParser.TupleElementSelectorContext ctx) { return of.createPropertyExpression() .withName(ctx.IDENTIFIER().getText()) .withValue(parseExpression(ctx.expression())); } @Override public Object visitTupleSelector(@NotNull cqlParser.TupleSelectorContext ctx) { ObjectExpression objectExpression = of.createObjectExpression(); for (cqlParser.TupleElementSelectorContext element : ctx.tupleElementSelector()) { objectExpression.getProperty().add((PropertyExpression)visit(element)); } return objectExpression; } @Override public Object visitListSelector(@NotNull cqlParser.ListSelectorContext ctx) { org.hl7.elm.r1.List list = of.createList().withTypeSpecifier(parseTypeSpecifier(ctx.typeSpecifier())); for (cqlParser.ExpressionContext element : ctx.expression()) { list.getElement().add(parseExpression(element)); } return list; } @Override public Null visitNullLiteral(@NotNull cqlParser.NullLiteralContext ctx) { return of.createNull(); } @Override public Expression visitQuantityLiteral(@NotNull cqlParser.QuantityLiteralContext ctx) { if (ctx.unit() != null) { DecimalFormat df = new DecimalFormat(" df.setParseBigDecimal(true); try { return of.createQuantity() .withValue((BigDecimal)df.parse(ctx.QUANTITY().getText())) .withUnit(ctx.unit().getText()); } catch (ParseException e) { // Should never occur, just return null return of.createNull(); } } else { String quantity = ctx.QUANTITY().getText(); return of.createLiteral() .withValue(quantity) .withValueType(resolveNamedType(quantity.contains(".") ? "Integer" : "Decimal")); } } @Override public Object visitValuesetLiteral(@NotNull cqlParser.ValuesetLiteralContext ctx) { return of.createValueSetRef().withName(parseString(ctx.VALUESET())); } @Override public Not visitNotExpression(@NotNull cqlParser.NotExpressionContext ctx) { return of.createNot().withOperand(parseExpression(ctx.expression())); } @Override public IsNotEmpty visitExistenceExpression(@NotNull cqlParser.ExistenceExpressionContext ctx) { return of.createIsNotEmpty().withOperand(parseExpression(ctx.expression())); } @Override public Multiply visitMultiplicationExpressionTerm(@NotNull cqlParser.MultiplicationExpressionTermContext ctx) { return of.createMultiply().withOperand( parseExpression(ctx.expressionTerm(0)), parseExpression(ctx.expressionTerm(1))); } @Override public Power visitPowerExpressionTerm(@NotNull cqlParser.PowerExpressionTermContext ctx) { return of.createPower().withOperand( parseExpression(ctx.expressionTerm(0)), parseExpression(ctx.expressionTerm(1))); } @Override public Object visitPolarityExpressionTerm(@NotNull cqlParser.PolarityExpressionTermContext ctx) { if (ctx.getChild(0).getText().equals("+")) { return visit(ctx.expressionTerm()); } return of.createNegate().withOperand(parseExpression(ctx.expressionTerm())); } @Override public Add visitAdditionExpressionTerm(@NotNull cqlParser.AdditionExpressionTermContext ctx) { return of.createAdd().withOperand( parseExpression(ctx.expressionTerm(0)), parseExpression(ctx.expressionTerm(1))); } @Override public Object visitPredecessorExpressionTerm(@NotNull cqlParser.PredecessorExpressionTermContext ctx) { return of.createPred().withOperand(parseExpression(ctx.expressionTerm())); } @Override public Object visitSuccessorExpressionTerm(@NotNull cqlParser.SuccessorExpressionTermContext ctx) { return of.createSucc().withOperand(parseExpression(ctx.expressionTerm())); } @Override public Object visitTimeBoundaryExpressionTerm(@NotNull cqlParser.TimeBoundaryExpressionTermContext ctx) { return ctx.getChild(0).getText().equals("start") ? of.createBegin().withOperand(parseExpression(ctx.expressionTerm())) : of.createEnd().withOperand(parseExpression(ctx.expressionTerm())); } @Override public Object visitTimeUnitExpressionTerm(@NotNull cqlParser.TimeUnitExpressionTermContext ctx) { String component = ctx.dateTimeComponent().getText(); switch (component) { case "date": return of.createDateOf().withOperand(parseExpression(ctx.expressionTerm())); case "time": return of.createTimeOf().withOperand(parseExpression(ctx.expressionTerm())); case "timezone": return of.createTimezoneOf().withOperand(parseExpression(ctx.expressionTerm())); case "year": return of.createYearOf().withOperand(parseExpression(ctx.expressionTerm())); case "month": return of.createMonthOf().withOperand(parseExpression(ctx.expressionTerm())); case "day": return of.createDayOf().withOperand(parseExpression(ctx.expressionTerm())); case "hour": return of.createHourOf().withOperand(parseExpression(ctx.expressionTerm())); case "minute": return of.createMinuteOf().withOperand(parseExpression(ctx.expressionTerm())); case "second": return of.createSecondOf().withOperand(parseExpression(ctx.expressionTerm())); case "millisecond": return of.createMillisecondOf().withOperand(parseExpression(ctx.expressionTerm())); } return of.createNull(); } @Override public Object visitDurationExpressionTerm(@NotNull cqlParser.DurationExpressionTermContext ctx) { // duration in days of X <=> days between start of X and end of X switch (ctx.pluralDateTimePrecision().getText()) { case "years" : return of.createYearsBetween().withOperand( of.createBegin().withOperand(parseExpression(ctx.expressionTerm())), of.createEnd().withOperand(parseExpression(ctx.expressionTerm())) ); case "months" : return of.createMonthsBetween().withOperand( of.createBegin().withOperand(parseExpression(ctx.expressionTerm())), of.createEnd().withOperand(parseExpression(ctx.expressionTerm())) ); case "days" : return of.createDaysBetween().withOperand( of.createBegin().withOperand(parseExpression(ctx.expressionTerm())), of.createEnd().withOperand(parseExpression(ctx.expressionTerm())) ); case "hours" : return of.createHoursBetween().withOperand( of.createBegin().withOperand(parseExpression(ctx.expressionTerm())), of.createEnd().withOperand(parseExpression(ctx.expressionTerm())) ); case "minutes" : return of.createMinutesBetween().withOperand( of.createBegin().withOperand(parseExpression(ctx.expressionTerm())), of.createEnd().withOperand(parseExpression(ctx.expressionTerm())) ); case "seconds" : return of.createSecondsBetween().withOperand( of.createBegin().withOperand(parseExpression(ctx.expressionTerm())), of.createEnd().withOperand(parseExpression(ctx.expressionTerm())) ); case "milliseconds" : return of.createMillisecondsBetween().withOperand( of.createBegin().withOperand(parseExpression(ctx.expressionTerm())), of.createEnd().withOperand(parseExpression(ctx.expressionTerm())) ); } return of.createNull(); } @Override public Object visitRangeExpression(@NotNull cqlParser.RangeExpressionContext ctx) { // X properly? between Y and Z Expression first = parseExpression(ctx.expression()); Expression second = parseExpression(ctx.expressionTerm(0)); Expression third = parseExpression(ctx.expressionTerm(1)); boolean isProper = ctx.getChild(0).getText().equals("properly"); return of.createAnd() .withOperand( (isProper ? of.createGreater() : of.createGreaterOrEqual()) .withOperand(first, second), (isProper ? of.createLess() : of.createLessOrEqual()) .withOperand(first, third) ); } @Override public Object visitTimeRangeExpression(@NotNull cqlParser.TimeRangeExpressionContext ctx) { String component = ctx.pluralDateTimePrecision().getText(); switch (component) { case "years": return of.createYearsBetween() .withOperand(parseExpression(ctx.expressionTerm(0)), parseExpression(ctx.expressionTerm(1))); case "months": return of.createMonthsBetween() .withOperand(parseExpression(ctx.expressionTerm(0)), parseExpression(ctx.expressionTerm(1))); case "days": return of.createDaysBetween() .withOperand(parseExpression(ctx.expressionTerm(0)), parseExpression(ctx.expressionTerm(1))); case "hours": return of.createHoursBetween() .withOperand(parseExpression(ctx.expressionTerm(0)), parseExpression(ctx.expressionTerm(1))); case "minutes": return of.createMinutesBetween() .withOperand(parseExpression(ctx.expressionTerm(0)), parseExpression(ctx.expressionTerm(1))); case "seconds": return of.createSecondsBetween() .withOperand(parseExpression(ctx.expressionTerm(0)), parseExpression(ctx.expressionTerm(1))); case "milliseconds": return of.createMillisecondsBetween() .withOperand(parseExpression(ctx.expressionTerm(0)), parseExpression(ctx.expressionTerm(1))); } return of.createNull(); } @Override public Object visitWidthExpressionTerm(@NotNull cqlParser.WidthExpressionTermContext ctx) { return of.createWidth().withOperand(parseExpression(ctx.expressionTerm())); } @Override public Expression visitParenthesizedTerm(@NotNull cqlParser.ParenthesizedTermContext ctx) { return parseExpression(ctx.expression()); } @Override public Object visitMembershipExpression(@NotNull cqlParser.MembershipExpressionContext ctx) { String operator = ctx.getChild(1).getText(); switch (operator) { case "in": return of.createIn().withOperand( parseExpression(ctx.expression(0)), parseExpression(ctx.expression(1)) ); case "contains": return of.createContains().withOperand( parseExpression(ctx.expression(0)), parseExpression(ctx.expression(1)) ); } return of.createNull(); } @Override public And visitAndExpression(@NotNull cqlParser.AndExpressionContext ctx) { return of.createAnd().withOperand( parseExpression(ctx.expression(0)), parseExpression(ctx.expression(1))); } @Override public Expression visitOrExpression(@NotNull cqlParser.OrExpressionContext ctx) { if (ctx.getChild(1).getText().equals("xor")) { return of.createXor().withOperand( parseExpression(ctx.expression(0)), parseExpression(ctx.expression(1))); } else { return of.createOr().withOperand( parseExpression(ctx.expression(0)), parseExpression(ctx.expression(1))); } } @Override public Object visitInFixSetExpression(@NotNull cqlParser.InFixSetExpressionContext ctx) { String operator = ctx.getChild(1).getText(); switch (operator) { case "union": return of.createUnion().withOperand( parseExpression(ctx.expression(0)), parseExpression(ctx.expression(1)) ); case "intersect": return of.createIntersect().withOperand( parseExpression(ctx.expression(0)), parseExpression(ctx.expression(1)) ); case "except": return of.createDifference().withOperand( parseExpression(ctx.expression(0)), parseExpression(ctx.expression(1)) ); } return of.createNull(); } @Override public BinaryExpression visitEqualityExpression(@NotNull cqlParser.EqualityExpressionContext ctx) { BinaryExpression exp = "=".equals(parseString(ctx.getChild(1))) ? of.createEqual() : of.createNotEqual(); return exp.withOperand( parseExpression(ctx.expression(0)), parseExpression(ctx.expression(1))); } @Override public BinaryExpression visitInequalityExpression(@NotNull cqlParser.InequalityExpressionContext ctx) { BinaryExpression exp; switch(parseString(ctx.getChild(1))) { case "<=": exp = of.createLessOrEqual(); break; case "<": exp = of.createLess(); break; case ">": exp = of.createGreater(); break; case ">=": exp = of.createGreaterOrEqual(); break; default: exp = of.createBinaryExpression(); } return exp.withOperand( parseExpression(ctx.expression(0)), parseExpression(ctx.expression(1))); } @Override public Expression visitQualifiedIdentifier(@NotNull cqlParser.QualifiedIdentifierContext ctx) { // QualifiedIdentifier can only appear as a query source, so it can only be an // ExpressionRef, a library qualified ExpressionRef, or an Alias qualified property ref. if (ctx.qualifier() != null) { String alias = resolveAlias(ctx.qualifier().getText()); if (alias != null) { return of.createProperty().withPath(parseString(ctx.IDENTIFIER())).withScope(alias); } } String alias = resolveAlias(ctx.IDENTIFIER().getText()); if (alias != null) { return of.createAliasRef().withName(alias); } return of.createExpressionRef() .withLibraryName(parseString(ctx.qualifier())) .withName(parseString(ctx.IDENTIFIER())); } @Override public Expression visitValueset(@NotNull cqlParser.ValuesetContext ctx) { Expression exp; if (ctx.VALUESET() != null) { exp = of.createValueSetRef() .withName(parseString(ctx.VALUESET())); if (ctx.qualifier() != null) { ((ValueSetRef)exp).withLibraryName(parseString(ctx.qualifier())); } } else { exp = of.createExpressionRef() .withLibraryName(parseString(ctx.qualifier())) .withName(parseString(ctx.IDENTIFIER())); } return exp; } @Override public Expression visitAccessorExpressionTerm(@NotNull cqlParser.AccessorExpressionTermContext ctx) { Expression left = parseExpression(ctx.expressionTerm()); // if left is a LibraryRef // if right is an IDENTIFIER // right may be a ParameterRef or an ExpressionRef -- need to resolve on the referenced library // return an ExpressionRef with the LibraryName set to the name of the LibraryRef // if right is a VALUESET // return a ValueSetRef with the LibraryName set to the name of the LibraryRef // if left is an ExpressionRef // if right is an IDENTIFIER // return a Property with the ExpressionRef as source and IDENTIFIER as Path // if right is a VALUESET, throw // if left is a PropertyRef // if right is an IDENTIFIER // modify the Property to append the IDENTIFIER to the PATH // if right is a VALUESET, throw // if left is an AliasRef // return a Property with a Path and no source, and Scope set to the Alias // if left is an Identifier // return a new Identifier with left as a qualifier // else // return an Identifier for resolution later by a method or accessor if (left instanceof LibraryRef) { if (ctx.IDENTIFIER() != null) { Library referencedLibrary = resolveLibrary(((LibraryRef)left).getLibraryName()); String parameterName = resolveParameterName(referencedLibrary, ctx.IDENTIFIER().getText()); if (parameterName != null) { return of.createParameterRef() .withLibraryName(((LibraryRef)left).getLibraryName()) .withName(ctx.IDENTIFIER().getText()); } String expressionName = resolveExpressionName(referencedLibrary, ctx.IDENTIFIER().getText()); if (expressionName != null) { return of.createExpressionRef() .withLibraryName(((LibraryRef)left).getLibraryName()) .withName(ctx.IDENTIFIER().getText()); } Identifier identifier = new Identifier(); identifier.setLibraryName(((LibraryRef)left).getLibraryName()); identifier.setIdentifier(ctx.IDENTIFIER().getText()); } if (ctx.VALUESET() != null) { return of.createValueSetRef() .withLibraryName(((LibraryRef)left).getLibraryName()) .withName(ctx.VALUESET().getText()); } } if (left instanceof ExpressionRef) { if (ctx.IDENTIFIER() != null) { return of.createProperty() .withSource(left) .withPath(ctx.IDENTIFIER().getText()); } } if (left instanceof AliasRef) { if (ctx.IDENTIFIER() != null) { return of.createProperty() .withScope(((AliasRef)left).getName()) .withPath(ctx.IDENTIFIER().getText()); } } if (left instanceof Property) { if (ctx.IDENTIFIER() != null) { Property property = (Property)left; property.setPath(String.format("%s.%s", property.getPath(), ctx.IDENTIFIER().getText())); return property; } } // TODO: Error handling, this should throw, or return an Error() or something. return of.createNull(); } @Override public Expression visitIdentifierTerm(@NotNull cqlParser.IdentifierTermContext ctx) { // An Identifier will always be: // 1: The name of a library // 2: The name of a parameter // 3: The name of an expression // 4: The name of an alias // 5: An unresolved identifier that must be resolved later (by a method or accessor) String identifier = ctx.IDENTIFIER().getText(); String libraryName = resolveLibraryName(identifier); if (libraryName != null) { LibraryRef libraryRef = new LibraryRef(); libraryRef.setLibraryName(libraryName); return libraryRef; } String parameterName = resolveParameterName(identifier); if (parameterName != null) { return of.createParameterRef().withName(parameterName); } String expressionName = resolveExpressionName(identifier); if (expressionName != null) { return of.createExpressionRef().withName(expressionName); } String alias = resolveAlias(identifier); if (alias != null) { return of.createAliasRef().withName(identifier); } Identifier id = new Identifier(); id.setIdentifier(identifier); return id; } @Override public Object visitTermExpression(@NotNull cqlParser.TermExpressionContext ctx) { return visit(ctx.expressionTerm()); } @Override public Object visitConversionExpressionTerm(@NotNull cqlParser.ConversionExpressionTermContext ctx) { return of.createConvert().withOperand(parseExpression(ctx.expression())) .withToType(resolveTypeSpecifierToQName(parseTypeSpecifier(ctx.typeSpecifier()))); } @Override public Object visitTypeExpression(@NotNull cqlParser.TypeExpressionContext ctx) { if (ctx.getChild(1).getText().equals("is")) { return of.createIs() .withOperand(parseExpression(ctx.expression())) .withIsTypeSpecifier(parseTypeSpecifier(ctx.typeSpecifier())); } return of.createAs() .withOperand(parseExpression(ctx.expression())) .withAsTypeSpecifier(parseTypeSpecifier(ctx.typeSpecifier())) .withStrict(false); // CQL doesn't support the notion of a strict type-cast } @Override public Expression visitBooleanExpression(@NotNull cqlParser.BooleanExpressionContext ctx) { Expression exp; Expression left = (Expression) visit(ctx.expression()); String lastChild = ctx.getChild(ctx.getChildCount() - 1).getText(); String nextToLast = ctx.getChild(ctx.getChildCount() - 2).getText(); if (lastChild.equals("null")) { exp = of.createIsNull().withOperand(left); } else { exp = of.createEqual().withOperand(left, createLiteral(Boolean.valueOf(lastChild))); } if ("not".equals(nextToLast)) { exp = of.createNot().withOperand(exp); } return exp; } @Override public Object visitTimingExpression(@NotNull cqlParser.TimingExpressionContext ctx) { Expression left = parseExpression(ctx.expression(0)); Expression right = parseExpression(ctx.expression(1)); TimingOperatorContext timingOperatorContext = new TimingOperatorContext(); timingOperators.push(timingOperatorContext); try { return visit(ctx.intervalOperatorPhrase()); } finally { timingOperators.pop(); } } @Override public Object visitConcurrentWithIntervalOperatorPhrase(@NotNull cqlParser.ConcurrentWithIntervalOperatorPhraseContext ctx) { // ('starts' | 'ends')? relativeQualifier? 'same' dateTimePrecision? 'as' ('start' | 'end')? TimingOperatorContext timingOperator = timingOperators.peek(); ParseTree firstChild = ctx.getChild(0); if ("starts".equals(firstChild.getText())) { timingOperator.setLeft(of.createBegin().withOperand(timingOperator.getLeft())); } if ("ends".equals(firstChild.getText())) { timingOperator.setLeft(of.createEnd().withOperand(timingOperator.getLeft())); } ParseTree lastChild = ctx.getChild(ctx.getChildCount() - 1); if ("start".equals(lastChild.getText())) { timingOperator.setRight(of.createBegin().withOperand(timingOperator.getRight())); } if ("end".equals(lastChild.getText())) { timingOperator.setRight(of.createEnd().withOperand(timingOperator.getRight())); } BinaryExpression operator = null; if (ctx.dateTimePrecision() != null) { switch (ctx.dateTimePrecision().getText()) { case "year": operator = of.createSameYearAs(); break; case "month": operator = of.createSameMonthAs(); break; case "day": operator = of.createSameDayAs(); break; case "hour": operator = of.createSameHourAs(); break; case "minute": operator = of.createSameMinuteAs(); break; case "second": operator = of.createSameSecondAs(); break; // NOTE: No milliseconds here, because same millisecond as is equivalent to same as } } if (operator == null) { operator = of.createSameAs(); } operator = operator.withOperand(timingOperator.getLeft(), timingOperator.getRight()); if (ctx.relativeQualifier() != null) { switch (ctx.relativeQualifier().getText()) { case "at least": return of.createOr().withOperand( operator, of.createGreater().withOperand(timingOperator.getLeft(), timingOperator.getRight()) ); case "at most": return of.createOr().withOperand( operator, of.createLess().withOperand(timingOperator.getLeft(), timingOperator.getRight()) ); } } return operator; } @Override public Object visitIncludesIntervalOperatorPhrase(@NotNull cqlParser.IncludesIntervalOperatorPhraseContext ctx) { // properly? includes (start | end)? boolean isProper = false; boolean isRightPoint = false; TimingOperatorContext timingOperator = timingOperators.peek(); for (ParseTree pt : ctx.children) { if ("properly".equals(pt.getText())) { isProper = true; continue; } if ("start".equals(pt.getText())) { timingOperator.setRight(of.createBegin().withOperand(timingOperator.getRight())); isRightPoint = true; continue; } if ("end".equals(pt.getText())) { timingOperator.setRight(of.createEnd().withOperand(timingOperator.getRight())); isRightPoint = true; continue; } } if (isRightPoint) { // TODO: Handle is proper (no ELM representation for ProperContains) return of.createContains().withOperand(timingOperator.getLeft(), timingOperator.getRight()); } if (isProper) { return of.createProperIncludes().withOperand(timingOperator.getLeft(), timingOperator.getRight()); } return of.createIncludes().withOperand(timingOperator.getLeft(), timingOperator.getRight()); } @Override public Object visitIncludedInIntervalOperatorPhrase(@NotNull cqlParser.IncludedInIntervalOperatorPhraseContext ctx) { // (starts | ends)? properly? (during | included in) boolean isProper = false; boolean isLeftPoint = false; TimingOperatorContext timingOperator = timingOperators.peek(); for (ParseTree pt : ctx.children) { if ("starts".equals(pt.getText())) { timingOperator.setLeft(of.createBegin().withOperand(timingOperator.getLeft())); isLeftPoint = true; continue; } if ("ends".equals(pt.getText())) { timingOperator.setLeft(of.createEnd().withOperand(timingOperator.getLeft())); isLeftPoint = true; continue; } if ("properly".equals(pt.getText())) { isProper = true; continue; } } if (isLeftPoint) { // TODO: Handle is proper (no ELM representation for ProperIn) return of.createIn().withOperand(timingOperator.getLeft(), timingOperator.getRight()); } if (isProper) { return of.createProperIncludedIn().withOperand(timingOperator.getLeft(), timingOperator.getRight()); } return of.createIncludedIn().withOperand(timingOperator.getLeft(), timingOperator.getRight()); } @Override public Object visitBeforeOrAfterIntervalOperatorPhrase(@NotNull cqlParser.BeforeOrAfterIntervalOperatorPhraseContext ctx) { // ('starts' | 'ends')? quantityOffset? ('before' | 'after') ('start' | 'end')? // duration before/after // A starts 3 days before start B // days between start of A and start of B = 3 // A starts 3 days after start B // days between start of A and start of B = -3 // at least/most duration before/after // A starts at least 3 days before start B // days between start of A and start of B >= 3 // A starts at least 3 days after start B // days between start of A and start of B <= -3 // A starts at most 3 days before start B // days between start of A and start of B <= 3 // A starts at most 3 days after start B // days between start of A and start of B >= -3 TimingOperatorContext timingOperator = timingOperators.peek(); Boolean isBefore = false; for (ParseTree child : ctx.children) { if ("starts".equals(child.getText())) { timingOperator.setLeft(of.createBegin().withOperand(timingOperator.getLeft())); continue; } if ("ends".equals(child.getText())) { timingOperator.setLeft(of.createBegin().withOperand(timingOperator.getLeft())); continue; } if ("start".equals(child.getText())) { timingOperator.setRight(of.createBegin().withOperand(timingOperator.getRight())); continue; } if ("end".equals(child.getText())) { timingOperator.setRight(of.createEnd().withOperand(timingOperator.getRight())); continue; } if ("before".equals(child.getText())) { isBefore = true; continue; } } if (ctx.quantityOffset() == null) { if (isBefore) { return of.createBefore().withOperand(timingOperator.getLeft(), timingOperator.getRight()); } else { return of.createAfter().withOperand(timingOperator.getLeft(), timingOperator.getRight()); } } else { Quantity quantity = (Quantity)visit(ctx.quantityOffset().quantityLiteral()); Literal quantityLiteral = createLiteral(quantity.getValue().intValueExact()); BinaryExpression betweenOperator = resolveBetweenOperator(quantity.getUnit(), timingOperator.getLeft(), timingOperator.getRight()); if (betweenOperator != null) { if (ctx.quantityOffset().relativeQualifier() == null) { if (isBefore) { return of.createEqual().withOperand( betweenOperator, quantityLiteral ); } else { return of.createEqual().withOperand( betweenOperator, of.createNegate().withOperand(quantityLiteral) ); } } else { switch (ctx.quantityOffset().relativeQualifier().getText()) { case "at least": if (isBefore) { return of.createGreaterOrEqual().withOperand( betweenOperator, quantityLiteral ); } else { return of.createLessOrEqual().withOperand( betweenOperator, of.createNegate().withOperand(quantityLiteral) ); } case "at most": if (isBefore) { return of.createLessOrEqual().withOperand( betweenOperator, quantityLiteral ); } else { return of.createGreaterOrEqual().withOperand( betweenOperator, of.createNegate().withOperand(quantityLiteral) ); } } } } } // TODO: Error handling return of.createNull(); } private BinaryExpression resolveBetweenOperator(String unit, Expression left, Expression right) { if (unit != null) { switch (unit) { case "year": case "years": return of.createYearsBetween().withOperand(left, right); case "month": case "months": return of.createMonthsBetween().withOperand(left, right); case "week": case "weeks": return of.createMultiply().withOperand( of.createDaysBetween().withOperand(left, right), createLiteral(7)); case "day": case "days": return of.createDaysBetween().withOperand(left, right); case "hour": case "hours": return of.createHoursBetween().withOperand(left, right); case "minute": case "minutes": return of.createMinutesBetween().withOperand(left, right); case "second": case "seconds": return of.createSecondsBetween().withOperand(left, right); case "millisecond": case "milliseconds": return of.createMillisecondsBetween().withOperand(left, right); } } return null; } @Override public Object visitWithinIntervalOperatorPhrase(@NotNull cqlParser.WithinIntervalOperatorPhraseContext ctx) { // ('starts' | 'ends')? 'properly'? 'within' quantityLiteral 'of' ('start' | 'end')? // A starts within 3 days of start B // days between start of A and start of B in [-3, 3] TimingOperatorContext timingOperator = timingOperators.peek(); boolean isProper = false; for (ParseTree child : ctx.children) { if ("starts".equals(child.getText())) { timingOperator.setLeft(of.createBegin().withOperand(timingOperator.getLeft())); continue; } if ("ends".equals(child.getText())) { timingOperator.setLeft(of.createBegin().withOperand(timingOperator.getLeft())); continue; } if ("start".equals(child.getText())) { timingOperator.setRight(of.createBegin().withOperand(timingOperator.getRight())); continue; } if ("end".equals(child.getText())) { timingOperator.setRight(of.createEnd().withOperand(timingOperator.getRight())); continue; } if ("properly".equals(child.getText())) { isProper = true; continue; } } Quantity quantity = (Quantity)visit(ctx.quantityLiteral()); Literal quantityLiteral = createLiteral(quantity.getValue().intValueExact()); Interval quantityInterval = of.createInterval() .withBegin(of.createNegate().withOperand(quantityLiteral)).withBeginOpen(isProper) .withEnd(quantityLiteral).withEndOpen(isProper); BinaryExpression betweenOperator = resolveBetweenOperator(quantity.getUnit(), timingOperator.getLeft(), timingOperator.getRight()); if (betweenOperator != null) { return of.createIn().withOperand(betweenOperator, quantityInterval); } // TODO: Error handling return of.createNull(); } @Override public Object visitMeetsIntervalOperatorPhrase(@NotNull cqlParser.MeetsIntervalOperatorPhraseContext ctx) { BinaryExpression operator; if (ctx.getChildCount() == 1) { operator = of.createMeets(); } else { if ("before".equals(ctx.getChild(1).getText())) { operator = of.createMeetsBefore(); } else { operator = of.createMeetsAfter(); } } return operator.withOperand(timingOperators.peek().getLeft(), timingOperators.peek().getRight()); } @Override public Object visitOverlapsIntervalOperatorPhrase(@NotNull cqlParser.OverlapsIntervalOperatorPhraseContext ctx) { BinaryExpression operator; if (ctx.getChildCount() == 1) { operator = of.createOverlaps(); } else { if ("before".equals(ctx.getChild(1).getText())) { operator = of.createOverlapsBefore(); } else { operator = of.createOverlapsAfter(); } } return operator.withOperand(timingOperators.peek().getLeft(), timingOperators.peek().getRight()); } @Override public Object visitStartsIntervalOperatorPhrase(@NotNull cqlParser.StartsIntervalOperatorPhraseContext ctx) { return of.createBegins().withOperand(timingOperators.peek().getLeft(), timingOperators.peek().getRight()); } @Override public Object visitStartedByIntervalOperatorPhrase(@NotNull cqlParser.StartedByIntervalOperatorPhraseContext ctx) { return of.createBegunBy().withOperand(timingOperators.peek().getLeft(), timingOperators.peek().getRight()); } @Override public Object visitEndsIntervalOperatorPhrase(@NotNull cqlParser.EndsIntervalOperatorPhraseContext ctx) { return of.createEnds().withOperand(timingOperators.peek().getLeft(), timingOperators.peek().getRight()); } @Override public Object visitEndedByIntervalOperatorPhrase(@NotNull cqlParser.EndedByIntervalOperatorPhraseContext ctx) { return of.createEndedBy().withOperand(timingOperators.peek().getLeft(), timingOperators.peek().getRight()); } @Override public Object visitIfThenElseExpressionTerm(@NotNull cqlParser.IfThenElseExpressionTermContext ctx) { return of.createConditional() .withCondition(parseExpression(ctx.expression(0))) .withThen(parseExpression(ctx.expression(1))) .withElse(parseExpression(ctx.expression(2))); } @Override public Object visitCaseExpressionTerm(@NotNull cqlParser.CaseExpressionTermContext ctx) { Case result = of.createCase(); Boolean hitElse = false; for (ParseTree pt : ctx.children) { if ("else".equals(pt.getText())) { hitElse = true; continue; } if (pt instanceof cqlParser.ExpressionContext) { if (hitElse) { result.setElse(parseExpression(pt)); } else { result.setComparand(parseExpression(pt)); } } if (pt instanceof cqlParser.CaseExpressionItemContext) { result.getCaseItem().add((CaseItem)visit(pt)); } } return result; } @Override public Object visitCaseExpressionItem(@NotNull cqlParser.CaseExpressionItemContext ctx) { return of.createCaseItem() .withWhen(parseExpression(ctx.expression(0))) .withThen(parseExpression(ctx.expression(1))); } @Override public Object visitCoalesceExpressionTerm(@NotNull cqlParser.CoalesceExpressionTermContext ctx) { List<Expression> expressions = new ArrayList<>(); for (cqlParser.ExpressionContext expression : ctx.expression()) { expressions.add(parseExpression(expression)); } return of.createCoalesce().withOperand(expressions); } @Override public Object visitAggregateExpressionTerm(@NotNull cqlParser.AggregateExpressionTermContext ctx) { switch (ctx.getChild(0).getText()) { case "distinct": return of.createDistinct().withSource(parseExpression(ctx.expression())); case "collapse": return of.createCollapse().withOperand(parseExpression(ctx.expression())); case "expand": return of.createExpand().withOperand(parseExpression(ctx.expression())); } // TODO: Error-handling return of.createNull(); } @Override public ClinicalRequest visitRetrieve(@NotNull cqlParser.RetrieveContext ctx) { String occ = ctx.occurrence() != null ? ctx.occurrence().getText() : "Occurrence"; // TODO: Default occurrence label by model? String topic = parseString(ctx.topic()); String modality = ctx.modality() != null ? ctx.modality().getText() : ""; ClassDetail detail = modelHelper.getClassDetail(occ, topic, modality); ClinicalRequest request = of.createClinicalRequest() .withDataType(resolveNamedType( detail != null ? detail.getClassInfo().getName() : String.format("%s%s%s", topic, modality, occ))); if (ctx.valueset() != null) { if (ctx.valuesetPathIdentifier() != null) { request.setCodeProperty(parseString(ctx.valuesetPathIdentifier())); } else if (detail != null && detail.getClassInfo().getPrimaryCodeAttribute() != null) { request.setCodeProperty(detail.getClassInfo().getPrimaryCodeAttribute()); } request.setCodes(parseExpression(ctx.valueset())); } if (ctx.expression() != null) { if (ctx.duringPathIdentifier() != null) { request.setDateProperty(parseString(ctx.duringPathIdentifier())); } else if (detail != null && detail.getClassInfo().getPrimaryDateAttribute() != null) { request.setDateProperty(detail.getClassInfo().getPrimaryDateAttribute()); } request.setDateRange(parseExpression(ctx.expression())); } clinicalRequests.add(request); return request; } @Override public Object visitQuery(@NotNull cqlParser.QueryContext ctx) { QueryContext queryContext = new QueryContext(); AliasedQuerySource aqs = (AliasedQuerySource) visit(ctx.aliasedQuerySource()); queryContext.addQuerySource(aqs); queries.push(queryContext); try { List<RelationshipClause> qicx = new ArrayList<>(); if (ctx.queryInclusionClause() != null) { for (cqlParser.QueryInclusionClauseContext queryInclusionClauseContext : ctx.queryInclusionClause()) { qicx.add((RelationshipClause) visit(queryInclusionClauseContext)); } } Expression where = ctx.whereClause() != null ? (Expression) visit(ctx.whereClause()) : null; Expression ret = ctx.returnClause() != null ? (Expression) visit(ctx.returnClause()) : null; SortClause sort = ctx.sortClause() != null ? (SortClause) visit(ctx.sortClause()) : null; return of.createQuery() .withSource(aqs) .withRelationship(qicx) .withWhere(where) .withReturn(ret) .withSort(sort); } finally { queries.pop(); } } @Override public Object visitAliasedQuerySource(@NotNull cqlParser.AliasedQuerySourceContext ctx) { return of.createAliasedQuerySource().withExpression(parseExpression(ctx.querySource())) .withAlias(ctx.alias().getText()); } @Override public Object visitQueryInclusionClause(@NotNull cqlParser.QueryInclusionClauseContext ctx) { boolean negated = ctx.getChild(0).equals("without"); AliasedQuerySource aqs = (AliasedQuerySource) visit(ctx.aliasedQuerySource()); queries.peek().addQuerySource(aqs); try { Expression expression = (Expression) visit(ctx.expression()); RelationshipClause result = negated ? of.createWithout() : of.createWith(); return result.withExpression(aqs.getExpression()).withAlias(aqs.getAlias()).withWhere(expression); } finally { queries.peek().removeQuerySource(aqs); } } @Override public Object visitWhereClause(@NotNull cqlParser.WhereClauseContext ctx) { return visit(ctx.expression()); } @Override public Object visitReturnClause(@NotNull cqlParser.ReturnClauseContext ctx) { return visit(ctx.expression()); } @Override public SortDirection visitSortDirection(@NotNull cqlParser.SortDirectionContext ctx) { if (ctx.getText().equals("desc")) { return SortDirection.DESC; } return SortDirection.ASC; } private SortDirection parseSortDirection(cqlParser.SortDirectionContext ctx) { if (ctx != null) { return visitSortDirection(ctx); } return SortDirection.ASC; } @Override public SortByItem visitSortByItem(@NotNull cqlParser.SortByItemContext ctx) { return of.createByExpression() .withExpression(parseExpression(ctx.expressionTerm())) .withDirection(parseSortDirection(ctx.sortDirection())); } @Override public Object visitSortClause(@NotNull cqlParser.SortClauseContext ctx) { if (ctx.sortDirection() != null) { return of.createSortClause() .withBy(of.createByDirection().withDirection(parseSortDirection(ctx.sortDirection()))); } List<SortByItem> sortItems = new ArrayList<>(); if (ctx.sortByItem() != null) { for (cqlParser.SortByItemContext sortByItemContext : ctx.sortByItem()) { sortItems.add((SortByItem) visit(sortByItemContext)); } } return of.createSortClause().withBy(sortItems); } @Override public Object visitQuerySource(@NotNull cqlParser.QuerySourceContext ctx) { ParseTree o = ctx.expression(); if (o == null) { o = ctx.retrieve(); } if (o == null) { o = ctx.qualifiedIdentifier(); } return visit(o); } @Override public Object visitIndexedExpressionTerm(@NotNull cqlParser.IndexedExpressionTermContext ctx) { return of.createIndexer() .withOperand(parseExpression(ctx.expressionTerm())) .withIndex(parseExpression(ctx.expression())); } @Override public Object visitMethodExpressionTerm(@NotNull cqlParser.MethodExpressionTermContext ctx) { FunctionRef fun = of.createFunctionRef(); Expression left = parseExpression(ctx.expressionTerm()); if (left instanceof Identifier) { fun.setLibraryName(((Identifier)left).getLibraryName()); fun.setName(((Identifier)left).getIdentifier()); } if (ctx.expression() != null) { for (cqlParser.ExpressionContext expressionContext : ctx.expression()) { fun.getOperand().add((Expression) visit(expressionContext)); } } return fun; } @Override public Object visitFunctionDefinition(@NotNull cqlParser.FunctionDefinitionContext ctx) { FunctionDef fun = of.createFunctionDef().withName(parseString(ctx.IDENTIFIER())); if (ctx.operandDefinition() != null) { for (cqlParser.OperandDefinitionContext opdef : ctx.operandDefinition()) { fun.getParameter().add( of.createParameterDef() .withName(parseString(opdef.IDENTIFIER())) .withParameterTypeSpecifier(parseTypeSpecifier(opdef.typeSpecifier())) ); } } fun.setExpression(parseExpression(ctx.functionBody())); fun.setContext(currentContext); addToLibrary(fun); return fun; } // TODO: Retrieve definition // NOTE: Not spending any time here until we know whether we actually need retrieve definitions @Override public Object visitValuesetIdentifier(@NotNull cqlParser.ValuesetIdentifierContext ctx) { // TODO: return super.visitValuesetIdentifier(ctx); } @Override public Object visitDuringIdentifier(@NotNull cqlParser.DuringIdentifierContext ctx) { // TODO: return super.visitDuringIdentifier(ctx); } @Override public Object visitRetrieveDefinition(@NotNull cqlParser.RetrieveDefinitionContext ctx) { // TODO: return super.visitRetrieveDefinition(ctx); } private String parseString(ParseTree pt) { if (pt == null) return null; String text = pt.getText(); if (pt instanceof TerminalNode) { int tokenType = ((TerminalNode) pt).getSymbol().getType(); if (cqlLexer.STRING == tokenType || cqlLexer.VALUESET == tokenType) { // chop off leading and trailing ' or " text = text.substring(1, text.length() - 1); } } return text; } private Expression parseExpression(ParseTree pt) { return pt == null ? null : (Expression) visit(pt); } private TypeSpecifier parseTypeSpecifier(ParseTree pt) { return pt == null ? null : (TypeSpecifier) visit(pt); } private String resolveSystemNamedType(String typeName) { switch (typeName) { case "Boolean": return "bool"; case "Integer": return "int"; case "Decimal": return "decimal"; case "String": return "string"; case "DateTime": return "datetime"; default: return null; } } private QName resolveAxisType(String occurrence, String topic, String modality) { ClassDetail detail = modelHelper.getClassDetail(occurrence, topic, modality); if (detail != null) { return resolveNamedType(detail.getClassInfo().getName()); } return resolveNamedType(String.format("%s%s%s", topic, modality, occurrence)); } private QName resolveTypeSpecifierToQName(TypeSpecifier typeSpecifier) { if (typeSpecifier instanceof NamedTypeSpecifier) { return ((NamedTypeSpecifier)typeSpecifier).getName(); } return resolveNamedType("SIMPLE_TYPE_REQUIRED"); // Should throw? } private QName resolveNamedType(String typeName) { // Resolve system primitive types first String className = resolveSystemNamedType(typeName); if (className != null) { return new QName("http://ww.w3.org/2001/XMLSchema", className); } // TODO: Should attempt resolution in all models and throw if ambiguous // Model qualifier should be required to resolve ambiguity // Requires CQL change to allow qualifiers in atomicTypeSpecifier (which should really be called namedTypeSpecifier) className = modelHelper.resolveClassName(typeName); if (className != null) { return new QName(modelHelper.getModelInfo().getUrl(), className); } // TODO: Error-handling return new QName("http: } private Literal createLiteral(String val, String type) { return of.createLiteral().withValue(val).withValueType(resolveNamedType(type)); } private Literal createLiteral(String string) { return createLiteral(String.valueOf(string), "String"); } private Literal createLiteral(Boolean bool) { return createLiteral(String.valueOf(bool), "Boolean"); } private Literal createLiteral(Integer integer) { return createLiteral(String.valueOf(integer), "Integer"); } private String resolveAlias(String identifier) { for (QueryContext query : queries) { AliasedQuerySource source = query.resolveAlias(identifier); if (source != null) { return source.getAlias(); } } return null; } private void addToLibrary(ModelReference model) { if (library.getDataModels() == null) { library.setDataModels(of.createLibraryDataModels()); } library.getDataModels().getModelReference().add(model); } private void addToLibrary(ValueSetDef vs) { if (library.getValueSets() == null) { library.setValueSets(of.createLibraryValueSets()); } library.getValueSets().getDef().add(vs); } private void addToLibrary(ExpressionDef expDef) { if (library.getStatements() == null) { library.setStatements(of.createLibraryStatements()); } library.getStatements().getDef().add(expDef); } private String resolveExpressionName(String identifier) { if (libraryInfo != null) { return libraryInfo.resolveExpressionName(identifier); } return null; } private String resolveExpressionName(Library library, String identifier) { if (library.getStatements() != null) { for (ExpressionDef current : library.getStatements().getDef()) { if (!(current instanceof FunctionDef) && !(current instanceof ClinicalRequestDef) && (current.getName() == identifier)) { return identifier; } } } return null; } private String resolveFunctionName(String identifier) { if (libraryInfo != null) { return libraryInfo.resolveFunctionName(identifier); } return null; } private String resolveFunctionName(Library library, String identifier) { if (library.getStatements() != null) { for (ExpressionDef current : library.getStatements().getDef()) { if (current instanceof FunctionDef && current.getName() == identifier) { return identifier; } } } return null; } private void addToLibrary(ParameterDef paramDef) { if (library.getParameters() == null) { library.setParameters(of.createLibraryParameters()); } library.getParameters().getDef().add(paramDef); } private String resolveParameterName(String identifier) { if (libraryInfo != null) { return libraryInfo.resolveParameterName(identifier); } return null; } private String resolveParameterName(Library library, String identifier) { if (library.getParameters() != null) { for (ParameterDef current : library.getParameters().getDef()) { if (current.getName() == identifier) { return identifier; } } } return null; } private void addToLibrary(LibraryReference libraryReference) { if (library.getLibraries() == null) { library.setLibraries(of.createLibraryLibraries()); } library.getLibraries().getLibraryReference().add(libraryReference); Library referencedLibrary = new Library() .withIdentifier( new VersionedIdentifier() .withId(libraryReference.getPath()) .withVersion(libraryReference.getVersion())); // TODO: Resolve and prepare the actual library libraries.put(libraryReference.getName(), referencedLibrary); } private String resolveLibraryName(String identifier) { if (library.getLibraries() != null) { for (LibraryReference current : library.getLibraries().getLibraryReference()) { if (current.getName() == identifier) { return identifier; } } } return null; } private Library resolveLibrary(String identifier) { return libraries.get(identifier); } private TrackBack track(Trackable trackable, ParserRuleContext ctx) { TrackBack tb = new TrackBack( //of.createVersionedIdentifier().withId(library.getIdentifier().getId()).withVersion(library.getIdentifier().getVersion()), library.getIdentifier(), ctx.getStart().getLine(), ctx.getStart().getCharPositionInLine() + 1, // 1-based instead of 0-based ctx.getStop().getLine(), ctx.getStop().getCharPositionInLine() + ctx.getStop().getText().length() // 1-based instead of 0-based ); trackable.getTrackbacks().add(tb); return tb; } public static void main(String[] args) throws IOException, JAXBException { String inputFile = null; if (args.length > 0) inputFile = args[0]; InputStream is = System.in; if (inputFile != null) { is = new FileInputStream(inputFile); } ANTLRInputStream input = new ANTLRInputStream(is); cqlLexer lexer = new cqlLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); cqlParser parser = new cqlParser(tokens); parser.setBuildParseTree(true); ParseTree tree = parser.logic(); ElmTranslatorVisitor visitor = new ElmTranslatorVisitor(); visitor.visit(tree); /* ToString output System.out.println(visitor.getLibrary().toString()); */ /* XML output JAXB.marshal((new ObjectFactory()).createLibrary(visitor.getLibrary()), System.out); */ /* JSON output */ JAXBContext jc = JAXBContext.newInstance(Library.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty("eclipselink.media-type", "application/json"); marshaller.marshal(new ObjectFactory().createLibrary(visitor.getLibrary()), System.out); } }
package com.team3925.robot2016.util; import edu.wpi.first.wpilibj.util.BoundaryException; public class LimitPID { private double angleMultiplier; private double m_P; // factor for "proportional" control private double m_I; // factor for "integral" control private double m_D; // factor for "derivative" control private double m_P_max; private double m_I_max; private double m_D_max; private double m_totalError_max; private double m_P_min; private double m_I_min; private double m_D_min; private double m_totalError_min; private double m_maximumOutput = 1.0; // |maximum output| private double m_minimumOutput = -1.0; // |minimum output| private double m_maximumInput = 0.0; // maximum input - limit setpoint to // this private double m_minimumInput = 0.0; // minimum input - limit setpoint to // this private boolean m_continuous = false; // do the endpoints wrap around? eg. // Absolute encoder private double m_prevError = 0.0; // the prior sensor input (used to compute // velocity) private double m_totalError = 0.0; // the sum of the errors for use in the // integral calc private double m_setpoint = 0.0; private double m_error = 0.0; private double m_P_value = 0.0; private double m_I_value = 0.0; private double m_D_value = 0.0; // private double prev_m_D_value; // private double avg_m_D_value; private double m_result = 0.0; private double m_last_input = Double.NaN; public LimitPID() { } /** * Allocate a PID object with the given constants for P, I, D, P limit, I limit, D limit, Total Error limit * If P, I, D, or total error limits are less than 0, P, I, D, and total error values are not limited * * @param Kp the proportional coefficient * @param Ki the integral coefficient * @param Kd the derivative coefficient */ public LimitPID(double Kp, double Ki, double Kd, double maxP, double maxI, double maxD, double maxError, double minP, double minI, double minD, double minError) { m_P = Kp; m_I = Ki; m_D = Kd; m_P_max = maxP; m_I_max = maxI; m_D_max = maxD; m_totalError_max = maxError; m_P_min = minP; m_I_min = minI; m_D_min = minD; m_totalError_min = minError; } /** * Read the input, calculate the output accordingly, and write to the * output. This should be called at a constant rate by the user (ex. in a * timed thread) * * @param input * the input */ public double calculate(double input) { m_last_input = input; m_error = m_setpoint - input; if (m_continuous) { if (Math.abs(m_error) > (m_maximumInput - m_minimumInput) / 2) { if (m_error > 0) { m_error = m_error - m_maximumInput + m_minimumInput; } else { m_error = m_error + m_maximumInput - m_minimumInput; } } } if ((m_error * m_P < m_maximumOutput) && (m_error * m_P > m_minimumOutput)) { m_totalError += m_error; } else { m_totalError = 0; } m_totalError = Math.max(m_totalError_min, Math.min(m_totalError_max, m_totalError)); m_P_value = Math.max(m_P_min, Math.min(m_P_max, m_P * m_error)); m_I_value = Math.max(m_I_min, Math.min(m_I_max, m_I * m_totalError)); m_D_value = Math.max(m_D_min, Math.min(m_D_max, m_D * (m_error - m_prevError))); // avg_m_D_value = m_D_value*0.3 + prev_m_D_value*0.7; m_result = (m_P_value + m_I_value + m_D_value); m_prevError = m_error; // prev_m_D_value = avg_m_D_value; // SmartDashboard.putNumber("Launcher_PID_Avg_D_value", avg_m_D_value); if (m_result > m_maximumOutput) { m_result = m_maximumOutput; } else if (m_result < m_minimumOutput) { m_result = m_minimumOutput; } return m_result; } /** * Set the PID controller gain parameters. Set the proportional, integral, * and differential coefficients. * * @param p * Proportional coefficient * @param i * Integral coefficient * @param d * Differential coefficient */ public void setPID(double p, double i, double d) { m_P = p; m_I = i; m_D = d; } public void setPIDLimits(double pMax, double iMax, double dMax, double totalErrorMax, double pMin, double iMin, double dMin, double totalErrorMin) { m_P_max = (double) pMax; m_I_max = (double) iMax; m_D_max = (double) dMax; m_totalError_max = (double) totalErrorMax; m_P_min = (double) pMin; m_I_min = (double) iMin; m_D_min = (double) dMin; m_totalError_min = (double) totalErrorMin; } /** * Get the total accumulated error * * @return totalError */ public double getTotalError() { return m_totalError; } /** * Get the Proportional coefficient * * @return proportional coefficient */ public double getP() { return m_P; } /** * Get the Integral coefficient * * @return integral coefficient */ public double getI() { return m_I; } /** * Get the Differential coefficient * * @return differential coefficient */ public double getD() { return m_D; } /** * Get the Proportional limit value * @return proportional limit value */ public double getPLimit() { return m_P_max; } /** * Get the Integral limit value * @return integral limit value */ public double getILimit() { return m_I_max; } /** * Get the Derivative limit value * @return derivative limit value */ public double getDLimit() { return m_D_max; } /** * Get the Proportional part of the output * * @return p_value */ public double getPValue() { return m_P_value; } /** * Get the Integral part of the output * * @return i_value */ public double getIValue() { return m_I_value; } /** * Get the Derivative part of the output * * @return d_value */ public double getDValue() { return m_D_value; } /** * Return the current PID result This is always centered on zero and * constrained the the max and min outs * * @return the latest calculated output */ public double get() { return m_result; } /** * Set the PID controller to consider the input to be continuous, Rather * then using the max and min in as constraints, it considers them to be the * same point and automatically calculates the shortest route to the * setpoint. * * @param continuous * Set to true turns on continuous, false turns off continuous */ public void setContinuous(boolean continuous) { m_continuous = continuous; } /** * Set the PID controller to consider the input to be continuous, Rather * then using the max and min in as constraints, it considers them to be the * same point and automatically calculates the shortest route to the * setpoint. */ public void setContinuous() { this.setContinuous(true); } /** * Sets the maximum and minimum values expected from the input. * * @param minimumInput * the minimum value expected from the input * @param maximumInput * the maximum value expected from the output */ public void setInputRange(double minimumInput, double maximumInput) { if (minimumInput > maximumInput) { throw new BoundaryException("Lower bound is greater than upper bound"); } m_minimumInput = minimumInput; m_maximumInput = maximumInput; setSetpoint(m_setpoint); } /** * Sets the minimum and maximum values to write. * * @param minimumOutput * the minimum value to write to the output * @param maximumOutput * the maximum value to write to the output */ public void setOutputRange(double minimumOutput, double maximumOutput) { if (minimumOutput > maximumOutput) { throw new BoundaryException("Lower bound is greater than upper bound"); } m_minimumOutput = minimumOutput; m_maximumOutput = maximumOutput; } /** * Set the setpoint for the PID controller * * @param setpoint * the desired setpoint */ public void setSetpoint(double setpoint) { if (m_maximumInput > m_minimumInput) { if (setpoint > m_maximumInput) { m_setpoint = m_maximumInput; } else if (setpoint < m_minimumInput) { m_setpoint = m_minimumInput; } else { m_setpoint = setpoint; } } else { m_setpoint = setpoint; } } /** * Returns the current setpoint of the PID controller * * @return the current setpoint */ public double getSetpoint() { return m_setpoint; } /** * Returns the previous difference of the input from the setpoint * * @return the previous error */ public double getPrevError() { return m_prevError; } /** * Returns the current difference of the input from the setpoint * * @return the current error */ public double getError() { return m_error; } /** * Return true if the error is within the tolerance * * @return true if the error is less than the tolerance */ public boolean onTarget(double tolerance) { return m_last_input != Double.NaN && Math.abs(m_last_input - m_setpoint) < tolerance; } /** * Reset all internal terms. */ public void reset() { m_last_input = Double.NaN; m_prevError = 0; m_totalError = 0; m_result = 0; m_setpoint = 0; } public void resetIntegrator() { m_totalError = 0; } public String getState() { String lState = ""; lState += "Kp: " + m_P + "\n"; lState += "Ki: " + m_I + "\n"; lState += "Kd: " + m_D + "\n"; return lState; } public String getType() { return "PIDController"; } }
package com.timepath.tf2.hudedit; import com.timepath.tf2.hudedit.display.HudCanvas; import com.timepath.tf2.hudedit.loaders.ResLoader; import com.timepath.tf2.hudedit.util.Element; import com.timepath.tf2.hudedit.util.Property; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Desktop; import java.awt.Dimension; import java.awt.DisplayMode; import java.awt.FileDialog; import java.awt.GraphicsEnvironment; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.Icon; import javax.swing.JDialog; import javax.swing.JEditorPane; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTable; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableModel; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeSelectionModel; import net.tomahawk.XFileDialog; @SuppressWarnings("serial") public class EditorFrame extends JFrame { public static void main(String... args) { //<editor-fold defaultstate="collapsed" desc="Try and get nimbus look and feel, if it is installed."> try { for(UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch(Exception ex) { Logger.getLogger(EditorFrame.class.getName()).log(Level.WARNING, null, ex); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Display the editor"> SwingUtilities.invokeLater(new Runnable() { @Override public void run() { EditorFrame frame = new EditorFrame(); frame.start(); } }); //</editor-fold> } //<editor-fold defaultstate="collapsed" desc="OS specific code"> private final static OS os; private final static int shortcutKey; private enum OS { Windows, Mac, Linux, Other } static { String osVer = System.getProperty("os.name").toLowerCase(); if(osVer.indexOf("windows") != -1) { os = OS.Windows; } else if(osVer.indexOf("mac") != -1 || osVer.indexOf("OS X") != -1) { os = OS.Mac; } else if(osVer.indexOf("linux") != -1) { os = OS.Linux; // if ("GTK look and feel".equals(UIManager.getLookAndFeel().getName())) { // UIManager.put("FileChooserUI", "eu.kostia.gtkjfilechooser.ui.GtkFileChooserUI"); } else { os = OS.Other; System.out.println("Unrecognised OS: " + osVer); } if(os == OS.Windows) { shortcutKey = ActionEvent.CTRL_MASK; XFileDialog.setTraceLevel(0); } else if(os == OS.Mac) { shortcutKey = ActionEvent.META_MASK; System.setProperty("apple.awt.showGrowBox", "true"); System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("com.apple.macos.useScreenMenuBar", "true"); System.setProperty("com.apple.mrj.application.apple.menu.about.name application property", "TF2 HUD Editor"); } else if(os == OS.Linux) { shortcutKey = ActionEvent.CTRL_MASK; } else { shortcutKey = ActionEvent.CTRL_MASK; } } //</editor-fold> public EditorFrame() { super(); this.setTitle(ResourceBundle.getBundle("com/timepath/tf2/hudedit/lang").getString("Title")); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); DisplayMode d = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayMode(); this.setMinimumSize(new Dimension(640, 480)); this.setPreferredSize(new Dimension((int) (d.getWidth() / 1.5), (int) (d.getHeight() / 1.5))); this.setLocation((d.getWidth() / 2) - (this.getPreferredSize().width / 2), (d.getHeight() / 2) - (this.getPreferredSize().height / 2)); this.setJMenuBar(new EditorMenuBar()); final JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); splitPane.setResizeWeight(0.8); canvas = new HudCanvas(); canvasPane = new JScrollPane(canvas); // canvasPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); // canvasPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); splitPane.setLeftComponent(canvasPane); JSplitPane browser = new JSplitPane(JSplitPane.VERTICAL_SPLIT, new EditorFileTree(), new EditorPropertiesTable()); browser.setResizeWeight(0.5); splitPane.setRightComponent(browser); this.add(splitPane); this.pack(); this.setFocusableWindowState(true); } public void start() { this.setVisible(true); this.createBufferStrategy(3); // Triple buffered, any more sees minimal gain. } private JScrollPane canvasPane; public static HudCanvas canvas; // should not be static private ResLoader resloader; private JTree fileSystem; private DefaultMutableTreeNode hudFilesRoot; private PropertiesTable propTable; //<editor-fold defaultstate="collapsed" desc="Broesel's stuff"> // private void selectSteamLocation() { // boolean installPathValid = false; // File steamFolder = new File(""); // File installDir; // if (installDir != null && installDir.exists()) { // steamFolder = installDir.getParentFile().getParentFile().getParentFile().getParentFile(); // final JFileChooser chooser = new JFileChooser(steamFolder); // chooser.setDialogTitle("Select Steam\\ folder"); // chooser.setToolTipText("Please select you Steam\\ folder! Not any subfolders of it."); // chooser.setDialogType(JFileChooser.OPEN_DIALOG); // chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // final int returnVal = chooser.showOpenDialog(this); // File zipFile = null; // if (returnVal == JFileChooser.APPROVE_OPTION) { // final File steamappsFolder = new File(chooser.getSelectedFile(), "SteamApps"); // if (!steamappsFolder.exists()) { // showErrorDialog("Invalid path to ...\\Steam\\SteamApps\\: " + steamappsFolder.getAbsolutePath(), "No SteamApps\\ Folder"); // else if (!steamappsFolder.isDirectory()) { // showErrorDialog("The entered path is not a folder: " + steamappsFolder.getAbsolutePath(), "This is not a Folder"); // else { // // Steam-User auswhlen lassen // // DropDown erstellen // final JComboBox dropDown = new JComboBox(); // final File[] userFolders = steamappsFolder.listFiles(); // for (int i = 0; i < userFolders.length; i++) { // if (userFolders[i].isDirectory() && !userFolders[i].getName().equalsIgnoreCase("common") // && !userFolders[i].getName().equalsIgnoreCase("sourcemods")) { // // berprfen, ob in dem User-Ordner ein tf2 Ordner // // vorhanden ist // final Collection<String> gameFolders = Arrays.asList(userFolders[i].list()); // if (gameFolders.contains("team fortress 2")) { // dropDown.addItem(userFolders[i].getName()); // // berprfen ob dropdown elemente hat und dialog anzeigen // if (dropDown.getItemCount() > 0) { // final JPanel dialogPanel = new JPanel(); // dialogPanel.setLayout(new BoxLayout(dialogPanel, BoxLayout.Y_AXIS)); // dialogPanel.add(new JLabel("Please choose for which user you want to install the HUD")); // dialogPanel.add(dropDown); // JOptionPane.showMessageDialog(this, dialogPanel, "Select user", JOptionPane.QUESTION_MESSAGE); // else { // showErrorDialog("No users have TF2 installed!", "No TF2 found"); // return; // installDir = new File(steamappsFolder, dropDown.getSelectedItem() + File.separator + "team fortress 2" + File.separator + "tf"); // if (installDir.isDirectory() && installDir.exists()) { // installPathValid = true; // steamInput.setText(installDir.getAbsolutePath()); // try { // String zipFilePath = ""; // if (zipFile != null && zipFileValid) { // zipFilePath = zipFile.getAbsolutePath(); // saveInstallPath(installDir.getAbsolutePath(), zipFilePath); // catch (final IOException e1) { // showErrorDialog(e1.getMessage(), "Could not save installpath"); // e1.printStackTrace(); // else { // showErrorDialog("This is not a valid install location for broeselhud", "No valid installpath"); //</editor-fold> /** * Start in the home directory * System.getProperty("user.home") * linux = ~ * windows = %userprofile% * mac = ? */ private void locateHudDirectory() { if(hudSelection == null) { if(os == OS.Mac) { System.setProperty("apple.awt.fileDialogForDirectories", "true"); System.setProperty("com.apple.macos.use-file-dialog-packages", "true"); FileDialog fd = new FileDialog(this, "Open a HUD folder"); fd.setVisible(true); hudSelection = fd.getFile(); System.setProperty("apple.awt.fileDialogForDirectories", "false"); System.setProperty("com.apple.macos.use-file-dialog-packages", "false"); } else if(os == OS.Windows) { XFileDialog fd = new XFileDialog(this); // was EditorFrame.this fd.setTitle("Open a HUD folder"); hudSelection = fd.getFolder(); fd.dispose(); // } else // if(os == OS.Linux) { // FileDialog fd = new FileDialog(this, "Open a HUD folder"); // fd.setVisible(true); // selection = fd.getFile(); } else { // Fall back to swing JFileChooser fd = new JFileChooser(); fd.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if(fd.showOpenDialog(EditorFrame.this) == JFileChooser.APPROVE_OPTION) { hudSelection = fd.getSelectedFile().getPath(); } } } if(hudSelection != null) { final File f = new File(hudSelection); new Thread() { @Override public void run() { loadHud(f); } }.start(); } else { // Throw error or load archive } } private void closeHud() { canvas.removeAllElements(); hudFilesRoot.removeAllChildren(); hudFilesRoot.setUserObject(null); fileSystem.setSelectionRow(0); DefaultTreeModel model1 = (DefaultTreeModel) fileSystem.getModel(); model1.reload(); DefaultTableModel model2 = (DefaultTableModel) propTable.getModel(); model2.setRowCount(0); propTable.repaint(); } private void loadHud(final File file) { System.out.println("You have selected: " + file); if(file.isDirectory()) { File[] folders = file.listFiles(); boolean valid = false; for(int i = 0; i < folders.length; i++) { if(folders[i].isDirectory() && ("resource".equalsIgnoreCase(folders[i].getName()) || "scripts".equalsIgnoreCase(folders[i].getName()))) { valid = true; break; } } if(!valid) { JOptionPane.showMessageDialog(this, "Selection not valid. Please choose a folder containing \'resources\' or \'scripts\'.", "Error", JOptionPane.ERROR_MESSAGE); return; } closeHud(); // SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { // @Override // public Void doInBackground() { // while(!isCancelled()) { // return null; // @Override // public void done() { // @Override // protected void process(List<Void> chunks) { // worker.execute(); this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); final long start = System.currentTimeMillis(); resloader = new ResLoader(file.getPath()); hudFilesRoot.setUserObject(file.getName()); // The only time a String is added to the Tree, that way I can treat it differently resloader.populate(hudFilesRoot); DefaultTreeModel model = (DefaultTreeModel) fileSystem.getModel(); model.reload(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { System.out.println(System.currentTimeMillis()-start); setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); System.out.println("loaded hud"); } }); } } private void changeResolution() { final JOptionPane optionPane = new JOptionPane("Change resoluton to 1920 * 1080? (There will be a way to put actual numbers in here soon)", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION); final JDialog dialog = new JDialog(this, "Click a button", true); dialog.setContentPane(optionPane); dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); dialog.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent we) { } }); optionPane.addPropertyChangeListener( new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { String prop = e.getPropertyName(); if(dialog.isVisible() && (e.getSource() == optionPane) && (prop.equals(JOptionPane.VALUE_PROPERTY))) { dialog.setVisible(false); } } }); dialog.pack(); dialog.setVisible(true); int value = ((Integer) optionPane.getValue()).intValue(); if(value == JOptionPane.YES_OPTION) { canvas.setPreferredSize(new Dimension(1920, 1080)); } else if(value == JOptionPane.NO_OPTION) { } } String hudSelection; private class EditorActionListener implements ActionListener { EditorActionListener() { } @Override public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if("Open...".equalsIgnoreCase(cmd)) { hudSelection = null; locateHudDirectory(); } else if("Close".equalsIgnoreCase(cmd)) { closeHud(); } else if("Revert".equalsIgnoreCase(cmd)) { locateHudDirectory(); } else if("Exit".equalsIgnoreCase(cmd)) { System.exit(0); } else if("Change Resolution".equalsIgnoreCase(cmd)) { changeResolution(); } else if("Select All".equalsIgnoreCase(cmd)) { for(int i = 0; i < canvas.getElements().size(); i++) { canvas.select(canvas.getElements().get(i)); } } else if("About".equalsIgnoreCase(cmd)) { String aboutText = "<html><h2>This is a <u>W</u>hat <u>Y</u>ou <u>S</u>ee <u>I</u>s <u>W</u>hat <u>Y</u>ou <u>G</u>et HUD Editor for TF2.</h2>"; aboutText += "<p>You can graphically edit TF2 HUDs with it!<br>"; aboutText += "<p>It was written by <a href=\"http: aboutText += "<p>Please give feedback or suggestions on my Reddit profile</p>"; aboutText += "</html>"; final JEditorPane panel = new JEditorPane("text/html", aboutText); panel.setEditable(false); panel.setOpaque(false); panel.addHyperlinkListener(new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent he) { if (he.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) { try { Desktop.getDesktop().browse(he.getURL().toURI()); } catch(Exception e) { // e.printStackTrace(); } } } }); JOptionPane.showMessageDialog(new JFrame(), panel, "About", JOptionPane.INFORMATION_MESSAGE); // this.getParent() } else { System.out.println(e.getActionCommand()); } } } private class PropertiesTable extends JTable { PropertiesTable() { super(); } PropertiesTable(TableModel model) { super(model); } @Override public boolean isCellEditable(int row, int column) { return (column != 0); // deny editing of key } @Override public TableCellEditor getCellEditor(int row, int column) { return super.getCellEditor(row, column); } @Override public TableCellRenderer getCellRenderer(int row, int column) { return super.getCellRenderer(row, column); } } private class EditorPropertiesTable extends JScrollPane { public EditorPropertiesTable() { super(); DefaultTableModel model = new DefaultTableModel(); model.addColumn("Key"); model.addColumn("Value"); model.addColumn("Info"); propTable = new PropertiesTable(model); propTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); propTable.setColumnSelectionAllowed(false); propTable.setRowSelectionAllowed(true); propTable.getTableHeader().setReorderingAllowed(false); this.setViewportView(propTable); this.setPreferredSize(new Dimension(400, 400)); } } private class CustomTreeCellRenderer extends DefaultTreeCellRenderer { CustomTreeCellRenderer() { super(); } private void setIcons(JTree tree, Icon ico) { if(tree.isEnabled()) { this.setIcon(ico); } else { this.setDisabledIcon(ico); } } JFileChooser iconFinder = new JFileChooser(); Color sameColor = Color.BLACK; Color diffColor = Color.BLUE; Color newColor = Color.GREEN.darker(); /** * Configures the renderer based on the passed in components. * The value is set from messaging the tree with * <code>convertValueToText</code>, which ultimately invokes * <code>toString</code> on <code>value</code>. * The foreground color is set based on the selection and the icon * is set based on on leaf and expanded. */ @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { String valueText = value.toString(); Color tColor = null; if(value instanceof DefaultMutableTreeNode) { Object nodeValue = ((DefaultMutableTreeNode) value).getUserObject(); if(nodeValue instanceof String) { tColor = sameColor; setIcons(tree, UIManager.getIcon("FileView.computerIcon")); } else if(nodeValue instanceof File) { // this will either be an actual file on the system (directories included), or an element within a file tColor = diffColor; File f = ((File) nodeValue); valueText = f.getName(); setIcons(tree, iconFinder.getIcon(f)); } else if(nodeValue instanceof Element) { tColor = newColor; Element e = (Element) nodeValue; if(e.getProps().isEmpty() && leaf) { // If no properties, warn because irrelevant. Only care if leaves are empty setIcons(tree, UIManager.getIcon("FileChooser.detailsViewIcon")); } else { setIcons(tree, UIManager.getIcon("FileChooser.listViewIcon")); } } else { if(nodeValue != null) { System.out.println(nodeValue.getClass()); } setIcons(tree, null); } } String stringValue = tree.convertValueToText(valueText, sel, expanded, leaf, row, hasFocus); this.hasFocus = hasFocus; this.setText(stringValue); if(tColor != null) { this.setForeground(sel ? tColor != newColor ? new Color(-tColor.getRed() + 255, -tColor.getGreen() + 255, -tColor.getBlue() + 255) : tColor.brighter() : tColor); } else { this.setForeground(sel ? getTextSelectionColor() : getTextNonSelectionColor()); } this.setEnabled(tree.isEnabled()); this.setComponentOrientation(tree.getComponentOrientation()); this.selected = sel; return this; } } private class EditorFileTree extends JScrollPane { EditorFileTree() { super(); hudFilesRoot = new DefaultMutableTreeNode(null); fileSystem = new JTree(hudFilesRoot); fileSystem.setShowsRootHandles(true); fileSystem.setSelectionRow(0); fileSystem.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); fileSystem.setCellRenderer(new CustomTreeCellRenderer()); fileSystem.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { DefaultTableModel model = (DefaultTableModel) propTable.getModel(); model.getDataVector().removeAllElements(); propTable.scrollRectToVisible(new Rectangle(0, 0, 0, 0)); DefaultMutableTreeNode node = (DefaultMutableTreeNode) fileSystem.getLastSelectedPathComponent(); if(node == null) { return; } Object nodeInfo = node.getUserObject(); if(nodeInfo instanceof Element) { Element element = (Element) nodeInfo; canvas.load(element); if(element.getProps().isEmpty()) { model.insertRow(0, new Object[] {"", "", ""}); } else { element.validate2(); for(int i = 0; i < element.getProps().size(); i++) { Property entry = element.getProps().get(i); model.insertRow(model.getRowCount(), new Object[] {entry.getKey(), entry.getValue(), entry.getInfo()}); } } } } }); this.setViewportView(fileSystem); this.setPreferredSize(new Dimension(400, 400)); } } private class EditorMenuBar extends JMenuBar { EditorMenuBar() { super(); EditorActionListener al = new EditorActionListener(); JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic(KeyEvent.VK_F); this.add(fileMenu); JMenuItem newItem = new JMenuItem("New", KeyEvent.VK_N); newItem.setEnabled(false); newItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, shortcutKey)); newItem.addActionListener(al); fileMenu.add(newItem); JMenuItem openItem = new JMenuItem("Open...", KeyEvent.VK_O); openItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, shortcutKey)); openItem.addActionListener(al); fileMenu.add(openItem); fileMenu.addSeparator(); JMenuItem saveItem = new JMenuItem("Save", KeyEvent.VK_S); saveItem.setEnabled(false); saveItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, shortcutKey)); saveItem.addActionListener(al); fileMenu.add(saveItem); JMenuItem saveAsItem = new JMenuItem("Save As...", KeyEvent.VK_A); saveAsItem.setEnabled(false); saveAsItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, shortcutKey + ActionEvent.SHIFT_MASK)); saveAsItem.addActionListener(al); fileMenu.add(saveAsItem); JMenuItem revertItem = new JMenuItem("Revert", KeyEvent.VK_R); revertItem.addActionListener(al); fileMenu.add(revertItem); fileMenu.addSeparator(); JMenuItem closeItem = new JMenuItem("Close", KeyEvent.VK_C); closeItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, shortcutKey)); closeItem.addActionListener(al); fileMenu.add(closeItem); fileMenu.addSeparator(); JMenuItem exitItem = new JMenuItem("Exit", KeyEvent.VK_X); exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, shortcutKey)); exitItem.addActionListener(al); fileMenu.add(exitItem); JMenu editMenu = new JMenu("Edit"); editMenu.setMnemonic(KeyEvent.VK_E); this.add(editMenu); JMenuItem undoItem = new JMenuItem("Undo", KeyEvent.VK_U); undoItem.setEnabled(false); undoItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK)); undoItem.addActionListener(al); editMenu.add(undoItem); JMenuItem redoItem = new JMenuItem("Redo", KeyEvent.VK_R); redoItem.setEnabled(false); redoItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK + ActionEvent.SHIFT_MASK)); redoItem.addActionListener(al); editMenu.add(redoItem); editMenu.addSeparator(); JMenuItem cutItem = new JMenuItem("Cut", KeyEvent.VK_T); cutItem.setEnabled(false); cutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, shortcutKey)); cutItem.addActionListener(al); editMenu.add(cutItem); JMenuItem copyItem = new JMenuItem("Copy", KeyEvent.VK_C); copyItem.setEnabled(false); copyItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, shortcutKey)); copyItem.addActionListener(al); editMenu.add(copyItem); JMenuItem pasteItem = new JMenuItem("Paste", KeyEvent.VK_P); pasteItem.setEnabled(false); pasteItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, shortcutKey)); pasteItem.addActionListener(al); editMenu.add(pasteItem); JMenuItem deleteItem = new JMenuItem("Delete"); deleteItem.setEnabled(false); deleteItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0)); deleteItem.addActionListener(al); editMenu.add(deleteItem); editMenu.addSeparator(); JMenuItem selectAllItem = new JMenuItem("Select All", KeyEvent.VK_A); selectAllItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, shortcutKey)); selectAllItem.addActionListener(al); editMenu.add(selectAllItem); editMenu.addSeparator(); JMenuItem preferencesItem = new JMenuItem("Preferences", KeyEvent.VK_E); preferencesItem.setEnabled(false); preferencesItem.addActionListener(al); editMenu.add(preferencesItem); JMenu viewMenu = new JMenu("View"); viewMenu.setMnemonic(KeyEvent.VK_V); this.add(viewMenu); JMenuItem resolutionItem = new JMenuItem("Change Resolution", KeyEvent.VK_R); resolutionItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, shortcutKey)); resolutionItem.addActionListener(al); viewMenu.add(resolutionItem); JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic(KeyEvent.VK_H); this.add(helpMenu); JMenuItem aboutItem = new JMenuItem("About", KeyEvent.VK_A); aboutItem.addActionListener(al); helpMenu.add(aboutItem); } } }
package org.osmdroid.views; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import microsoft.mappoint.TileSystem; import net.wigle.wigleandroid.ZoomButtonsController; import net.wigle.wigleandroid.ZoomButtonsController.OnZoomListener; import org.metalev.multitouch.controller.MultiTouchController; import org.metalev.multitouch.controller.MultiTouchController.MultiTouchObjectCanvas; import org.metalev.multitouch.controller.MultiTouchController.PointInfo; import org.metalev.multitouch.controller.MultiTouchController.PositionAndScale; import org.osmdroid.DefaultResourceProxyImpl; import org.osmdroid.ResourceProxy; import org.osmdroid.api.IGeoPoint; import org.osmdroid.api.IMapView; import org.osmdroid.api.IProjection; import org.osmdroid.events.MapListener; import org.osmdroid.events.ScrollEvent; import org.osmdroid.events.ZoomEvent; import org.osmdroid.tileprovider.MapTileProviderBase; import org.osmdroid.tileprovider.MapTileProviderBasic; import org.osmdroid.tileprovider.tilesource.IStyledTileSource; import org.osmdroid.tileprovider.tilesource.ITileSource; import org.osmdroid.tileprovider.tilesource.TileSourceFactory; import org.osmdroid.tileprovider.util.SimpleInvalidationHandler; import org.osmdroid.util.BoundingBoxE6; import org.osmdroid.util.GeoPoint; import org.osmdroid.util.constants.GeoConstants; import org.osmdroid.views.overlay.Overlay; import org.osmdroid.views.overlay.OverlayManager; import org.osmdroid.views.overlay.TilesOverlay; import org.osmdroid.views.util.constants.MapViewConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import android.content.Context; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Point; import android.graphics.Rect; import android.os.Handler; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.ScaleAnimation; import android.widget.Scroller; public class MapView extends ViewGroup implements IMapView, MapViewConstants, MultiTouchObjectCanvas<Object> { // Constants private static final Logger logger = LoggerFactory.getLogger(MapView.class); private static final double ZOOM_SENSITIVITY = 1.3; private static final double ZOOM_LOG_BASE_INV = 1.0 / Math.log(2.0 / ZOOM_SENSITIVITY); // Fields /** Current zoom level for map tiles. */ private int mZoomLevel = 0; private final OverlayManager mOverlayManager; private Projection mProjection; private final TilesOverlay mMapOverlay; private final GestureDetector mGestureDetector; /** Handles map scrolling */ private final Scroller mScroller; private final AtomicInteger mTargetZoomLevel = new AtomicInteger(); private final AtomicBoolean mIsAnimating = new AtomicBoolean(false); private final ScaleAnimation mZoomInAnimation; private final ScaleAnimation mZoomOutAnimation; private final MapController mController; // XXX we can use android.widget.ZoomButtonsController if we upgrade the // dependency to Android 1.6 private final ZoomButtonsController mZoomController; private boolean mEnableZoomController = false; private final ResourceProxy mResourceProxy; private MultiTouchController<Object> mMultiTouchController; private float mMultiTouchScale = 1.0f; protected MapListener mListener; // for speed (avoiding allocations) private final Matrix mMatrix = new Matrix(); private final MapTileProviderBase mTileProvider; private final Handler mTileRequestCompleteHandler; /* a point that will be reused to design added views */ private final Point mPoint = new Point(); // Constructors private MapView(final Context context, final int tileSizePixels, final ResourceProxy resourceProxy, MapTileProviderBase tileProvider, final Handler tileRequestCompleteHandler, final AttributeSet attrs) { super(context, attrs); mResourceProxy = resourceProxy; this.mController = new MapController(this); this.mScroller = new Scroller(context); TileSystem.setTileSize(tileSizePixels); if (tileProvider == null) { final ITileSource tileSource = getTileSourceFromAttributes(attrs); tileProvider = new MapTileProviderBasic(context, tileSource); } mTileRequestCompleteHandler = tileRequestCompleteHandler == null ? new SimpleInvalidationHandler( this) : tileRequestCompleteHandler; mTileProvider = tileProvider; mTileProvider.setTileRequestCompleteHandler(mTileRequestCompleteHandler); this.mMapOverlay = new TilesOverlay(mTileProvider, mResourceProxy); mOverlayManager = new OverlayManager(mMapOverlay); this.mZoomController = new ZoomButtonsController(this); this.mZoomController.setOnZoomListener(new MapViewZoomListener()); mZoomInAnimation = new ScaleAnimation(1, 2, 1, 2, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); mZoomOutAnimation = new ScaleAnimation(1, 0.5f, 1, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); mZoomInAnimation.setDuration(ANIMATION_DURATION_SHORT); mZoomOutAnimation.setDuration(ANIMATION_DURATION_SHORT); mGestureDetector = new GestureDetector(context, new MapViewGestureDetectorListener()); mGestureDetector.setOnDoubleTapListener(new MapViewDoubleClickListener()); } /** * Constructor used by XML layout resource (uses default tile source). */ public MapView(final Context context, final AttributeSet attrs) { this(context, 256, new DefaultResourceProxyImpl(context), null, null, attrs); } /** * Standard Constructor. */ public MapView(final Context context, final int tileSizePixels) { this(context, tileSizePixels, new DefaultResourceProxyImpl(context)); } public MapView(final Context context, final int tileSizePixels, final ResourceProxy resourceProxy) { this(context, tileSizePixels, resourceProxy, null); } public MapView(final Context context, final int tileSizePixels, final ResourceProxy resourceProxy, final MapTileProviderBase aTileProvider) { this(context, tileSizePixels, resourceProxy, aTileProvider, null); } public MapView(final Context context, final int tileSizePixels, final ResourceProxy resourceProxy, final MapTileProviderBase aTileProvider, final Handler tileRequestCompleteHandler) { this(context, tileSizePixels, resourceProxy, aTileProvider, tileRequestCompleteHandler, null); } // Getter & Setter @Override public MapController getController() { return this.mController; } /** * You can add/remove/reorder your Overlays using the List of {@link Overlay}. The first (index * 0) Overlay gets drawn first, the one with the highest as the last one. */ public List<Overlay> getOverlays() { return mOverlayManager; } public OverlayManager getOverlayManager() { return mOverlayManager; } public MapTileProviderBase getTileProvider() { return mTileProvider; } public Scroller getScroller() { return mScroller; } public Handler getTileRequestCompleteHandler() { return mTileRequestCompleteHandler; } @Override public int getLatitudeSpan() { return this.getBoundingBox().getLatitudeSpanE6(); } @Override public int getLongitudeSpan() { return this.getBoundingBox().getLongitudeSpanE6(); } public BoundingBoxE6 getBoundingBox() { return getBoundingBox(getWidth(), getHeight()); } public BoundingBoxE6 getBoundingBox(final int pViewWidth, final int pViewHeight) { final int world_2 = TileSystem.MapSize(mZoomLevel) / 2; final Rect screenRect = getScreenRect(null); screenRect.offset(world_2, world_2); final IGeoPoint neGeoPoint = TileSystem.PixelXYToLatLong(screenRect.right, screenRect.top, mZoomLevel, null); final IGeoPoint swGeoPoint = TileSystem.PixelXYToLatLong(screenRect.left, screenRect.bottom, mZoomLevel, null); return new BoundingBoxE6(neGeoPoint.getLatitudeE6(), neGeoPoint.getLongitudeE6(), swGeoPoint.getLatitudeE6(), swGeoPoint.getLongitudeE6()); } /** * Gets the current bounds of the screen in <I>screen coordinates</I>. */ public Rect getScreenRect(final Rect reuse) { final Rect out = reuse == null ? new Rect() : reuse; out.set(getScrollX() - getWidth() / 2, getScrollY() - getHeight() / 2, getScrollX() + getWidth() / 2, getScrollY() + getHeight() / 2); return out; } /** * Get a projection for converting between screen-pixel coordinates and latitude/longitude * coordinates. You should not hold on to this object for more than one draw, since the * projection of the map could change. * * @return The Projection of the map in its current state. You should not hold on to this object * for more than one draw, since the projection of the map could change. */ @Override public Projection getProjection() { if (mProjection == null) { mProjection = new Projection(); } return mProjection; } void setMapCenter(final IGeoPoint aCenter) { this.setMapCenter(aCenter.getLatitudeE6(), aCenter.getLongitudeE6()); } void setMapCenter(final int aLatitudeE6, final int aLongitudeE6) { final Point coords = TileSystem.LatLongToPixelXY(aLatitudeE6 / 1E6, aLongitudeE6 / 1E6, getZoomLevel(), null); final int worldSize_2 = TileSystem.MapSize(mZoomLevel) / 2; if (getAnimation() == null || getAnimation().hasEnded()) { logger.debug("StartScroll"); mScroller.startScroll(getScrollX(), getScrollY(), coords.x - worldSize_2 - getScrollX(), coords.y - worldSize_2 - getScrollY(), 500); postInvalidate(); } } public void setTileSource(final ITileSource aTileSource) { mTileProvider.setTileSource(aTileSource); TileSystem.setTileSize(aTileSource.getTileSizePixels()); this.checkZoomButtons(); this.setZoomLevel(mZoomLevel); // revalidate zoom level postInvalidate(); } /** * @param aZoomLevel * the zoom level bound by the tile source */ int setZoomLevel(final int aZoomLevel) { final int minZoomLevel = getMinZoomLevel(); final int maxZoomLevel = getMaxZoomLevel(); final int newZoomLevel = Math.max(minZoomLevel, Math.min(maxZoomLevel, aZoomLevel)); final int curZoomLevel = this.mZoomLevel; this.mZoomLevel = newZoomLevel; this.checkZoomButtons(); if (newZoomLevel > curZoomLevel) { // We are going from a lower-resolution plane to a higher-resolution plane, so we have // to do it the hard way. final int worldSize_current_2 = TileSystem.MapSize(curZoomLevel) / 2; final int worldSize_new_2 = TileSystem.MapSize(newZoomLevel) / 2; final IGeoPoint centerGeoPoint = TileSystem.PixelXYToLatLong(getScrollX() + worldSize_current_2, getScrollY() + worldSize_current_2, curZoomLevel, null); final Point centerPoint = TileSystem.LatLongToPixelXY(centerGeoPoint.getLatitudeE6() / 1E6, centerGeoPoint.getLongitudeE6() / 1E6, newZoomLevel, null); scrollTo(centerPoint.x - worldSize_new_2, centerPoint.y - worldSize_new_2); } else if (newZoomLevel < curZoomLevel) { // We are going from a higher-resolution plane to a lower-resolution plane, so we can do // it the easy way. scrollTo(getScrollX() >> curZoomLevel - newZoomLevel, getScrollY() >> curZoomLevel - newZoomLevel); } // snap for all snappables final Point snapPoint = new Point(); // XXX why do we need a new projection here? mProjection = new Projection(); if (mOverlayManager.onSnapToItem(getScrollX(), getScrollY(), snapPoint, this)) { scrollTo(snapPoint.x, snapPoint.y); } // do callback on listener if (newZoomLevel != curZoomLevel && mListener != null) { final ZoomEvent event = new ZoomEvent(this, newZoomLevel); mListener.onZoom(event); } return this.mZoomLevel; } /** * Get the current ZoomLevel for the map tiles. * * @return the current ZoomLevel between 0 (equator) and 18/19(closest), depending on the tile * source chosen. */ @Override public int getZoomLevel() { return getZoomLevel(true); } /** * Get the current ZoomLevel for the map tiles. * * @param aPending * if true and we're animating then return the zoom level that we're animating * towards, otherwise return the current zoom level * @return the zoom level */ public int getZoomLevel(final boolean aPending) { if (aPending && isAnimating()) { return mTargetZoomLevel.get(); } else { return mZoomLevel; } } /** * Returns the minimum zoom level for the point currently at the center. * * @return The minimum zoom level for the map's current center. */ public int getMinZoomLevel() { return mMapOverlay.getMinimumZoomLevel(); } /** * Returns the maximum zoom level for the point currently at the center. * * @return The maximum zoom level for the map's current center. */ @Override public int getMaxZoomLevel() { return mMapOverlay.getMaximumZoomLevel(); } public boolean canZoomIn() { final int maxZoomLevel = getMaxZoomLevel(); if (mZoomLevel >= maxZoomLevel) { return false; } if (isAnimating() & mTargetZoomLevel.get() >= maxZoomLevel) { return false; } return true; } public boolean canZoomOut() { final int minZoomLevel = getMinZoomLevel(); if (mZoomLevel <= minZoomLevel) { return false; } if (isAnimating() && mTargetZoomLevel.get() <= minZoomLevel) { return false; } return true; } /** * Zoom in by one zoom level. */ boolean zoomIn() { if (canZoomIn()) { if (isAnimating()) { // TODO extend zoom (and return true) return false; } else { mTargetZoomLevel.set(mZoomLevel + 1); startAnimation(mZoomInAnimation); return true; } } else { return false; } } boolean zoomInFixing(final IGeoPoint point) { setMapCenter(point); // TODO should fix on point, not center on it return zoomIn(); } boolean zoomInFixing(final int xPixel, final int yPixel) { setMapCenter(xPixel, yPixel); // TODO should fix on point, not center on it return zoomIn(); } /** * Zoom out by one zoom level. */ boolean zoomOut() { if (canZoomOut()) { if (isAnimating()) { // TODO extend zoom (and return true) return false; } else { mTargetZoomLevel.set(mZoomLevel - 1); startAnimation(mZoomOutAnimation); return true; } } else { return false; } } boolean zoomOutFixing(final IGeoPoint point) { setMapCenter(point); // TODO should fix on point, not center on it return zoomOut(); } boolean zoomOutFixing(final int xPixel, final int yPixel) { setMapCenter(xPixel, yPixel); // TODO should fix on point, not center on it return zoomOut(); } /** * Returns the current center-point position of the map, as a GeoPoint (latitude and longitude). * * @return A GeoPoint of the map's center-point. */ @Override public IGeoPoint getMapCenter() { final int world_2 = TileSystem.MapSize(mZoomLevel) / 2; final Rect screenRect = getScreenRect(null); screenRect.offset(world_2, world_2); return TileSystem.PixelXYToLatLong(screenRect.centerX(), screenRect.centerY(), mZoomLevel, null); } public ResourceProxy getResourceProxy() { return mResourceProxy; } /** * Whether to use the network connection if it's available. */ public boolean useDataConnection() { return mMapOverlay.useDataConnection(); } /** * Set whether to use the network connection if it's available. * * @param aMode * if true use the network connection if it's available. if false don't use the * network connection even if it's available. */ public void setUseDataConnection(final boolean aMode) { mMapOverlay.setUseDataConnection(aMode); } // Methods from SuperClass/Interfaces /** * Returns a set of layout parameters with a width of * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT}, a height of * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} at the {@link GeoPoint} (0, 0) align * with {@link MapView.LayoutParams#BOTTOM_CENTER}. */ @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { return new MapView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, null, MapView.LayoutParams.BOTTOM_CENTER, 0, 0); } @Override public ViewGroup.LayoutParams generateLayoutParams(final AttributeSet attrs) { return new MapView.LayoutParams(getContext(), attrs); } // Override to allow type-checking of LayoutParams. @Override protected boolean checkLayoutParams(final ViewGroup.LayoutParams p) { return p instanceof MapView.LayoutParams; } @Override protected ViewGroup.LayoutParams generateLayoutParams(final ViewGroup.LayoutParams p) { return new MapView.LayoutParams(p); } @Override protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) { final int count = getChildCount(); int maxHeight = 0; int maxWidth = 0; // Find out how big everyone wants to be measureChildren(widthMeasureSpec, heightMeasureSpec); // Find rightmost and bottom-most child for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final MapView.LayoutParams lp = (MapView.LayoutParams) child.getLayoutParams(); final int childHeight = child.getMeasuredHeight(); final int childWidth = child.getMeasuredWidth(); getProjection().toMapPixels(lp.geoPoint, mPoint); final int x = mPoint.x + getWidth() / 2; final int y = mPoint.y + getHeight() / 2; int childRight = x; int childBottom = y; switch (lp.alignment) { case MapView.LayoutParams.TOP_LEFT: childRight = x + childWidth; childBottom = y; break; case MapView.LayoutParams.TOP_CENTER: childRight = x + childWidth / 2; childBottom = y; break; case MapView.LayoutParams.TOP_RIGHT: childRight = x; childBottom = y; break; case MapView.LayoutParams.CENTER_LEFT: childRight = x + childWidth; childBottom = y + childHeight / 2; break; case MapView.LayoutParams.CENTER: childRight = x + childWidth / 2; childBottom = y + childHeight / 2; break; case MapView.LayoutParams.CENTER_RIGHT: childRight = x; childBottom = y + childHeight / 2; break; case MapView.LayoutParams.BOTTOM_LEFT: childRight = x + childWidth; childBottom = y + childHeight; break; case MapView.LayoutParams.BOTTOM_CENTER: childRight = x + childWidth / 2; childBottom = y + childHeight; break; case MapView.LayoutParams.BOTTOM_RIGHT: childRight = x; childBottom = y + childHeight; break; } childRight += lp.offsetX; childBottom += lp.offsetY; maxWidth = Math.max(maxWidth, childRight); maxHeight = Math.max(maxHeight, childBottom); } } // Account for padding too maxWidth += getPaddingLeft() + getPaddingRight(); maxHeight += getPaddingTop() + getPaddingBottom(); // Check against minimum height and width maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight()); maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth()); setMeasuredDimension(resolveSize(maxWidth, widthMeasureSpec), resolveSize(maxHeight, heightMeasureSpec)); } @Override protected void onLayout(final boolean changed, final int l, final int t, final int r, final int b) { final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final MapView.LayoutParams lp = (MapView.LayoutParams) child.getLayoutParams(); final int childHeight = child.getMeasuredHeight(); final int childWidth = child.getMeasuredWidth(); getProjection().toMapPixels(lp.geoPoint, mPoint); final int x = mPoint.x + getWidth() / 2; final int y = mPoint.y + getHeight() / 2; int childLeft = x; int childTop = y; switch (lp.alignment) { case MapView.LayoutParams.TOP_LEFT: childLeft = getPaddingLeft() + x; childTop = getPaddingTop() + y; break; case MapView.LayoutParams.TOP_CENTER: childLeft = getPaddingLeft() + x - childWidth / 2; childTop = getPaddingTop() + y; break; case MapView.LayoutParams.TOP_RIGHT: childLeft = getPaddingLeft() + x - childWidth; childTop = getPaddingTop() + y; break; case MapView.LayoutParams.CENTER_LEFT: childLeft = getPaddingLeft() + x; childTop = getPaddingTop() + y - childHeight / 2; break; case MapView.LayoutParams.CENTER: childLeft = getPaddingLeft() + x - childWidth / 2; childTop = getPaddingTop() + y - childHeight / 2; break; case MapView.LayoutParams.CENTER_RIGHT: childLeft = getPaddingLeft() + x - childWidth; childTop = getPaddingTop() + y - childHeight / 2; break; case MapView.LayoutParams.BOTTOM_LEFT: childLeft = getPaddingLeft() + x; childTop = getPaddingTop() + y - childHeight; break; case MapView.LayoutParams.BOTTOM_CENTER: childLeft = getPaddingLeft() + x - childWidth / 2; childTop = getPaddingTop() + y - childHeight; break; case MapView.LayoutParams.BOTTOM_RIGHT: childLeft = getPaddingLeft() + x - childWidth; childTop = getPaddingTop() + y - childHeight; break; } childLeft += lp.offsetX; childTop += lp.offsetY; child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight); } } } public void onDetach() { mOverlayManager.onDetach(this); } @Override public boolean onKeyDown(final int keyCode, final KeyEvent event) { final boolean result = mOverlayManager.onKeyDown(keyCode, event, this); return result || super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(final int keyCode, final KeyEvent event) { final boolean result = mOverlayManager.onKeyUp(keyCode, event, this); return result || super.onKeyUp(keyCode, event); } @Override public boolean onTrackballEvent(final MotionEvent event) { if (mOverlayManager.onTrackballEvent(event, this)) { return true; } scrollBy((int) (event.getX() * 25), (int) (event.getY() * 25)); return super.onTrackballEvent(event); } @Override public boolean dispatchTouchEvent(final MotionEvent event) { if (DEBUGMODE) { logger.debug("dispatchTouchEvent(" + event + ")"); } if (mZoomController.isVisible() && mZoomController.onTouch(this, event)) { return true; } if (mOverlayManager.onTouchEvent(event, this)) { return true; } if (mMultiTouchController != null && mMultiTouchController.onTouchEvent(event)) { if (DEBUGMODE) { logger.debug("mMultiTouchController handled onTouchEvent"); } return true; } final boolean r = super.dispatchTouchEvent(event); if (mGestureDetector.onTouchEvent(event)) { if (DEBUGMODE) { logger.debug("mGestureDetector handled onTouchEvent"); } return true; } if (r) { if (DEBUGMODE) { logger.debug("super handled onTouchEvent"); } } else { if (DEBUGMODE) { logger.debug("no-one handled onTouchEvent"); } } return r; } @Override public void computeScroll() { if (mScroller.computeScrollOffset()) { if (mScroller.isFinished()) { // This will facilitate snapping-to any Snappable points. setZoomLevel(mZoomLevel); } else { scrollTo(mScroller.getCurrX(), mScroller.getCurrY()); } postInvalidate(); // Keep on drawing until the animation has // finished. } } @Override public void scrollTo(int x, int y) { final int worldSize_2 = TileSystem.MapSize(mZoomLevel) / 2; while (x < -worldSize_2) { x += (worldSize_2 * 2); } while (x > worldSize_2) { x -= (worldSize_2 * 2); } while (y < -worldSize_2) { y += (worldSize_2 * 2); } while (y > worldSize_2) { y -= (worldSize_2 * 2); } super.scrollTo(x, y); // do callback on listener if (mListener != null) { final ScrollEvent event = new ScrollEvent(this, x, y); mListener.onScroll(event); } } @Override public void setBackgroundColor(final int pColor) { mMapOverlay.setLoadingBackgroundColor(pColor); invalidate(); } @Override protected void dispatchDraw(final Canvas c) { final long startMs = System.currentTimeMillis(); mProjection = new Projection(); // Save the current canvas matrix c.save(); if (mMultiTouchScale == 1.0f) { c.translate(getWidth() / 2, getHeight() / 2); } else { c.getMatrix(mMatrix); mMatrix.postTranslate(getWidth() / 2, getHeight() / 2); mMatrix.preScale(mMultiTouchScale, mMultiTouchScale, getScrollX(), getScrollY()); c.setMatrix(mMatrix); } /* Draw background */ // c.drawColor(mBackgroundColor); /* Draw all Overlays. */ mOverlayManager.onDraw(c, this); // Restore the canvas matrix c.restore(); super.dispatchDraw(c); final long endMs = System.currentTimeMillis(); if (DEBUGMODE) { logger.debug("Rendering overall: " + (endMs - startMs) + "ms"); } } @Override protected void onDetachedFromWindow() { this.mZoomController.setVisible(false); this.onDetach(); super.onDetachedFromWindow(); } // Animation @Override protected void onAnimationStart() { mIsAnimating.set(true); super.onAnimationStart(); } @Override protected void onAnimationEnd() { mIsAnimating.set(false); clearAnimation(); setZoomLevel(mTargetZoomLevel.get()); this.isAnimating(); super.onAnimationEnd(); } /** * Check mAnimationListener.isAnimating() to determine if view is animating. Useful for overlays * to avoid recalculating during an animation sequence. * * @return boolean indicating whether view is animating. */ public boolean isAnimating() { return mIsAnimating.get(); } // Implementation of MultiTouchObjectCanvas @Override public Object getDraggableObjectAtPoint(final PointInfo pt) { return this; } @Override public void getPositionAndScale(final Object obj, final PositionAndScale objPosAndScaleOut) { objPosAndScaleOut.set(0, 0, true, mMultiTouchScale, false, 0, 0, false, 0); } @Override public void selectObject(final Object obj, final PointInfo pt) { // if obj is null it means we released the pointers // if scale is not 1 it means we pinched if (obj == null && mMultiTouchScale != 1.0f) { final float scaleDiffFloat = (float) (Math.log(mMultiTouchScale) * ZOOM_LOG_BASE_INV); final int scaleDiffInt = Math.round(scaleDiffFloat); setZoomLevel(mZoomLevel + scaleDiffInt); // XXX maybe zoom in/out instead of zooming direct to zoom level // - probably not a good idea because you'll repeat the animation } // reset scale mMultiTouchScale = 1.0f; } @Override public boolean setPositionAndScale(final Object obj, final PositionAndScale aNewObjPosAndScale, final PointInfo aTouchPoint) { float multiTouchScale = aNewObjPosAndScale.getScale(); // If we are at the first or last zoom level, prevent pinching/expanding if ((multiTouchScale > 1) && !canZoomIn()) { multiTouchScale = 1; } if ((multiTouchScale < 1) && !canZoomOut()) { multiTouchScale = 1; } mMultiTouchScale = multiTouchScale; invalidate(); // redraw return true; } /* * Set the MapListener for this view */ public void setMapListener(final MapListener ml) { mListener = ml; } // Methods private void checkZoomButtons() { this.mZoomController.setZoomInEnabled(canZoomIn()); this.mZoomController.setZoomOutEnabled(canZoomOut()); } public void setBuiltInZoomControls(final boolean on) { this.mEnableZoomController = on; this.checkZoomButtons(); } public void setMultiTouchControls(final boolean on) { mMultiTouchController = on ? new MultiTouchController<Object>(this, false) : null; } private ITileSource getTileSourceFromAttributes(final AttributeSet aAttributeSet) { ITileSource tileSource = TileSourceFactory.DEFAULT_TILE_SOURCE; if (aAttributeSet != null) { final String tileSourceAttr = aAttributeSet.getAttributeValue(null, "tilesource"); if (tileSourceAttr != null) { try { final ITileSource r = TileSourceFactory.getTileSource(tileSourceAttr); logger.info("Using tile source specified in layout attributes: " + r); tileSource = r; } catch (final IllegalArgumentException e) { logger.warn("Invalid tile souce specified in layout attributes: " + tileSource); } } } if (aAttributeSet != null && tileSource instanceof IStyledTileSource) { String style = aAttributeSet.getAttributeValue(null, "style"); if (style == null) { // historic - old attribute name style = aAttributeSet.getAttributeValue(null, "cloudmadeStyle"); } if (style == null) { logger.info("Using default style: 1"); } else { logger.info("Using style specified in layout attributes: " + style); ((IStyledTileSource<?>) tileSource).setStyle(style); } } logger.info("Using tile source: " + tileSource); return tileSource; } // Inner and Anonymous Classes /** * A Projection serves to translate between the coordinate system of x/y on-screen pixel * coordinates and that of latitude/longitude points on the surface of the earth. You obtain a * Projection from MapView.getProjection(). You should not hold on to this object for more than * one draw, since the projection of the map could change. <br /> * <br /> * <I>Screen coordinates</I> are in the coordinate system of the screen's Canvas. The origin is * in the center of the plane. <I>Screen coordinates</I> are appropriate for using to draw to * the screen.<br /> * <br /> * <I>Map coordinates</I> are in the coordinate system of the standard Mercator projection. The * origin is in the upper-left corner of the plane. <I>Map coordinates</I> are appropriate for * use in the TileSystem class.<br /> * <br /> * <I>Intermediate coordinates</I> are used to cache the computationally heavy part of the * projection. They aren't suitable for use until translated into <I>screen coordinates</I> or * <I>map coordinates</I>. * * @author Nicolas Gramlich * @author Manuel Stahl */ public class Projection implements IProjection, GeoConstants { private final int viewWidth_2 = getWidth() / 2; private final int viewHeight_2 = getHeight() / 2; private final int worldSize_2 = TileSystem.MapSize(mZoomLevel) / 2; private final int offsetX = -worldSize_2; private final int offsetY = -worldSize_2; private final BoundingBoxE6 mBoundingBoxProjection; private final int mZoomLevelProjection; private final Rect mScreenRectProjection; private Projection() { /* * Do some calculations and drag attributes to local variables to save some performance. */ mZoomLevelProjection = MapView.this.mZoomLevel; mBoundingBoxProjection = MapView.this.getBoundingBox(); mScreenRectProjection = MapView.this.getScreenRect(null); } public int getZoomLevel() { return mZoomLevelProjection; } public BoundingBoxE6 getBoundingBox() { return mBoundingBoxProjection; } public Rect getScreenRect() { return mScreenRectProjection; } /** * @deprecated Use TileSystem.getTileSize() instead. */ @Deprecated public int getTileSizePixels() { return TileSystem.getTileSize(); } /** * @deprecated Use * <code>Point out = TileSystem.PixelXYToTileXY(screenRect.centerX(), screenRect.centerY(), null);</code> * instead. */ @Deprecated public Point getCenterMapTileCoords() { final Rect rect = getScreenRect(); return TileSystem.PixelXYToTileXY(rect.centerX(), rect.centerY(), null); } /** * @deprecated Use * <code>final Point out = TileSystem.TileXYToPixelXY(centerMapTileCoords.x, centerMapTileCoords.y, null);</code> * instead. */ @Deprecated public Point getUpperLeftCornerOfCenterMapTile() { final Point centerMapTileCoords = getCenterMapTileCoords(); return TileSystem.TileXYToPixelXY(centerMapTileCoords.x, centerMapTileCoords.y, null); } /** * Converts <I>screen coordinates</I> to the underlying GeoPoint. * * @param x * @param y * @return GeoPoint under x/y. */ public IGeoPoint fromPixels(final float x, final float y) { final Rect screenRect = getScreenRect(); return TileSystem.PixelXYToLatLong(screenRect.left + (int) x + worldSize_2, screenRect.top + (int) y + worldSize_2, mZoomLevelProjection, null); } public Point fromMapPixels(final int x, final int y, final Point reuse) { final Point out = reuse != null ? reuse : new Point(); out.set(x - viewWidth_2, y - viewHeight_2); out.offset(getScrollX(), getScrollY()); return out; } /** * Converts a GeoPoint to its <I>screen coordinates</I>. * * @param in * the GeoPoint you want the <I>screen coordinates</I> of * @param reuse * just pass null if you do not have a Point to be 'recycled'. * @return the Point containing the <I>screen coordinates</I> of the GeoPoint passed. */ public Point toMapPixels(final IGeoPoint in, final Point reuse) { final Point out = reuse != null ? reuse : new Point(); final Point coords = TileSystem.LatLongToPixelXY(in.getLatitudeE6() / 1E6, in.getLongitudeE6() / 1E6, getZoomLevel(), null); out.set(coords.x, coords.y); out.offset(offsetX, offsetY); return out; } /** * Performs only the first computationally heavy part of the projection. Call * toMapPixelsTranslated to get the final position. * * @param latituteE6 * the latitute of the point * @param longitudeE6 * the longitude of the point * @param reuse * just pass null if you do not have a Point to be 'recycled'. * @return intermediate value to be stored and passed to toMapPixelsTranslated. */ public Point toMapPixelsProjected(final int latituteE6, final int longitudeE6, final Point reuse) { final Point out = reuse != null ? reuse : new Point(); TileSystem .LatLongToPixelXY(latituteE6 / 1E6, longitudeE6 / 1E6, MAXIMUM_ZOOMLEVEL, out); return out; } /** * Performs the second computationally light part of the projection. Returns results in * <I>screen coordinates</I>. * * @param in * the Point calculated by the toMapPixelsProjected * @param reuse * just pass null if you do not have a Point to be 'recycled'. * @return the Point containing the <I>Screen coordinates</I> of the initial GeoPoint passed * to the toMapPixelsProjected. */ public Point toMapPixelsTranslated(final Point in, final Point reuse) { final Point out = reuse != null ? reuse : new Point(); final int zoomDifference = MAXIMUM_ZOOMLEVEL - getZoomLevel(); out.set((in.x >> zoomDifference) + offsetX, (in.y >> zoomDifference) + offsetY); return out; } /** * Translates a rectangle from <I>screen coordinates</I> to <I>intermediate coordinates</I>. * * @param in * the rectangle in <I>screen coordinates</I> * @return a rectangle in </I>intermediate coordindates</I>. */ public Rect fromPixelsToProjected(final Rect in) { final Rect result = new Rect(); final int zoomDifference = MAXIMUM_ZOOMLEVEL - getZoomLevel(); final int x0 = in.left - offsetX << zoomDifference; final int x1 = in.right - offsetX << zoomDifference; final int y0 = in.bottom - offsetY << zoomDifference; final int y1 = in.top - offsetY << zoomDifference; result.set(Math.min(x0, x1), Math.min(y0, y1), Math.max(x0, x1), Math.max(y0, y1)); return result; } /** * @deprecated Use TileSystem.TileXYToPixelXY */ @Deprecated public Point toPixels(final Point tileCoords, final Point reuse) { return toPixels(tileCoords.x, tileCoords.y, reuse); } /** * @deprecated Use TileSystem.TileXYToPixelXY */ @Deprecated public Point toPixels(final int tileX, final int tileY, final Point reuse) { return TileSystem.TileXYToPixelXY(tileX, tileY, reuse); } // not presently used public Rect toPixels(final BoundingBoxE6 pBoundingBoxE6) { final Rect rect = new Rect(); final Point reuse = new Point(); toMapPixels( new GeoPoint(pBoundingBoxE6.getLatNorthE6(), pBoundingBoxE6.getLonWestE6()), reuse); rect.left = reuse.x; rect.top = reuse.y; toMapPixels( new GeoPoint(pBoundingBoxE6.getLatSouthE6(), pBoundingBoxE6.getLonEastE6()), reuse); rect.right = reuse.x; rect.bottom = reuse.y; return rect; } @Override public float metersToEquatorPixels(final float meters) { return meters / (float) TileSystem.GroundResolution(0, mZoomLevelProjection); } @Override public Point toPixels(final IGeoPoint in, final Point out) { return toMapPixels(in, out); } @Override public IGeoPoint fromPixels(final int x, final int y) { return fromPixels((float) x, (float) y); } } private class MapViewGestureDetectorListener implements OnGestureListener { @Override public boolean onDown(final MotionEvent e) { if (MapView.this.mOverlayManager.onDown(e, MapView.this)) { return true; } mZoomController.setVisible(mEnableZoomController); return true; } @Override public boolean onFling(final MotionEvent e1, final MotionEvent e2, final float velocityX, final float velocityY) { if (MapView.this.mOverlayManager.onFling(e1, e2, velocityX, velocityY, MapView.this)) { return true; } final int worldSize = TileSystem.MapSize(mZoomLevel); mScroller.fling(getScrollX(), getScrollY(), (int) -velocityX, (int) -velocityY, -worldSize, worldSize, -worldSize, worldSize); return true; } @Override public void onLongPress(final MotionEvent e) { MapView.this.mOverlayManager.onLongPress(e, MapView.this); } @Override public boolean onScroll(final MotionEvent e1, final MotionEvent e2, final float distanceX, final float distanceY) { if (MapView.this.mOverlayManager.onScroll(e1, e2, distanceX, distanceY, MapView.this)) { return true; } scrollBy((int) distanceX, (int) distanceY); return true; } @Override public void onShowPress(final MotionEvent e) { MapView.this.mOverlayManager.onShowPress(e, MapView.this); } @Override public boolean onSingleTapUp(final MotionEvent e) { if (MapView.this.mOverlayManager.onSingleTapUp(e, MapView.this)) { return true; } return false; } } private class MapViewDoubleClickListener implements GestureDetector.OnDoubleTapListener { @Override public boolean onDoubleTap(final MotionEvent e) { if (mOverlayManager.onDoubleTap(e, MapView.this)) { return true; } final IGeoPoint center = getProjection().fromPixels(e.getX(), e.getY()); return zoomInFixing(center); } @Override public boolean onDoubleTapEvent(final MotionEvent e) { if (mOverlayManager.onDoubleTapEvent(e, MapView.this)) { return true; } return false; } @Override public boolean onSingleTapConfirmed(final MotionEvent e) { if (mOverlayManager.onSingleTapConfirmed(e, MapView.this)) { return true; } return false; } } private class MapViewZoomListener implements OnZoomListener { @Override public void onZoom(final boolean zoomIn) { if (zoomIn) { getController().zoomIn(); } else { getController().zoomOut(); } } @Override public void onVisibilityChanged(final boolean visible) { } } // Public Classes /** * Per-child layout information associated with OpenStreetMapView. */ public static class LayoutParams extends ViewGroup.LayoutParams { /** * Special value for the alignment requested by a View. TOP_LEFT means that the location * will at the top left the View. */ public static final int TOP_LEFT = 1; /** * Special value for the alignment requested by a View. TOP_RIGHT means that the location * will be centered at the top of the View. */ public static final int TOP_CENTER = 2; /** * Special value for the alignment requested by a View. TOP_RIGHT means that the location * will at the top right the View. */ public static final int TOP_RIGHT = 3; /** * Special value for the alignment requested by a View. CENTER_LEFT means that the location * will at the center left the View. */ public static final int CENTER_LEFT = 4; /** * Special value for the alignment requested by a View. CENTER means that the location will * be centered at the center of the View. */ public static final int CENTER = 5; /** * Special value for the alignment requested by a View. CENTER_RIGHT means that the location * will at the center right the View. */ public static final int CENTER_RIGHT = 6; /** * Special value for the alignment requested by a View. BOTTOM_LEFT means that the location * will be at the bottom left of the View. */ public static final int BOTTOM_LEFT = 7; /** * Special value for the alignment requested by a View. BOTTOM_CENTER means that the * location will be centered at the bottom of the view. */ public static final int BOTTOM_CENTER = 8; /** * Special value for the alignment requested by a View. BOTTOM_RIGHT means that the location * will be at the bottom right of the View. */ public static final int BOTTOM_RIGHT = 9; /** * The location of the child within the map view. */ public GeoPoint geoPoint; /** * The alignment the alignment of the view compared to the location. */ public int alignment; public int offsetX; public int offsetY; /** * Creates a new set of layout parameters with the specified width, height and location. * * @param width * the width, either {@link #FILL_PARENT}, {@link #WRAP_CONTENT} or a fixed size * in pixels * @param height * the height, either {@link #FILL_PARENT}, {@link #WRAP_CONTENT} or a fixed size * in pixels * @param geoPoint * the location of the child within the map view * @param alignment * the alignment of the view compared to the location {@link #BOTTOM_CENTER}, * {@link #BOTTOM_LEFT}, {@link #BOTTOM_RIGHT} {@link #TOP_CENTER}, * {@link #TOP_LEFT}, {@link #TOP_RIGHT} * @param offsetX * the additional X offset from the alignment location to draw the child within * the map view * @param offsetY * the additional Y offset from the alignment location to draw the child within * the map view */ public LayoutParams(final int width, final int height, final GeoPoint geoPoint, final int alignment, final int offsetX, final int offsetY) { super(width, height); if (geoPoint != null) { this.geoPoint = geoPoint; } else { this.geoPoint = new GeoPoint(0, 0); } this.alignment = alignment; this.offsetX = offsetX; this.offsetY = offsetY; } /** * Since we cannot use XML files in this project this constructor is useless. Creates a new * set of layout parameters. The values are extracted from the supplied attributes set and * context. * * @param c * the application environment * @param attrs * the set of attributes fom which to extract the layout parameters values */ public LayoutParams(final Context c, final AttributeSet attrs) { super(c, attrs); this.geoPoint = new GeoPoint(0, 0); this.alignment = BOTTOM_CENTER; } /** * {@inheritDoc} */ public LayoutParams(final ViewGroup.LayoutParams source) { super(source); } } }
package com.njackson.gps; import android.location.Location; import android.net.Uri; import android.util.Log; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.InputStreamReader; import javax.inject.Singleton; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; @Singleton public class Navigator { private static final String TAG = "PB-Navigator"; protected class Poi extends Location { public boolean seen = false; public float distance = 0; public int index = 0; public Poi(Location l) { super(l); } } Poi[] _pointsIni; private int _nbPointsIni = 0; Poi[] _pointsSimpl; private int _nbPointsSimpl = 0; private float _nextDistance = 0; private float _nextBearing = 0; private int _nextIndex = 0; private int _maxSeenIndex = -1; private float _error = 0; public Navigator() { } public void onLocationChanged(Location location) { if (_nbPointsIni == 0) { return; } Log.d(TAG, "onLocationChanged: lat:"+location.getLatitude()+",lon:"+location.getLongitude() + " nbPointsSimpl:" + _nbPointsSimpl); float minDist = 1000000; int minPoint = 0; float minBearing = 0; float minError = 0; for(int i = 0; i < _nbPointsSimpl; i++) { float dist = location.distanceTo(_pointsSimpl[i]); float bearing = (location.bearingTo(_pointsSimpl[i]) + 360) % 360; float error = i > 0 ? crossTrackError(_pointsSimpl[i-1], _pointsSimpl[i], location) : 0; Log.d(TAG, i + "[" + _pointsSimpl[i].index + "] dist:" + dist + " bearing:" + bearing + " error:" + error + " seen:" + (_pointsSimpl[i].seen ? "y" : "n")); if (dist < minDist && _maxSeenIndex < i) { minDist = dist; minPoint = i; minBearing = bearing; minError = error; } if (dist < 50) { _pointsSimpl[i].seen = true; _maxSeenIndex = i > _maxSeenIndex ? i : _maxSeenIndex; } } Log.d(TAG, "min:" + minDist + " bearing: " + minBearing + " error: " + minError + " DTD:" + Math.round(_pointsSimpl[_nbPointsSimpl-1].distance - _pointsSimpl[minPoint].distance) + " point #" + minPoint); _nextDistance = minDist; _nextBearing = minBearing; _nextIndex = minPoint; _error = minError; } public void loadGpx(String gpx) { _nbPointsIni = 0; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new InputSource(new ByteArrayInputStream(gpx.getBytes("utf-8")))); XPath xpath = XPathFactory.newInstance().newXPath(); String expression = ""; NodeList nodes; Node node; expression = "//trkpt"; nodes = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET); Log.d(TAG, "length:" + nodes.getLength()); float distance = 0; _pointsIni = new Poi[nodes.getLength()]; Location loc = new Location("Ventoo"); for (int i = 0; i < nodes.getLength(); i++) { node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) node; //Log.d(TAG, "lat " + eElement.getAttribute("lat")); //Log.d(TAG, "ele: " + eElement.getElementsByTagName("ele").item(0).getTextContent()); try { loc.setLatitude(Float.parseFloat(eElement.getAttribute("lat"))); loc.setLongitude(Float.parseFloat(eElement.getAttribute("lon"))); _pointsIni[_nbPointsIni] = new Poi(loc); _pointsIni[_nbPointsIni].index = i; if (_nbPointsIni > 0) { distance += _pointsIni[_nbPointsIni].distanceTo(_pointsIni[_nbPointsIni-1]); _pointsIni[_nbPointsIni].distance = distance; } _nbPointsIni++; } catch (NumberFormatException e) { Log.e(TAG, "Exception:" + e); } } } } catch (Exception e) { Log.e(TAG, "Exception:" + e); } Log.d(TAG, "nbPointsIni:" + _nbPointsIni); simplifyRoute(); // debug //if (_nbPointsSimpl > 15) { // onLocationChanged(_pointsSimpl[0]); // onLocationChanged(_pointsSimpl[10]); // onLocationChanged(_pointsSimpl[_nbPointsSimpl-1]); } public void simplifyRoute() { Log.d(TAG, "simplifyRoute nbPointsIni:" + _nbPointsIni); if (_nbPointsIni == 0) { return; } int lastIndex = 0; int lastIndex2 = 0; StringBuilder debug = new StringBuilder(); _pointsSimpl = new Poi[_nbPointsIni]; // force 1st point _pointsSimpl[0] = _pointsIni[0]; _nbPointsSimpl = 1; for(int i = 1; i < _nbPointsIni - 1; i++) { float bearingLastToMe = (_pointsIni[lastIndex].bearingTo(_pointsIni[i]) + 360) % 360; float bearingLastToNext = (_pointsIni[lastIndex].bearingTo(_pointsIni[i + 1]) + 360) % 360; float bearingMeToNext = (_pointsIni[i].bearingTo(_pointsIni[i + 1]) + 360) % 360; boolean keep = false; float diff1 = 0; float diff2 = 0; String tmp = ""; diff1 = bearingLastToNext - bearingLastToMe; diff2 = bearingMeToNext - bearingLastToMe; if (lastIndex != i - 1) { if (Math.abs(diff1) > 5) { tmp += "a"+Math.round(Math.abs(diff1)); keep = true; } } if (Math.abs(diff2) > 30) { tmp += "b"+Math.round(Math.abs(diff2)); keep = true; } Log.d(TAG, i + ": " + lastIndex2 + "-" + lastIndex + " dist:" + Math.round(_pointsIni[i].distance) + " b1:" + Math.round(bearingLastToMe) + " b2:" + Math.round(bearingLastToNext) + " b3:" + Math.round(bearingMeToNext) + " d1:" + Math.round(diff1) + " d2:" + Math.round(diff2) + " " + (keep ? ("KEEP " + _pointsIni[i].getLatitude() + "," + _pointsIni[i].getLongitude()) : "REMOVE")); if (keep) { debug.append(i + ": " + lastIndex2 + "-" + lastIndex + tmp +", " + _pointsIni[i].getLatitude() + "," + _pointsIni[i].getLongitude()+"\n"); lastIndex2 = lastIndex; lastIndex = i; _pointsSimpl[_nbPointsSimpl] = _pointsIni[i]; _nbPointsSimpl++; } } // force last point _pointsSimpl[_nbPointsSimpl] = _pointsIni[_nbPointsIni - 1]; _nbPointsSimpl++; Log.d(TAG, "simplifyRoute nbPointsIni:" + _nbPointsIni + " nbPointsSimpl:" + _nbPointsSimpl); Log.d(TAG, debug.toString()); } private static float R = 6371000; // radius of earth (meter) private static float DTR = 1.0f / 180 * 3.14159f; // conversion degrees -> radians static float crossTrackError(Location p1, Location p2, Location p3) { // distance of a point from a great-circle path (sometimes called cross track error). // http://www.movable-type.co.uk/scripts/latlong.html#cross-track // The along-track distance, from the start point to the closest point on the path to the third point, is // var dAt = Math.acos(Math.cos(d13/R)/Math.cos(dXt/R)) * R; float d13 = p1.distanceTo(p3); float t13 = p1.bearingTo(p3); float t12 = p1.bearingTo(p2); float dXt = (float) (Math.asin(Math.sin(d13/R) * Math.sin((t13-t12) * DTR)) * R); float dAt = (float) (Math.acos(Math.cos(d13/R) / Math.cos(dXt / R)) * R); return dXt; } public float getDistanceToDestination() { return _nbPointsSimpl > 0 ? (_pointsSimpl[_nbPointsSimpl-1].distance - _pointsSimpl[_nextIndex].distance + _nextDistance) : 0; } public float getNextDistance() { return _nextDistance; } public float getNextBearing() { return _nextBearing; } public int getNextIndex() { return _nextIndex; } public float getError() { return _error; } public int getNbPoints() { return _nbPointsSimpl; } }
package com.wsfmn.model; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Base64; import com.wsfmn.exceptions.HabitCommentTooLongException; import com.wsfmn.exceptions.HabitEventCommentTooLongException; import com.wsfmn.exceptions.HabitEventNameException; import java.io.Serializable; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; public class HabitEvent{ /** * Variables For the Habit Event that the user will enter or be created * when a user creates a new Habit Event */ private String title; private Habit habit; private String comment; String id; Date date = null; private java.util.Date actualdate; //Path of the file Where image is stored String CurrentPhotoPath; Bitmap imageBitmap; //change by wei, change location parts private Geolocation geolocation; public HabitEvent(){ this.title = ""; } public HabitEvent(Habit habit, String title, String comment, String CurrentPhotoPath, Date date) throws HabitCommentTooLongException, HabitEventCommentTooLongException, ParseException { this.habit = habit; this.title = title; setComment(comment); this.CurrentPhotoPath = CurrentPhotoPath; this.id = null; this.date = date; DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); java.util.Date adate = formatter.parse(this.date.toDateString()); this.actualdate = adate; this.geolocation = null; // this.imageBitmap = imageBitmap; } // public HabitEvent(Habit habit, String title, String comment, Date date) throws HabitCommentTooLongException, // HabitEventCommentTooLongException, ParseException { // this.habit = habit; // this.title = title; // setComment(comment); // this.CurrentPhotoPath = null; // this.id = null; // this.date = date; // DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); // java.util.Date adate = formatter.parse(this.date.toDateString()); // this.actualdate = adate; // this.geolocation = null; //// this.imageBitmap = imageBitmap; /** * Constructor for the Habit Event. * @param habit * @param title * @param comment * @param CurrentPhotoPath * @param date * @param geolocation * @throws HabitCommentTooLongException * @throws HabitEventCommentTooLongException */ public HabitEvent(Habit habit, String title, String comment, String CurrentPhotoPath, Date date, Geolocation geolocation) throws HabitCommentTooLongException, HabitEventCommentTooLongException, ParseException { this.habit = habit; this.title = title; setComment(comment); this.CurrentPhotoPath = CurrentPhotoPath; this.id = null; this.date = date; DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); java.util.Date adate = formatter.parse(this.date.toDateString()); this.actualdate = adate; this.geolocation = geolocation; // this.imageBitmap = imageBitmap; } public void setDate(Date date){ this.date = date; } public Date getDate(){ return this.date; } public java.util.Date getActualDate() throws ParseException { return this.actualdate; } /** * Get the path of the file where image is stored for the habit Event * @return mCurrentPhotoPath: filename of the image */ public String getCurrentPhotoPath(){ return CurrentPhotoPath; } /** * Get the Habit the user selects for the HabitEvent * @return Habit */ public Habit getHabitFromEvent(){ return habit; } /** * Get the Habit title for the Habit Event * @return habit Title */ public String getHabitTitle(){ return this.habit.getTitle(); } * /*Changes the Habit for the HabitEvent * @param habit */ public void setHabit(Habit habit){ this.habit = habit; } /** * Get Id for ElasticSearch * @return Id */ public String getId() {return id;} /** * Set Id for ElasticSearch * @param id */ public void setId(String id) { this.id = id; } /** * Get the Habit for the HabitEvent * @return habit */ public Habit getHabit() { return habit; } /** * Get the Title of the Habit Event * @return title of the HabitEvent * @throws HabitEventNameException */ public String getHabitEventTitle() throws HabitEventNameException{ /*Checks the title length of the HabitEvent*/ if(title.length() > 35 || title.length()<1){ /*Throws Exception if violates the condition*/ throw new HabitEventNameException(); } return title; } /** * Change Title of the HabitEvent * @param title * @throws HabitEventNameException */ public String setTitle(String title)throws HabitEventNameException{ /*Checks the length of the title*/ if(title.length() > 35 || title.length()<1){ /*Throws this exception*/ throw new HabitEventNameException(); } return this.title = title; } /** * Get the comment for HabitEvent that user created * @return comment */ public String getComment(){ return comment; } * /*Changing the Comment of Habit Event * @param comment * @throws HabitEventCommentTooLongException */ public void setComment(String comment) throws HabitEventCommentTooLongException { /*Checking if comment size does not exceed 20 characters*/ if(comment != null) { if (comment.length() > 20) { /* Throw HabitEventCommentTooLongException*/ throw new HabitEventCommentTooLongException(); } } this.comment = comment; } /** * * @param geolocation */ public void setGeolocation(Geolocation geolocation){ this.geolocation = geolocation; } /** * * @return */ public Geolocation getGeolocation(){ return geolocation; } /** * Compares two String Dates * * @param otherDate the other date that compare with the calling objects' ate * @return int 0 if equal, -1 if the calling object's date is smaller than otherDate, * 1 otherwise. */ public int compareDate(Date otherDate){ return date.compareDate(otherDate); } @Override public String toString(){ return title + " " + this.date; } public Bitmap getImageBitmap() { if(CurrentPhotoPath!=null) { byte[] decodedString = Base64.decode(this.CurrentPhotoPath, Base64.DEFAULT); Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); return decodedByte; } return null; } }
package erogenousbeef.bigreactors.common.item; import java.util.List; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemStack; public class ItemIngot extends ItemBase { public static final int DUST_OFFSET = 4; public static final String[] TYPES = { "ingotYellorium", "ingotCyanite", "ingotGraphite", "ingotBlutonium", "dustYellorium", "dustCyanite", "dustGraphite", "dustBlutonium" }; public static final String[] MATERIALS = { "Yellorium", "Cyanite", "Graphite", "Blutonium" }; public ItemIngot(int id) { super("ingot", id); this.setHasSubtypes(true); this.setMaxDamage(0); } @Override protected int getNumberOfSubItems() { return TYPES.length; } @Override protected String[] getSubItemNames() { return TYPES; } @Override public int getMetadata(int damage) { return damage; } @Override public String getUnlocalizedName(ItemStack itemStack) { int idx = Math.max(TYPES.length, itemStack.getItemDamage()); return "item." + TYPES[idx]; } @Override public void getSubItems(int par1, CreativeTabs creativeTabs, List list) { for (int i = 0; i < TYPES.length; i++) { list.add(new ItemStack(this, 1, i)); } } public static boolean isFuel(int itemDamage) { return itemDamage == 0 || itemDamage == 3; } public static boolean isWaste(int itemDamage) { return itemDamage == 1; } public static boolean isGraphite(int itemDamage) { return itemDamage == 2; } public ItemStack getItemStackForType(String typeName) { for(int i = 0; i < TYPES.length; i++) { if(TYPES[i].equals(typeName)) { return new ItemStack(this, 1, i); } } return null; } public ItemStack getIngotItemStackForMaterial(String name) { int i = 0; for(i = 0; i < MATERIALS.length; i++) { if(name.equals(MATERIALS[i])) { break; } } return new ItemStack(this, 1, i); } }
package enmasse.address.controller.api.v3.http; import enmasse.address.controller.api.v3.Address; import enmasse.address.controller.api.v3.AddressList; import enmasse.address.controller.api.v3.ApiHandler; import enmasse.address.controller.model.TenantId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.Optional; @Path("/v3/address") public class AddressingService { private static final Logger log = LoggerFactory.getLogger(AddressingService.class.getName()); private final ApiHandler apiHandler; private final TenantId tenantId = TenantId.fromString("mytenant"); public AddressingService(@Context ApiHandler apiHandler) { this.apiHandler = apiHandler; } @GET @Produces({MediaType.APPLICATION_JSON}) public Response listAddresses() { try { return Response.ok(apiHandler.getAddresses(tenantId)).build(); } catch (Exception e) { log.warn("Error listing addresses", e); return Response.serverError().build(); } } @PUT @Produces({MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_JSON}) public Response putAddresses(AddressList addressList) { try { return Response.ok(apiHandler.putAddresses(tenantId, addressList)).build(); } catch (Exception e) { log.warn("Error putting addresses", e); return Response.serverError().build(); } } @POST @Produces({MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_JSON}) public Response appendAddress(Address address) { try { return Response.ok(apiHandler.appendAddress(tenantId, address)).build(); } catch (Exception e) { log.warn("Error appending addresses", e); return Response.serverError().build(); } } @GET @Path("{address}") @Produces({MediaType.APPLICATION_JSON}) public Response getAddress(@PathParam("address") String address) { try { Optional<Address> addr = apiHandler.getAddress(tenantId, address); if (addr.isPresent()) { return Response.ok(addr.get()).build(); } else { return Response.status(404).build(); } } catch (Exception e) { log.warn("Error getting address", e); return Response.serverError().build(); } } @PUT @Path("{address}") @Produces({MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_JSON}) public Response putAddress(@PathParam("address") String address) { return Response.status(405).build(); } @DELETE @Path("{address}") @Produces({MediaType.APPLICATION_JSON}) public Response deleteAddress(@PathParam("address") String address) { try { return Response.ok(apiHandler.deleteAddress(tenantId, address)).build(); } catch (Exception e) { log.warn("Error deleting address", e); return Response.serverError().build(); } } }
package org.skywalking.apm.agent.core.context; import java.util.LinkedList; import org.skywalking.apm.agent.core.boot.ServiceManager; import org.skywalking.apm.agent.core.conf.Config; import org.skywalking.apm.agent.core.context.trace.AbstractSpan; import org.skywalking.apm.agent.core.context.trace.AbstractTracingSpan; import org.skywalking.apm.agent.core.context.trace.SpanType; import org.skywalking.apm.agent.core.context.trace.TraceSegment; import org.skywalking.apm.agent.core.dictionary.DictionaryManager; import org.skywalking.apm.agent.core.sampling.SamplingService; /** * @author wusheng */ public class TracingContext implements AbstractTracerContext { private SamplingService samplingService; private TraceSegment segment; /** * Active spans stored in a Stack, usually called 'ActiveSpanStack'. * This {@link LinkedList} is the in-memory storage-structure. * <p> * I use {@link LinkedList#removeLast()}, {@link LinkedList#addLast(Object)} and {@link LinkedList#last} instead of * {@link #pop()}, {@link #push(AbstractTracingSpan)}, {@link #peek()} */ private LinkedList<AbstractTracingSpan> activeSpanStack = new LinkedList<AbstractTracingSpan>(); private int spanIdGenerator; TracingContext() { this.segment = new TraceSegment(DictionaryManager.getApplicationDictionary().findId(Config.Agent.APPLICATION_CODE)); this.spanIdGenerator = 0; if (samplingService == null) { samplingService = ServiceManager.INSTANCE.findService(SamplingService.class); } } @Override public void inject(ContextCarrier carrier) { } @Override public void extract(ContextCarrier carrier) { } @Override public String getGlobalTraceId() { return segment.getRelatedGlobalTraces().get(0).get(); } @Override public AbstractSpan createSpan(String operationName, SpanType spanType) { return null; } @Override public AbstractTracingSpan activeSpan() { AbstractTracingSpan span = peek(); if (span == null) { throw new IllegalStateException("No active span."); } return span; } @Override public void stopSpan(AbstractSpan span) { } @Override public void dispose() { this.segment = null; this.activeSpanStack = null; } /** * @return the top element of 'ActiveSpanStack', and remove it. */ private AbstractTracingSpan pop() { return activeSpanStack.removeLast(); } /** * Add a new Span at the top of 'ActiveSpanStack' * * @param span */ private void push(AbstractTracingSpan span) { activeSpanStack.addLast(span); } /** * @return the top element of 'ActiveSpanStack' only. */ private AbstractTracingSpan peek() { if (activeSpanStack.isEmpty()) { return null; } return activeSpanStack.getLast(); } }
package com.etiennelawlor.quickreturn.listeners; import android.os.Build; import android.view.View; import android.view.animation.TranslateAnimation; import android.widget.AbsListView; import com.etiennelawlor.quickreturn.enums.QuickReturnType; import com.etiennelawlor.quickreturn.utils.QuickReturnUtils; public class QuickReturnListViewOnScrollListener implements AbsListView.OnScrollListener { // region Member Variables private int mMinFooterTranslation; private int mMinHeaderTranslation; private int mPrevScrollY = 0; private int mHeaderDiffTotal = 0; private int mFooterDiffTotal = 0; private TranslateAnimation mFooterAnim; private TranslateAnimation mHeaderAnim; private View mHeader; private View mFooter; private QuickReturnType mQuickReturnType; // endregion // region Constructors public QuickReturnListViewOnScrollListener(QuickReturnType quickReturnType, View view, int viewHeight){ mQuickReturnType = quickReturnType; switch (mQuickReturnType){ case HEADER: mMinHeaderTranslation = -viewHeight; mHeader = view; break; case FOOTER: mMinFooterTranslation = viewHeight; mFooter = view; break; default: break; } } public QuickReturnListViewOnScrollListener(QuickReturnType quickReturnType, View headerView, int headerViewHeight, View footerView, int footerViewHeight){ mQuickReturnType = quickReturnType; switch (mQuickReturnType){ case BOTH: mMinHeaderTranslation = -headerViewHeight; mHeader = headerView; mMinFooterTranslation = footerViewHeight; mFooter = footerView; default: break; } } // endregion @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } @Override public void onScroll(AbsListView listview, int firstVisibleItem, int visibleItemCount, int totalItemCount) { int scrollY = QuickReturnUtils.getScrollY(listview); int diff = mPrevScrollY - scrollY; switch (mQuickReturnType){ case HEADER: if(diff <=0){ // scrolling down mHeaderDiffTotal = Math.max(mHeaderDiffTotal + diff, mMinHeaderTranslation); } else { // scrolling up mHeaderDiffTotal = Math.min(Math.max(mHeaderDiffTotal + diff, mMinHeaderTranslation), 0); } if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB) { mHeaderAnim = new TranslateAnimation(0, 0, mHeaderDiffTotal, mHeaderDiffTotal); mHeaderAnim.setFillAfter(true); mHeaderAnim.setDuration(0); mHeader.startAnimation(mHeaderAnim); } else { mHeader.setTranslationY(mHeaderDiffTotal); } break; case FOOTER: if(diff <=0){ // scrolling down mFooterDiffTotal = Math.max(mFooterDiffTotal + diff, -mMinFooterTranslation); } else { // scrolling up mFooterDiffTotal = Math.min(Math.max(mFooterDiffTotal + diff, -mMinFooterTranslation), 0); } if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB) { mFooterAnim = new TranslateAnimation(0, 0, -mFooterDiffTotal, -mFooterDiffTotal); mFooterAnim.setFillAfter(true); mFooterAnim.setDuration(0); mFooter.startAnimation(mFooterAnim); } else { mFooter.setTranslationY(-mFooterDiffTotal); } break; case BOTH: if(diff <=0){ // scrolling down mHeaderDiffTotal = Math.max(mHeaderDiffTotal + diff, mMinHeaderTranslation); } else { // scrolling up mHeaderDiffTotal = Math.min(Math.max(mHeaderDiffTotal + diff, mMinHeaderTranslation), 0); } if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB) { mHeaderAnim = new TranslateAnimation(0, 0, mHeaderDiffTotal, mHeaderDiffTotal); mHeaderAnim.setFillAfter(true); mHeaderAnim.setDuration(0); mHeader.startAnimation(mHeaderAnim); } else { mHeader.setTranslationY(mHeaderDiffTotal); } if(diff <=0){ // scrolling down mFooterDiffTotal = Math.max(mFooterDiffTotal + diff, -mMinFooterTranslation); } else { // scrolling up mFooterDiffTotal = Math.min(Math.max(mFooterDiffTotal + diff, -mMinFooterTranslation), 0); } if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB) { mFooterAnim = new TranslateAnimation(0, 0, -mFooterDiffTotal, -mFooterDiffTotal); mFooterAnim.setFillAfter(true); mFooterAnim.setDuration(0); mFooter.startAnimation(mFooterAnim); } else { mFooter.setTranslationY(-mFooterDiffTotal); } default: break; } mPrevScrollY = scrollY; } }
// SysExec.java package ed.io; import java.io.*; import java.util.*; import ed.js.*; import ed.js.engine.*; import ed.security.*; public class SysExec extends ed.js.func.JSFunctionCalls4 { /** * adds quotes as needed */ static String[] fix( String s ){ String base[] = s.split( "\\s+" ); List<String> fixed = new ArrayList(); boolean changed = false; for ( int i=0; i<base.length; i++ ){ if ( ! base[i].startsWith( "\"" ) ){ fixed.add( base[i] ); continue; } int end = i; while( end < base.length && ! base[end].endsWith( "\"" ) ) end++; String foo = base[i++].substring( 1 ); for ( ; i<=end && i < base.length; i++ ) foo += " " + base[i]; i if ( foo.endsWith( "\"" ) ) foo = foo.substring( 0 , foo.length() - 1 ); fixed.add( foo ); changed = true; } if ( changed ){ System.out.println( fixed ); base = new String[fixed.size()]; for ( int i=0; i<fixed.size(); i++ ) base[i] = fixed.get(i); } return base; } public static Result exec( String cmdString ){ return exec( cmdString , null , null , null ); } public static Result exec( String cmdString , String env[] , File procDir , String toSend ){ String cmd[] = fix( cmdString ); try { final Process p = Runtime.getRuntime().exec( cmd , env , procDir); if ( toSend != null ){ OutputStream out = p.getOutputStream(); out.write( toSend.getBytes() ); out.close(); } final Result res = new Result(); final IOException threadException[] = new IOException[1]; Thread a = new Thread(){ public void run(){ try { synchronized ( res ){ res.setErr( StreamUtil.readFully( p.getErrorStream() ) ); } } catch ( IOException e ){ threadException[0] = e; } } }; a.start(); synchronized( res ){ res.setOut( StreamUtil.readFully( p.getInputStream() ) ); } a.join(); if ( threadException[0] != null ) throw threadException[0]; res.exitValue( p.waitFor() ); return res; } catch ( Exception e ){ throw new JSException( e.toString() , e ); } } public Object call( Scope scope , Object o , Object toSendObj , Object envObj , Object pathObj , Object extra[] ){ if ( o == null ) return null; if ( ! Security.isCoreJS() ) throw new JSException( "can't do sysexec from [" + Security.getTopJS() + "]" ); File root = scope.getRoot(); if ( root == null ) throw new JSException( "no root" ); String env[] = new String[]{}; String toSend = null; if ( toSendObj != null ) toSend = toSendObj.toString(); if ( envObj instanceof JSObject ){ JSObject foo = (JSObject)envObj; env = new String[ foo.keySet().size() ]; int pos = 0; for ( String name : foo.keySet() ){ Object val = foo.get( name ); if ( val == null ) val = ""; env[pos++] = name + "=" + val.toString(); } } File procDir = root; if ( pathObj instanceof JSString ){ procDir = new File( root , pathObj.toString() ); try { if (!procDir.getCanonicalPath().contains(root.getCanonicalPath())) { throw new JSException("directory offset moves execution outside of root"); } } catch (IOException e) { throw new JSException("directory offset problem", e); } } return exec( o.toString() , env , procDir , toSend ); } public static class Result extends JSObjectBase { void setOut( String s ){ set( "out" , s ); } void setErr( String s ){ set( "err" , s ); } void exitValue( int ev ){ set( "exitValue" , ev ); } public String getOut(){ return get( "out" ).toString(); } public String getErr(){ return get( "err" ).toString(); } public int exitValue(){ return ((Number)get( "exitValue" )).intValue(); } public String toString(){ return "{\n" + "\t exitValue : " + exitValue() + " , \n " + "\t out : " + getOut() + " , \n " + "\t err : " + getErr() + " , \n " + "}\n"; } } }
package com.whitfield.james.simplenetworkspeedmonitor.services; import android.app.NotificationManager; import android.app.Service; import android.content.Context; import android.content.Intent; import android.net.TrafficStats; import android.os.*; import android.support.annotation.Nullable; import android.support.v7.app.NotificationCompat; import android.text.Html; import android.util.Log; import android.widget.Toast; import com.whitfield.james.simplenetworkspeedmonitor.R; import com.whitfield.james.simplenetworkspeedmonitor.home.HomeActivity; public class NetworkIntentService extends Service { private Looper mServiceLooper; private ServiceHandler mServiceHandler; private boolean stop = false; /** * Creates an IntentService. Invoked by your subclass's constructor. * * @param name Used to name the worker thread, important only for debugging. */ private static final int NOTIFICATION_ID = 10000; public static final String NAME = "NetworkService"; Boolean up,down,lockScreen = null; private Intent intent; @Override public void onDestroy() { super.onDestroy(); stop = true; mServiceHandler = null; Log.i(NAME, "Stop"); } @Override public void onCreate() { // Start up the thread running the service. Note that we create a // separate thread because the service normally runs in the process's // main thread, which we don't want to block. We also make it // background priority so CPU-intensive work will not disrupt our UI. HandlerThread thread = new HandlerThread("ServiceStartArguments", android.os.Process.THREAD_PRIORITY_BACKGROUND); thread.start(); // Get the HandlerThread's Looper and use it for our Handler mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } private final class ServiceHandler extends Handler { public ServiceHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { Log.i(NAME, "Start"); Bundle bundle = intent.getExtras(); if(bundle.containsKey(HomeActivity.INTENT_TAG_DOWN)){ down = bundle.getBoolean(HomeActivity.INTENT_TAG_DOWN); } if(bundle.containsKey(HomeActivity.INTENT_TAG_UP)){ up = bundle.getBoolean(HomeActivity.INTENT_TAG_UP); } if(bundle.containsKey(HomeActivity.INTENT_TAG_LOCK_SCREEN)){ lockScreen = bundle.getBoolean(HomeActivity.INTENT_TAG_LOCK_SCREEN); } NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(getApplicationContext()) .setContentTitle("Network speed") // .setContentText("Setup...") .setSmallIcon(R.drawable.ic_stat_) ; if(lockScreen == true){ builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); }else{ builder.setVisibility(NotificationCompat.VISIBILITY_SECRET); } startForeground(NOTIFICATION_ID, builder.build()); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Long downStart = TrafficStats.getTotalRxBytes(); Long upStart = TrafficStats.getTotalTxBytes(); Long downCurrent; Long upCurrent; try { while (!stop){ downCurrent = TrafficStats.getTotalRxBytes(); upCurrent = TrafficStats.getTotalTxBytes(); String output = ""; if(down){ Long kbs = (downCurrent - downStart)/1024; kbs = Long.valueOf(3567); if(kbs > 1024){ double x = (double)kbs/(double)1024; output = output + Html.fromHtml("\u25bc")+ (Math.round(x *100.0)/100.0) + "/Mbs "; }else{ output = output + Html.fromHtml("\u25bc")+ kbs + "/kbs "; } } if(up){ Long kbs = (upCurrent - upStart)/1024; kbs = Long.valueOf(287); if(kbs > 1024){ double x = (double)kbs/(double)1024; output = output + Html.fromHtml("\u25b2") + (Math.round(x *100.0)/100.0) + "/Mbs"; }else{ output = output + Html.fromHtml("\u25b2") + kbs + "/kbs"; } } builder.setContentTitle(output) .setShowWhen(false); notificationManager.notify(NOTIFICATION_ID, builder.build()); downStart = downCurrent; upStart = upCurrent; Thread.sleep(1*1000); } } catch (InterruptedException e) { e.printStackTrace(); } // Stop the service using the startId, so that we don't stop // the service in the middle of handling another job stopSelf(msg.arg1); } } @Override public int onStartCommand(Intent intent, int flags, int startId) { this.intent = intent; // For each start request, send a message to start a job and deliver the // start ID so we know which request we're stopping when we finish the job Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; mServiceHandler.sendMessage(msg); // If we get killed, after returning from here, restart return START_STICKY; } }
package io.oldering.tvfoot.red.app.common.rxdatabinding; import android.databinding.ObservableBoolean; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.android.MainThreadDisposable; import static io.oldering.tvfoot.red.app.common.PreConditions.checkMainThread; final class ObservableBooleanObservable extends Observable<ObservableBooleanPropertyChangedEvent> { private final ObservableBoolean field; ObservableBooleanObservable(ObservableBoolean observableField) { this.field = observableField; } @Override protected void subscribeActual(Observer<? super ObservableBooleanPropertyChangedEvent> observer) { if (!checkMainThread(observer)) { return; } Listener listener = new Listener(field, observer); observer.onSubscribe(listener); field.addOnPropertyChangedCallback(listener.onPropertyChangedCallback); } private final class Listener extends MainThreadDisposable { private final ObservableBoolean observableField; final android.databinding.Observable.OnPropertyChangedCallback onPropertyChangedCallback; Listener(ObservableBoolean observableField, final Observer<? super ObservableBooleanPropertyChangedEvent> observer) { this.observableField = observableField; this.onPropertyChangedCallback = new android.databinding.Observable.OnPropertyChangedCallback() { @Override public void onPropertyChanged(android.databinding.Observable observableField, int propertyId) { if (!isDisposed()) { observer.onNext(ObservableBooleanPropertyChangedEvent.create( (ObservableBoolean) observableField, propertyId, ((ObservableBoolean) observableField).get())); } } }; } @Override protected void onDispose() { observableField.removeOnPropertyChangedCallback(onPropertyChangedCallback); } } }
package main.java; public class Position { private int row; private int column; public String toString() { return Integer.toString(row) + ", " + Integer.toString(column); } public Position(int row, int column) throws IndexOutsideOfGridException { /*Check row is in valid range*/ if (isValidCoordinate(row)) { this.row = row; } else { String msg = "Row value=" + row + " is out of bounds."; throw new IndexOutsideOfGridException(msg); } /*Check column is in valid range*/ if (isValidCoordinate(column)) { this.column = column; } else { String msg = "Column value=" + column + " is out of bounds."; throw new IndexOutsideOfGridException(msg); } } int getRow() { return this.row; } int getColumn() { return this.column; } /** * Determine if the coordinate is within the bounds of the grid dimensions. * * @param coordinate Row or column used to place a piece on the board. * @return True if the coordinate is within the bounds. */ protected boolean isValidCoordinate(int coordinate) { return (0 <= coordinate && coordinate < Board.GRID_SIZE); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Position)) { return false; } Position other = (Position) obj; if (this.column != other.column) { return false; } if (this.row != other.row) { return false; } return true; } }
// Note: I'm not crazy about writing code in Java, so the idea behind this // file is to do the absolute minimum amount of work necessary to call into // the Sqlite3 C/C++ interface from within Scala. I'm not trying to impose a // more Java-like interface on Sqlite, or add object orientation, or anything // like that. In fact, I would prefer that this file were generated by an // automated program. I played around a bit with gluegen and couldn't get // it to work. And SWIG seems to save effort only if you're making wrappers // for multiple languages. Luckily there aren't too many functions to wrap. package org.srhea.scalaqlite; public class Sqlite3C { public static final int OK = 0; public static final int ERROR = 1; public static final int ROW = 100; public static final int DONE = 101; public static final int INTEGER = 1; public static final int FLOAT = 2; public static final int TEXT = 3; public static final int BLOB = 4; public static final int NULL = 5; native static public int open(String path, long[] db); native static public int close(long db); native static public int enable_load_extension(long db, int onoff); native static public int prepare_v2(long db, String sql, long[] stmt); native static public int reset(long stmt); native static public int bind_null(long stmt, int index); native static public int bind_int64(long stmt, int index, long value); native static public int bind_double(long stmt, int index, double value); native static public int bind_text(long stmt, int index, byte[] value); native static public int bind_blob(long stmt, int index, byte[] value); native static public int step(long stmt); native static public int finalize(long stmt); native static public int column_count(long stmt); native static public int column_type(long stmt, int n); native static public long column_int64(long stmt, int n); native static public double column_double(long stmt, int n); native static public byte[] column_blob(long stmt, int n); native static public String errmsg(long db); native static public int sqlite3_changes(long db); static { // Using Runtime.loadLibrary makes the calling class Sqlite3C instead of System, // thus loading scalaqlite in the local class loader instead of the system class loader. Runtime.getRuntime().loadLibrary("scalaqlite"); } }
// -*- mode: java; c-basic-offset: 2; -*- package com.google.appinventor.client.editor.simple.components; import static com.google.appinventor.client.Ode.MESSAGES; import com.google.appinventor.client.editor.simple.SimpleEditor; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Widget; /** * Mock CheckBox component. * * @author lizlooney@google.com (Liz Looney) */ public final class MockCheckBox extends MockWrapper { /** * Component type name. */ public static final String TYPE = "CheckBox"; // GWT checkbox widget used to mock a Simple CheckBox private CheckBox checkboxWidget; /** * Creates a new MockCheckbox component. * * @param editor editor of source file the component belongs to */ public MockCheckBox(SimpleEditor editor) { super(editor, TYPE, images.checkbox()); // Initialize mock checkbox UI checkboxWidget = new CheckBox(); initWrapper(checkboxWidget); } /** * Class that extends CheckBox so we can use a protected constructor. * * <p/>The purpose of this class is to create a clone of the CheckBox * passed to the constructor. It will be used to determine the preferred size * of the CheckBox, without having the size constrained by its parent, * since the cloned CheckBox won't have a parent. */ static class ClonedCheckBox extends CheckBox { ClonedCheckBox(CheckBox ptb) { // Get the Element from the CheckBox. // Call DOM.clone to make a deep clone of that element. // Pass that cloned element to the super constructor. super(DOM.clone(ptb.getElement(), true)); } } @Override protected Widget createClonedWidget() { return new ClonedCheckBox(checkboxWidget); } @Override public void onCreateFromPalette() { // Change checkbox caption to component name changeProperty(PROPERTY_NAME_TEXT, MESSAGES.textPropertyValue(getName())); } /* * Sets the checkbox's BackgroundColor property to a new value. */ private void setBackgroundColorProperty(String text) { if (MockComponentsUtil.isDefaultColor(text)) { text = "&HFFFFFFFF"; // white } MockComponentsUtil.setWidgetBackgroundColor(checkboxWidget, text); } /* * Sets the checkbox's Enabled property to a new value. */ private void setEnabledProperty(String text) { MockComponentsUtil.setEnabled(this, text); } /* * Sets the checkbox's FontBold property to a new value. */ private void setFontBoldProperty(String text) { MockComponentsUtil.setWidgetFontBold(checkboxWidget, text); updatePreferredSize(); } /* * Sets the checkbox's FontItalic property to a new value. */ private void setFontItalicProperty(String text) { MockComponentsUtil.setWidgetFontItalic(checkboxWidget, text); updatePreferredSize(); } @Override int getHeightHint() { int hint = super.getHeightHint(); if (hint == MockVisibleComponent.LENGTH_PREFERRED) { float height = Float.parseFloat(getPropertyValue(MockVisibleComponent.PROPERTY_NAME_FONTSIZE)); return Math.round(height); } else { return hint; } } /* * Sets the checkbox's FontSize property to a new value. */ private void setFontSizeProperty(String text) { MockComponentsUtil.setWidgetFontSize(checkboxWidget, text); updatePreferredSize(); } /* * Sets the checkbox's FontTypeface property to a new value. */ private void setFontTypefaceProperty(String text) { MockComponentsUtil.setWidgetFontTypeface(checkboxWidget, text); updatePreferredSize(); } /* * Sets the checkbox's Text property to a new value. */ private void setTextProperty(String text) { checkboxWidget.setText(text); updatePreferredSize(); } /* * Sets the checkbox's TextColor property to a new value. */ private void setTextColorProperty(String text) { if (MockComponentsUtil.isDefaultColor(text)) { text = "&HFF000000"; // black } MockComponentsUtil.setWidgetTextColor(checkboxWidget, text); } /* * Sets the checkbox's Checked property to a new value. */ private void setCheckedProperty(String text) { checkboxWidget.setChecked(Boolean.parseBoolean(text)); } // PropertyChangeListener implementation @Override public void onPropertyChange(String propertyName, String newValue) { super.onPropertyChange(propertyName, newValue); // Apply changed properties to the mock component if (propertyName.equals(PROPERTY_NAME_BACKGROUNDCOLOR)) { setBackgroundColorProperty(newValue); } else if (propertyName.equals(PROPERTY_NAME_ENABLED)) { setEnabledProperty(newValue); } else if (propertyName.equals(PROPERTY_NAME_FONTBOLD)) { setFontBoldProperty(newValue); refreshForm(); } else if (propertyName.equals(PROPERTY_NAME_FONTITALIC)) { setFontItalicProperty(newValue); refreshForm(); } else if (propertyName.equals(PROPERTY_NAME_FONTSIZE)) { setFontSizeProperty(newValue); refreshForm(); } else if (propertyName.equals(PROPERTY_NAME_FONTTYPEFACE)) { setFontTypefaceProperty(newValue); refreshForm(); } else if (propertyName.equals(PROPERTY_NAME_TEXT)) { setTextProperty(newValue); refreshForm(); } else if (propertyName.equals(PROPERTY_NAME_TEXTCOLOR)) { setTextColorProperty(newValue); } else if (propertyName.equals(PROPERTY_NAME_CHECKED)) { setCheckedProperty(newValue); } } }
package em; import java.io.*; import java.util.ArrayList; public class Lexer { private FileInput input; private ArrayList<Lexeme> lexemes; private File file; public Lexer(String filename){ this(new File(filename)); } public Lexer(File file){ this.file = file; try{ input = new FileInput(file); } catch(IOException e){ Logger.error("Error in reading file"); e.printStackTrace(); System.exit(1); } //Create the list for the lexemes lexemes = new ArrayList<>(); } public ArrayList<Lexeme> getLexemes(){ boolean go; do{ go = lex(); }while(go); return lexemes; } public boolean lex(){ input.skipWhitespace(); // Read a codepoint in int row = input.getRow(); int col = input.getCol(); int in = input.read(); // end of file, stop lexing if(in <= 0 || in == 65535){ return false; } if(in < Character.MAX_VALUE){ switch((char) in){ case '.': lexemes.add(new Lexeme(LexemeType.DOT, row, col, this.file)); return true; case ';': lexemes.add(new Lexeme(LexemeType.SEMICOLON, row, col, this.file)); return true; case ',': lexemes.add(new Lexeme(LexemeType.COMMA, row, col, this.file)); return true; case '(': lexemes.add(new Lexeme(LexemeType.OPEN_PAREN, row, col, this.file)); return true; case ')': lexemes.add(new Lexeme(LexemeType.CLOSE_PAREN, row, col, this.file)); return true; case '{': lexemes.add(new Lexeme(LexemeType.OPEN_CURLY, row, col, this.file)); return true; case '}': lexemes.add(new Lexeme(LexemeType.CLOSE_CURLY, row, col, this.file)); return true; case '[': lexemes.add(new Lexeme(LexemeType.OPEN_BRACKET, row, col, this.file)); return true; case ']': lexemes.add(new Lexeme(LexemeType.CLOSE_BRACKET, row, col, this.file)); return true; case '*': lexemes.add(new Lexeme(LexemeType.MULTIPLY, row, col, this.file)); return true; case '%': lexemes.add(new Lexeme(LexemeType.MODULO, row, col, this.file)); return true; default: input.pushback(in); if(lexMultiCharacterOperators()){ return true; } if(Character.isDigit(in)){ return lexNumber(); } if(in == '"'){ return lexString(); } } } //Check for identifiers and keywords if(in >= Character.MAX_VALUE){ input.pushback(in); } return lexKeywordsAndIdentifiers(); } /*Specialized lexing functions*/ /** * Parse all the non-single character operators * @return Whether a lexeme was parsed or not */ private boolean lexMultiCharacterOperators(){ int row = input.getRow(); int col = input.getCol(); int in = input.read(); if(in == '+'){ int test = input.read(); if(test == '+'){ lexemes.add(new Lexeme(LexemeType.INCREMENT, row, col, this.file)); } else{ input.pushback(test); lexemes.add(new Lexeme(LexemeType.PLUS, row, col, this.file)); } return true; } if(in == '-'){ int test = input.read(); if(test == '-'){ lexemes.add(new Lexeme(LexemeType.DECREMENT, row, col, this.file)); } else if(Character.isDigit(test)){ //For handling negative numbers input.pushback(test); input.pushback(in); return lexNumber(); } else if(test == '>'){ lexemes.add(new Lexeme(LexemeType.ARROW, row, col, this.file)); } else{ input.pushback(test); lexemes.add(new Lexeme(LexemeType.MINUS, row, col, this.file)); } return true; } if(in == '/'){ int test = input.read(); if(test == '/'){ input.skipLine(); } else{ input.pushback(test); lexemes.add(new Lexeme(LexemeType.DIVIDE, row, col, this.file)); } return true; } if(in == '>'){ int test = input.read(); if(test == '='){ lexemes.add(new Lexeme(LexemeType.GTE, row, col, this.file)); } else{ input.pushback(test); lexemes.add(new Lexeme(LexemeType.GT, row, col, this.file)); } return true; } if(in == '<'){ int test = input.read(); if(test == '='){ lexemes.add(new Lexeme(LexemeType.LTE, row, col, this.file)); } else{ input.pushback(test); lexemes.add(new Lexeme(LexemeType.LT, row, col, this.file)); } return true; } if(in == '&'){ int test = input.read(); if(test == '&'){ lexemes.add(new Lexeme(LexemeType.AND, row, col, this.file)); return true; } return false; } if(in == '|'){ int test = input.read(); if(test == '|'){ lexemes.add(new Lexeme(LexemeType.OR, row, col, this.file)); return true; } return false; } if(in == '='){ int test = input.read(); if(test == '='){ lexemes.add(new Lexeme(LexemeType.EQUALITY, row, col, this.file)); } else{ input.pushback(test); lexemes.add(new Lexeme(LexemeType.ASSIGN, row, col, this.file)); } return true; } if(in == '!'){ int test = input.read(); if(test == '='){ lexemes.add(new Lexeme(LexemeType.NOT_EQUALS, row, col, this.file)); } else{ input.pushback(test); lexemes.add(new Lexeme(LexemeType.NOT, row, col, this.file)); } return true; } input.pushback(in); return false; } /** * Parse lexemes for language keywords and identifiers * @return Where a keyword or identifier was parsed */ private boolean lexKeywordsAndIdentifiers(){ int row = input.getRow(); int col = input.getCol(); int in = input.read(); StringBuilder sb = new StringBuilder(); while(Character.isDigit(in) || Character.isAlphabetic(in) || Character.isSupplementaryCodePoint(in) || in == '_' || in == '-'){ sb.appendCodePoint(in); in = input.read(); } //Push back whatever broke the loop input.pushback(in); //Check all the keywords String inputString = sb.toString(); if(inputString.equals("var")){ lexemes.add(new Lexeme(LexemeType.VAR, row, col, this.file)); return true; } else if(inputString.equals("function")){ lexemes.add(new Lexeme(LexemeType.FUNCTION, row, col, this.file)); return true; } else if(inputString.equals("if")){ lexemes.add(new Lexeme(LexemeType.IF, row, col, this.file)); return true; } else if(inputString.equals("else")){ lexemes.add(new Lexeme(LexemeType.ELSE, row, col, this.file)); return true; } else if(inputString.equals("for")){ lexemes.add(new Lexeme(LexemeType.FOR, row, col, this.file)); return true; } else if(inputString.equals("while")){ lexemes.add(new Lexeme(LexemeType.WHILE, row, col, this.file)); return true; } else if(inputString.equals("do")) { lexemes.add(new Lexeme(LexemeType.DO, row, col, this.file)); return true; } else if(inputString.equals("true")) { lexemes.add(new Lexeme(LexemeType.TRUE, row, col, this.file)); return true; } else if(inputString.equals("false")) { lexemes.add(new Lexeme(LexemeType.FALSE, row, col, this.file)); return true; } else if(inputString.equals("null")) { lexemes.add(new Lexeme(LexemeType.NULL, row, col, this.file)); return true; } else if(inputString.equals("lambda")) { lexemes.add(new Lexeme(LexemeType.LAMBDA, row, col, this.file)); return true; } else if(inputString.equals("class")) { lexemes.add(new Lexeme(LexemeType.CLASS, row, col, this.file)); return true; } else if(inputString.equals("is")) { lexemes.add(new Lexeme(LexemeType.IS, row, col, this.file)); return true; } else{ //Must be an identifier, if it didn't match any keyword lexemes.add(new Lexeme(LexemeType.IDENTIFIER, inputString, row, col, this.file)); return true; } } /** * Lex a string literal * @return If a String lexeme was parsed */ private boolean lexString(){ int row = input.getRow(); int col = input.getCol(); Logger.silly("Lexing a string"); int in = input.read(); if(in == '"'){ StringBuilder sb = new StringBuilder(); in = input.read(); do{ if(in != '\\'){ sb.appendCodePoint(in); } in = input.read(); if(in == '\\'){ int test = input.read(); sb.appendCodePoint(test); } }while(in != '"' && in != -1); lexemes.add(new Lexeme(LexemeType.STRING, sb.toString(), row, col, this.file)); return true; } else{ input.pushback(in); return false; } } /** * Lex a number * @return If a number was parsed */ private boolean lexNumber(){ int row = input.getRow(); int col = input.getCol(); Logger.silly("Lexing a number"); StringBuilder sb = new StringBuilder(); int in = input.read(); //This'll either be a "-" or a digit do{ sb.appendCodePoint(in); in = input.read(); }while(Character.isDigit(in)); //Push back the non-digit character input.pushback(in); lexemes.add(new Lexeme(LexemeType.INTEGER, Integer.parseInt(sb.toString()), row, col, this.file)); return true; } }
import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.*; public class main_gui { private String file; private char[] key; public JPanel panel1; private JTextArea text_body; private JButton save_button; private JButton change_button; private JButton exit_button; public main_gui(String file_in) { this.file = file_in; // No file given so lets ask the user what they want to open if(this.file == null) { JFileChooser fc = new JFileChooser(); int returnVal = fc.showSaveDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file_selected = fc.getSelectedFile(); this.file = file_selected.getAbsolutePath(); } else { System.exit(0); } } //Ask for the key JPasswordField pf = new JPasswordField(); int okCxl = JOptionPane.showConfirmDialog(null, pf, "Enter Password", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (okCxl == JOptionPane.OK_OPTION) { this.key = pf.getPassword(); } else { System.exit(0); //Didn't enter a password } save_button.setEnabled(false); save_button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { boolean success = false; OutputStream os = null; try { os = EncryptIO.EncryptStream(file, key); } catch (EncryptIOException e) { e.printStackTrace(); } if(os == null) { System.out.println("Error: Output stream error"); return; } try { text_body.write(new OutputStreamWriter(os)); success = true; } catch (IOException e) { e.printStackTrace(); } try { os.flush(); os.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Saved file"); if(success) { save_button.setEnabled(false); } } }); change_button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { //Ask for the new key JPasswordField pf = new JPasswordField(); int okCxl = JOptionPane.showConfirmDialog(null, pf, "Enter new Password", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (okCxl == JOptionPane.OK_OPTION) { key = pf.getPassword(); save_button.setEnabled(true); } } }); exit_button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { for(int i=0; i<key.length;i++) { key[i] = (char)0; //zero the key } System.exit(0); } }); try { InputStream is = EncryptIO.DecryptStream(file, key); try { text_body.read(new InputStreamReader(is), null); } catch (IOException e) { e.printStackTrace(); } } catch (EncryptIOException e) { e.printStackTrace(); } text_body.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { super.keyTyped(e); save_button.setEnabled(true); } }); } }
package org.intermine.bio.dataconversion; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.DecimalFormat; import java.util.Arrays; 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 org.apache.log4j.Logger; import org.intermine.dataconversion.ItemWriter; import org.intermine.metadata.Model; import org.intermine.objectstore.ObjectStoreException; import org.intermine.sql.Database; import org.intermine.util.Util; import org.intermine.xml.full.Item; import org.intermine.xml.full.ReferenceList; /** * * @author sc */ public class BarExpressionsConverter extends BioDBConverter { private static final Logger LOG = Logger.getLogger(BarExpressionsConverter.class); // private static final String DATASET_TITLE = "Expressions data set"; // private static final String DATA_SOURCE_NAME = "atgenexp_hormone"; // private static final String EXPERIMENT_CATEGORY = "hormone"; // used to carrect a data issue in this data set.. private static final String BAD_BAR = "atgenexp"; private static final String BAR_URL = "http://bar.utoronto.ca/"; private static final String DATA_SOURCE_NAME = "The Bio-Analytic Resource for Plant Biology"; private static final int TAXON_ID = 3702; private static final String SAMPLE_CONTROL = "control"; private static final String SAMPLE_TREATMENT = "treatment"; private static final List<String> PROPERTY_TYPES = Arrays.asList( "stock", "geneticVar", "tissue", "diseased", "growthCondition", "growthStage", "timePoint"); //pi, item Id private Map<String, String> labIdRefMap = new HashMap<String, String>(); //barId, item Id // private Map<Integer, String> experimentIdRefMap = new HashMap<Integer, String>(); private Map<String, String> experimentIdRefMap = new HashMap<String, String>(); //barId, item Id private Map<Integer, String> sampleIdRefMap = new HashMap<Integer, String>(); //probeset, item Id private Map<String, String> probeIdRefMap = new HashMap<String, String>(); //propertyType.propertyValue, item Id private Map<String, String> propertyIdRefMap = new HashMap<String, String>(); //propertyType.propertyValue, objectId private Map<String, Integer> propertyIdMap = new HashMap<String, Integer>(); //property objectId, list of sampleRefId private Map<Integer, Set<String>> propertySampleMap = new HashMap<Integer, Set<String>>(); //sample id, sample objectId private Map<Integer, Integer> sampleMap = new HashMap<Integer, Integer>(); //sample_repl, list of controls sample_Id private Map<String, Set<Integer>> replicatesMap = new HashMap<String, Set<Integer>>(); //sample_id treat, list of controls sample_Id private Map<Integer, Set<Integer>> treatmentControlsMap = new HashMap<Integer, Set<Integer>>(); //sample_Id, probeset, avgSignal private Map<Integer, Map<String, Double>> averagesMap = new HashMap<Integer, Map<String, Double>>(); private String dataSetRef = null; /** * Construct a new BarExpressionsConverter. * @param database the database to read from * @param model the Model used by the object store we will write to with the ItemWriter * @param writer an ItemWriter used to handle Items created */ // public BarExpressionsConverter(Database database, Model model, ItemWriter writer) { // super(database, model, writer, DATA_SOURCE_NAME, DATASET_TITLE); public BarExpressionsConverter(Database database, Model model, ItemWriter writer) { super(database, model, writer); } /** * {@inheritDoc} */ public void process() throws Exception { Connection connection = null; if (getDatabase() == null) { // no Database when testing and no connection needed connection = null; } else { // a database has been initialised from properties starting with db.bar-expressions connection = getDatabase().getConnection(); } createDataSource(); processExperiments(connection); processSamples(connection); createSamplesAverages(connection); processSampleProperties(connection); setSamplePropertiesRefs(connection); setSampleRepRefs(connection); processSampleData(connection); } /** * create datasource and dataset * */ private void createDataSource() throws ObjectStoreException { Item dataSource = createItem("DataSource"); dataSource.setAttribute("name", DATA_SOURCE_NAME); dataSource.setAttribute("url", BAR_URL); Item dataSet = createItem("DataSet"); dataSet.setAttribute("name", getDataSourceName()); dataSet.setAttribute("url", BAR_URL); store(dataSource); dataSet.setReference("dataSource", dataSource.getIdentifier()); store(dataSet); dataSetRef = dataSet.getIdentifier(); // used in experiment } /** * process the experiments (bar projects) * @param connection */ private void processExperiments(Connection connection) throws SQLException, ObjectStoreException { ResultSet res = getExperiments(connection); while (res.next()) { String experimentBarId = res.getString(1); String title = res.getString(2); String pi = res.getString(3); String affiliation = res.getString(4); String address = res.getString(5); String experimentRefId = createExperiment(experimentBarId, title, pi, affiliation, address); experimentIdRefMap.put(experimentBarId, experimentRefId); } res.close(); } /** * process the samples * @param connection */ private void processSamples(Connection connection) throws SQLException, ObjectStoreException { ResultSet res = getSamples(connection); Map<Integer, String> sampleControlMap = new HashMap<Integer, String>(); while (res.next()) { String experimentBarId = res.getString(1); Integer sampleBarId = new Integer(res.getInt(2)); String name = res.getString(3); String alias = res.getString(4); String description = res.getString(5); // TODO: correct data? String control = getCorrectValue(res.getString(6), sampleBarId); String replication = getCorrectValue(res.getString(7), sampleBarId); String file = res.getString(8); String type = null; // add to the replicates map // Note: "replicates" also for set of controls Util.addToSetMap(replicatesMap, replication, sampleBarId); // set sample type and fill treatment-controls map if (control.equalsIgnoreCase(replication)) { type=SAMPLE_CONTROL; } else { type=SAMPLE_TREATMENT; // save controls sampleControlMap.put(sampleBarId, control); } String sampleRefId = createSample(experimentBarId, sampleBarId, name, alias, description, control, replication, file, type); sampleIdRefMap.put(sampleBarId, sampleRefId); } res.close(); // add to the treatmentControls map (sample-id, set of controls) for(Entry<Integer, String> sc: sampleControlMap.entrySet()) { Set<Integer> controls = replicatesMap.get(sc.getValue()); treatmentControlsMap.put(sc.getKey(), controls); } LOG.info("AAAreps: " + replicatesMap); LOG.info("AAAcontrols: " + treatmentControlsMap); } /** * to correct data issues * @param queried the value returned by the query * @param sampleBarId */ private String getCorrectValue(String queried, Integer sampleBarId) { if (getDataSourceName().equalsIgnoreCase(BAD_BAR) && sampleBarId == 244) { return "CTRL_7"; } return queried; } /** * create the averages for the groups of replicates * note that this includes also groups of controls * @param connection */ // TODO possibly better using java, instead of db // try it private void createSamplesAverages(Connection connection) throws SQLException, ObjectStoreException { // scan replicates map and for each group of replicates get for each probe // the averages signal. // put this in a map, and link this map to all the samples in the group // (using another map) LOG.info("START sample averages"); long bT = System.currentTimeMillis(); for (Set<Integer> replicates: replicatesMap.values()){ //probeset, avgSignal Map<String, Double> thisAveragesMap = new HashMap<String, Double>(); String inClause = getInClause(replicates); // get the averages for this set ResultSet res = getAverages(connection, inClause); while (res.next()) { String probeset = res.getString(1); Double avgSignal = res.getDouble(2); thisAveragesMap.put(probeset, avgSignal); } // fill averages map for (Integer sample: replicates) { averagesMap.put(sample, thisAveragesMap); } } LOG.info("AVG TIME: " + (System.currentTimeMillis() - bT) + " ms"); } /** * builds the in clause string for the sql statement from the elements of the set * @param the set of sample */ private String getInClause(Set<Integer> controls) { StringBuffer sb = new StringBuffer(); for (Integer term : controls) { sb.append(term + ","); } sb.delete(sb.lastIndexOf(","), sb.length()); return sb.toString(); } /** * process the sample properties * @param connection */ private void processSampleProperties(Connection connection) throws SQLException, ObjectStoreException { String source = this.getDataSourceName(); ResultSet res = getSampleProperties(connection, source); while (res.next()) { Integer sampleBarId = new Integer(res.getInt(1)); String stock = res.getString(2); String geneticVar = res.getString(3); String tissue = res.getString(4); String diseased = res.getString(5); String growthCondition = res.getString(6); String growthStage = res.getString(7); String timePoint = res.getString(8); String sampleRefId = createSampleProperties(sampleBarId, stock, geneticVar, tissue, diseased, growthCondition, growthStage, timePoint); } res.close(); } /** * process the sample data (expressions) * @param connection */ private void processSampleData(Connection connection) throws SQLException, ObjectStoreException { ResultSet res = getSampleData(connection); while (res.next()) { Integer sampleBarId = new Integer(res.getInt(1)); String probeSet = res.getString(2); Double signal = res.getDouble(3); String call = res.getString(4); Double pValue = res.getDouble(5); String sampleDataRefId = createSampleData(sampleBarId, probeSet, signal, call, pValue); } res.close(); } /** * create an experiment * @param bar Id * @param title * @param pi * @param affiliation * @param address */ private String createExperiment(String experimentBarId, String title, String pi, String affiliation, String address) throws ObjectStoreException { Item experiment = createItem("Experiment"); experiment.setAttribute("experimentBarId", experimentBarId.toString()); experiment.setAttribute("title", title); experiment.setAttribute("category", this.getDataSourceName()); // check if lab already stored if (!labIdRefMap.containsKey(pi)) { LOG.info("LAB: " + pi); String labRefId=createLab(pi, affiliation, address); labIdRefMap.put(pi, labRefId); } experiment.setReference("lab", labIdRefMap.get(pi)); experiment.setReference("dataSet", dataSetRef); store(experiment); return experiment.getIdentifier(); } /** * create a lab * @param pi * @param affiliation * @param address */ private String createLab(String pi, String affiliation, String address) throws ObjectStoreException { Item lab = createItem("Lab"); lab.setAttribute("name", pi); lab.setAttribute("affiliation", affiliation); lab.setAttribute("address", address); store(lab); return lab.getIdentifier(); } /** * create a sample * @param experiment bar Id * @param sample bar Id * @param name * @param alias * @param description * @param control obsolete * @param replication obsolete * @param file * @param type * */ private String createSample (String experimentBarId, Integer sampleBarId, String name, String alias, String description, String control, String replication, String file, String type) throws ObjectStoreException { Item sample = createItem("Sample"); sample.setAttribute("barId", sampleBarId.toString()); sample.setAttribute("name", name); sample.setAttribute("alias", alias); if (description != null) { sample.setAttribute("description", description); } sample.setAttribute("control", control); sample.setAttribute("replication", replication); sample.setAttribute("file", file); sample.setAttribute("type", type); sample.setReference("experiment", experimentIdRefMap.get(experimentBarId)); Integer sampleObjId = store(sample); sampleMap.put(sampleBarId, sampleObjId); return sample.getIdentifier(); } /** * set the references between samples (all) and their respective replicates * and between samples (treatments) and their controls * @param connection */ private void setSampleRepRefs(Connection connection) throws ObjectStoreException { // replicates for(Entry<String, Set<Integer>> group: replicatesMap.entrySet()) { String thisRep = group.getKey(); ReferenceList collection = new ReferenceList(); collection.setName("replicates"); for (Integer sample: group.getValue()){ String sampleRef = sampleIdRefMap.get(sample); collection.addRefId(sampleRef); } // storing the reference for all (also to self!) if (!collection.equals(null)) { for (Integer sample: group.getValue()){ Integer sampleOId = sampleMap.get(sample); store(collection, sampleOId); } } } // treatment controls for(Entry<Integer, Set<Integer>> controls: treatmentControlsMap.entrySet()) { Integer treatment = controls.getKey(); if (treatment == null) { continue; } ReferenceList collection = new ReferenceList(); collection.setName("controls"); if (controls.getValue() != null) { for (Integer sample: controls.getValue()){ String sampleRef = sampleIdRefMap.get(sample); collection.addRefId(sampleRef); } } // storing the references if (!collection.equals(null)) { Integer sampleOId = sampleMap.get(treatment); store(collection, sampleOId); } } } /** * create sample properties * @param sample bar id * @param stock * @param geneticVar * @param tissue * @param diseased * @param growthCondition * @param growthStage * @param timePoint */ private String createSampleProperties(Integer sampleBarId, String stock, String geneticVar, String tissue, String diseased, String growthCondition, String growthStage, String timePoint) throws ObjectStoreException { // create list of values List<String> PROPERTY_VALUES = Arrays.asList( stock, geneticVar, tissue, diseased, growthCondition, growthStage, timePoint); // needed to compensate for missing experiments for some samples String sampleIdRef = sampleIdRefMap.get(sampleBarId); if (sampleIdRef == null) { LOG.warn("SAMPLE id = " + sampleBarId + ". The experiment for this sample is missing."); return "orphaned sample"; } int i=0; for (String p: PROPERTY_TYPES){ String name = PROPERTY_TYPES.get(i); String value = PROPERTY_VALUES.get(i); if (value == null || value.isEmpty()) { LOG.debug("SAMPLE " + sampleBarId + ": empty prop value for " + p); i++; continue; } String propertyRefId = propertyIdRefMap.get(name.concat(value)); if (propertyRefId == null) { // prop not yet seen: store it Item property = createItem("SampleProperty"); property.setAttribute("name", name); property.setAttribute("value", value); Integer propObjId = store(property); propertyRefId=property.getIdentifier(); propertyIdRefMap.put(name.concat(value), propertyRefId); propertyIdMap.put(name.concat(value), propObjId); Set<String> others = new HashSet<String>(); others.add(sampleIdRef); propertySampleMap.put(propObjId, others); LOG.debug("SAMPLE " + sampleBarId + ": created property " + p + " - "+ value); } else { // setting ref if prop already in.. Integer propObjId=propertyIdMap.get(name.concat(value)); LOG.debug("SAMPLE " + sampleBarId + ": adding property " + p + " - "+ value + " to collection"); Set<String> others = propertySampleMap.get(propObjId); others.add(sampleIdRef); propertySampleMap.put(propObjId, others); } i++; } return sampleIdRef; } /** * set the references between sample properties and samples * @param connection */ private void setSamplePropertiesRefs(Connection connection) throws ObjectStoreException { for(Entry<Integer, Set<String>> prop: propertySampleMap.entrySet()) { Integer thisProp = prop.getKey(); ReferenceList collection = new ReferenceList(); collection.setName("samples"); for (String sampleRef: prop.getValue()){ collection.addRefId(sampleRef); } if (!collection.equals(null)) { store(collection, thisProp); } } } /** * create sample data (expressions) * @param sample bar id * @param probe * @param signal * @param call * @param pValue */ private String createSampleData(Integer sampleBarId, String probeSet, Double signal, String call, Double pValue) throws ObjectStoreException { // needed to compensate for missing experiments for some samples String sampleIdRef = sampleIdRefMap.get(sampleBarId); if (sampleIdRef == null) { // this is already logged in createSampleProperties return "orphaned sample"; } // get the map of averages (replicates) Map<String, Double> avgMap = new HashMap<String, Double>(); if (averagesMap.containsKey(sampleBarId)) { avgMap=averagesMap.get(sampleBarId); } // check this is a treatment and get the avg map for the control too // NOTES: - rounding for ratio is done after the calculation // - there are 0 averages in the controls (-> ratio null) Map<String, Double> controlAvgMap = new HashMap<String, Double>(); String ratio = null; String avgControl = null; // String avgSignal = round(avgMap.get(probeSet)," String avgSignal = getFormat(avgMap.get(probeSet)," if (treatmentControlsMap.containsKey(sampleBarId)) { controlAvgMap=averagesMap. get(treatmentControlsMap.get(sampleBarId).toArray()[0]); Double realControl = controlAvgMap.get(probeSet); ratio = getRatio(avgMap.get(probeSet), realControl, " avgControl = getFormat(realControl, " } String probeRefId = probeIdRefMap.get(probeSet); if (probeRefId == null) { Item probe = createItem("Probe"); probe.setAttribute("name", probeSet); store(probe); probeRefId=probe.getIdentifier(); probeIdRefMap.put(probeSet, probeRefId); } Item sampleData = createItem("Expression"); sampleData.setAttribute("signal", signal.toString()); if (call!=null && !call.isEmpty()) { sampleData.setAttribute("call", call); } sampleData.setAttribute("pValue", pValue.toString()); sampleData.setAttribute("averageSignal", avgSignal); // if this is a treatment, do the ratio between this value and the one // from the avg of the control sample for the same probe if (ratio != null) { sampleData.setAttribute("averageRatio", ratio); sampleData.setAttribute("averageControl", avgControl); } sampleData.setReference("sample", sampleIdRef); sampleData.setReference("probe", probeRefId); store(sampleData); return sampleData.getIdentifier(); } /** * Returns a string representation of the Double rounded and formatted * according to format * If signal and/or control is not a number, returns null * * @param signal Double * @param control Double * @param format String */ private String getRatio(Double signal, Double control, String format) { if (control == null) { return "NaN"; } if (signal.isNaN()){ return "NaN"; } DecimalFormat df = new DecimalFormat(format); Double ratio = signal/control; if (ratio.isInfinite() || ratio.isNaN()) { return "NaN"; } return Double.valueOf(df.format(ratio)).toString(); } /** * Returns a string representation of the Double rounded and formatted * according to format * If Double is not a number, returns null * * @param signal Double * @param format String */ private String getFormat(Double signal, String format) { // LOG.info("GG " + signal); if (signal == null) { return "NaN"; } if (signal.isNaN()){ return "NaN"; } DecimalFormat df = new DecimalFormat(format); return Double.valueOf(df.format(signal)).toString(); } /** * Return the expressions from the bar-expressions table * This is a protected method so that it can be overridden for testing. * @param connection the bar database connection * @throws SQLException if there is a problem while querying * @return the expressions */ protected ResultSet getExperiments(Connection connection) throws SQLException { String query = "SELECT p.proj_id, p.proj_res_area, p.proj_pi, " + " p.proj_pi_inst, p.proj_pi_addr " + " FROM proj_info p;"; // + " FROM proj_info p WHERE proj_id not Like 'G%';"; return doQuery(connection, query, "getExperiments"); } /** * Return the samples from the bar-expressions table * This is a protected method so that it can be overridden for testing. * @param connection the bar database connection * @throws SQLException if there is a problem while querying * @return the samples */ protected ResultSet getSamples(Connection connection) throws SQLException { String query = "SELECT p.proj_id, sb.sample_id, sb.sample_bio_name, sb.sample_alias, " + "sg.sample_desc, sg.sample_ctrl, sg.sample_repl, sg.sample_file_name " + "FROM sample_biosource_info sb, sample_general_info sg, proj_info p " + "WHERE sb.sample_id=sg.sample_id " + "AND p.proj_id=sb.proj_id;"; // + "AND p.proj_id=sb.proj_id AND sb.sample_id <245;"; return doQuery(connection, query, "getSamples"); } /** * Return the samples properties from the bar-expressions table * This is a protected method so that it can be overridden for testing. * @param connection the bar database connection * @param source depending on the expression database the field growth condition * is present or absent. * @throws SQLException if there is a problem while querying * @return the samples properties */ protected ResultSet getSampleProperties(Connection connection, String source) throws SQLException { String query = null; if (source.equalsIgnoreCase("atgenexp")) { query = "SELECT sample_id, sample_stock_code, sample_genetic_var, " + "sample_tissue, sample_diseased, 'NA', " + "sample_growth_stage,sample_time_point " + "FROM sample_biosource_info;"; return doQuery(connection, query, "getSampleProperties"); } query = "SELECT sample_id, sample_stock_code, sample_genetic_var, " + "sample_tissue, sample_diseased, sample_growth_condition, " + "sample_growth_stage,sample_time_point " + "FROM sample_biosource_info;"; return doQuery(connection, query, "getSampleProperties"); } /** * Return the expressions from the bar-expressions table * This is a protected method so that it can be overridden for testing. * @param connection the bar database connection * @throws SQLException if there is a problem while querying * @return the expressions */ protected ResultSet getSampleData(Connection connection) throws SQLException { String query = "SELECT sample_id, data_probeset_id, data_signal, " + "data_call, data_p_val " + "FROM sample_data " + "WHERE data_probeset_id is not null;"; // added for pathogen // + "FROM sample_data limit 1000;"; return doQuery(connection, query, "getSampleData"); } /** * Return the average expressions from the bar-expressions table given a group * samples. * This is a protected method so that it can be overridden for testing. * @param connection the bar database connection * @param inClause String the in clause string for the query * @throws SQLException if there is a problem while querying * @return the expressions */ protected ResultSet getAverages(Connection connection, String inClause) throws SQLException { String query = "SELECT data_probeset_id, avg(data_signal) " + "FROM sample_data " + "WHERE sample_id in (" + inClause + ") " + "GROUP BY data_probeset_id;"; // + "FROM sample_data limit 1000;"; return doQuery(connection, query, "getAverages"); } /** * Default implementation that makes a data set title based on the data source name. * {@inheritDoc} */ @Override public String getDataSetTitle(int taxonId) { return getDataSourceName() + " expressions data set"; } /** * method to wrap the execution of a query with log info * @param connection * @param query * @param comment for not logging * @return the result set * @throws SQLException */ private ResultSet doQuery(Connection connection, String query, String comment) throws SQLException { // see ModEncodeMetaDataProcessor LOG.info("executing: " + query); long bT = System.currentTimeMillis(); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); LOG.info("QUERY TIME " + comment + ": " + (System.currentTimeMillis() - bT) + " ms"); return res; } }
package com.barbarysoftware.watchservice; import java.io.Closeable; import java.io.IOException; import java.util.concurrent.TimeUnit; public abstract class WatchService implements Closeable { protected WatchService() { } /** * Closes this watch service. * <p/> * <p> If a thread is currently blocked in the {@link #take take} or {@link * #poll(long,TimeUnit) poll} methods waiting for a key to be queued then * it immediately receives a {@link ClosedWatchServiceException}. Any * valid keys associated with this watch service are {@link WatchKey#isValid * invalidated}. * <p/> * <p> After a watch service is closed, any further attempt to invoke * operations upon it will throw {@link ClosedWatchServiceException}. * If this watch service is already closed then invoking this method * has no effect. * * @throws IOException if an I/O error occurs */ @Override public abstract void close() throws IOException; /** * Retrieves and removes the next watch key, or {@code null} if none are * present. * * @return the next watch key, or {@code null} * @throws ClosedWatchServiceException if this watch service is closed */ public abstract WatchKey poll(); /** * Retrieves and removes the next watch key, waiting if necessary up to the * specified wait time if none are yet present. * * @param timeout how to wait before giving up, in units of unit * @param unit a {@code TimeUnit} determining how to interpret the timeout * parameter * @return the next watch key, or {@code null} * @throws ClosedWatchServiceException if this watch service is closed, or it is closed while waiting * for the next key * @throws InterruptedException if interrupted while waiting */ public abstract WatchKey poll(long timeout, TimeUnit unit) throws InterruptedException; /** * Retrieves and removes next watch key, waiting if none are yet present. * * @return the next watch key * @throws ClosedWatchServiceException if this watch service is closed, or it is closed while waiting * for the next key * @throws InterruptedException if interrupted while waiting */ public abstract WatchKey take() throws InterruptedException; public static WatchService newWatchService() { final String[] osVersion = System.getProperty("os.version").split("\\."); final int majorVersion = Integer.parseInt(osVersion[0]); final int minorVersion = Integer.parseInt(osVersion[1]); if ((majorVersion < 11) & (minorVersion < 5)) { throw new UnsupportedOperationException("barbarywatchservice not " + "supported on Mac OS X prior to Leopard (10.5)"); } else { // for Mac OS X Leopard (10.5) and upwards return new MacOSXListeningWatchService(); } } }
package helper; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Enumeration; import java.util.Properties; import javax.net.ssl.HttpsURLConnection; public class Connector { private static URLConnection urlConn = null; private URL url = null; private static final int HTTP = 0; private static final int HTTPS = 1; private int protocol = -1; private int httpStatus = -1; private String redirectLocation = null; private Properties reqProp = new Properties(); private InputStream inStream = null; private Connector() { } public String getRedirectLocation() { return this.redirectLocation; } /** * Initiate URLConnection as https connection if protocol in URL is https * * @param url * @return HttpURLConnection */ private HttpURLConnection getHttpConn(URL url) { HttpURLConnection httpConn = null; try { httpConn = (HttpURLConnection) url.openConnection(); addProperties(httpConn); httpStatus = httpConn.getResponseCode(); this.redirectLocation = httpConn.getHeaderField("Location"); this.inStream = httpConn.getInputStream(); play.Logger.debug("http Status Code: " + httpStatus + ", Location Header: " + redirectLocation + "\n Connection : " + httpConn.toString() + "\n ContentType der Response: " + httpConn.getContentType() + "\n Accept-Header " + httpConn.getHeaderField("Accept")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return httpConn; } /** * Initiate URLConnection as https connection if protocol in URL is https * * @param url * @return HttpsURLConnection */ private HttpsURLConnection getHttpsConn(URL url) { HttpsURLConnection httpsConn = null; try { httpsConn = (HttpsURLConnection) url.openConnection(); addProperties(httpsConn); this.httpStatus = httpsConn.getResponseCode(); this.redirectLocation = httpsConn.getHeaderField("Location"); this.inStream = httpsConn.getInputStream(); play.Logger.debug("http Status Code: " + httpStatus + ", Location Header: " + redirectLocation + "\n Connection : " + httpsConn.toString() + "\n ContentType der Response: " + httpsConn.getContentType() + "\n Accept-Header " + httpsConn.getHeaderField("Accept")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return httpsConn; } private void addProperties(URLConnection connect) { Enumeration<Object> propEnum = reqProp.keys(); while (propEnum.hasMoreElements()) { String key = propEnum.nextElement().toString(); connect.setRequestProperty((String) key, (String) reqProp.get(key)); } }; /** * Generates and returns URL Instance from String * * @param urlString * @return */ private static URL createUrl(String urlString) { URL url = null; try { url = new URL(urlString); } catch (MalformedURLException e) { play.Logger.warn("cannot create URL Instance from " + urlString); } return url; } /** * Checks if http Status determines redirect and if redirect location is * associated with protocol change from http to https. If both is true, * initiate new HttpsURLConnection * */ private void performProtocolChange() { if ((299 < getStatusCode() && getStatusCode() < 400) && getRedirectLocation().startsWith("https")) { play.Logger.debug("found https-protocol and redirect-location: " + this.getRedirectLocation()); urlConn = this.getHttpsConn(createUrl(getRedirectLocation())); } } public URLConnection getConnection() { return urlConn; } public int getStatusCode() { return httpStatus; } public InputStream getInputStream() { return inStream; } public void setConnectorProperty(String key, String value) { reqProp.put(key, value); } public void connect() { switch (protocol) { case 0: urlConn = getHttpConn(url); break; case 1: urlConn = getHttpsConn(url); break; } performProtocolChange(); } public static class Factory { private static Connector conn = new Connector(); /** * Provide Connector Instance that automatically returns the appropriate * URLConnector. This is either HttpURLConnector or HttpsURLConnector. * * @param url * @return */ public static Connector getInstance(URL url) { // first free all static variables conn.protocol = -1; conn.httpStatus = -1; conn.redirectLocation = null; conn.reqProp = new Properties(); conn.inStream = null; if (url.getProtocol().equals("http")) { conn.protocol = HTTP; } else { conn.protocol = HTTPS; } conn.url = url; return conn; } } }
package it.unitn.disi.smatch.loaders; import it.unitn.disi.smatch.data.Context; import it.unitn.disi.smatch.data.IContext; import org.apache.log4j.Level; import org.apache.log4j.Logger; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; /** * Loads context from a tab-separated file. * Expects a single-rooted hierarchy, otherwise adds an artificial "Top" node. * * @author Mikalai Yatskevich mikalai.yatskevich@comlab.ox.ac.uk * @author Aliaksandr Autayeu avtaev@gmail.com * @author Juan Pane pane@disi.unitn.it */ public class TABLoader implements ILoader { private static final Logger log = Logger.getLogger(TABLoader.class); //TODO the loader could be made static, but this requires a change in the ILoader interface public IContext loadContext(String fileName) { IContext result = null; try { BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "UTF-8")); try { result = process(input); } finally { input.close(); } } catch (Exception e) { if (log.isEnabledFor(Level.ERROR)) { log.error("Exception: " + e.getMessage(), e); } } return result; } /** * Processes the file loading the content. This content is supposed to be * formatted in tab indented format. * * @param input Reader for the input file * @return the loaded IContext * @throws IOException IOException */ private IContext process(BufferedReader input) throws IOException { IContext result = new Context(); ArrayList<String> rootPath = new ArrayList<String>(); //loads the root node String fatherConceptId = result.newNode(input.readLine(), null); rootPath.add(fatherConceptId); int artificialLevel = 0;//flags that we added Top and need an increment in level String fatherId; int old_depth = 0; String line; while ((line = input.readLine()) != null && !line.startsWith(" !line.equals("")) { int int_depth = numOfTabs(line); String name = line.substring(int_depth); int_depth = int_depth + artificialLevel; if (int_depth == old_depth) { fatherId = rootPath.get(old_depth - 1); String newCID = result.newNode(name, fatherId); setArrayNodeID(int_depth, rootPath, newCID); } else if (int_depth > old_depth) { fatherId = rootPath.get(old_depth); String newCID = result.newNode(name, fatherId); setArrayNodeID(int_depth, rootPath, newCID); old_depth = int_depth; } else if (int_depth < old_depth) { if (0 == int_depth) {//looks like we got multiple roots in the input artificialLevel = 1; fatherId = result.newNode("Top", null); rootPath.add(0, fatherId); int_depth = 1; } fatherId = rootPath.get(int_depth - 1); String newCID = result.newNode(name, fatherId); setArrayNodeID(int_depth, rootPath, newCID); old_depth = int_depth; } } return result; } /** * Counts the number of tabs in the line. * * @param line the string of the each line of file * @return the number of tabs at the beginning of the line */ private int numOfTabs(String line) { int close_counter = 0; while (close_counter < line.length() && '\t' == line.charAt(close_counter)) { close_counter++; } return close_counter; } /** * Sets the nodeID at a given position of the array. * Changes the current value if there is one, if there is no value, add a new one. * * @param index position to be filled * @param array array to be modified * @param nodeID value to be set */ private static void setArrayNodeID(int index, ArrayList<String> array, String nodeID){ if(index < array.size() ){ array.set(index, nodeID); } else { array.add(index, nodeID); } } }
package com.sequenceiq.cloudbreak.cloud.aws; import static com.sequenceiq.cloudbreak.cloud.aws.TestConstants.LATEST_AWS_CLOUD_FORMATION_TEMPLATE_PATH; import static java.util.Collections.emptyList; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonList; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.core.IsNot.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.base.InstanceGroupType; import com.sequenceiq.cloudbreak.cloud.aws.CloudFormationTemplateBuilder.ModelContext; import com.sequenceiq.cloudbreak.cloud.context.AuthenticatedContext; import com.sequenceiq.cloudbreak.cloud.context.CloudContext; import com.sequenceiq.cloudbreak.cloud.model.AvailabilityZone; import com.sequenceiq.cloudbreak.cloud.model.CloudCredential; import com.sequenceiq.cloudbreak.cloud.model.CloudInstance; import com.sequenceiq.cloudbreak.cloud.model.CloudStack; import com.sequenceiq.cloudbreak.cloud.model.Group; import com.sequenceiq.cloudbreak.cloud.model.Image; import com.sequenceiq.cloudbreak.cloud.model.InstanceAuthentication; import com.sequenceiq.cloudbreak.cloud.model.InstanceStatus; import com.sequenceiq.cloudbreak.cloud.model.InstanceTemplate; import com.sequenceiq.cloudbreak.cloud.model.Location; import com.sequenceiq.cloudbreak.cloud.model.Network; import com.sequenceiq.cloudbreak.cloud.model.PortDefinition; import com.sequenceiq.cloudbreak.cloud.model.Region; import com.sequenceiq.cloudbreak.cloud.model.Security; import com.sequenceiq.cloudbreak.cloud.model.SecurityRule; import com.sequenceiq.cloudbreak.cloud.model.Subnet; import com.sequenceiq.cloudbreak.cloud.model.Volume; import com.sequenceiq.cloudbreak.common.service.DefaultCostTaggingService; import com.sequenceiq.cloudbreak.common.type.CloudbreakResourceType; import com.sequenceiq.cloudbreak.util.FreeMarkerTemplateUtils; import com.sequenceiq.cloudbreak.util.JsonUtil; import freemarker.template.Configuration; @RunWith(Parameterized.class) public class CloudFormationTemplateBuilderTest { private static final String USER_ID = "horton@hortonworks.com"; private static final Long WORKSPACE_ID = 1L; private static final String CIDR = "10.0.0.0/16"; private static final int ROOT_VOLUME_SIZE = 17; @Mock private DefaultCostTaggingService defaultCostTaggingService; @Mock private FreeMarkerTemplateUtils freeMarkerTemplateUtils; @InjectMocks private final CloudFormationTemplateBuilder cloudFormationTemplateBuilder = new CloudFormationTemplateBuilder(); private CloudStack cloudStack; private String name; private ModelContext modelContext; private String awsCloudFormationTemplate; private AuthenticatedContext authenticatedContext; private String existingSubnetCidr; private final String templatePath; private final Map<String, String> defaultTags = new HashMap<>(); private Image image; private InstanceAuthentication instanceAuthentication; private CloudInstance instance; public CloudFormationTemplateBuilderTest(String templatePath) { this.templatePath = templatePath; } @Parameters(name = "{0}") public static Iterable<?> getTemplatesPath() { List<String> templates = Lists.newArrayList(LATEST_AWS_CLOUD_FORMATION_TEMPLATE_PATH); File[] templateFiles = new File(CloudFormationTemplateBuilderTest.class.getClassLoader().getResource("templates").getPath()).listFiles(); List<String> olderTemplates = Arrays.stream(templateFiles).map(file -> { String[] path = file.getPath().split("/"); return "templates/" + path[path.length - 1]; }).collect(Collectors.toList()); templates.addAll(olderTemplates); return templates; } @Before public void setUp() throws Exception { initMocks(this); FreeMarkerConfigurationFactoryBean factoryBean = new FreeMarkerConfigurationFactoryBean(); factoryBean.setPreferFileSystemAccess(false); factoryBean.setTemplateLoaderPath("classpath:/"); factoryBean.afterPropertiesSet(); Configuration configuration = factoryBean.getObject(); ReflectionTestUtils.setField(cloudFormationTemplateBuilder, "freemarkerConfiguration", configuration); when(freeMarkerTemplateUtils.processTemplateIntoString(any(), any())).thenCallRealMethod(); awsCloudFormationTemplate = configuration.getTemplate(templatePath, "UTF-8").toString(); authenticatedContext = authenticatedContext(); existingSubnetCidr = "testSubnet"; name = "master"; List<Volume> volumes = Arrays.asList(new Volume("/hadoop/fs1", "HDD", 1), new Volume("/hadoop/fs2", "HDD", 1)); InstanceTemplate instanceTemplate = new InstanceTemplate("m1.medium", name, 0L, volumes, InstanceStatus.CREATE_REQUESTED, new HashMap<>(), 0L, "cb-centos66-amb200-2015-05-25"); instanceAuthentication = new InstanceAuthentication("sshkey", "", "cloudbreak"); instance = new CloudInstance("SOME_ID", instanceTemplate, instanceAuthentication); Security security = getDefaultCloudStackSecurity(); Map<InstanceGroupType, String> userData = ImmutableMap.of( InstanceGroupType.CORE, "CORE", InstanceGroupType.GATEWAY, "GATEWAY" ); image = new Image("cb-centos66-amb200-2015-05-25", userData, "redhat6", "redhat6", "", "default", "default-id", new HashMap<>()); List<Group> groups = List.of(createDefaultGroup(InstanceGroupType.CORE, ROOT_VOLUME_SIZE, security), createDefaultGroup(InstanceGroupType.GATEWAY, ROOT_VOLUME_SIZE, security)); defaultTags.put(CloudbreakResourceType.DISK.templateVariable(), CloudbreakResourceType.DISK.key()); defaultTags.put(CloudbreakResourceType.INSTANCE.templateVariable(), CloudbreakResourceType.INSTANCE.key()); defaultTags.put(CloudbreakResourceType.IP.templateVariable(), CloudbreakResourceType.IP.key()); defaultTags.put(CloudbreakResourceType.NETWORK.templateVariable(), CloudbreakResourceType.NETWORK.key()); defaultTags.put(CloudbreakResourceType.SECURITY.templateVariable(), CloudbreakResourceType.SECURITY.key()); defaultTags.put(CloudbreakResourceType.STORAGE.templateVariable(), CloudbreakResourceType.STORAGE.key()); defaultTags.put(CloudbreakResourceType.TEMPLATE.templateVariable(), CloudbreakResourceType.TEMPLATE.key()); cloudStack = createDefaultCloudStack(groups, getDefaultCloudStackParameters(), getDefaultCloudStackTags()); } @Test public void buildTestInstanceGroupsAndRootVolumeSize() { //WHEN modelContext = new ModelContext() .withAuthenticatedContext(authenticatedContext) .withStack(cloudStack) .withExistingVpc(true) .withExistingIGW(true) .withExistingSubnetCidr(singletonList(existingSubnetCidr)) .mapPublicIpOnLaunch(true) .withEnableInstanceProfile(true) .withInstanceProfileAvailable(true) .withTemplate(awsCloudFormationTemplate); when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); String templateString = cloudFormationTemplateBuilder.build(modelContext); //THEN Assert.assertTrue("Ivalid JSON: " + templateString, JsonUtil.isValid(templateString)); assertThat(templateString, containsString("AmbariNodes" + name)); assertThat(templateString, containsString("AmbariNodeLaunchConfig" + name)); assertThat(templateString, containsString("ClusterNodeSecurityGroup" + name)); assertThat(templateString, not(containsString("testtagkey"))); assertThat(templateString, not(containsString("testtagvalue"))); assertThat(templateString, containsString(Integer.toString(ROOT_VOLUME_SIZE))); } @Test public void buildTestInstanceGroupsWhenRootVolumeSizeIsSuperLarge() throws IOException { //GIVEN Integer rootVolumeSize = Integer.MAX_VALUE; Security security = getDefaultCloudStackSecurity(); List<Group> groups = List.of(createDefaultGroup(InstanceGroupType.CORE, rootVolumeSize, security), createDefaultGroup(InstanceGroupType.GATEWAY, rootVolumeSize, security)); CloudStack cloudStack = createDefaultCloudStack(groups, getDefaultCloudStackParameters(), getDefaultCloudStackTags()); //WHEN modelContext = new ModelContext() .withAuthenticatedContext(authenticatedContext) .withStack(cloudStack) .withExistingVpc(true) .withExistingIGW(true) .withExistingSubnetCidr(singletonList(existingSubnetCidr)) .mapPublicIpOnLaunch(true) .withEnableInstanceProfile(true) .withInstanceProfileAvailable(true) .withTemplate(awsCloudFormationTemplate); when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); String templateString = cloudFormationTemplateBuilder.build(modelContext); //THEN Assert.assertTrue("Ivalid JSON: " + templateString, JsonUtil.isValid(templateString)); assertThat(templateString, containsString(Integer.toString(rootVolumeSize))); JsonNode firstBlockDeviceMapping = getJsonNode(JsonUtil.readTree(templateString), "BlockDeviceMappings").get(0); String volumeSize = getJsonNode(firstBlockDeviceMapping, "VolumeSize").textValue(); assertEquals(Integer.valueOf(volumeSize), rootVolumeSize); } @Test public void buildTestInstanceGroupsWhenRootVolumeSizeIsSuperSmall() throws IOException { //GIVEN Integer rootVolumeSize = Integer.MIN_VALUE; Security security = getDefaultCloudStackSecurity(); List<Group> groups = List.of(createDefaultGroup(InstanceGroupType.CORE, rootVolumeSize, security), createDefaultGroup(InstanceGroupType.GATEWAY, rootVolumeSize, security)); CloudStack cloudStack = createDefaultCloudStack(groups, getDefaultCloudStackParameters(), getDefaultCloudStackTags()); //WHEN modelContext = new ModelContext() .withAuthenticatedContext(authenticatedContext) .withStack(cloudStack) .withExistingVpc(true) .withExistingIGW(true) .withExistingSubnetCidr(singletonList(existingSubnetCidr)) .mapPublicIpOnLaunch(true) .withEnableInstanceProfile(true) .withInstanceProfileAvailable(true) .withTemplate(awsCloudFormationTemplate); when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); String templateString = cloudFormationTemplateBuilder.build(modelContext); //THEN Assert.assertTrue("Ivalid JSON: " + templateString, JsonUtil.isValid(templateString)); assertThat(templateString, containsString(Integer.toString(rootVolumeSize))); JsonNode firstBlockDeviceMapping = getJsonNode(JsonUtil.readTree(templateString), "BlockDeviceMappings").get(0); String volumeSize = getJsonNode(firstBlockDeviceMapping, "VolumeSize").textValue(); assertEquals(Integer.valueOf(volumeSize), rootVolumeSize); } @Test public void buildTestWithVPCAndIGWAndPublicIpOnLaunchAndInstanceProfileAndRole() { //WHEN modelContext = new ModelContext() .withAuthenticatedContext(authenticatedContext) .withStack(cloudStack) .withExistingVpc(true) .withExistingIGW(true) .withExistingSubnetCidr(singletonList(existingSubnetCidr)) .mapPublicIpOnLaunch(true) .withEnableInstanceProfile(true) .withInstanceProfileAvailable(true) .withTemplate(awsCloudFormationTemplate); when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); String templateString = cloudFormationTemplateBuilder.build(modelContext); //THEN Assert.assertTrue("Ivalid JSON: " + templateString, JsonUtil.isValid(templateString)); assertThat(templateString, containsString("InstanceProfile")); assertThat(templateString, containsString("VPCId")); assertThat(templateString, not(containsString("SubnetCIDR"))); assertThat(templateString, containsString("SubnetId")); assertThat(templateString, not(containsString("SubnetConfig"))); assertThat(templateString, not(containsString("\"AttachGateway\""))); assertThat(templateString, not(containsString("\"InternetGateway\""))); assertThat(templateString, containsString("AvailabilitySet")); assertThat(templateString, containsString("EIP")); } @Test public void buildTestWithVPCAndIGWAndPublicIpOnLaunchAndRoleWithoutInstanceProfile() { //WHEN modelContext = new ModelContext() .withAuthenticatedContext(authenticatedContext) .withStack(cloudStack) .withExistingVpc(true) .withExistingIGW(true) .withExistingSubnetCidr(singletonList(existingSubnetCidr)) .mapPublicIpOnLaunch(true) .withEnableInstanceProfile(false) .withInstanceProfileAvailable(true) .withTemplate(awsCloudFormationTemplate); when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); String templateString = cloudFormationTemplateBuilder.build(modelContext); //THEN Assert.assertTrue("Ivalid JSON: " + templateString, JsonUtil.isValid(templateString)); assertThat(templateString, containsString("InstanceProfile")); assertThat(templateString, containsString("VPCId")); assertThat(templateString, not(containsString("SubnetCIDR"))); assertThat(templateString, containsString("SubnetId")); assertThat(templateString, not(containsString("SubnetConfig"))); assertThat(templateString, not(containsString("\"AttachGateway\""))); assertThat(templateString, not(containsString("\"InternetGateway\""))); assertThat(templateString, containsString("AvailabilitySet")); assertThat(templateString, containsString("EIP")); } @Test public void buildTestWithVPCAndIGWAndPublicIpOnLaunchAndInstanceProfileWithoutRole() { //WHEN modelContext = new ModelContext() .withAuthenticatedContext(authenticatedContext) .withStack(cloudStack) .withExistingVpc(true) .withExistingIGW(true) .withExistingSubnetCidr(singletonList(existingSubnetCidr)) .mapPublicIpOnLaunch(true) .withEnableInstanceProfile(true) .withInstanceProfileAvailable(false) .withTemplate(awsCloudFormationTemplate); when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); String templateString = cloudFormationTemplateBuilder.build(modelContext); //THEN Assert.assertTrue("Ivalid JSON: " + templateString, JsonUtil.isValid(templateString)); assertThat(templateString, containsString("InstanceProfile")); assertThat(templateString, containsString("VPCId")); assertThat(templateString, not(containsString("SubnetCIDR"))); assertThat(templateString, containsString("SubnetId")); assertThat(templateString, not(containsString("SubnetConfig"))); assertThat(templateString, not(containsString("\"AttachGateway\""))); assertThat(templateString, not(containsString("\"InternetGateway\""))); assertThat(templateString, containsString("AvailabilitySet")); assertThat(templateString, containsString("EIP")); } @Test public void buildTestWithVPCAndIGWAndPublicIpOnLaunchWithoutInstanceProfileAndRole() { //WHEN modelContext = new ModelContext() .withAuthenticatedContext(authenticatedContext) .withStack(cloudStack) .withExistingVpc(true) .withExistingIGW(true) .withExistingSubnetCidr(singletonList(existingSubnetCidr)) .mapPublicIpOnLaunch(true) .withEnableInstanceProfile(false) .withInstanceProfileAvailable(false) .withTemplate(awsCloudFormationTemplate); when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); String templateString = cloudFormationTemplateBuilder.build(modelContext); //THEN Assert.assertTrue("Ivalid JSON: " + templateString, JsonUtil.isValid(templateString)); assertThat(templateString, not(containsString("InstanceProfile"))); assertThat(templateString, containsString("VPCId")); assertThat(templateString, not(containsString("SubnetCIDR"))); assertThat(templateString, containsString("SubnetId")); assertThat(templateString, not(containsString("SubnetConfig"))); assertThat(templateString, not(containsString("\"AttachGateway\""))); assertThat(templateString, not(containsString("\"InternetGateway\""))); assertThat(templateString, containsString("AvailabilitySet")); assertThat(templateString, containsString("EIP")); } @Test public void buildTestWithVPCAndIGWAndInstanceProfileAndRoleWithoutPublicIpOnLaunch() { //WHEN modelContext = new ModelContext() .withAuthenticatedContext(authenticatedContext) .withStack(cloudStack) .withExistingVpc(true) .withExistingIGW(true) .withExistingSubnetCidr(singletonList(existingSubnetCidr)) .mapPublicIpOnLaunch(false) .withEnableInstanceProfile(true) .withInstanceProfileAvailable(true) .withTemplate(awsCloudFormationTemplate); when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); String templateString = cloudFormationTemplateBuilder.build(modelContext); //THEN Assert.assertTrue("Ivalid JSON: " + templateString, JsonUtil.isValid(templateString)); assertThat(templateString, containsString("InstanceProfile")); assertThat(templateString, containsString("VPCId")); assertThat(templateString, not(containsString("SubnetCIDR"))); assertThat(templateString, containsString("SubnetId")); assertThat(templateString, not(containsString("SubnetConfig"))); assertThat(templateString, not(containsString("\"AttachGateway\""))); assertThat(templateString, not(containsString("\"InternetGateway\""))); assertThat(templateString, containsString("AvailabilitySet")); assertThat(templateString, not(containsString("EIP"))); } @Test public void buildTestWithVPCAndIGWAndRoleWithoutPublicIpOnLaunchAndInstanceProfile() { //WHEN modelContext = new ModelContext() .withAuthenticatedContext(authenticatedContext) .withStack(cloudStack) .withExistingVpc(true) .withExistingIGW(true) .withExistingSubnetCidr(singletonList(existingSubnetCidr)) .mapPublicIpOnLaunch(false) .withEnableInstanceProfile(false) .withInstanceProfileAvailable(true) .withTemplate(awsCloudFormationTemplate); when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); String templateString = cloudFormationTemplateBuilder.build(modelContext); //THEN Assert.assertTrue("Ivalid JSON: " + templateString, JsonUtil.isValid(templateString)); assertThat(templateString, containsString("InstanceProfile")); assertThat(templateString, containsString("VPCId")); assertThat(templateString, not(containsString("SubnetCIDR"))); assertThat(templateString, containsString("SubnetId")); assertThat(templateString, not(containsString("SubnetConfig"))); assertThat(templateString, not(containsString("\"AttachGateway\""))); assertThat(templateString, not(containsString("\"InternetGateway\""))); assertThat(templateString, containsString("AvailabilitySet")); assertThat(templateString, not(containsString("EIP"))); } @Test public void buildTestWithVPCAndIGWAndInstanceProfileWithoutPublicIpOnLaunchAndRole() { //WHEN modelContext = new ModelContext() .withAuthenticatedContext(authenticatedContext) .withStack(cloudStack) .withExistingVpc(true) .withExistingIGW(true) .withExistingSubnetCidr(singletonList(existingSubnetCidr)) .mapPublicIpOnLaunch(false) .withEnableInstanceProfile(true) .withInstanceProfileAvailable(false) .withTemplate(awsCloudFormationTemplate); when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); String templateString = cloudFormationTemplateBuilder.build(modelContext); //THEN Assert.assertTrue("Ivalid JSON: " + templateString, JsonUtil.isValid(templateString)); assertThat(templateString, containsString("InstanceProfile")); assertThat(templateString, containsString("VPCId")); assertThat(templateString, not(containsString("SubnetCIDR"))); assertThat(templateString, containsString("SubnetId")); assertThat(templateString, not(containsString("SubnetConfig"))); assertThat(templateString, not(containsString("\"AttachGateway\""))); assertThat(templateString, not(containsString("\"InternetGateway\""))); assertThat(templateString, containsString("AvailabilitySet")); assertThat(templateString, not(containsString("EIP"))); } @Test public void buildTestWithVPCAndIGWWithoutPublicIpOnLaunchAndInstanceProfileAndRole() { //WHEN modelContext = new ModelContext() .withAuthenticatedContext(authenticatedContext) .withStack(cloudStack) .withExistingVpc(true) .withExistingIGW(true) .withExistingSubnetCidr(singletonList(existingSubnetCidr)) .mapPublicIpOnLaunch(false) .withEnableInstanceProfile(false) .withInstanceProfileAvailable(false) .withTemplate(awsCloudFormationTemplate); when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); String templateString = cloudFormationTemplateBuilder.build(modelContext); //THEN Assert.assertTrue("Ivalid JSON: " + templateString, JsonUtil.isValid(templateString)); assertThat(templateString, not(containsString("InstanceProfile"))); assertThat(templateString, containsString("VPCId")); assertThat(templateString, not(containsString("SubnetCIDR"))); assertThat(templateString, containsString("SubnetId")); assertThat(templateString, not(containsString("SubnetConfig"))); assertThat(templateString, not(containsString("\"AttachGateway\""))); assertThat(templateString, not(containsString("\"InternetGateway\""))); assertThat(templateString, containsString("AvailabilitySet")); assertThat(templateString, not(containsString("EIP"))); } @Test public void buildTestWithVPCAndInstanceProfileAndRoleWithoutIGWAndPublicIpOnLaunch() { //WHEN modelContext = new ModelContext() .withAuthenticatedContext(authenticatedContext) .withStack(cloudStack) .withExistingVpc(true) .withExistingIGW(false) .withExistingSubnetCidr(singletonList(existingSubnetCidr)) .mapPublicIpOnLaunch(false) .withEnableInstanceProfile(true) .withInstanceProfileAvailable(true) .withTemplate(awsCloudFormationTemplate); when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); String templateString = cloudFormationTemplateBuilder.build(modelContext); //THEN Assert.assertTrue("Ivalid JSON: " + templateString, JsonUtil.isValid(templateString)); assertThat(templateString, containsString("InstanceProfile")); assertThat(templateString, containsString("VPCId")); assertThat(templateString, not(containsString("SubnetCIDR"))); assertThat(templateString, containsString("SubnetId")); assertThat(templateString, not(containsString("SubnetConfig"))); assertThat(templateString, not(containsString("\"AttachGateway\""))); assertThat(templateString, not(containsString("\"InternetGateway\""))); assertThat(templateString, containsString("AvailabilitySet")); assertThat(templateString, not(containsString("EIP"))); } @Test public void buildTestWithVPCAndRoleWithoutIGWAndPublicIpOnLaunchAndInstanceProfile() { //WHEN modelContext = new ModelContext() .withAuthenticatedContext(authenticatedContext) .withStack(cloudStack) .withExistingVpc(true) .withExistingIGW(false) .withExistingSubnetCidr(singletonList(existingSubnetCidr)) .mapPublicIpOnLaunch(false) .withEnableInstanceProfile(false) .withInstanceProfileAvailable(true) .withTemplate(awsCloudFormationTemplate); when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); String templateString = cloudFormationTemplateBuilder.build(modelContext); //THEN Assert.assertTrue("Ivalid JSON: " + templateString, JsonUtil.isValid(templateString)); assertThat(templateString, containsString("InstanceProfile")); assertThat(templateString, containsString("VPCId")); assertThat(templateString, not(containsString("SubnetCIDR"))); assertThat(templateString, containsString("SubnetId")); assertThat(templateString, not(containsString("SubnetConfig"))); assertThat(templateString, not(containsString("\"AttachGateway\""))); assertThat(templateString, not(containsString("\"InternetGateway\""))); assertThat(templateString, containsString("AvailabilitySet")); assertThat(templateString, not(containsString("EIP"))); } @Test public void buildTestWithVPCAndInstanceProfileWithoutIGWAndPublicIpOnLaunchAndRole() { //WHEN modelContext = new ModelContext() .withAuthenticatedContext(authenticatedContext) .withStack(cloudStack) .withExistingVpc(true) .withExistingIGW(false) .withExistingSubnetCidr(singletonList(existingSubnetCidr)) .mapPublicIpOnLaunch(false) .withEnableInstanceProfile(true) .withInstanceProfileAvailable(false) .withTemplate(awsCloudFormationTemplate); when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); String templateString = cloudFormationTemplateBuilder.build(modelContext); //THEN Assert.assertTrue("Ivalid JSON: " + templateString, JsonUtil.isValid(templateString)); assertThat(templateString, containsString("InstanceProfile")); assertThat(templateString, containsString("VPCId")); assertThat(templateString, not(containsString("SubnetCIDR"))); assertThat(templateString, containsString("SubnetId")); assertThat(templateString, not(containsString("SubnetConfig"))); assertThat(templateString, not(containsString("\"AttachGateway\""))); assertThat(templateString, not(containsString("\"InternetGateway\""))); assertThat(templateString, containsString("AvailabilitySet")); assertThat(templateString, not(containsString("EIP"))); } @Test public void buildTestWithVPCWithoutIGWAndPublicIpOnLaunchAndInstanceProfileAndRole() { //WHEN modelContext = new ModelContext() .withAuthenticatedContext(authenticatedContext) .withStack(cloudStack) .withExistingVpc(true) .withExistingIGW(false) .withExistingSubnetCidr(singletonList(existingSubnetCidr)) .mapPublicIpOnLaunch(false) .withEnableInstanceProfile(false) .withInstanceProfileAvailable(false) .withTemplate(awsCloudFormationTemplate); when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); String templateString = cloudFormationTemplateBuilder.build(modelContext); //THEN Assert.assertTrue("Ivalid JSON: " + templateString, JsonUtil.isValid(templateString)); assertThat(templateString, not(containsString("InstanceProfile"))); assertThat(templateString, containsString("VPCId")); assertThat(templateString, not(containsString("SubnetCIDR"))); assertThat(templateString, containsString("SubnetId")); assertThat(templateString, not(containsString("SubnetConfig"))); assertThat(templateString, not(containsString("\"AttachGateway\""))); assertThat(templateString, not(containsString("\"InternetGateway\""))); assertThat(templateString, containsString("AvailabilitySet")); assertThat(templateString, not(containsString("EIP"))); } @Test public void buildTestWithInstanceProfileAndRoleWithoutVPCAndIGWAndPublicIpOnLaunch() { //WHEN modelContext = new ModelContext() .withAuthenticatedContext(authenticatedContext) .withStack(cloudStack) .withExistingVpc(false) .withExistingIGW(false) .withExistingSubnetCidr(singletonList(existingSubnetCidr)) .mapPublicIpOnLaunch(false) .withEnableInstanceProfile(true) .withInstanceProfileAvailable(true) .withTemplate(awsCloudFormationTemplate); when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); String templateString = cloudFormationTemplateBuilder.build(modelContext); //THEN Assert.assertTrue("Ivalid JSON: " + templateString, JsonUtil.isValid(templateString)); assertThat(templateString, containsString("InstanceProfile")); assertThat(templateString, not(containsString("VPCId"))); assertThat(templateString, not(containsString("SubnetCIDR"))); assertThat(templateString, containsString("SubnetId")); assertThat(templateString, containsString("SubnetConfig")); assertThat(templateString, containsString("\"AttachGateway\"")); assertThat(templateString, containsString("\"InternetGateway\"")); assertThat(templateString, containsString("AvailabilitySet")); assertThat(templateString, not(containsString("EIP"))); } @Test public void buildTestWithInstanceProfileWithoutVPCAndIGWAndPublicIpOnLaunchAndRole() { //WHEN modelContext = new ModelContext() .withAuthenticatedContext(authenticatedContext) .withStack(cloudStack) .withExistingVpc(false) .withExistingIGW(false) .withExistingSubnetCidr(singletonList(existingSubnetCidr)) .mapPublicIpOnLaunch(false) .withEnableInstanceProfile(true) .withInstanceProfileAvailable(false) .withTemplate(awsCloudFormationTemplate); when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); String templateString = cloudFormationTemplateBuilder.build(modelContext); //THEN Assert.assertTrue("Ivalid JSON: " + templateString, JsonUtil.isValid(templateString)); assertThat(templateString, containsString("InstanceProfile")); assertThat(templateString, not(containsString("VPCId"))); assertThat(templateString, not(containsString("SubnetCIDR"))); assertThat(templateString, containsString("SubnetId")); assertThat(templateString, containsString("SubnetConfig")); assertThat(templateString, containsString("\"AttachGateway\"")); assertThat(templateString, containsString("\"InternetGateway\"")); assertThat(templateString, containsString("AvailabilitySet")); assertThat(templateString, not(containsString("EIP"))); } @Test public void buildTestWithRoleWithoutVPCAndIGWAndPublicIpOnLaunchAndInstanceProfile() { //WHEN modelContext = new ModelContext() .withAuthenticatedContext(authenticatedContext) .withStack(cloudStack) .withExistingVpc(false) .withExistingIGW(false) .withExistingSubnetCidr(singletonList(existingSubnetCidr)) .mapPublicIpOnLaunch(false) .withEnableInstanceProfile(false) .withInstanceProfileAvailable(true) .withTemplate(awsCloudFormationTemplate); when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); String templateString = cloudFormationTemplateBuilder.build(modelContext); //THEN Assert.assertTrue("Ivalid JSON: " + templateString, JsonUtil.isValid(templateString)); assertThat(templateString, containsString("InstanceProfile")); assertThat(templateString, not(containsString("VPCId"))); assertThat(templateString, not(containsString("SubnetCIDR"))); assertThat(templateString, containsString("SubnetId")); assertThat(templateString, containsString("SubnetConfig")); assertThat(templateString, containsString("\"AttachGateway\"")); assertThat(templateString, containsString("\"InternetGateway\"")); assertThat(templateString, containsString("AvailabilitySet")); assertThat(templateString, not(containsString("EIP"))); } @Test public void buildTestWithoutVPCAndIGWAndPublicIpOnLaunchAndInstanceProfileAndRole() { //GIVEN when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); //WHEN modelContext = new ModelContext() .withAuthenticatedContext(authenticatedContext) .withStack(cloudStack) .withExistingVpc(false) .withExistingIGW(false) .withExistingSubnetCidr(singletonList(existingSubnetCidr)) .mapPublicIpOnLaunch(false) .withEnableInstanceProfile(false) .withInstanceProfileAvailable(false) .withTemplate(awsCloudFormationTemplate); when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); String templateString = cloudFormationTemplateBuilder.build(modelContext); //THEN Assert.assertTrue("Ivalid JSON: " + templateString, JsonUtil.isValid(templateString)); assertThat(templateString, not(containsString("InstanceProfile"))); assertThat(templateString, not(containsString("VPCId"))); assertThat(templateString, not(containsString("SubnetCIDR"))); assertThat(templateString, containsString("SubnetId")); assertThat(templateString, containsString("SubnetConfig")); assertThat(templateString, containsString("\"AttachGateway\"")); assertThat(templateString, containsString("\"InternetGateway\"")); assertThat(templateString, containsString("AvailabilitySet")); assertThat(templateString, not(containsString("EIP"))); } @Test public void buildTestWithVPCAndIGWAndSingleSG() { //GIVEN when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); List<Group> groups = new ArrayList<>(); Security security = new Security(emptyList(), singletonList("single-sg-id")); groups.add(new Group(name, InstanceGroupType.CORE, emptyList(), security, instance, instanceAuthentication, instanceAuthentication.getLoginUserName(), "publickey", ROOT_VOLUME_SIZE)); CloudStack cloudStack = new CloudStack(groups, new Network(new Subnet(CIDR)), image, emptyMap(), emptyMap(), "template", instanceAuthentication, instanceAuthentication.getLoginUserName(), "publicKey", null); //WHEN modelContext = new ModelContext() .withAuthenticatedContext(authenticatedContext) .withStack(cloudStack) .withExistingVpc(true) .withExistingIGW(true) .withExistingSubnetCidr(singletonList(existingSubnetCidr)) .withStack(cloudStack) .mapPublicIpOnLaunch(false) .withTemplate(awsCloudFormationTemplate); when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); String templateString = cloudFormationTemplateBuilder.build(modelContext); //THEN // older templates are invalids if ("templates/aws-cf-stack.ftl".equals(templatePath)) { Assert.assertTrue("Ivalid JSON: " + templateString, JsonUtil.isValid(templateString)); } assertThat(templateString, containsString("VPCId")); assertThat(templateString, containsString("\"single-sg-id\"")); } @Test public void buildTestWithVPCAndIGWAndSingleSGAndMultiGroup() { //GIVEN when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); List<Group> groups = new ArrayList<>(); Security security = new Security(emptyList(), singletonList("single-sg-id")); groups.add(new Group(name, InstanceGroupType.GATEWAY, emptyList(), security, instance, instanceAuthentication, instanceAuthentication.getLoginUserName(), "publickey", ROOT_VOLUME_SIZE)); groups.add(new Group(name, InstanceGroupType.CORE, emptyList(), security, instance, instanceAuthentication, instanceAuthentication.getLoginUserName(), "publickey", ROOT_VOLUME_SIZE)); CloudStack cloudStack = new CloudStack(groups, new Network(new Subnet(CIDR)), image, emptyMap(), emptyMap(), "template", instanceAuthentication, instanceAuthentication.getLoginUserName(), "publicKey", null); //WHEN modelContext = new ModelContext() .withAuthenticatedContext(authenticatedContext) .withStack(cloudStack) .withExistingVpc(true) .withExistingIGW(true) .withExistingSubnetCidr(singletonList(existingSubnetCidr)) .withStack(cloudStack) .mapPublicIpOnLaunch(false) .withTemplate(awsCloudFormationTemplate); when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); String templateString = cloudFormationTemplateBuilder.build(modelContext); //THEN // older templates are invalids if ("templates/aws-cf-stack.ftl".equals(templatePath)) { Assert.assertTrue("Ivalid JSON: " + templateString, JsonUtil.isValid(templateString)); } assertThat(templateString, containsString("VPCId")); assertThat(templateString, containsString("\"single-sg-id\"")); } @Test public void buildTestWithVPCAndIGWAndMultiSG() { //GIVEN when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); List<Group> groups = new ArrayList<>(); Security security = new Security(emptyList(), List.of("multi-sg-id1", "multi-sg-id2")); groups.add(new Group(name, InstanceGroupType.CORE, emptyList(), security, instance, instanceAuthentication, instanceAuthentication.getLoginUserName(), "publickey", ROOT_VOLUME_SIZE)); CloudStack cloudStack = new CloudStack(groups, new Network(new Subnet(CIDR)), image, emptyMap(), emptyMap(), "template", instanceAuthentication, instanceAuthentication.getLoginUserName(), "publicKey", null); //WHEN modelContext = new ModelContext() .withAuthenticatedContext(authenticatedContext) .withStack(cloudStack) .withExistingVpc(true) .withExistingIGW(true) .withExistingSubnetCidr(singletonList(existingSubnetCidr)) .withStack(cloudStack) .mapPublicIpOnLaunch(false) .withTemplate(awsCloudFormationTemplate); when(defaultCostTaggingService.prepareAllTagsForTemplate()).thenReturn(defaultTags); String templateString = cloudFormationTemplateBuilder.build(modelContext); //THEN // older templates are invalids if ("templates/aws-cf-stack.ftl".equals(templatePath)) { Assert.assertTrue("Ivalid JSON: " + templateString, JsonUtil.isValid(templateString)); // we don't support the multiple security groups in older templates assertThat(templateString, containsString("\"multi-sg-id1\",\"multi-sg-id2\"")); } assertThat(templateString, containsString("VPCId")); } private AuthenticatedContext authenticatedContext() { Location location = Location.location(Region.region("region"), AvailabilityZone.availabilityZone("az")); CloudContext cloudContext = new CloudContext(5L, "name", "platform", "variant", location, USER_ID, WORKSPACE_ID); CloudCredential credential = new CloudCredential(1L, null); return new AuthenticatedContext(cloudContext, credential); } private CloudStack createDefaultCloudStack(Collection<Group> groups, Map<String, String> parameters, Map<String, String> tags) { Network network = new Network(new Subnet("testSubnet")); return new CloudStack(groups, network, image, parameters, tags, null, instanceAuthentication, instanceAuthentication.getLoginUserName(), instanceAuthentication.getPublicKey(), null); } private Group createDefaultGroup(InstanceGroupType type, int rootVolumeSize, Security security) { return new Group(name, type, singletonList(instance), security, null, instanceAuthentication, instanceAuthentication.getLoginUserName(), instanceAuthentication.getPublicKey(), rootVolumeSize); } private Map<String, String> getDefaultCloudStackParameters() { return Map.of("persistentStorage", "persistentStorageTest", "attachedStorageOption", "attachedStorageOptionTest"); } private Map<String, String> getDefaultCloudStackTags() { return Map.of("testtagkey", "testtagvalue"); } private Security getDefaultCloudStackSecurity() { return new Security(getDefaultSecurityRules(), emptyList()); } private List<SecurityRule> getDefaultSecurityRules() { return singletonList(new SecurityRule("0.0.0.0/0", new PortDefinition[]{new PortDefinition("22", "22"), new PortDefinition("443", "443")}, "tcp")); } private JsonNode getJsonNode(JsonNode node, String value) { if (node == null) { throw new RuntimeException("No Json node provided for seeking value!"); } return Optional.ofNullable(node.findValue(value)).orElseThrow(() -> new RuntimeException("No value find in json with the name of: \"" + value + "\"")); } }
package ViewManager; import java.math.BigInteger; import java.util.Arrays; import java.util.List; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; import org.json.simple.JSONObject; import client.client.XmlHandler; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.ColumnDefinitions; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import com.datastax.driver.core.Session; import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy; import com.datastax.driver.core.policies.DefaultRetryPolicy; import com.datastax.driver.core.policies.TokenAwarePolicy; public class ViewManagerController { Cluster currentCluster = null; ViewManager vm = null; private static XMLConfiguration baseTableKeysConfig; List<String> baseTableName; List<String> pkName; List<String> deltaTableName; List<String> reverseTableName; List<String> preaggTableNames; List<String> preaggJoinTableNames; List<String> rj_joinTables; List<String> rj_joinKeys; List<String> rj_joinKeyTypes; List<String> rj_nrDelta; int rjoins; public ViewManagerController() { connectToCluster(); retrieveLoadXmlHandlers(); parseXmlMapping(); vm = new ViewManager(currentCluster); } private void retrieveLoadXmlHandlers() { baseTableKeysConfig = new XMLConfiguration(); baseTableKeysConfig.setDelimiterParsingDisabled(true); try { baseTableKeysConfig .load("ViewManager/properties/baseTableKeys.xml"); } catch (ConfigurationException e) { e.printStackTrace(); } } public void parseXmlMapping() { baseTableName = baseTableKeysConfig.getList("tableSchema.table.name"); pkName = baseTableKeysConfig.getList("tableSchema.table.pkName"); deltaTableName = VmXmlHandler.getInstance().getDeltaPreaggMapping() .getList("mapping.unit.deltaTable"); reverseTableName = VmXmlHandler.getInstance().getRjJoinMapping() .getList("mapping.unit.reverseJoin"); rj_joinTables = VmXmlHandler.getInstance().getDeltaReverseJoinMapping() .getList("mapping.unit.Join.name"); rj_joinKeys = VmXmlHandler.getInstance().getDeltaReverseJoinMapping() .getList("mapping.unit.Join.JoinKey"); rj_joinKeyTypes = VmXmlHandler.getInstance() .getDeltaReverseJoinMapping().getList("mapping.unit.Join.type"); rj_nrDelta = VmXmlHandler.getInstance().getDeltaReverseJoinMapping() .getList("mapping.unit.nrDelta"); rjoins = VmXmlHandler.getInstance().getDeltaReverseJoinMapping() .getInt("mapping.nrUnit"); preaggTableNames = VmXmlHandler.getInstance().getHavingPreAggMapping() .getList("mapping.unit.preaggTable"); preaggJoinTableNames = VmXmlHandler.getInstance() .getHavingJoinAggMapping().getList("mapping.unit.preaggTable"); } private void connectToCluster() { currentCluster = Cluster .builder() .addContactPoint( XmlHandler.getInstance().getClusterConfig() .getString("config.host.localhost")) .withRetryPolicy(DefaultRetryPolicy.INSTANCE) .withLoadBalancingPolicy( new TokenAwarePolicy(new DCAwareRoundRobinPolicy())) .build(); } public void update(JSONObject json) { // get position of basetable from xml list // retrieve pk of basetable and delta from XML mapping file int indexBaseTableName = baseTableName.indexOf((String) json .get("table")); String baseTablePrimaryKey = pkName.get(indexBaseTableName); Row deltaUpdatedRow = null; // 1. update Delta Table // 1.a If successful, retrieve entire updated Row from Delta to pass on // as streams if (vm.updateDelta(json, indexBaseTableName, baseTablePrimaryKey)) { deltaUpdatedRow = vm.getDeltaUpdatedRow(); } // update selection view // for each delta, loop on all selection views possible // check if selection condition is met based on selection key // if yes then update selection, if not ignore // also compare old values of selection condition, if they have changed // then delete row from table int position1 = deltaTableName.indexOf("delta_" + (String) json.get("table")); if (position1 != -1) { String temp4 = "mapping.unit("; temp4 += Integer.toString(position1); temp4 += ")"; int nrConditions = VmXmlHandler.getInstance() .getDeltaSelectionMapping().getInt(temp4 + ".nrCond"); for (int i = 0; i < nrConditions; i++) { String s = temp4 + ".Cond(" + Integer.toString(i) + ")"; String selecTable = VmXmlHandler.getInstance() .getDeltaSelectionMapping().getString(s + ".name"); String nrAnd = VmXmlHandler.getInstance() .getDeltaSelectionMapping().getString(s + ".nrAnd"); boolean eval = true; boolean eval_old = true; for (int j = 0; j < Integer.parseInt(nrAnd); j++) { String s11 = s + ".And("; s11 += Integer.toString(j); s11 += ")"; String operation = VmXmlHandler.getInstance() .getDeltaSelectionMapping() .getString(s11 + ".operation"); String value = VmXmlHandler.getInstance() .getDeltaSelectionMapping() .getString(s11 + ".value"); String type = VmXmlHandler.getInstance() .getDeltaSelectionMapping() .getString(s11 + ".type"); String selColName = VmXmlHandler.getInstance() .getDeltaSelectionMapping() .getString(s11 + ".selectionCol"); switch (type) { case "text": if (operation.equals("=")) { if (deltaUpdatedRow.getString(selColName + "_new") .equals(value)) { eval &= true; } else { eval &= false; } if (deltaUpdatedRow.getString(selColName + "_old") == null) { eval_old = false; } else if (deltaUpdatedRow.getString( selColName + "_old").equals(value)) { eval_old &= true; } else { eval_old &= false; } } else if (operation.equals("!=")) { if (!deltaUpdatedRow.getString(selColName + "_new") .equals(value)) { eval = true; } else { eval = false; } if (deltaUpdatedRow.getString(selColName + "_old") == null) { eval_old = false; } else if (!deltaUpdatedRow.getString( selColName + "_old").equals(value)) { eval_old &= true; } else { eval_old &= false; } } break; case "varchar": if (operation.equals("=")) { if (deltaUpdatedRow.getString(selColName + "_new") .equals(value)) { eval &= true; } else { eval &= false; } if (deltaUpdatedRow.getString(selColName + "_old") == null) { eval_old = false; } else if (deltaUpdatedRow.getString( selColName + "_old").equals(value)) { eval_old &= true; } else { eval_old &= false; } } else if (operation.equals("!=")) { if (!deltaUpdatedRow.getString(selColName + "_new") .equals(value)) { eval &= true; } else { eval &= false; } if (deltaUpdatedRow.getString(selColName + "_old") == null) { eval_old = false; } else if (!deltaUpdatedRow.getString( selColName + "_old").equals(value)) { eval_old &= true; } else { eval_old &= false; } } break; case "int": // for _new col String s1 = Integer.toString(deltaUpdatedRow .getInt(selColName + "_new")); Integer valueInt = new Integer(s1); int compareValue = valueInt .compareTo(new Integer(value)); if ((operation.equals(">") && (compareValue > 0))) { eval &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval &= true; } else { eval &= false; } // for _old col int v = deltaUpdatedRow.getInt(selColName + "_old"); compareValue = valueInt.compareTo(new Integer(v)); if ((operation.equals(">") && (compareValue > 0))) { eval_old &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval_old &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval_old &= true; } else { eval_old &= false; } break; case "varint": // for _new col s1 = deltaUpdatedRow.getVarint(selColName + "_new") .toString(); valueInt = new Integer(new BigInteger(s1).intValue()); compareValue = valueInt.compareTo(new Integer(value)); if ((operation.equals(">") && (compareValue > 0))) { eval &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval &= true; } else { eval &= false; } // for _old col BigInteger bigInt = deltaUpdatedRow .getVarint(selColName + "_old"); if (bigInt != null) { valueInt = bigInt.intValue(); } else { valueInt = 0; } compareValue = valueInt.compareTo(new Integer(value)); if ((operation.equals(">") && (compareValue > 0))) { eval_old &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval_old &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval_old &= true; } else { eval_old &= false; } break; case "float": break; } } // if condition matching now & matched before if (eval && eval_old) { vm.updateSelection(deltaUpdatedRow, (String) json.get("keyspace"), selecTable, baseTablePrimaryKey); // if matching now & not matching before } else if (eval && !eval_old) { vm.updateSelection(deltaUpdatedRow, (String) json.get("keyspace"), selecTable, baseTablePrimaryKey); // if not matching now & matching before } else if (!eval && eval_old) { vm.deleteRowSelection(vm.getDeltaUpdatedRow(), (String) json.get("keyspace"), selecTable, baseTablePrimaryKey, json); // if not matching now & not before, ignore } } } // 2. for the delta table updated, get the depending preaggregation/agg // tables // preagg tables hold all column values, hence they have to be updated int position = deltaTableName.indexOf("delta_" + (String) json.get("table")); if (position != -1) { String temp = "mapping.unit("; temp += Integer.toString(position); temp += ")"; int nrPreagg = VmXmlHandler.getInstance().getDeltaPreaggMapping() .getInt(temp + ".nrPreagg"); for (int i = 0; i < nrPreagg; i++) { String s = temp + ".Preagg(" + Integer.toString(i) + ")"; String AggKey = VmXmlHandler.getInstance() .getDeltaPreaggMapping().getString(s + ".AggKey"); String AggKeyType = VmXmlHandler.getInstance() .getDeltaPreaggMapping().getString(s + ".AggKeyType"); String preaggTable = VmXmlHandler.getInstance() .getDeltaPreaggMapping().getString(s + ".name"); String AggCol = VmXmlHandler.getInstance() .getDeltaPreaggMapping().getString(s + ".AggCol"); String AggColType = VmXmlHandler.getInstance() .getDeltaPreaggMapping().getString(s + ".AggColType"); // 2.a after getting the preagg table name & neccessary // parameters, // check if aggKey in delta (_old & _new ) is null // if null then dont update, else update boolean isNull = checkIfAggIsNull(AggKey, deltaUpdatedRow); if (!isNull) { //WHERE clause condition evaluation String condName = VmXmlHandler.getInstance() .getDeltaPreaggMapping() .getString(s + ".Cond.name"); if (!condName.equals("none")) { String nrAnd = VmXmlHandler.getInstance() .getDeltaPreaggMapping() .getString(s + ".Cond.nrAnd"); boolean eval = true; for (int j = 0; j < Integer.parseInt(nrAnd); j++) { String s11 = s + ".Cond.And("; s11 += Integer.toString(j); s11 += ")"; String operation = VmXmlHandler.getInstance() .getDeltaPreaggMapping() .getString(s11 + ".operation"); String value = VmXmlHandler.getInstance() .getDeltaPreaggMapping() .getString(s11 + ".value"); String type = VmXmlHandler.getInstance() .getDeltaPreaggMapping() .getString(s11 + ".type"); String colName = VmXmlHandler.getInstance() .getDeltaPreaggMapping() .getString(s11 + ".selectionCol"); eval &= evaluateCondition(deltaUpdatedRow, operation, value, type, colName + "_new"); } System.out.println((String) json.get("table") + " condition is " + eval); // condition fulfilled if (eval) { // by passing the whole delta Row, we have agg key // value // even if it is not in json vm.updatePreaggregation(deltaUpdatedRow, AggKey, AggKeyType, json, preaggTable, baseTablePrimaryKey, AggCol, AggColType, false, false); } else { // cascade delete String pkVAlue = ""; switch (AggColType) { case "int": pkVAlue = Integer.toString(deltaUpdatedRow.getInt(baseTablePrimaryKey)); break; case "float": pkVAlue = Float.toString(deltaUpdatedRow.getFloat(baseTablePrimaryKey)); break; case "varint": pkVAlue = deltaUpdatedRow.getVarint(baseTablePrimaryKey).toString(); break; case "varchar": pkVAlue = deltaUpdatedRow.getString(baseTablePrimaryKey); break; case "text": pkVAlue = deltaUpdatedRow.getString(baseTablePrimaryKey); break; } // 1. retrieve the row to be deleted from delta table StringBuilder selectQuery = new StringBuilder("SELECT *"); selectQuery.append(" FROM ").append(json.get("keyspace")).append(".") .append("delta_" + json.get("table")).append(" WHERE ") .append(baseTablePrimaryKey).append(" = ") .append(pkVAlue).append(";"); System.out.println(selectQuery); ResultSet selectionResult; try { Session session = currentCluster.connect(); selectionResult = session.execute(selectQuery.toString()); } catch (Exception e) { e.printStackTrace(); return; } // 2. set DeltaDeletedRow variable for streaming vm.setDeltaDeletedRow(selectionResult.one()); cascadeDelete(json, false); // continue continue; } } else { // by passing the whole delta Row, we have agg key value // even if it is not in json vm.updatePreaggregation(deltaUpdatedRow, AggKey, AggKeyType, json, preaggTable, baseTablePrimaryKey, AggCol, AggColType, false, false); } } // 2.1 update preaggregations with having clause // check if preagg has some having clauses or not position = preaggTableNames.indexOf(preaggTable); if (position1 != -1) { String temp4 = "mapping.unit("; temp4 += Integer.toString(position1); temp4 += ")"; int nrConditions = VmXmlHandler.getInstance() .getHavingPreAggMapping().getInt(temp4 + ".nrCond"); for (i = 0; i < nrConditions; i++) { String s1 = temp4 + ".Cond(" + Integer.toString(i) + ")"; String havingTable = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s1 + ".name"); String nrAnd = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s1 + ".nrAnd"); boolean eval1 = true; boolean eval2 = true; for (int j = 0; j < Integer.parseInt(nrAnd); j++) { String s11 = s1 + ".And("; s11 += Integer.toString(j); s11 += ")"; String aggFct = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s11 + ".aggFct"); String operation = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s11 + ".operation"); String value = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s11 + ".value"); String type = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s11 + ".type"); String selColName = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s11 + ".selectionCol"); Row PreagRow = vm.getUpdatedPreaggRow(); Row PreagRowAK = vm.getUpdatedPreaggRowChangeAK(); float min1 = PreagRow.getFloat("min"); float max1 = PreagRow.getFloat("max"); float average1 = PreagRow.getFloat("average"); int sum1 = PreagRow.getInt("sum"); int count1 = PreagRow.getInt("count"); float min2 = 0; float max2 = 0; float average2 = 0; int sum2 = 0; int count2 = 0; if (PreagRowAK != null) { min2 = PreagRowAK.getFloat("min"); max2 = PreagRowAK.getFloat("max"); average2 = PreagRowAK.getFloat("average"); sum2 = PreagRowAK.getInt("sum"); count2 = PreagRowAK.getInt("count"); } if (aggFct.equals("sum")) { int compareValue = new Integer(sum1) .compareTo(new Integer(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } if (PreagRowAK != null) { compareValue = new Integer(sum2) .compareTo(new Integer(value)); if ((operation.equals(">") && (compareValue > 0))) { eval2 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval2 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval2 &= true; } else { eval2 &= false; } } } else if (aggFct.equals("average")) { int compareValue = Float.compare(average1, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } if (PreagRowAK != null) { compareValue = Float.compare(average2, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } } } else if (aggFct.equals("count")) { int compareValue = new Integer(count1) .compareTo(new Integer(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } if (PreagRowAK != null) { compareValue = new Integer(count2) .compareTo(new Integer(value)); if ((operation.equals(">") && (compareValue > 0))) { eval2 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval2 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval2 &= true; } else { eval2 &= false; } } } else if (aggFct.equals("min")) { int compareValue = Float.compare(min1, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } if (PreagRowAK != null) { compareValue = Float.compare(min2, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } } } else if (aggFct.equals("max")) { int compareValue = Float.compare(max1, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } if (PreagRowAK != null) { compareValue = Float.compare(max2, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval2 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval2 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval2 &= true; } else { eval2 &= false; } } } // if matching now & not matching before // if condition matching now & matched before if (eval1) { vm.updateHaving(deltaUpdatedRow, (String) json.get("keyspace"), havingTable, PreagRow); if (PreagRowAK != null && eval2) { vm.updateHaving(deltaUpdatedRow, (String) json.get("keyspace"), havingTable, PreagRowAK); } // if not matching now } else if (!eval1) { vm.deleteRowHaving(deltaUpdatedRow, (String) json.get("keyspace"), havingTable, PreagRow); if (PreagRowAK != null && !eval2) { vm.deleteRowHaving(deltaUpdatedRow, (String) json.get("keyspace"), havingTable, PreagRowAK); } // if not matching now & not before, ignore } Row deletedRow = vm.getUpdatedPreaggRowDeleted(); if (deletedRow != null) { vm.deleteRowHaving(deltaUpdatedRow, (String) json.get("keyspace"), havingTable, deletedRow); } } } } else { System.out .println("No Having table for this joinpreaggregation Table " + preaggTable + " available"); } } } // End of updating preagg with having clause else { System.out.println("No Preaggregation table for this delta table " + " delta_" + (String) json.get("table") + " available"); } // 3. for the delta table updated, get update depending reverse join // tables int cursor = 0; for (int j = 0; j < rjoins; j++) { // basetables int nrOfTables = Integer.parseInt(rj_nrDelta.get(j)); String joinTable = rj_joinTables.get(j); // include only indices from 1 to nrOfTables // get basetables from name of rj table List<String> baseTables = Arrays.asList( rj_joinTables.get(j).split("_")).subList(1, nrOfTables + 1); String tableName = (String) json.get("table"); String keyspace = (String) json.get("keyspace"); int column = baseTables.indexOf(tableName) + 1; String joinKeyName = rj_joinKeys.get(cursor + column - 1); String joinKeyType = rj_joinKeyTypes.get(j); if (column == 0) { System.out.println("No ReverseJoin for this delta update"); continue; } vm.updateReverseJoin(json, cursor, nrOfTables, joinTable, baseTables, joinKeyName, tableName, keyspace, joinKeyType, column); // HERE UPDATE JOIN TABLES // 4. update Join tables String updatedReverseJoin = vm.getReverseJoinName(); position = reverseTableName.indexOf(updatedReverseJoin); if (position != -1) { String temp = "mapping.unit("; temp += Integer.toString(position); temp += ")"; int nrJoin = VmXmlHandler.getInstance().getRjJoinMapping() .getInt(temp + ".nrJoin"); for (int i = 0; i < nrJoin; i++) { String s = temp + ".join(" + Integer.toString(i) + ")"; String innerJoinTableName = VmXmlHandler.getInstance() .getRjJoinMapping().getString(s + ".innerJoin"); String leftJoinTableName = VmXmlHandler.getInstance() .getRjJoinMapping().getString(s + ".leftJoin"); String rightJoinTableName = VmXmlHandler.getInstance() .getRjJoinMapping().getString(s + ".rightJoin"); String leftJoinTable = VmXmlHandler.getInstance() .getRjJoinMapping().getString(s + ".LeftTable"); String rightJoinTable = VmXmlHandler.getInstance() .getRjJoinMapping().getString(s + ".RightTable"); tableName = (String) json.get("table"); Boolean updateLeft = false; Boolean updateRight = false; if (tableName.equals(leftJoinTable)) { updateLeft = true; } else { updateRight = true; } vm.updateJoinController(deltaUpdatedRow, innerJoinTableName, leftJoinTableName, rightJoinTableName, json, updateLeft, updateRight, joinKeyType, joinKeyName, baseTablePrimaryKey); } } else { System.out.println("No join table for this reverse join table " + updatedReverseJoin + " available"); } // END OF UPATE JOIN TABLES // Update JoinPreagg if (position != -1) { String temp = "mapping.unit("; temp += Integer.toString(position); temp += ")"; int nrJoinAgg = VmXmlHandler.getInstance().getJoinAggMapping() .getInt(temp + ".nrJoinAgg"); for (int i = 0; i < nrJoinAgg; i++) { System.out.println("i22222222"+i); String s = temp + ".joinAgg(" + Integer.toString(i) + ")"; String basetable = VmXmlHandler.getInstance() .getJoinAggMapping().getString(s + ".basetable"); String otherTable = VmXmlHandler.getInstance() .getJoinAggMapping().getString(s + ".othertable"); String aggColOfTable = VmXmlHandler.getInstance() .getJoinAggMapping().getString(s + ".AggColinTable"); String joinAggTableName = VmXmlHandler.getInstance() .getJoinAggMapping().getString(s + ".name"); String joinType = VmXmlHandler.getInstance() .getJoinAggMapping().getString(s + ".joinType"); String aggKey = VmXmlHandler.getInstance() .getJoinAggMapping().getString(s + ".AggKey"); String aggKeyType = VmXmlHandler.getInstance() .getJoinAggMapping().getString(s + ".AggKeyType"); String aggCol = VmXmlHandler.getInstance() .getJoinAggMapping().getString(s + ".AggCol"); String aggColType = VmXmlHandler.getInstance() .getJoinAggMapping().getString(s + ".AggColType"); Row oldReverseRow = vm.getReverseJoinUpdateOldRow(); Row newReverseRow = vm.getReverseJoinUpdatedNewRow(); Row deletedFrom = vm.getReverseJoinUpdatedOldRow_changeJoinKey(); tableName = (String) json.get("table"); if(!tableName.equals(basetable) && !tableName.equals(otherTable)){ continue; } Boolean leftUpdateHappened = false; if(tableName.equals(basetable)){ leftUpdateHappened = true; } String aggKeyValue = ""; switch (aggKeyType) { case "int": aggKeyValue = "'" + Integer .toString(newReverseRow.getInt(aggKey)) + "'"; break; case "float": aggKeyValue = "'" + Float.toString(newReverseRow.getFloat(aggKey)) + "'"; break; case "varint": aggKeyValue = "'" + newReverseRow.getVarint(aggKey).toString() + "'"; break; case "text": aggKeyValue = "'" + newReverseRow.getString(aggKey).toString() + "'"; break; case "varchar": aggKeyValue = "'" + newReverseRow.getString(aggKey).toString() + "'"; break; } String aggKeyValueDelete = ""; if(deletedFrom!=null){ switch(aggKeyType){ case "int": aggKeyValueDelete = "'"+Integer.toString(deletedFrom.getInt(aggKey))+"'"; break; case "float": aggKeyValueDelete = "'"+Float.toString(deletedFrom.getFloat(aggKey))+"'"; break; case "varint": aggKeyValueDelete = "'"+deletedFrom.getVarint(aggKey).toString()+"'"; break; case "text": aggKeyValueDelete = "'"+deletedFrom.getString(aggKey).toString()+"'"; break; case "varchar": aggKeyValueDelete = "'"+deletedFrom.getString(aggKey).toString()+"'"; break; } } //check if join_preagg has some having clauses or not position = preaggJoinTableNames.indexOf(joinAggTableName); String temp4 = null; int nrConditions = 0; if (position != -1) { temp4 = "mapping.unit("; temp4 += Integer.toString(position); temp4 += ")"; nrConditions = VmXmlHandler.getInstance() .getHavingJoinAggMapping() .getInt(temp4 + ".nrCond"); } boolean update = true; switch (joinType) { case "left": if(deletedFrom!=null && (deletedFrom.getMap("list_item1", String.class, String.class).isEmpty() && deletedFrom.getMap("list_item2", String.class, String.class).isEmpty())){ vm.deleteEntireRowWithPK((String)json.get("keyspace"), joinAggTableName, aggKey, aggKeyValueDelete); //TO DO HAVING update = false; } if(!newReverseRow.getMap("list_item1", String.class, String.class).isEmpty() && !newReverseRow.getMap("list_item2", String.class, String.class).isEmpty()){ vm.deleteEntireRowWithPK((String)json.get("keyspace"), joinAggTableName, aggKey, aggKeyValue); if (position != -1) { for (int ii = 0; ii < nrConditions; ii++) { String s1 = temp4 + ".Cond(" + Integer.toString(ii) + ")"; String havingTable = VmXmlHandler.getInstance() .getHavingJoinAggMapping().getString(s1 + ".name"); vm.deleteEntireRowWithPK((String)json.get("keyspace"), havingTable, aggKey, aggKeyValue); } } update = false; }else if(!newReverseRow.getMap("list_item1", String.class, String.class).isEmpty() && newReverseRow.getMap("list_item2", String.class, String.class).isEmpty()&& (leftUpdateHappened && aggColOfTable.equals("left"))){ update = true; }else{ update = false; } break; case "right": if(deletedFrom!=null && (deletedFrom.getMap("list_item1", String.class, String.class).isEmpty() && deletedFrom.getMap("list_item2", String.class, String.class).isEmpty())){ vm.deleteEntireRowWithPK((String)json.get("keyspace"), joinAggTableName, aggKey, aggKeyValueDelete); //TO DO HAVING update = false; } if( !newReverseRow.getMap("list_item2", String.class, String.class).isEmpty() && !newReverseRow.getMap("list_item1", String.class, String.class).isEmpty()){ vm.deleteEntireRowWithPK((String)json.get("keyspace"), joinAggTableName, aggKey, aggKeyValue); if (position != -1) { for (int iii = 0; iii < nrConditions; iii++) { String s1 = temp4 + ".Cond(" + Integer.toString(iii) + ")"; String havingTable = VmXmlHandler.getInstance() .getHavingJoinAggMapping().getString(s1 + ".name"); vm.deleteEntireRowWithPK((String)json.get("keyspace"), havingTable, aggKey, aggKeyValue); } } update = false; }else if(newReverseRow.getMap("list_item1", String.class, String.class).isEmpty() && !newReverseRow.getMap("list_item2", String.class, String.class).isEmpty() && (!leftUpdateHappened && aggColOfTable.equals("right"))){ update = true; }else{ update = false; } break; case "inner": if(deletedFrom!=null){ if(deletedFrom.getMap("list_item1", String.class, String.class).isEmpty()||deletedFrom.getMap("list_item2", String.class, String.class).isEmpty()){ vm.deleteEntireRowWithPK((String)json.get("keyspace"), joinAggTableName, aggKey, aggKeyValueDelete); update = false; //To Do: missing having stuff for inner }else{ if(aggColOfTable.equals("left") && leftUpdateHappened ){ leftUpdateHappened = true; update = true; }else if(aggColOfTable.equals("right") && !leftUpdateHappened ){ leftUpdateHappened = false; update = true; }else if(aggColOfTable.equals("left") && !leftUpdateHappened ){ vm.updateInnerJoinAgg(deltaUpdatedRow,json,joinAggTableName,aggKey,aggKeyType,aggCol,aggColType,oldReverseRow,deletedFrom,leftUpdateHappened,false, false,basetable); update = false; }else if(aggColOfTable.equals("right") && leftUpdateHappened ){ vm.updateInnerJoinAgg(deltaUpdatedRow,json,joinAggTableName,aggKey,aggKeyType,aggCol,aggColType,oldReverseRow,deletedFrom,leftUpdateHappened,false, false,basetable); update = false; } } } if(newReverseRow.getMap("list_item1", String.class, String.class).isEmpty()||newReverseRow.getMap("list_item2", String.class, String.class).isEmpty()){ vm.deleteEntireRowWithPK((String)json.get("keyspace"), joinAggTableName, aggKey, aggKeyValue); update = false; //To Do: missing having stuff for inner }else{ if(aggColOfTable.equals("left") && leftUpdateHappened ){ leftUpdateHappened = true; update = true; }else if(aggColOfTable.equals("right") && !leftUpdateHappened ){ leftUpdateHappened = false; update = true; }else if(aggColOfTable.equals("left") && !leftUpdateHappened ){ vm.updateInnerJoinAgg(deltaUpdatedRow,json,joinAggTableName,aggKey,aggKeyType,aggCol,aggColType,oldReverseRow,newReverseRow,leftUpdateHappened,false, false,basetable); update = false; }else if(aggColOfTable.equals("right") && leftUpdateHappened ){ vm.updateInnerJoinAgg(deltaUpdatedRow,json,joinAggTableName,aggKey,aggKeyType,aggCol,aggColType,oldReverseRow,newReverseRow,leftUpdateHappened,false, false,basetable); update = false; } } break; case "full": if(aggColOfTable.equals("left") && leftUpdateHappened ){ leftUpdateHappened = true; update = true; }else if(aggColOfTable.equals("right") && !leftUpdateHappened ){ leftUpdateHappened = false; update = true; }else if(aggColOfTable.equals("left") && !leftUpdateHappened ){ vm.updateInnerJoinAgg(deltaUpdatedRow,json,joinAggTableName,aggKey,aggKeyType,aggCol,aggColType,oldReverseRow,newReverseRow,leftUpdateHappened,false, false,basetable); update = false; }else if(aggColOfTable.equals("right") && leftUpdateHappened ){ vm.updateInnerJoinAgg(deltaUpdatedRow,json,joinAggTableName,aggKey,aggKeyType,aggCol,aggColType,oldReverseRow,newReverseRow,leftUpdateHappened,false, false,basetable); update = false; } break; } if(update){ vm.updateJoinAgg(deltaUpdatedRow,json,joinAggTableName,aggKey,aggKeyType,aggCol,aggColType,oldReverseRow,newReverseRow,leftUpdateHappened,false, false); // update having_joinaggs as well if (position != -1) { for (int r = 0; r < nrConditions; r++) { String s1 = temp4 + ".Cond(" + Integer.toString(r) + ")"; String havingTable = VmXmlHandler.getInstance() .getHavingJoinAggMapping() .getString(s1 + ".name"); String nrAnd = VmXmlHandler.getInstance() .getHavingJoinAggMapping() .getString(s1 + ".nrAnd"); boolean eval1 = true; boolean eval2 = true; for (int k = 0; k < Integer.parseInt(nrAnd); k++) { String s11 = s1 + ".And("; s11 += Integer.toString(k); s11 += ")"; String aggFct = VmXmlHandler.getInstance() .getHavingJoinAggMapping() .getString(s11 + ".aggFct"); String operation = VmXmlHandler .getInstance() .getHavingJoinAggMapping() .getString(s11 + ".operation"); String value = VmXmlHandler.getInstance() .getHavingJoinAggMapping() .getString(s11 + ".value"); String type = VmXmlHandler.getInstance() .getHavingJoinAggMapping() .getString(s11 + ".type"); String selColName = VmXmlHandler .getInstance() .getHavingJoinAggMapping() .getString(s11 + ".selectionCol"); Row PreagRow = vm.getJoinAggRow(); Row PreagRowAK = vm.getJoinAggRowChangeAK(); if (!(PreagRow == null && PreagRowAK == null)) { float min1 = PreagRow.getFloat("min"); float max1 = PreagRow.getFloat("max"); float average1 = PreagRow .getFloat("average"); int sum1 = PreagRow.getInt("sum"); int count1 = PreagRow.getInt("count"); float min2 = 0; float max2 = 0; float average2 = 0; int sum2 = 0; int count2 = 0; if (PreagRowAK != null) { min2 = PreagRowAK.getFloat("min"); max2 = PreagRowAK.getFloat("max"); average2 = PreagRowAK .getFloat("average"); sum2 = PreagRowAK.getInt("sum"); count2 = PreagRowAK.getInt("count"); } if (aggFct.equals("sum")) { int compareValue = new Integer(sum1) .compareTo(new Integer( value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } if (PreagRowAK != null) { compareValue = new Integer(sum2) .compareTo(new Integer( value)); if ((operation.equals(">") && (compareValue > 0))) { eval2 &= true; } else if ((operation .equals("<") && (compareValue < 0))) { eval2 &= true; } else if ((operation .equals("=") && (compareValue == 0))) { eval2 &= true; } else { eval2 &= false; } } } else if (aggFct.equals("average")) { int compareValue = Float.compare( average1, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } if (PreagRowAK != null) { compareValue = Float.compare( average2, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation .equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation .equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } } } else if (aggFct.equals("count")) { int compareValue = new Integer( count1) .compareTo(new Integer( value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } if (PreagRowAK != null) { compareValue = new Integer( count2) .compareTo(new Integer( value)); if ((operation.equals(">") && (compareValue > 0))) { eval2 &= true; } else if ((operation .equals("<") && (compareValue < 0))) { eval2 &= true; } else if ((operation .equals("=") && (compareValue == 0))) { eval2 &= true; } else { eval2 &= false; } } } else if (aggFct.equals("min")) { int compareValue = Float.compare( min1, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } if (PreagRowAK != null) { compareValue = Float.compare( min2, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation .equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation .equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } } } else if (aggFct.equals("max")) { int compareValue = Float.compare( max1, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } if (PreagRowAK != null) { compareValue = Float.compare( max2, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval2 &= true; } else if ((operation .equals("<") && (compareValue < 0))) { eval2 &= true; } else if ((operation .equals("=") && (compareValue == 0))) { eval2 &= true; } else { eval2 &= false; } } } // if matching now & not matching before // if condition matching now & matched // before if (eval1) { vm.updateJoinHaving((String) json .get("keyspace"), havingTable, PreagRow); if (PreagRowAK != null && eval2) { vm.updateJoinHaving( (String) json .get("keyspace"), havingTable, PreagRowAK); } // if not matching now } else if (!eval1) { vm.deleteRowJoinHaving( (String) json .get("keyspace"), havingTable, PreagRow); if (PreagRowAK != null && !eval2) { vm.deleteRowJoinHaving( (String) json .get("keyspace"), havingTable, PreagRowAK); } // if not matching now & not before, // ignore } Row deletedRow = vm .getUpdatedPreaggRowDeleted(); if (deletedRow != null) { vm.deleteRowJoinHaving( (String) json .get("keyspace"), havingTable, deletedRow); } } } } } else { System.out .println("No having for this join agg table!"); } } } } else { System.out.println("No agg table for this reverse join table " + updatedReverseJoin + " available"); } // END OF UPDATE JoinPreag cursor += nrOfTables; } } private boolean checkIfAggIsNull(String aggKey, Row deltaUpdatedRow) { if (deltaUpdatedRow != null) { ColumnDefinitions colDef = deltaUpdatedRow.getColumnDefinitions(); int indexNew = colDef.getIndexOf(aggKey + "_new"); int indexOld = colDef.getIndexOf(aggKey + "_old"); if (deltaUpdatedRow.isNull(indexNew) && deltaUpdatedRow.isNull(indexOld)) { return true; } } return false; } public void cascadeDelete(JSONObject json, boolean deleteOperation) { //boolean deleteOperation is set to false if this method is called from the update method //i.e WHERE clause condition evaluates to fasle // get position of basetable from xml list // retrieve pk of basetable and delta from XML mapping file int indexBaseTableName = baseTableName.indexOf((String) json .get("table")); String baseTablePrimaryKey = pkName.get(indexBaseTableName); Row deltaDeletedRow = null; // 1. delete from Delta Table // 1.a If successful, retrieve entire delta Row from Delta to pass on as // streams if(deleteOperation){ if (vm.deleteRowDelta(json)) { deltaDeletedRow = vm.getDeltaDeletedRow(); } } else deltaDeletedRow = vm.getDeltaDeletedRow(); // 2. for the delta table updated, get the depending preaggregation/agg // tables // preagg tables hold all column values, hence they have to be updated int position = deltaTableName.indexOf("delta_" + (String) json.get("table")); if (position != -1) { String temp = "mapping.unit("; temp += Integer.toString(position); temp += ")"; int nrPreagg = VmXmlHandler.getInstance().getDeltaPreaggMapping() .getInt(temp + ".nrPreagg"); for (int i = 0; i < nrPreagg; i++) { String s = temp + ".Preagg(" + Integer.toString(i) + ")"; String AggKey = VmXmlHandler.getInstance() .getDeltaPreaggMapping().getString(s + ".AggKey"); String AggKeyType = VmXmlHandler.getInstance() .getDeltaPreaggMapping().getString(s + ".AggKeyType"); String preaggTable = VmXmlHandler.getInstance() .getDeltaPreaggMapping().getString(s + ".name"); String AggCol = VmXmlHandler.getInstance() .getDeltaPreaggMapping().getString(s + ".AggCol"); String AggColType = VmXmlHandler.getInstance() .getDeltaPreaggMapping().getString(s + ".AggColType"); // by passing the whole delta Row, we have agg key value even if // it is not in json vm.deleteRowPreaggAgg(deltaDeletedRow, baseTablePrimaryKey, json, preaggTable, AggKey, AggKeyType, AggCol, AggColType); // update the corresponding preagg wih having clause position = preaggTableNames.indexOf(preaggTable); if (position != -1) { String temp4 = "mapping.unit("; temp4 += Integer.toString(position); temp4 += ")"; int nrConditions = VmXmlHandler.getInstance() .getHavingPreAggMapping().getInt(temp4 + ".nrCond"); for (int r = 0; r < nrConditions; r++) { String s1 = temp4 + ".Cond(" + Integer.toString(r) + ")"; String havingTable = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s1 + ".name"); String nrAnd = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s1 + ".nrAnd"); boolean eval1 = true; for (int j = 0; j < Integer.parseInt(nrAnd); j++) { String s11 = s1 + ".And("; s11 += Integer.toString(j); s11 += ")"; String aggFct = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s11 + ".aggFct"); String operation = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s11 + ".operation"); String value = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s11 + ".value"); String type = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s11 + ".type"); String selColName = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s11 + ".selectionCol"); Row DeletedPreagRow = vm.getDeletePreaggRow(); Row DeletedPreagRowMapSize1 = vm .getDeletePreaggRowDeleted(); float min1 = 0; float max1 = 0; float average1 = 0; int sum1 = 0; int count1 = 0; if (DeletedPreagRow != null) { min1 = DeletedPreagRow.getFloat("min"); max1 = DeletedPreagRow.getFloat("max"); average1 = DeletedPreagRow.getFloat("average"); sum1 = DeletedPreagRow.getInt("sum"); count1 = DeletedPreagRow.getInt("count"); } if (aggFct.equals("sum")) { if (DeletedPreagRow != null) { int compareValue = new Integer(sum1) .compareTo(new Integer(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } } } else if (aggFct.equals("average")) { if (DeletedPreagRow != null) { int compareValue = Float.compare(average1, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } } } else if (aggFct.equals("count")) { if (DeletedPreagRow != null) { int compareValue = new Integer(count1) .compareTo(new Integer(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } } } else if (aggFct.equals("min")) { if (DeletedPreagRow != null) { int compareValue = Float.compare(min1, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } } } else if (aggFct.equals("max")) { if (DeletedPreagRow != null) { int compareValue = Float.compare(max1, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } } } if (DeletedPreagRow != null) { if (eval1) { vm.updateHaving(deltaDeletedRow, (String) json.get("keyspace"), havingTable, DeletedPreagRow); } else { vm.deleteRowHaving(deltaDeletedRow, (String) json.get("keyspace"), havingTable, DeletedPreagRow); } } else if (DeletedPreagRowMapSize1 != null) { vm.deleteRowHaving(deltaDeletedRow, (String) json.get("keyspace"), havingTable, DeletedPreagRowMapSize1); } } } } } } else { System.out.println("No Preaggregation table for this delta table " + " delta_" + (String) json.get("table") + " available"); } // 3. for the delta table updated, get the depending selection tables // tables // check if condition is true based on selection true // if true, delete row from selection table int position1 = deltaTableName.indexOf("delta_" + (String) json.get("table")); if (deleteOperation && position1 != -1) { String temp4 = "mapping.unit("; temp4 += Integer.toString(position1); temp4 += ")"; int nrConditions = VmXmlHandler.getInstance() .getDeltaSelectionMapping().getInt(temp4 + ".nrCond"); for (int i = 0; i < nrConditions; i++) { String s = temp4 + ".Cond(" + Integer.toString(i) + ")"; String selecTable = VmXmlHandler.getInstance() .getDeltaSelectionMapping().getString(s + ".name"); String nrAnd = VmXmlHandler.getInstance() .getDeltaSelectionMapping().getString(s + ".nrAnd"); boolean eval = false; for (int j = 0; j < Integer.parseInt(nrAnd); j++) { String s11 = s + ".And("; s11 += Integer.toString(j); s11 += ")"; String operation = VmXmlHandler.getInstance() .getDeltaSelectionMapping() .getString(s11 + ".operation"); String value = VmXmlHandler.getInstance() .getDeltaSelectionMapping() .getString(s11 + ".value"); String type = VmXmlHandler.getInstance() .getDeltaSelectionMapping() .getString(s11 + ".type"); String selColName = VmXmlHandler.getInstance() .getDeltaSelectionMapping() .getString(s11 + ".selectionCol"); switch (type) { case "text": if (operation.equals("=")) { if (vm.getDeltaDeletedRow() .getString(selColName + "_new") .equals(value)) { eval = true; } else { eval = false; } } else if (operation.equals("!=")) { if (!vm.getDeltaDeletedRow() .getString(selColName + "_new") .equals(value)) { eval = true; } else { eval = false; } } break; case "varchar": if (operation.equals("=")) { if (vm.getDeltaDeletedRow() .getString(selColName + "_new") .equals(value)) { eval = true; } else { eval = false; } } else if (operation.equals("!=")) { if (!vm.getDeltaDeletedRow() .getString(selColName + "_new") .equals(value)) { eval = true; } else { eval = false; } } break; case "int": String s1 = Integer.toString(vm.getDeltaDeletedRow() .getInt(selColName + "_new")); Integer valueInt = new Integer(s1); int compareValue = valueInt .compareTo(new Integer(value)); if ((operation.equals(">") && (compareValue < 0))) { eval = false; } else if ((operation.equals("<") && (compareValue > 0))) { eval = false; } else if ((operation.equals("=") && (compareValue != 0))) { eval = false; } else { eval = true; } break; case "varint": s1 = vm.getDeltaDeletedRow() .getVarint(selColName + "_new").toString(); valueInt = new Integer(new BigInteger(s1).intValue()); compareValue = valueInt.compareTo(new Integer(value)); if ((operation.equals(">") && (compareValue < 0))) { eval = false; } else if ((operation.equals("<") && (compareValue > 0))) { eval = false; } else if ((operation.equals("=") && (compareValue != 0))) { eval = false; } else { eval = true; } break; case "float": break; } } if (eval) vm.deleteRowSelection(vm.getDeltaDeletedRow(), (String) json.get("keyspace"), selecTable, baseTablePrimaryKey, json); } } // 4. reverse joins // check for rj mappings after updating delta int cursor = 0; // for each join for (int j = 0; j < rjoins; j++) { // basetables int nrOfTables = Integer.parseInt(rj_nrDelta.get(j)); String joinTable = rj_joinTables.get(j); // include only indices from 1 to nrOfTables // get basetables from name of rj table List<String> baseTables = Arrays.asList( rj_joinTables.get(j).split("_")).subList(1, nrOfTables + 1); String tableName = (String) json.get("table"); String keyspace = (String) json.get("keyspace"); int column = baseTables.indexOf(tableName) + 1; String joinKeyName = rj_joinKeys.get(cursor + column - 1); String aggKeyType = rj_joinKeyTypes.get(j); vm.deleteReverseJoin(json, cursor, nrOfTables, joinTable, baseTables, joinKeyName, tableName, keyspace, aggKeyType, column); // HERE DELETE FROM JOIN TABLES // 5. delete from join tables String updatedReverseJoin = vm.getReverseJoinName(); position = reverseTableName.indexOf(updatedReverseJoin); if (position != -1) { String temp = "mapping.unit("; temp += Integer.toString(position); temp += ")"; int nrJoin = VmXmlHandler.getInstance().getRjJoinMapping() .getInt(temp + ".nrJoin"); for (int i = 0; i < nrJoin; i++) { String s = temp + ".join(" + Integer.toString(i) + ")"; String innerJoinTableName = VmXmlHandler.getInstance() .getRjJoinMapping().getString(s + ".innerJoin"); String leftJoinTableName = VmXmlHandler.getInstance() .getRjJoinMapping().getString(s + ".leftJoin"); String rightJoinTableName = VmXmlHandler.getInstance() .getRjJoinMapping().getString(s + ".rightJoin"); String leftJoinTable = VmXmlHandler.getInstance() .getRjJoinMapping().getString(s + ".LeftTable"); String rightJoinTable = VmXmlHandler.getInstance() .getRjJoinMapping().getString(s + ".RightTable"); tableName = (String) json.get("table"); Boolean updateLeft = false; Boolean updateRight = false; if (tableName.equals(leftJoinTable)) { updateLeft = true; } else { updateRight = true; } vm.deleteJoinController(deltaDeletedRow, innerJoinTableName, leftJoinTableName, rightJoinTableName, json, updateLeft, updateRight); } } else { System.out.println("No join table for this reverse join table " + updatedReverseJoin + " available"); } // END OF DELETE FROM JOIN TABLES // delete operations on agg of joins based on each deletion update // of reverse join // Update JoinPreagg if (position != -1) { String temp = "mapping.unit("; temp += Integer.toString(position); temp += ")"; int nrJoinAgg = VmXmlHandler.getInstance().getJoinAggMapping() .getInt(temp + ".nrJoinAgg"); for (int i = 0; i < nrJoinAgg; i++) { String s = temp + ".joinAgg(" + Integer.toString(i) + ")"; String basetable = VmXmlHandler.getInstance() .getJoinAggMapping().getString(s + ".basetable"); tableName = (String) json.get("table"); if (!basetable.equals(tableName)) continue; String joinAggTableName = VmXmlHandler.getInstance() .getJoinAggMapping().getString(s + ".name"); Boolean leftTable = VmXmlHandler.getInstance() .getJoinAggMapping().getBoolean(s + ".leftTable"); Boolean rightTable = VmXmlHandler.getInstance() .getJoinAggMapping().getBoolean(s + ".rightTable"); String aggKey = VmXmlHandler.getInstance() .getJoinAggMapping().getString(s + ".AggKey"); String aggKeyType1 = VmXmlHandler.getInstance() .getJoinAggMapping().getString(s + ".AggKeyType"); String aggCol = VmXmlHandler.getInstance() .getJoinAggMapping().getString(s + ".AggCol"); String aggColType = VmXmlHandler.getInstance() .getJoinAggMapping().getString(s + ".AggColType"); Row oldReverseRow = vm.getRevereJoinDeleteOldRow(); Row newReverseRow = vm.getReverseJoinDeleteNewRow(); vm.deleteFromJoinAgg(deltaDeletedRow, json, joinAggTableName, aggKey, aggKeyType1, aggCol, aggColType, oldReverseRow, newReverseRow, leftTable); // check if join_preagg has some having clauses or not position = preaggJoinTableNames.indexOf(joinAggTableName); if (position != -1) { String temp4 = "mapping.unit("; temp4 += Integer.toString(position); temp4 += ")"; int nrConditions = VmXmlHandler.getInstance() .getHavingJoinAggMapping() .getInt(temp4 + ".nrCond"); for (int r = 0; r < nrConditions; r++) { String s1 = temp4 + ".Cond(" + Integer.toString(r) + ")"; String havingTable = VmXmlHandler.getInstance() .getHavingJoinAggMapping() .getString(s1 + ".name"); String nrAnd = VmXmlHandler.getInstance() .getHavingJoinAggMapping() .getString(s1 + ".nrAnd"); boolean eval1 = true; for (int k = 0; k < Integer.parseInt(nrAnd); k++) { String s11 = s1 + ".And("; s11 += Integer.toString(k); s11 += ")"; String aggFct = VmXmlHandler.getInstance() .getHavingJoinAggMapping() .getString(s11 + ".aggFct"); String operation = VmXmlHandler.getInstance() .getHavingJoinAggMapping() .getString(s11 + ".operation"); String value = VmXmlHandler.getInstance() .getHavingJoinAggMapping() .getString(s11 + ".value"); String type = VmXmlHandler.getInstance() .getHavingJoinAggMapping() .getString(s11 + ".type"); String selColName = VmXmlHandler.getInstance() .getHavingJoinAggMapping() .getString(s11 + ".selectionCol"); Row DeletedPreagRow = vm.getDeleteRowJoinAgg(); Row DeletedPreagRowMapSize1 = vm .getDeleteRowJoinAggDeleted(); float min1 = 0; float max1 = 0; float average1 = 0; int sum1 = 0; int count1 = 0; if (DeletedPreagRow != null) { min1 = DeletedPreagRow.getFloat("min"); max1 = DeletedPreagRow.getFloat("max"); average1 = DeletedPreagRow .getFloat("average"); sum1 = DeletedPreagRow.getInt("sum"); count1 = DeletedPreagRow.getInt("count"); } if (aggFct.equals("sum")) { if (DeletedPreagRow != null) { int compareValue = new Integer(sum1) .compareTo(new Integer(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } } } else if (aggFct.equals("average")) { if (DeletedPreagRow != null) { int compareValue = Float.compare( average1, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } } } else if (aggFct.equals("count")) { if (DeletedPreagRow != null) { int compareValue = new Integer(count1) .compareTo(new Integer(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } } } else if (aggFct.equals("min")) { if (DeletedPreagRow != null) { int compareValue = Float.compare(min1, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } } } else if (aggFct.equals("max")) { if (DeletedPreagRow != null) { int compareValue = Float.compare(max1, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } } } if (DeletedPreagRow != null) { if (eval1) { vm.updateJoinHaving( (String) json.get("keyspace"), havingTable, DeletedPreagRow); } else { vm.deleteRowJoinHaving( (String) json.get("keyspace"), havingTable, DeletedPreagRow); } } else if (DeletedPreagRowMapSize1 != null) { vm.deleteRowJoinHaving( (String) json.get("keyspace"), havingTable, DeletedPreagRowMapSize1); } } } } } } else { System.out.println("No agg table for this reverse join table " + updatedReverseJoin + " available"); } // END OF UPDATE JoinPreag cursor += nrOfTables; } } public boolean evaluateCondition(Row row, String operation, String value, String type, String colName) { boolean eval = true; switch (type) { case "text": if (operation.equals("=")) { if (row.getString(colName).equals(value)) { eval &= true; } else { eval &= false; } } else if (operation.equals("!=")) { if (!row.getString(colName).equals(value)) { eval = true; } else { eval = false; } } break; case "varchar": if (operation.equals("=")) { if (row.getString(colName).equals(value)) { eval &= true; } else { eval &= false; } } else if (operation.equals("!=")) { if (!row.getString(colName).equals(value)) { eval &= true; } else { eval &= false; } } break; case "int": // for _new col String s1 = Integer.toString(row.getInt(colName)); Integer valueInt = new Integer(s1); int compareValue = valueInt.compareTo(new Integer(value)); if ((operation.equals(">") && (compareValue > 0))) { eval &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval &= true; } else { eval &= false; } break; case "varint": // for _new col s1 = row.getVarint(colName).toString(); valueInt = new Integer(new BigInteger(s1).intValue()); compareValue = valueInt.compareTo(new Integer(value)); if ((operation.equals(">") && (compareValue > 0))) { eval &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval &= true; } else { eval &= false; } break; case "float": break; } return eval; } }
package org.wildfly.clustering.ee.infinispan; import javax.transaction.InvalidTransactionException; import javax.transaction.NotSupportedException; import javax.transaction.RollbackException; import javax.transaction.Synchronization; import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import org.infinispan.Cache; import org.infinispan.commons.CacheException; import org.wildfly.clustering.ee.BatchContext; import org.wildfly.clustering.ee.Batcher; /** * A {@link Batcher} implementation based on Infinispan's {@link org.infinispan.batch.BatchContainer}, except that its transaction reference * is stored within the returned Batch object instead of a ThreadLocal. This also allows the user to call {@link Batch#close()} from a * different thread than the one that created the {@link Batch}. In this case, however, the user must first resume the batch * via {@link #resumeBatch(TransactionBatch)}. * @author Paul Ferraro */ public class InfinispanBatcher implements Batcher<TransactionBatch> { private static final BatchContext PASSIVE_BATCH_CONTEXT = () -> { // Do nothing }; private static final TransactionBatch NON_TX_BATCH = new TransactionBatch() { @Override public void close() { // No-op } @Override public void discard() { // No-op } @Override public Transaction getTransaction() { return null; } @Override public TransactionBatch interpose() { return this; } }; // Used to coalesce interposed transactions static final ThreadLocal<TransactionBatch> CURRENT_BATCH = new ThreadLocal<>(); private static final Synchronization CURRENT_BATCH_REMOVER = new Synchronization() { @Override public void beforeCompletion() { } @Override public void afterCompletion(int status) { CURRENT_BATCH.remove(); } }; private final TransactionManager tm; public InfinispanBatcher(Cache<?, ?> cache) { this(cache.getAdvancedCache().getTransactionManager()); } public InfinispanBatcher(TransactionManager tm) { this.tm = tm; } @Override public TransactionBatch createBatch() { if (this.tm == null) return NON_TX_BATCH; TransactionBatch batch = CURRENT_BATCH.get(); if (batch != null) { return batch.interpose(); } try { this.tm.suspend(); this.tm.begin(); Transaction tx = this.tm.getTransaction(); tx.registerSynchronization(CURRENT_BATCH_REMOVER); batch = new InfinispanBatch(tx); CURRENT_BATCH.set(batch); return batch; } catch (RollbackException | SystemException | NotSupportedException e) { throw new CacheException(e); } } @Override public BatchContext resumeBatch(TransactionBatch batch) { TransactionBatch existingBatch = CURRENT_BATCH.get(); // Trivial case - nothing to suspend/resume if (batch == existingBatch) return PASSIVE_BATCH_CONTEXT; Transaction tx = (batch != null) ? batch.getTransaction() : null; // Non-tx case, just swap thread local if ((batch == null) || (tx == null)) { CURRENT_BATCH.set(batch); return () -> { CURRENT_BATCH.set(existingBatch); }; } try { if (existingBatch != null) { Transaction existingTx = this.tm.suspend(); if (existingBatch.getTransaction() != existingTx) { throw new IllegalStateException(); } } this.tm.resume(tx); CURRENT_BATCH.set(batch); return () -> { try { this.tm.suspend(); if (existingBatch != null) { try { this.tm.resume(existingBatch.getTransaction()); CURRENT_BATCH.set(existingBatch); } catch (InvalidTransactionException e) { throw new CacheException(e); } } else { CURRENT_BATCH.remove(); } } catch (SystemException e) { throw new CacheException(e); } }; } catch (SystemException | InvalidTransactionException e) { throw new CacheException(e); } } @Override public TransactionBatch suspendBatch() { if (this.tm == null) return NON_TX_BATCH; TransactionBatch batch = CURRENT_BATCH.get(); if (batch != null) { try { Transaction tx = this.tm.suspend(); if (batch.getTransaction() != tx) { throw new IllegalStateException(); } } catch (SystemException e) { throw new CacheException(e); } finally { CURRENT_BATCH.remove(); } } return batch; } }
package edu.duke.cabig.c3pr.esb.impl; import edu.duke.cabig.c3pr.esb.*; import gov.nih.nci.cagrid.caxchange.client.CaXchangeRequestProcessorClient; import gov.nih.nci.cagrid.caxchange.context.client.CaXchangeResponseServiceClient; import gov.nih.nci.cagrid.caxchange.context.stubs.types.CaXchangeResponseServiceReference; import gov.nih.nci.caxchange.*; import org.apache.axis.types.URI; import org.apache.log4j.Logger; import org.globus.gsi.GlobusCredential; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.StringReader; import java.rmi.RemoteException; import java.util.Map; import java.util.concurrent.*; public class CaXchangeMessageBroadcasterImpl implements CCTSMessageBroadcaster, CaXchangeMessageResponseNotifier { private String caXchangeURL; //default valut. Should not change private Map messageTypesMapping; private CaXchangeMessageResponseHandlerSet messageResponseHandlers = new CaXchangeMessageResponseHandlerSet(); private DelegatedCredentialProvider delegatedCredentialProvider; private Logger log = Logger.getLogger(CaXchangeMessageBroadcasterImpl.class); private MessageWorkflowCallback messageWorkflowCallback; /** * Will just use a dummy id to broadcast message * * @param message * @throws BroadcastException */ public void broadcast(String message) throws BroadcastException { broadcast(message, "DUMMY_ID"); } /** * * will broadcast the domain object to caXchange * * @param cctsDomainObjectXML xml message * @param externalId business id of the message. You can track messages by this id * @throws BroadcastException */ public void broadcast(String cctsDomainObjectXML, String externalId) throws BroadcastException { CaXchangeRequestProcessorClient caXchangeClient = null; Credentials creds = new Credentials(); creds.setUserName("hmarwaha"); creds.setPassword("password"); try { GlobusCredential proxy = null; // if a provider is registered then use it to get credentials if (delegatedCredentialProvider != null) { log.debug("Using delegated crential provider to set credentials"); DelegatedCredential cred = delegatedCredentialProvider.provideDelegatedCredentials(); if (cred != null) { proxy = cred.getCredential(); log.debug("Found valid proxy. Using it for esb communication"); //set the delegated epr. creds.setDelegatedCredentialReference(cred.getDelegatedEPR()); } } caXchangeClient = new CaXchangeRequestProcessorClient(caXchangeURL, proxy); } catch (Exception e) { throw new BroadcastException("caXchange could not initialize caExchange client. Using URL " + caXchangeURL, e); } //marshall the bean Document messageDOM = null; try { messageDOM = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(cctsDomainObjectXML))); } catch (SAXException e) { throw new BroadcastException("caXchange could not serialize domain object", e); } catch (IOException e) { throw new BroadcastException("caXchange could not serialize domain object", e); } catch (ParserConfigurationException e) { throw new BroadcastException("caXchange could not serialize domain object", e); } CaXchangeResponseServiceReference responseRef = null; try { Message xchangeMessage = CaXchangeMessageHelper.createXchangeMessage(messageDOM); Metadata mData = new Metadata(); mData.setOperation(Operations.PROCESS); mData.setMessageType(MessageTypes.fromString((String) messageTypesMapping.get(messageDOM.getDocumentElement().getNodeName()))); mData.setExternalIdentifier(externalId); //will be removed. temp mData.setCredentials(creds); xchangeMessage.setMetadata(mData); log.debug("Sending message to caXchange"); responseRef = caXchangeClient.processRequestAsynchronously(xchangeMessage); if (messageWorkflowCallback != null) { messageWorkflowCallback.messageSendSuccessful(externalId); } } catch (RemoteException e) { log.error("caXchange could not process request", e); if (messageWorkflowCallback != null) { messageWorkflowCallback.messageSendFailed(externalId); } throw new BroadcastException("caXchange could not process message", e); } //check on the response asynchronously //only if someone is interested if (messageWorkflowCallback != null || messageResponseHandlers.size() > 0) { log.debug("Will track response from caXchange"); try { FutureTask asyncTask = new AsynchronousResponseRetreiver(new SynchronousResponseProcessor(responseRef)); //ToDo make this like a global service not single thread executor ExecutorService es = Executors.newSingleThreadExecutor(); es.submit(asyncTask); es.shutdown(); //these exceptions do not mean a message send failure } catch (URI.MalformedURIException e) { log.error(e); } catch (RemoteException e) { log.error(e); } } } public void setDelegatedCredentialProvider(DelegatedCredentialProvider delegatedCredentialProvider) { this.delegatedCredentialProvider = delegatedCredentialProvider; } public void addResponseHandler(CaXchangeMessageResponseHandler handler) { messageResponseHandlers.add(handler); } public CaXchangeMessageResponseHandlerSet getMessageResponseHandlers() { return messageResponseHandlers; } public void setMessageResponseHandlers(CaXchangeMessageResponseHandlerSet messageResponseHandlers) { this.messageResponseHandlers = messageResponseHandlers; } public String getCaXchangeURL() { return caXchangeURL; } public void setCaXchangeURL(String caXchangeURL) { this.caXchangeURL = caXchangeURL; } public void setNotificationHandler(MessageWorkflowCallback handler) { this.messageWorkflowCallback = handler; } public Map getMessageTypesMapping() { return messageTypesMapping; } public void setMessageTypesMapping(Map messageTypesMapping) { this.messageTypesMapping = messageTypesMapping; } class AsynchronousResponseRetreiver extends FutureTask { public AsynchronousResponseRetreiver(Callable callable) { super(callable); } protected void done() { try { ResponseMessage response = (ResponseMessage) get(); if (response != null) { log.debug("Received response from caXchange"); String objectId = response.getResponseMetadata().getExternalIdentifier(); log.debug("Received response from caXchange for externalId" + objectId); if (response.getResponse().getResponseStatus().equals(Statuses.SUCCESS)) { log.debug("Received delivery confirmation from caXchange"); messageWorkflowCallback.messageSendConfirmed(objectId); // notify response handlers log.debug("Notifying " + messageResponseHandlers.size() + " handlers"); messageResponseHandlers.notifyAll(objectId, response.getResponse()); } if (response.getResponse().getResponseStatus().equals(Statuses.FAILURE)) { log.debug("Received failure from caXchange"); messageWorkflowCallback.messageSendFailed(objectId); } } } catch (InterruptedException e) { log.warn(e); } catch (ExecutionException e) { log.warn(e); } //call handlers for the result } } class SynchronousResponseProcessor implements Callable { CaXchangeResponseServiceClient responseService; private long startTime; public SynchronousResponseProcessor(CaXchangeResponseServiceReference responseRef) throws org.apache.axis.types.URI.MalformedURIException, RemoteException { responseService = new CaXchangeResponseServiceClient(responseRef.getEndpointReference()); } public ResponseMessage call() throws Exception { //only run this for 60 seconds if (startTime == 0l) { startTime = System.currentTimeMillis(); } long elapsedTime = (System.currentTimeMillis() - startTime) / 1000; log.debug("Elapsed time : " + elapsedTime + " seconds"); if (elapsedTime > 60) { log.debug("Giving up. caXchange never returned a response for more than 60 seconds."); return null; } try { log.debug("Checking caXchange for response"); return responseService.getResponse(); } catch (RemoteException e) { //sleep for 3 seconds and check again Thread.sleep(3000); return call(); } } protected void finalize() throws Throwable { log.debug("Killing listening thread"); super.finalize(); //To change body of overridden methods use File | Settings | File Templates. } } }
package me.calebjones.spacelaunchnow.common.content.calendar; import android.content.Context; import android.net.Uri; import android.preference.PreferenceManager; import android.provider.CalendarContract; import com.pixplicity.easyprefs.library.Prefs; import io.realm.Realm; import io.realm.RealmList; import io.realm.RealmResults; import me.calebjones.spacelaunchnow.common.content.calendar.model.CalendarItem; import me.calebjones.spacelaunchnow.common.base.BaseManager; import me.calebjones.spacelaunchnow.common.content.util.FilterBuilder; import me.calebjones.spacelaunchnow.common.prefs.SwitchPreferences; import me.calebjones.spacelaunchnow.data.models.Constants; import me.calebjones.spacelaunchnow.data.models.Result; import me.calebjones.spacelaunchnow.data.models.main.CalendarEvent; import me.calebjones.spacelaunchnow.data.models.main.Launch; import me.calebjones.spacelaunchnow.common.content.util.QueryBuilder; import me.calebjones.spacelaunchnow.data.networking.DataClient; import me.calebjones.spacelaunchnow.data.networking.error.ErrorUtil; import me.calebjones.spacelaunchnow.data.networking.responses.base.LaunchResponse; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import timber.log.Timber; public class CalendarSyncManager extends BaseManager { public static final String SYNC_EVENTS_ALL = "me.calebjones.spacelaunchnow.content.services.action.SYNC_EVENTS_ALL"; public static final String DELETE_EVENTS_ALL = "me.calebjones.spacelaunchnow.content.services.action.DELETE_EVENTS_ALL"; public static final String SYNC_EVENT = "me.calebjones.spacelaunchnow.content.services.action.SYNC_EVENT"; public static final String DELETE_EVENT = "me.calebjones.spacelaunchnow.content.services.action.DELETE_EVENT"; public static final String RESYNC_ALL = "me.calebjones.spacelaunchnow.content.services.action.RESYNC_ALL"; public static final String EVENT_ID = "me.calebjones.spacelaunchnow.content.services.extra.EVENT_ID"; public static final String LAUNCH_ID = "me.calebjones.spacelaunchnow.content.services.extra.LAUNCH_ID"; private RealmResults<Launch> launches; private CalendarUtility calendarUtil; private CalendarItem calendarItem; public CalendarSyncManager(Context context) { super(context); calendarItem = mRealm.where(CalendarItem.class).findFirst(); if (calendarItem != null) { calendarUtil = new CalendarUtility(calendarItem); } else { Prefs.putBoolean("calendar_sync_state", false); switchPreferences.setCalendarStatus(false); } } public void resyncCalendarItem(){ calendarItem = mRealm.where(CalendarItem.class).findFirst(); calendarUtil = new CalendarUtility(calendarItem); } public void syncAllEevnts() { if (calendarUtil != null) { handleActionSyncAll(); } } public void deleteEvent(Long id) { if (calendarUtil != null) { Timber.v("Hello?"); return; } } public void deleteAllEvents() { if (calendarUtil != null) { handleActionDeleteAll(); } } public void resyncAllEvents() { if (calendarUtil != null) { handleActionDeleteAll(); handleActionSyncAll(); } } private void handleActionSyncAll() { sharedPref = PreferenceManager.getDefaultSharedPreferences(context); launches = QueryBuilder.buildUpcomingSwitchQueryForCalendar(context, mRealm); RealmList<Launch> launchResults = new RealmList<>(); int size = 5; if (launches.size() == 0){ getLaunchesFromNetwork(); } else if (launches.size() > size) { launchResults.addAll(launches.subList(0, size)); } else { launchResults.addAll(launches); } Timber.d("Found some launches! Count: %s", launchResults.size()); for (final Launch launch : launchResults) { syncCalendar(launch); } } private void getLaunchesFromNetwork() { String locationIds = null; String lspIds = null; SwitchPreferences switchPreferences = SwitchPreferences.getInstance(context); if (!switchPreferences.getAllSwitch()) { lspIds = FilterBuilder.getLSPIds(context); locationIds = FilterBuilder.getLocationIds(context); } DataClient.getInstance().getNextUpcomingLaunches(10, 0, locationIds, lspIds, new Callback<LaunchResponse>() { @Override public void onResponse(Call<LaunchResponse> call, Response<LaunchResponse> response) { if (response.isSuccessful()) { LaunchResponse launchResponse = response.body(); Timber.v("UpcomingLaunches Count: %s", launchResponse.getCount()); if (launchResponse.getLaunches() != null) { Realm mRealm = Realm.getDefaultInstance(); mRealm.executeTransaction((Realm mRealm1) -> mRealm1.copyToRealmOrUpdate(launchResponse.getLaunches())); mRealm.close(); RealmList<Launch> launchResults = new RealmList<>(); launches = QueryBuilder.buildUpcomingSwitchQueryForCalendar(context, mRealm); if (launches.size() > 10) { launchResults.addAll(launches.subList(0, 10)); } else if (launches.size() > 0) { launchResults.addAll(launches); Timber.d("Found some launches! Count: %s", launchResults.size()); for (final Launch launch : launchResults) { syncCalendar(launch); } } } } else { Timber.w("Response received: %s", response.errorBody()); } } @Override public void onFailure(Call<LaunchResponse> call, Throwable t) { Timber.e(t); } }); } private void syncCalendar(final Launch launch) { Timber.d("Syncing launch: %s %s", launch.getName(), launch); RealmResults<CalendarEvent> calendarEvents = mRealm.where(CalendarEvent.class).equalTo("launchId", launch.getId()).findAll(); if (calendarEvents.size() > 1){ for (CalendarEvent calendarEvent : calendarEvents){ calendarUtil.deleteEvent(context, calendarEvent.getId()); } createEvent(launch); } else if (calendarEvents.size() == 1) { if (!calendarUtil.updateEvent(context, launch, calendarEvents.first().getId())){ createEvent(launch); } } else { createEvent(launch); } } private void createEvent(Launch launch) { Long id = calendarUtil.addEvent(context, launch); Timber.d("Created event %d for %s", id, launch.getName()); mRealm.executeTransaction(realm -> { CalendarEvent calendarEvent = realm.createObject(CalendarEvent.class); calendarEvent.setId(id); calendarEvent.setLaunchId(launch.getId()); }); } private void handleActionDeleteAll() { RealmResults<CalendarEvent> calendarEvents = mRealm.where(CalendarEvent.class) .findAll(); for (CalendarEvent calendarEvent : calendarEvents) { Timber.d("Deleting launch event %d for %s", calendarEvent.getId(), calendarEvent.getLaunchId()); calendarUtil.deleteEvent(context, calendarEvent.getId()); mRealm.executeTransaction(realm -> calendarEvent.deleteFromRealm()); } calendarUtil.deleteAll(context); } }
package org.helioviewer.jhv; import java.awt.Desktop; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.concurrent.ExecutorService; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; import org.helioviewer.jhv.base.logging.Log; import org.helioviewer.jhv.threads.JHVExecutor; /** * Intended to be a class for static functions and fields relevant to the * application as a whole. * * @author caplins */ public class JHVGlobals { public static final String TEMP_FILENAME_DELETE_PLUGIN_FILES = "delete-plugins.tmp"; public static final String downloadURL = "http://swhv.oma.be/download/"; private static final String name = "ESA JHelioviewer"; private static String version = ""; private static String revision = ""; private static String agent = "JHV/SWHV-"; private JHVGlobals() {} public static final boolean GoForTheBroke = true; public static final int hiDpiCutoff = 1024; private static ExecutorService executorService; public static ExecutorService getExecutorService() { if (executorService == null) { executorService = JHVExecutor.getJHVWorkersExecutorService("MAIN", 10); } return executorService; } /** * @return standard read timeout */ public static int getStdReadTimeout() { return Integer.parseInt(Settings.getSingletonInstance().getProperty("connection.read.timeout")); } /** * @return standard connect timeout */ public static int getStdConnectTimeout() { return Integer.parseInt(Settings.getSingletonInstance().getProperty("connection.connect.timeout")); } /** * This function must be called prior to the first call to getJhvVersion and * getJhvRevision */ public static void determineVersionAndRevision() { File jarPath; try { jarPath = new File(JHVGlobals.class.getProtectionDomain().getCodeSource().getLocation().toURI()); Log.info(">> JHVGlobals.determineVersionAndRevision() > Look for jar file: " + jarPath.getAbsolutePath()); } catch (URISyntaxException e1) { Log.error(">> JHVGlobals.determineVersionAndRevision() > Could not open code source location: " + JHVGlobals.class.getProtectionDomain().getCodeSource().getLocation().toString()); Log.warn(">> JHVGlobals.determineVersionAndRevision() > Set version and revision to null."); return; } JarFile jarFile = null; if (jarPath.isFile()) { try { jarFile = new JarFile(jarPath); Manifest manifest = jarFile.getManifest(); Attributes mainAttributes = manifest.getMainAttributes(); version = mainAttributes.getValue("version"); revision = mainAttributes.getValue("revision"); agent += version + "." + revision + " (" + System.getProperty("os.arch") + " " + System.getProperty("os.name") + " " + System.getProperty("os.version") + ") " + System.getProperty("java.vendor") + " JRE " + System.getProperty("java.version"); System.setProperty("jhv.version", version); System.setProperty("jhv.revision", revision); } catch (IOException e) { Log.error(">> JHVGlobals.determineVersionAndRevision() > Error while reading version and revision from manifest in jar file: " + jarFile.getName(), e); } finally { if (jarFile != null) { try { jarFile.close(); } catch (IOException e) { Log.error(">> JHVGlobals.determineVersionAndRevision() > Error while closing stream to jar file: " + jarFile.getName(), e); } } } } else { Log.warn(">> JHVGlobals.determineVersionAndRevision() > Classes are not within a jar file. Set version and revision to null."); } } /** * Returns the version of JHelioviewer as found in the manifest file of the * jar archive * * @return the version or empty string if the classes are not within a jar archive * or the manifest does not contain the version */ public static String getJhvVersion() { return version; } /** * Returns the revision of JHelioviewer as found in the manifest file of the * jar archive * * @return the revision or empty string if the classes are not within a jar archive * or the manifest does not contain the revision */ public static String getJhvRevision() { return revision; } public static String getUserAgent() { return agent; } public static String getProgramName() { return name; } /** * Attempts to create the necessary directories if they do not exist. It * gets its list of directories to create from the JHVDirectory class. * * @throws SecurityException */ public static void createDirs() { JHVDirectory[] dirs = JHVDirectory.values(); for (JHVDirectory dir : dirs) { File f = dir.getFile(); if (!f.exists()) { f.mkdirs(); } } } public static void openURL(String url) { try { Desktop.getDesktop().browse(new URI(url)); } catch (Exception e) { e.printStackTrace(); } } public static void displayNotification(String msg, String openURL) { if (System.getProperty("jhv.os").equals("mac")) { try { File jarPath = new File(JHVGlobals.class.getProtectionDomain().getCodeSource().getLocation().toURI()); String[] cmd = new String[] { jarPath.getCanonicalFile().getParentFile().getParent() + "/Helpers/terminal-notifier.app/Contents/MacOS/terminal-notifier", "-message", "\"" + msg + "\"", "-execute", "open " + "\"" + openURL + "\"", "-title", "JHelioviewer" }; Log.info(">> displayNotification " + Arrays.toString(cmd)); Runtime.getRuntime().exec(cmd); } catch (Exception e) { StringWriter errors = new StringWriter(); e.printStackTrace(new PrintWriter(errors)); Log.error(">> displayNotification " + errors.toString()); } } } }
package com.github.sebhoss.contract.verifier.impl; import com.github.sebhoss.contract.verifier.ContractVerifierFactory; import com.google.inject.AbstractModule; /** * Guice module which configures the contract verifier factory. */ public final class ContractVerifierModule extends AbstractModule { @Override protected void configure() { this.bind(ContractVerifierFactory.class).to(ContextBasedContractVerifierFactory.class); } }
package com.yahoo.vespa.hosted.controller.deployment; import com.google.common.collect.ImmutableMap; import com.yahoo.component.Version; import com.yahoo.config.application.api.DeploymentInstanceSpec; import com.yahoo.config.application.api.DeploymentSpec; import com.yahoo.config.application.api.DeploymentSpec.DeclaredTest; import com.yahoo.config.application.api.DeploymentSpec.DeclaredZone; import com.yahoo.config.provision.ApplicationId; import com.yahoo.config.provision.InstanceName; import com.yahoo.config.provision.SystemName; import com.yahoo.config.provision.zone.ZoneId; import com.yahoo.vespa.hosted.controller.Application; import com.yahoo.vespa.hosted.controller.Instance; import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobId; import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobType; import com.yahoo.vespa.hosted.controller.application.Change; import com.yahoo.vespa.hosted.controller.application.Deployment; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.yahoo.config.provision.Environment.prod; import static com.yahoo.config.provision.Environment.staging; import static com.yahoo.config.provision.Environment.test; import static com.yahoo.vespa.hosted.controller.api.integration.deployment.JobType.stagingTest; import static com.yahoo.vespa.hosted.controller.api.integration.deployment.JobType.systemTest; import static java.util.Comparator.comparing; import static java.util.Comparator.naturalOrder; import static java.util.Objects.requireNonNull; import static java.util.function.BinaryOperator.maxBy; import static java.util.stream.Collectors.collectingAndThen; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.toMap; import static java.util.stream.Collectors.toUnmodifiableList; /** * Status of the deployment jobs of an {@link Application}. * * @author jonmv */ public class DeploymentStatus { public static List<JobId> jobsFor(Application application, SystemName system) { if (DeploymentSpec.empty.equals(application.deploymentSpec())) return List.of(); return application.deploymentSpec().instances().stream() .flatMap(spec -> Stream.concat(Stream.of(systemTest, stagingTest), flatten(spec).filter(step -> step.concerns(prod)) .map(step -> { if (step instanceof DeclaredZone) return JobType.from(system, prod, ((DeclaredZone) step).region().get()); return JobType.testFrom(system, ((DeclaredTest) step).region()); }) .flatMap(Optional::stream)) .map(type -> new JobId(application.id().instance(spec.name()), type))) .collect(toUnmodifiableList()); } private static Stream<DeploymentSpec.Step> flatten(DeploymentSpec.Step step) { return step instanceof DeploymentSpec.Steps ? step.steps().stream().flatMap(DeploymentStatus::flatten) : Stream.of(step); } private static <T> List<T> union(List<T> first, List<T> second) { return Stream.concat(first.stream(), second.stream()).distinct().collect(toUnmodifiableList()); } private final Application application; private final JobList allJobs; private final SystemName system; private final Version systemVersion; private final Instant now; private final Map<JobId, StepStatus> jobSteps; private final List<StepStatus> allSteps; public DeploymentStatus(Application application, Map<JobId, JobStatus> allJobs, SystemName system, Version systemVersion, Instant now) { this.application = requireNonNull(application); this.allJobs = JobList.from(allJobs.values()); this.system = requireNonNull(system); this.systemVersion = requireNonNull(systemVersion); this.now = requireNonNull(now); List<StepStatus> allSteps = new ArrayList<>(); this.jobSteps = jobDependencies(application.deploymentSpec(), allSteps); this.allSteps = List.copyOf(allSteps); } /** The application this deployment status concerns. */ public Application application() { return application; } /** A filterable list of the status of all jobs for this application. */ public JobList jobs() { return allJobs; } /** Whether any jobs of this application are failing with other errors than lack of capacity in a test zone. */ public boolean hasFailures() { return ! allJobs.failing() .not().withStatus(RunStatus.outOfCapacity) .isEmpty(); } /** All job statuses, by job type, for the given instance. */ public Map<JobType, JobStatus> instanceJobs(InstanceName instance) { return allJobs.asList().stream() .filter(job -> job.id().application().equals(application.id().instance(instance))) .collect(Collectors.toUnmodifiableMap(job -> job.id().type(), job -> job)); } /** Filterable job status lists for each instance of this application. */ public Map<ApplicationId, JobList> instanceJobs() { return allJobs.asList().stream() .collect(groupingBy(job -> job.id().application(), collectingAndThen(toUnmodifiableList(), JobList::from))); } /** * The set of jobs that need to run for the changes of each instance of the application to be considered complete, * and any test jobs for any oustanding change, which will likely be needed to lated deploy this change. */ public Map<JobId, List<Versions>> jobsToRun() { Map<InstanceName, Change> changes = new LinkedHashMap<>(); for (InstanceName instance : application.deploymentSpec().instanceNames()) changes.put(instance, application.require(instance).change()); Map<JobId, List<Versions>> jobs = jobsToRun(changes); // Add test jobs for any outstanding change. for (InstanceName instance : application.deploymentSpec().instanceNames()) changes.put(instance, outstandingChange(instance).onTopOf(application.require(instance).change())); var testJobs = jobsToRun(changes).entrySet().stream() .filter(entry -> ! entry.getKey().type().isProduction()); return Stream.concat(jobs.entrySet().stream(), testJobs) .collect(collectingAndThen(toMap(Map.Entry::getKey, Map.Entry::getValue, DeploymentStatus::union, LinkedHashMap::new), ImmutableMap::copyOf)); } /** The set of jobs that need to run for the given changes to be considered complete. */ public Map<JobId, List<Versions>> jobsToRun(Map<InstanceName, Change> changes) { Map<JobId, Versions> productionJobs = new LinkedHashMap<>(); changes.forEach((instance, change) -> productionJobs.putAll(productionJobs(instance, change))); Map<JobId, List<Versions>> testJobs = testJobs(productionJobs); Map<JobId, List<Versions>> jobs = new LinkedHashMap<>(testJobs); productionJobs.forEach((job, versions) -> jobs.put(job, List.of(versions))); // Add runs for idle, declared test jobs if they have no successes on their instance's change's versions. jobSteps.forEach((job, step) -> { if ( ! step.isDeclared() || jobs.containsKey(job)) return; Change change = changes.get(job.application().instance()); if (change == null || ! change.hasTargets()) return; Optional<JobId> firstProductionJobWithDeployment = jobSteps.keySet().stream() .filter(jobId -> jobId.type().isProduction() && jobId.type().isDeployment()) .filter(jobId -> deploymentFor(jobId).isPresent()) .findFirst(); Versions versions = Versions.from(change, application, firstProductionJobWithDeployment.flatMap(this::deploymentFor), systemVersion); if (step.completedAt(change, firstProductionJobWithDeployment).isEmpty()) jobs.merge(job, List.of(versions), DeploymentStatus::union); }); return ImmutableMap.copyOf(jobs); } /** The step status for all steps in the deployment spec of this, which are jobs, in the same order as in the deployment spec. */ public Map<JobId, StepStatus> jobSteps() { return jobSteps; } public Map<InstanceName, StepStatus> instanceSteps() { ImmutableMap.Builder<InstanceName, StepStatus> instances = ImmutableMap.builder(); for (StepStatus status : allSteps) if (status instanceof InstanceStatus) instances.put(status.instance(), status); return instances.build(); } /** The step status for all steps in the deployment spec of this, in the same order as in the deployment spec. */ public List<StepStatus> allSteps() { return allSteps; } public Optional<Deployment> deploymentFor(JobId job) { return Optional.ofNullable(application.require(job.application().instance()) .deployments().get(job.type().zone(system))); } /** * The change of this application's latest submission, if this upgrades any of its production deployments, * and has not yet started rolling out, due to some other change or a block window being present at the time of submission. */ public Change outstandingChange(InstanceName instance) { return application.latestVersion().map(Change::of) .filter(change -> application.require(instance).change().application().map(change::upgrades).orElse(true)) .filter(change -> ! jobsToRun(Map.of(instance, change)).isEmpty()) .orElse(Change.empty()); } /** * True if the job has already been triggered on the given versions, or if all test types (systemTest, stagingTest), * restricted to the job's instance if declared in that instance, have successful runs on the given versions. */ public boolean isTested(JobId job, Change change) { Versions versions = Versions.from(change, application, deploymentFor(job), systemVersion); return allJobs.triggeredOn(versions).get(job).isPresent() || Stream.of(systemTest, stagingTest) .noneMatch(testType -> declaredTest(job.application(), testType).map(__ -> allJobs.instance(job.application().instance())) .orElse(allJobs) .type(testType) .successOn(versions).isEmpty()); } /** The production jobs that need to run to complete roll-out of the given change to production. */ public Map<JobId, Versions> productionJobs(InstanceName instance, Change change) { ImmutableMap.Builder<JobId, Versions> jobs = ImmutableMap.builder(); jobSteps.forEach((job, step) -> { if ( job.application().instance().equals(instance) && job.type().isProduction() && step.completedAt(change).isEmpty()) jobs.put(job, Versions.from(change, application, deploymentFor(job), systemVersion)); }); return jobs.build(); } /** The test jobs that need to run prior to the given production deployment jobs. */ public Map<JobId, List<Versions>> testJobs(Map<JobId, Versions> jobs) { Map<JobId, List<Versions>> testJobs = new LinkedHashMap<>(); for (JobType testType : List.of(systemTest, stagingTest)) { jobs.forEach((job, versions) -> { if (job.type().isProduction() && job.type().isDeployment()) { declaredTest(job.application(), testType).ifPresent(testJob -> { if (allJobs.successOn(versions).get(testJob).isEmpty()) testJobs.merge(testJob, List.of(versions), DeploymentStatus::union); }); } }); jobs.forEach((job, versions) -> { if ( job.type().isProduction() && job.type().isDeployment() && allJobs.successOn(versions).type(testType).isEmpty() && testJobs.keySet().stream() .noneMatch(test -> test.type() == testType && testJobs.get(test).contains(versions))) testJobs.merge(firstDeclaredOrElseImplicitTest(testType), List.of(versions), DeploymentStatus::union); }); // Add runs for declared tests in instances without production jobs, if no successes exist for given change. } return ImmutableMap.copyOf(testJobs); } private JobId firstDeclaredOrElseImplicitTest(JobType testJob) { return application.deploymentSpec().instanceNames().stream() .map(name -> new JobId(application.id().instance(name), testJob)) .min(comparing(id -> !jobSteps.get(id).isDeclared())).orElseThrow(); } /** JobId of any declared test of the given type, for the given instance. */ private Optional<JobId> declaredTest(ApplicationId instanceId, JobType testJob) { JobId jobId = new JobId(instanceId, testJob); return jobSteps.get(jobId).isDeclared() ? Optional.of(jobId) : Optional.empty(); } /** A DAG of the dependencies between the primitive steps in the spec, with iteration order equal to declaration order. */ private Map<JobId, StepStatus> jobDependencies(DeploymentSpec spec, List<StepStatus> allSteps) { if (DeploymentSpec.empty.equals(spec)) return Map.of(); Map<JobId, StepStatus> dependencies = new LinkedHashMap<>(); List<StepStatus> previous = List.of(); for (DeploymentSpec.Step step : spec.steps()) previous = fillStep(dependencies, allSteps, step, previous, null); return ImmutableMap.copyOf(dependencies); } /** Adds the primitive steps contained in the given step, which depend on the given previous primitives, to the dependency graph. */ private List<StepStatus> fillStep(Map<JobId, StepStatus> dependencies, List<StepStatus> allSteps, DeploymentSpec.Step step, List<StepStatus> previous, InstanceName instance) { if (step.steps().isEmpty()) { if (instance == null) return previous; // Ignore test and staging outside all instances. if ( ! step.delay().isZero()) { StepStatus stepStatus = new DelayStatus((DeploymentSpec.Delay) step, previous, instance); allSteps.add(stepStatus); return List.of(stepStatus); } JobType jobType; StepStatus stepStatus; if (step.concerns(test) || step.concerns(staging)) { jobType = JobType.from(system, ((DeclaredZone) step).environment(), null) .orElseThrow(() -> new IllegalStateException(application + " specifies " + step + ", but this has no job in " + system)); stepStatus = JobStepStatus.ofTestDeployment((DeclaredZone) step, List.of(), this, instance, jobType, true); previous = new ArrayList<>(previous); previous.add(stepStatus); } else if (step.isTest()) { jobType = JobType.testFrom(system, ((DeclaredTest) step).region()) .orElseThrow(() -> new IllegalStateException(application + " specifies " + step + ", but this has no job in " + system)); JobType preType = JobType.from(system, prod, ((DeclaredTest) step).region()) .orElseThrow(() -> new IllegalStateException(application + " specifies " + step + ", but this has no job in " + system)); stepStatus = JobStepStatus.ofProductionTest((DeclaredTest) step, previous, this, instance, jobType, preType); previous = List.of(stepStatus); } else if (step.concerns(prod)) { jobType = JobType.from(system, ((DeclaredZone) step).environment(), ((DeclaredZone) step).region().get()) .orElseThrow(() -> new IllegalStateException(application + " specifies " + step + ", but this has no job in " + system)); stepStatus = JobStepStatus.ofProductionDeployment((DeclaredZone) step, previous, this, instance, jobType); previous = List.of(stepStatus); } else return previous; // Empty container steps end up here, and are simply ignored. JobId jobId = new JobId(application.id().instance(instance), jobType); allSteps.removeIf(existing -> existing.job().equals(Optional.of(jobId))); // Replace implicit tests with explicit ones. allSteps.add(stepStatus); dependencies.put(jobId, stepStatus); return previous; } if (step instanceof DeploymentInstanceSpec) { DeploymentInstanceSpec spec = ((DeploymentInstanceSpec) step); StepStatus instanceStatus = new InstanceStatus(spec, previous, now, application.require(spec.name()), this); instance = spec.name(); allSteps.add(instanceStatus); previous = List.of(instanceStatus); for (JobType test : List.of(systemTest, stagingTest)) { JobId job = new JobId(application.id().instance(instance), test); if ( ! dependencies.containsKey(job)) { var testStatus = JobStepStatus.ofTestDeployment(new DeclaredZone(test.environment()), List.of(), this, job.application().instance(), test, false); dependencies.put(job, testStatus); allSteps.add(testStatus); } } } if (step.isOrdered()) { for (DeploymentSpec.Step nested : step.steps()) previous = fillStep(dependencies, allSteps, nested, previous, instance); return previous; } List<StepStatus> parallel = new ArrayList<>(); for (DeploymentSpec.Step nested : step.steps()) parallel.addAll(fillStep(dependencies, allSteps, nested, previous, instance)); return List.copyOf(parallel); } public enum StepType { instance, /** A timed delay. */ delay, /** A system, staging or production test. */ test, /** A production deployment. */ deployment, } public static abstract class StepStatus { private final StepType type; private final DeploymentSpec.Step step; private final List<StepStatus> dependencies; private final InstanceName instance; private StepStatus(StepType type, DeploymentSpec.Step step, List<StepStatus> dependencies, InstanceName instance) { this.type = requireNonNull(type); this.step = requireNonNull(step); this.dependencies = List.copyOf(dependencies); this.instance = instance; } /** The type of step this is. */ public final StepType type() { return type; } /** The step defining this. */ public final DeploymentSpec.Step step() { return step; } /** The list of steps that need to be complete before this may start. */ public final List<StepStatus> dependencies() { return dependencies; } /** The instance of this. */ public final InstanceName instance() { return instance; } /** The id of the job this corresponds to, if any. */ public Optional<JobId> job() { return Optional.empty(); } /** The time at which this is, or was, complete on the given change and / or versions. */ public Optional<Instant> completedAt(Change change) { return completedAt(change, Optional.empty()); } /** The time at which this is, or was, complete on the given change and / or versions. */ abstract Optional<Instant> completedAt(Change change, Optional<JobId> dependent); /** The time at which this step is ready to run the specified change and / or versions. */ public Optional<Instant> readyAt(Change change) { return readyAt(change, Optional.empty()); } /** The time at which this step is ready to run the specified change and / or versions. */ Optional<Instant> readyAt(Change change, Optional<JobId> dependent) { return dependenciesCompletedAt(change, dependent) .map(ready -> Stream.of(blockedUntil(change), pausedUntil(), coolingDownUntil(change)) .flatMap(Optional::stream) .reduce(ready, maxBy(naturalOrder()))); } /** The time at which all dependencies completed on the given change and / or versions. */ Optional<Instant> dependenciesCompletedAt(Change change, Optional<JobId> dependent) { return dependencies.stream().allMatch(step -> step.completedAt(change, dependent).isPresent()) ? dependencies.stream().map(step -> step.completedAt(change, dependent).get()) .max(naturalOrder()) .or(() -> Optional.of(Instant.EPOCH)) : Optional.empty(); } /** The time until which this step is blocked by a change blocker. */ public Optional<Instant> blockedUntil(Change change) { return Optional.empty(); } /** The time until which this step is paused by user intervention. */ public Optional<Instant> pausedUntil() { return Optional.empty(); } /** The time until which this step is cooling down, due to consecutive failures. */ public Optional<Instant> coolingDownUntil(Change change) { return Optional.empty(); } /** Whether this step is declared in the deployment spec, or is an implicit step. */ public boolean isDeclared() { return true; } } private static class DelayStatus extends StepStatus { private DelayStatus(DeploymentSpec.Delay step, List<StepStatus> dependencies, InstanceName instance) { super(StepType.delay, step, dependencies, instance); } @Override public Optional<Instant> completedAt(Change change, Optional<JobId> dependent) { return readyAt(change, dependent).map(completion -> completion.plus(step().delay())); } } private static class InstanceStatus extends StepStatus { private final DeploymentInstanceSpec spec; private final Instant now; private final Instance instance; private final DeploymentStatus status; private InstanceStatus(DeploymentInstanceSpec spec, List<StepStatus> dependencies, Instant now, Instance instance, DeploymentStatus status) { super(StepType.instance, spec, dependencies, spec.name()); this.spec = spec; this.now = now; this.instance = instance; this.status = status; } /** * Time of completion of its dependencies, if all parts of the given change are contained in the change * for this instance, or if no more jobs should run for this instance for the given change. */ @Override public Optional<Instant> completedAt(Change change, Optional<JobId> dependent) { return ( (change.platform().isEmpty() || change.platform().equals(instance.change().platform())) && (change.application().isEmpty() || change.application().equals(instance.change().application())) || status.jobsToRun(Map.of(instance.name(), change)).isEmpty()) ? dependenciesCompletedAt(change, dependent) : Optional.empty(); } @Override public Optional<Instant> blockedUntil(Change change) { for (Instant current = now; now.plus(Duration.ofDays(7)).isAfter(current); ) { boolean blocked = false; for (DeploymentSpec.ChangeBlocker blocker : spec.changeBlocker()) { while ( blocker.window().includes(current) && now.plus(Duration.ofDays(7)).isAfter(current) && ( change.platform().isPresent() && blocker.blocksVersions() || change.application().isPresent() && blocker.blocksRevisions())) { blocked = true; current = current.plus(Duration.ofHours(1)).truncatedTo(ChronoUnit.HOURS); } } if ( ! blocked) return current == now ? Optional.empty() : Optional.of(current); } return Optional.of(now.plusSeconds(1 << 30)); // Some time in the future that doesn't look like anything you'd expect. } } private static abstract class JobStepStatus extends StepStatus { private final JobStatus job; private final DeploymentStatus status; private JobStepStatus(StepType type, DeploymentSpec.Step step, List<StepStatus> dependencies, JobStatus job, DeploymentStatus status) { super(type, step, dependencies, job.id().application().instance()); this.job = requireNonNull(job); this.status = requireNonNull(status); } @Override public Optional<JobId> job() { return Optional.of(job.id()); } @Override public Optional<Instant> pausedUntil() { return status.application().require(job.id().application().instance()).jobPause(job.id().type()); } @Override public Optional<Instant> coolingDownUntil(Change change) { if (job.lastTriggered().isEmpty()) return Optional.empty(); if (job.lastCompleted().isEmpty()) return Optional.empty(); if (job.firstFailing().isEmpty()) return Optional.empty(); Versions lastVersions = job.lastCompleted().get().versions(); if (change.platform().isPresent() && ! change.platform().get().equals(lastVersions.targetPlatform())) return Optional.empty(); if (change.application().isPresent() && ! change.application().get().equals(lastVersions.targetApplication())) return Optional.empty(); if (status.application.deploymentSpec().requireInstance(job.id().application().instance()).upgradePolicy() == DeploymentSpec.UpgradePolicy.canary) return Optional.empty(); if (job.id().type().environment().isTest() && job.isOutOfCapacity()) return Optional.empty(); Instant firstFailing = job.firstFailing().get().end().get(); Instant lastCompleted = job.lastCompleted().get().end().get(); return firstFailing.equals(lastCompleted) ? Optional.of(lastCompleted) : Optional.of(lastCompleted.plus(Duration.ofMinutes(10)) .plus(Duration.between(firstFailing, lastCompleted) .dividedBy(2))) .filter(status.now::isBefore); } private static JobStepStatus ofProductionDeployment(DeclaredZone step, List<StepStatus> dependencies, DeploymentStatus status, InstanceName instance, JobType jobType) { ZoneId zone = ZoneId.from(step.environment(), step.region().get()); JobStatus job = status.instanceJobs(instance).get(jobType); Optional<Deployment> existingDeployment = Optional.ofNullable(status.application().require(instance) .deployments().get(zone)); return new JobStepStatus(StepType.deployment, step, dependencies, job, status) { @Override public Optional<Instant> readyAt(Change change, Optional<JobId> dependent) { return super.readyAt(change, Optional.of(job.id())) .filter(__ -> status.isTested(job.id(), change)); } /** Complete if deployment is on pinned version, and last successful deployment, or if given versions is strictly a downgrade, and this isn't forced by a pin. */ @Override public Optional<Instant> completedAt(Change change, Optional<JobId> dependent) { if ( change.isPinned() && change.platform().isPresent() && ! existingDeployment.map(Deployment::version).equals(change.platform())) return Optional.empty(); Change fullChange = status.application().require(instance).change(); if (existingDeployment.map(deployment -> ! (change.upgrades(deployment.version()) || change.upgrades(deployment.applicationVersion())) && (fullChange.downgrades(deployment.version()) || fullChange.downgrades(deployment.applicationVersion()))) .orElse(false)) return job.lastCompleted().flatMap(Run::end); return job.lastSuccess() .filter(run -> change.platform().map(run.versions().targetPlatform()::equals).orElse(true) && change.application().map(run.versions().targetApplication()::equals).orElse(true)) .flatMap(Run::end); } }; } private static JobStepStatus ofProductionTest(DeclaredTest step, List<StepStatus> dependencies, DeploymentStatus status, InstanceName instance, JobType testType, JobType prodType) { JobStatus job = status.instanceJobs(instance).get(testType); return new JobStepStatus(StepType.test, step, dependencies, job, status) { @Override public Optional<Instant> completedAt(Change change, Optional<JobId> dependent) { Versions versions = Versions.from(change, status.application, status.deploymentFor(job.id()), status.systemVersion); return job.lastSuccess() .filter(run -> versions.targetsMatch(run.versions())) .filter(run -> ! status.jobs() .instance(instance) .type(prodType) .lastCompleted().endedNoLaterThan(run.start()) .isEmpty()) .map(run -> run.end().get()); } }; } private static JobStepStatus ofTestDeployment(DeclaredZone step, List<StepStatus> dependencies, DeploymentStatus status, InstanceName instance, JobType jobType, boolean declared) { JobStatus job = status.instanceJobs(instance).get(jobType); return new JobStepStatus(StepType.test, step, dependencies, job, status) { @Override public Optional<Instant> completedAt(Change change, Optional<JobId> dependent) { return RunList.from(job) .matching(run -> change.platform().map(run.versions().targetPlatform()::equals).orElse(true)) .matching(run -> change.application().map(run.versions().targetApplication()::equals).orElse(true)) .matching(run -> dependent.flatMap(status::deploymentFor) .map(deployment -> Versions.from(change, deployment)) .map(run.versions()::targetsMatch) .orElse(true)) .status(RunStatus.success) .asList().stream() .map(run -> run.end().get()) .max(naturalOrder()); } @Override public boolean isDeclared() { return declared; } }; } } }
package com.yahoo.vespa.hosted.controller.restapi.user; import com.yahoo.component.annotation.Inject; import com.yahoo.config.provision.ApplicationName; import com.yahoo.config.provision.TenantName; import com.yahoo.container.jdisc.HttpRequest; import com.yahoo.container.jdisc.HttpResponse; import com.yahoo.container.jdisc.ThreadedHttpRequestHandler; import com.yahoo.io.IOUtils; import com.yahoo.jdisc.http.filter.security.misc.User; import com.yahoo.restapi.ErrorResponse; import com.yahoo.restapi.MessageResponse; import com.yahoo.restapi.Path; import com.yahoo.restapi.SlimeJsonResponse; import com.yahoo.slime.Cursor; import com.yahoo.slime.Inspector; import com.yahoo.slime.Slime; import com.yahoo.slime.SlimeStream; import com.yahoo.slime.SlimeUtils; import com.yahoo.text.Text; import com.yahoo.vespa.configserver.flags.FlagsDb; import com.yahoo.vespa.flags.FlagSource; import com.yahoo.vespa.flags.IntFlag; import com.yahoo.vespa.flags.PermanentFlags; import com.yahoo.vespa.hosted.controller.Controller; import com.yahoo.vespa.hosted.controller.LockedTenant; import com.yahoo.vespa.hosted.controller.api.integration.billing.Plan; import com.yahoo.vespa.hosted.controller.api.integration.billing.PlanId; import com.yahoo.vespa.hosted.controller.api.integration.user.Roles; import com.yahoo.vespa.hosted.controller.api.integration.user.UserId; import com.yahoo.vespa.hosted.controller.api.integration.user.UserManagement; import com.yahoo.vespa.hosted.controller.api.role.Role; import com.yahoo.vespa.hosted.controller.api.role.RoleDefinition; import com.yahoo.vespa.hosted.controller.api.role.SecurityContext; import com.yahoo.vespa.hosted.controller.api.role.SimplePrincipal; import com.yahoo.vespa.hosted.controller.api.role.TenantRole; import com.yahoo.vespa.hosted.controller.application.TenantAndApplicationId; import com.yahoo.vespa.hosted.controller.restapi.ErrorResponses; import com.yahoo.vespa.hosted.controller.restapi.application.EmptyResponse; import com.yahoo.vespa.hosted.controller.tenant.Tenant; import com.yahoo.yolean.Exceptions; import java.security.PublicKey; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.logging.Logger; import java.util.stream.Collectors; /** * API for user management related to access control. * * @author jonmv */ @SuppressWarnings("unused") // Handler public class UserApiHandler extends ThreadedHttpRequestHandler { private final static Logger log = Logger.getLogger(UserApiHandler.class.getName()); private final UserManagement users; private final Controller controller; private final FlagsDb flagsDb; private final IntFlag maxTrialTenants; @Inject public UserApiHandler(Context parentCtx, UserManagement users, Controller controller, FlagSource flagSource, FlagsDb flagsDb) { super(parentCtx); this.users = users; this.controller = controller; this.flagsDb = flagsDb; this.maxTrialTenants = PermanentFlags.MAX_TRIAL_TENANTS.bindTo(flagSource); } @Override public HttpResponse handle(HttpRequest request) { try { Path path = new Path(request.getUri()); switch (request.getMethod()) { case GET: return handleGET(path, request); case POST: return handlePOST(path, request); case DELETE: return handleDELETE(path, request); case OPTIONS: return handleOPTIONS(); default: return ErrorResponse.methodNotAllowed("Method '" + request.getMethod() + "' is not supported"); } } catch (IllegalArgumentException e) { return ErrorResponse.badRequest(Exceptions.toMessageString(e)); } catch (RuntimeException e) { return ErrorResponses.logThrowing(request, log, e); } } private HttpResponse handleGET(Path path, HttpRequest request) { if (path.matches("/user/v1/user")) return userMetadata(request); if (path.matches("/user/v1/find")) return findUser(request); if (path.matches("/user/v1/tenant/{tenant}")) return listTenantRoleMembers(path.get("tenant")); if (path.matches("/user/v1/tenant/{tenant}/application/{application}")) return listApplicationRoleMembers(path.get("tenant"), path.get("application")); return ErrorResponse.notFoundError(Text.format("No '%s' handler at '%s'", request.getMethod(), request.getUri().getPath())); } private HttpResponse handlePOST(Path path, HttpRequest request) { if (path.matches("/user/v1/tenant/{tenant}")) return addTenantRoleMember(path.get("tenant"), request); return ErrorResponse.notFoundError(Text.format("No '%s' handler at '%s'", request.getMethod(), request.getUri().getPath())); } private HttpResponse handleDELETE(Path path, HttpRequest request) { if (path.matches("/user/v1/tenant/{tenant}")) return removeTenantRoleMember(path.get("tenant"), request); return ErrorResponse.notFoundError(Text.format("No '%s' handler at '%s'", request.getMethod(), request.getUri().getPath())); } private HttpResponse handleOPTIONS() { EmptyResponse response = new EmptyResponse(); response.headers().put("Allow", "GET,PUT,POST,PATCH,DELETE,OPTIONS"); return response; } private static final Set<RoleDefinition> hostedOperators = Set.of( RoleDefinition.hostedOperator, RoleDefinition.hostedSupporter, RoleDefinition.hostedAccountant); private HttpResponse findUser(HttpRequest request) { var email = request.getProperty("email"); var query = request.getProperty("query"); if (email != null) return userMetadataFromUserId(email); if (query != null) return userMetadataQuery(query); return ErrorResponse.badRequest("Need 'email' or 'query' parameter"); } private HttpResponse userMetadataFromUserId(String email) { var maybeUser = users.findUser(email); var slime = new Slime(); var root = slime.setObject(); var usersRoot = root.setArray("users"); if (maybeUser.isPresent()) { var user = maybeUser.get(); var roles = users.listRoles(new UserId(user.email())); renderUserMetaData(usersRoot.addObject(), user, Set.copyOf(roles)); } return new SlimeJsonResponse(slime); } private HttpResponse userMetadataQuery(String query) { var userList = users.findUsers(query); var slime = new Slime(); var root = slime.setObject(); var userSlime = root.setArray("users"); for (var user : userList) { var roles = users.listRoles(new UserId((user.email()))); renderUserMetaData(userSlime.addObject(), user, Set.copyOf(roles)); } return new SlimeJsonResponse(slime); } private HttpResponse userMetadata(HttpRequest request) { User user; if (request.getJDiscRequest().context().get(User.ATTRIBUTE_NAME) instanceof User) { user = getAttribute(request, User.ATTRIBUTE_NAME, User.class); } else { // Remove this after June 2021 (once all security filters are setting this) @SuppressWarnings("unchecked") Map<String, String> attr = (Map<String, String>) getAttribute(request, User.ATTRIBUTE_NAME, Map.class); user = new User(attr.get("email"), attr.get("name"), attr.get("nickname"), attr.get("picture")); } Set<Role> roles = getAttribute(request, SecurityContext.ATTRIBUTE_NAME, SecurityContext.class).roles(); var slime = new Slime(); renderUserMetaData(slime.setObject(), user, roles); return new SlimeJsonResponse(slime); } private void renderUserMetaData(Cursor root, User user, Set<Role> roles) { Map<TenantName, List<TenantRole>> tenantRolesByTenantName = roles.stream() .flatMap(role -> filterTenantRoles(role).stream()) .distinct() .sorted(Comparator.comparing(Role::definition).reversed()) .collect(Collectors.groupingBy(TenantRole::tenant, Collectors.toList())); // List of operator roles as defined in `hostedOperators` above List<Role> operatorRoles = roles.stream() .filter(role -> hostedOperators.contains(role.definition())) .sorted(Comparator.comparing(Role::definition)) .toList(); root.setBool("isPublic", controller.system().isPublic()); root.setBool("isCd", controller.system().isCd()); root.setBool("hasTrialCapacity", hasTrialCapacity()); toSlime(root.setObject("user"), user); Cursor tenants = root.setObject("tenants"); tenantRolesByTenantName.keySet().stream() .sorted() .forEach(tenant -> { Cursor tenantObject = tenants.setObject(tenant.value()); tenantObject.setBool("supported", hasSupportedPlan(tenant)); Cursor tenantRolesObject = tenantObject.setArray("roles"); tenantRolesByTenantName.getOrDefault(tenant, List.of()) .forEach(role -> tenantRolesObject.addString(role.definition().name())); }); if (!operatorRoles.isEmpty()) { Cursor operator = root.setArray("operator"); operatorRoles.forEach(role -> operator.addString(role.definition().name())); } UserFlagsSerializer.toSlime(root, flagsDb.getAllFlagData(), tenantRolesByTenantName.keySet(), !operatorRoles.isEmpty(), user.email()); } private HttpResponse listTenantRoleMembers(String tenantName) { if (controller.tenants().get(tenantName).isPresent()) { Slime slime = new Slime(); Cursor root = slime.setObject(); root.setString("tenant", tenantName); fillRoles(root, Roles.tenantRoles(TenantName.from(tenantName)), Collections.emptyList()); return new SlimeJsonResponse(slime); } return ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist"); } private HttpResponse listApplicationRoleMembers(String tenantName, String applicationName) { var id = TenantAndApplicationId.from(tenantName, applicationName); if (controller.applications().getApplication(id).isPresent()) { Slime slime = new Slime(); Cursor root = slime.setObject(); root.setString("tenant", tenantName); root.setString("application", applicationName); fillRoles(root, Roles.applicationRoles(TenantName.from(tenantName), ApplicationName.from(applicationName)), Roles.tenantRoles(TenantName.from(tenantName))); return new SlimeJsonResponse(slime); } return ErrorResponse.notFoundError("Application '" + id + "' does not exist"); } private void fillRoles(Cursor root, List<? extends Role> roles, List<? extends Role> superRoles) { Cursor rolesArray = root.setArray("roleNames"); for (Role role : roles) rolesArray.addString(valueOf(role)); Map<User, List<Role>> memberships = new LinkedHashMap<>(); List<Role> allRoles = new ArrayList<>(superRoles); // Membership in a super role may imply membership in a role. allRoles.addAll(roles); for (Role role : allRoles) for (User user : users.listUsers(role)) { memberships.putIfAbsent(user, new ArrayList<>()); memberships.get(user).add(role); } Cursor usersArray = root.setArray("users"); memberships.forEach((user, userRoles) -> { Cursor userObject = usersArray.addObject(); toSlime(userObject, user); Cursor rolesObject = userObject.setObject("roles"); for (Role role : roles) { Cursor roleObject = rolesObject.setObject(valueOf(role)); roleObject.setBool("explicit", userRoles.contains(role)); roleObject.setBool("implied", userRoles.stream().anyMatch(userRole -> userRole.implies(role))); } }); } private static void toSlime(Cursor userObject, User user) { if (user.name() != null) userObject.setString("name", user.name()); userObject.setString("email", user.email()); if (user.nickname() != null) userObject.setString("nickname", user.nickname()); if (user.picture() != null) userObject.setString("picture", user.picture()); userObject.setBool("verified", user.isVerified()); if (!user.lastLogin().equals(User.NO_DATE)) userObject.setString("lastLogin", user.lastLogin().format(DateTimeFormatter.ISO_DATE)); if (user.loginCount() > -1) userObject.setLong("loginCount", user.loginCount()); } private HttpResponse addTenantRoleMember(String tenantName, HttpRequest request) { Inspector requestObject = bodyInspector(request); var tenant = TenantName.from(tenantName); var user = new UserId(require("user", Inspector::asString, requestObject)); var roles = SlimeStream.fromArray(requestObject.field("roles"), Inspector::asString) .map(roleName -> Roles.toRole(tenant, roleName)) .toList(); users.addToRoles(user, roles); return new MessageResponse(user + " is now a member of " + roles.stream().map(Role::toString).collect(Collectors.joining(", "))); } private HttpResponse removeTenantRoleMember(String tenantName, HttpRequest request) { Inspector requestObject = bodyInspector(request); var tenant = TenantName.from(tenantName); var user = new UserId(require("user", Inspector::asString, requestObject)); var roles = SlimeStream.fromArray(requestObject.field("roles"), Inspector::asString) .map(roleName -> Roles.toRole(tenant, roleName)) .toList(); enforceLastAdminOfTenant(tenant, user, roles); removeDeveloperKey(tenant, user, roles); users.removeFromRoles(user, roles); controller.tenants().lockIfPresent(tenant, LockedTenant.class, lockedTenant -> { if (lockedTenant instanceof LockedTenant.Cloud cloudTenant) controller.tenants().store(cloudTenant.withInvalidateUserSessionsBefore(controller.clock().instant())); }); return new MessageResponse(user + " is no longer a member of " + roles.stream().map(Role::toString).collect(Collectors.joining(", "))); } private void enforceLastAdminOfTenant(TenantName tenantName, UserId user, List<Role> roles) { for (Role role : roles) { if (role.definition().equals(RoleDefinition.administrator)) { if (Set.of(user.value()).equals(users.listUsers(role).stream().map(User::email).collect(Collectors.toSet()))) { throw new IllegalArgumentException("Can't remove the last administrator of a tenant."); } break; } } } private void removeDeveloperKey(TenantName tenantName, UserId user, List<Role> roles) { for (Role role : roles) { if (role.definition().equals(RoleDefinition.developer)) { controller.tenants().lockIfPresent(tenantName, LockedTenant.Cloud.class, tenant -> { PublicKey key = tenant.get().developerKeys().inverse().get(new SimplePrincipal(user.value())); if (key != null) controller.tenants().store(tenant.withoutDeveloperKey(key)); }); break; } } } private boolean hasTrialCapacity() { if (! controller.system().isPublic()) return true; var existing = controller.tenants().asList().stream().map(Tenant::name).collect(Collectors.toList()); var trialTenants = controller.serviceRegistry().billingController().tenantsWithPlan(existing, PlanId.from("trial")); return maxTrialTenants.value() < 0 || trialTenants.size() < maxTrialTenants.value(); } private static Inspector bodyInspector(HttpRequest request) { return Exceptions.uncheck(() -> SlimeUtils.jsonToSlime(IOUtils.readBytes(request.getData(), 1 << 10)).get()); } private static <Type> Type require(String name, Function<Inspector, Type> mapper, Inspector object) { if ( ! object.field(name).valid()) throw new IllegalArgumentException("Missing field '" + name + "'."); return mapper.apply(object.field(name)); } private static String valueOf(Role role) { switch (role.definition()) { case administrator: return "administrator"; case developer: return "developer"; case reader: return "reader"; case headless: return "headless"; default: throw new IllegalArgumentException("Unexpected role type '" + role.definition() + "'."); } } private static Collection<TenantRole> filterTenantRoles(Role role) { if (role instanceof TenantRole tenantRole) { switch (tenantRole.definition()) { case administrator, developer, reader, hostedDeveloper: return Set.of(tenantRole); case athenzTenantAdmin: return Roles.tenantRoles(tenantRole.tenant()); } } return Set.of(); } private static <T> T getAttribute(HttpRequest request, String attributeName, Class<T> clazz) { return Optional.ofNullable(request.getJDiscRequest().context().get(attributeName)) .filter(clazz::isInstance) .map(clazz::cast) .orElseThrow(() -> new IllegalArgumentException("Attribute '" + attributeName + "' was not set on request")); } private boolean hasSupportedPlan(TenantName tenantName) { var planId = controller.serviceRegistry().billingController().getPlan(tenantName); return controller.serviceRegistry().planRegistry().plan(planId) .map(Plan::isSupported) .orElse(false); } }
package main.java.exercise; import main.java.exercise.graph.Graph; import main.java.exercise.helper.Heuristic; import main.java.exercise.helper.Point; import main.java.exercise.helper.PriorityQueue; import main.java.framework.StudentInformation; import main.java.framework.StudentSolution; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class StudentSolutionImplementation implements StudentSolution { @Override public StudentInformation provideStudentInformation() { return new StudentInformation( "Joaquin", // Vorname "Telleria", // Nachname "01408189" // Matrikelnummer ); } public double heuristicManhattanDistance(Point point1, Point point2) { // The manhattan distance is the sum of the absolute differences // it defines the distance of two points on a two dimensional grid system // The latter names allude to the grid layout of most streets on the island of Manhattan return Math.abs(point1.getX()-point2.getX()) + Math.abs(point1.getY()-point2.getY()); } public double heuristicEuclideanDistance(Point point1, Point point2) { // Euclidean distance between two points in Euclidean space is the length of a line segment between the two points. // It can be calculated from the Cartesian coordinates of the points using the Pythagorean theorem, // therefore occasionally being called the Pythagorean distance. return Math.sqrt(Math.pow(point1.getX() - point2.getX(),2) + Math.pow(point1.getY() - point2.getY(),2)); } public void aStar(Graph g, PriorityQueue q, Heuristic h, int source, int target, int[] path) { // A* find the shortest path from a source node to a target node in a directed weighted graph G=(V,A) // A Priority Queue data structure is used to help solve A* // the source node is added to the open set // In order to traverse to the next node, we will pick the node with the lowest f_score from the open set // when we pick a node, we will update the f_score of all of its neighbors // f_score = g_score + h_score. // Where g_score is the shortest known cost distance to a node and // h_score is its heuristic score(distance to end node) // Graph g -> the graph we will conduct the A* search on // PriorityQueue q -> data structure to model the open set and help pick the next node in the open set with lowest f_score // Heuristic h -> heuristic used to determine the distance of a node to the end node System.out.println("Hello A* from source: " + source + " to target: " + target + ", with total vertices: " + g.numberOfVertices() + ", and total edges: " + g.numberOfEdges() ); HashMap<Integer, Double> gScore = new HashMap<>(); // gscore = {map with default value of infinity} use the gscore map to store gscore gScore.put(source,0.0); // gScore(s) = 0 set g score of initial node to 0 HashMap<Integer,Integer> cameFrom = new HashMap<>(); // cameFrom = {an empty map} use the cameFrom map to store predecessors q.add(source,h.evaluate(source)); while(!q.isEmpty()){ int x = q.removeFirst(); if (x == target){ // if x = target then System.out.println("Found target node"); tracePath(cameFrom,x); // build the path s, . . . , predecessors_of(t), t } int[] xSuccessors = g.getSuccessors(x); System.out.println("x has " + xSuccessors.length + " successors"); for (int i = 0; i < xSuccessors.length; i++){ System.out.println("successor: " + i); double gCandidate = gScore.getOrDefault(x,Double.MAX_VALUE) + g.getEdgeWeight(x,xSuccessors[i]); System.out.println("gCandidate = " + gCandidate); } } } private void tracePath(HashMap<Integer, Integer> cameFrom, int x) { System.out.println("TODO: TRACE PATH"); } }
package io.tetrapod.core; import static io.tetrapod.protocol.core.Core.*; import static io.tetrapod.protocol.core.CoreContract.*; import io.netty.buffer.ByteBuf; import io.netty.channel.*; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.DecoderException; import io.netty.util.ReferenceCountUtil; import io.tetrapod.core.rpc.*; import io.tetrapod.core.rpc.Error; import io.tetrapod.core.web.WebRoutes; import io.tetrapod.protocol.core.*; import java.io.IOException; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import javax.net.ssl.SSLException; import org.slf4j.*; /** * Manages a tetrapod session */ abstract public class Session extends ChannelInboundHandlerAdapter { /** * Listeners of session life-cycle events */ public interface Listener { public void onSessionStart(Session ses); public void onSessionStop(Session ses); } public static interface Helper { public Dispatcher getDispatcher(); public Async dispatchRequest(RequestHeader header, Request req, Session fromSession); public List<SubscriptionAPI> getMessageHandlers(int contractId, int structId); public int getContractId(); } public static interface RelayHandler { public int getAvailableService(int contractid); public Session getRelaySession(int toId, int contractid); public void relayMessage(MessageHeader header, ByteBuf buf, boolean isBroadcast) throws IOException; public WebRoutes getWebRoutes(); public boolean validate(int entityId, long token); } protected static final Logger logger = LoggerFactory.getLogger(Session.class); protected static final Logger commsLog = LoggerFactory.getLogger("comms"); public static final byte DEFAULT_REQUEST_TIMEOUT = 30; public static final int DEFAULT_OVERLOAD_THRESHOLD = 1024 * 128; protected static final AtomicInteger sessionCounter = new AtomicInteger(); protected final int sessionNum = sessionCounter.incrementAndGet(); protected final List<Listener> listeners = new LinkedList<Listener>(); protected final Map<Integer, Async> pendingRequests = new ConcurrentHashMap<>(); protected final AtomicInteger requestCounter = new AtomicInteger(); protected final Session.Helper helper; protected final SocketChannel channel; protected final AtomicLong lastHeardFrom = new AtomicLong(System.currentTimeMillis()); protected final AtomicLong lastSentTo = new AtomicLong(System.currentTimeMillis()); protected RelayHandler relayHandler; protected int myId = 0; protected byte myType = Core.TYPE_ANONYMOUS; protected int theirId = 0; protected byte theirType = Core.TYPE_ANONYMOUS; protected int myContractId; public Session(SocketChannel channel, Session.Helper helper) { this.channel = channel; this.helper = helper; this.myContractId = helper.getContractId(); } /** * Check to see if this session is still alive and close it, if not */ // TODO: needs configurable timeouts public void checkHealth() { if (isConnected()) { final long now = System.currentTimeMillis(); if (now - lastHeardFrom.get() > 5000 || now - lastSentTo.get() > 5000) { if (theirType == TYPE_SERVICE || theirType == TYPE_TETRAPOD) logger.trace("{} Sending PING ({}/{} ms)", this, now - lastHeardFrom.get(), now - lastSentTo.get()); sendPing(); } if (now - lastHeardFrom.get() > 20000) { logger.warn("{} Timeout ({} ms)", this, now - lastHeardFrom.get()); if (theirId == myId && myId != 0) { logger.error("{} Timeout on LOOPBACK!", this); } else { close(); } } } timeoutPendingRequests(); } public void timeoutPendingRequests() { for (Entry<Integer, Async> entry : pendingRequests.entrySet()) { Async a = entry.getValue(); if (a.isTimedout()) { pendingRequests.remove(entry.getKey()); a.setResponse(ERROR_TIMEOUT); } } } abstract protected Object makeFrame(Structure header, Structure payload, byte envelope); abstract protected Object makeFrame(Structure header, ByteBuf payload, byte envelope); protected void sendPing() {} protected void sendPong() {} public Dispatcher getDispatcher() { return helper.getDispatcher(); } public int getSessionNum() { return sessionNum; } public long getLastHeardFrom() { return lastHeardFrom.get(); } protected void scheduleHealthCheck() { if (isConnected() || !pendingRequests.isEmpty()) { getDispatcher().dispatch(1, TimeUnit.SECONDS, new Runnable() { public void run() { checkHealth(); scheduleHealthCheck(); } }); } } @Override public String toString() { return String.format("%s #%d [0x%08X]", getClass().getSimpleName(), sessionNum, theirId); } protected String getStructName(int contractId, int structId) { Structure s = StructureFactory.make(contractId, structId); if (s == null) { return "Struct-" + structId; } return s.getClass().getSimpleName(); } protected void dispatchRequest(final RequestHeader header, final Request req) { helper.dispatchRequest(header, req, this).handle(new ResponseHandler() { @Override public void onResponse(Response res) { sendResponse(res, header.requestId); } }); } protected void dispatchMessage(final MessageHeader header, final Message msg) { // we need to hijack this now to prevent a race with dispatching subsequent messages if (header.structId == EntityMessage.STRUCT_ID) { if (getTheirEntityType() == Core.TYPE_TETRAPOD) { EntityMessage m = (EntityMessage) msg; setMyEntityId(m.entityId); } } // OPTIMIZE: use senderId to queue instead of using this single threaded queue final MessageContext ctx = new SessionMessageContext(header, this); getDispatcher().dispatchSequential(new Runnable() { public void run() { for (SubscriptionAPI handler : helper.getMessageHandlers(header.contractId, header.structId)) { msg.dispatch(handler, ctx); } } }); } public Response sendPendingRequest(Request req, int toId, byte timeoutSeconds, final PendingResponseHandler pendingHandler) { final Async async = sendRequest(req, toId, timeoutSeconds); async.handle(new ResponseHandler() { @Override public void onResponse(Response res) { Response pendingRes = null; try { pendingRes = pendingHandler.onResponse(res); } catch (ErrorResponseException e1) { pendingRes = Response.error(e1.errorCode); } catch (Throwable e) { logger.error(e.getMessage(), e); } finally { // finally return the pending response we were waiting on if (pendingRes == null) { pendingRes = new Error(ERROR_UNKNOWN); } if (pendingHandler.session != null) { pendingHandler.session.sendResponse(pendingRes, pendingHandler.originalRequestId); } else { sendResponse(pendingRes, pendingHandler.originalRequestId); } } } }); return Response.PENDING; } public Async sendRequest(Request req, int toId) { return sendRequest(req, toId, DEFAULT_REQUEST_TIMEOUT); } public Async sendRequest(Request req, int toId, byte timeoutSeconds) { final RequestHeader header = new RequestHeader(); header.requestId = requestCounter.incrementAndGet(); header.toId = toId; header.fromId = myId; header.timeout = timeoutSeconds; header.contractId = req.getContractId(); header.structId = req.getStructId(); header.fromType = myType; return sendRequest(req, header); } public Async sendRequest(Request req, final RequestHeader header) { final Async async = new Async(req, header, this); if (channel.isActive()) { pendingRequests.put(header.requestId, async); if (!commsLogIgnore(req)) commsLog("%s [%d] => %s (to %d)", this, header.requestId, req.dump(), header.toId); final Object buffer = makeFrame(header, req, ENVELOPE_REQUEST); if (buffer != null) { writeFrame(buffer); } else { async.setResponse(ERROR_SERIALIZATION); } } else { async.setResponse(ERROR_CONNECTION_CLOSED); } return async; } public void sendResponse(Response res, int requestId) { if (res != Response.PENDING) { if (!commsLogIgnore(res)) commsLog("%s [%d] => %s", this, requestId, res.dump()); final Object buffer = makeFrame(res, requestId); if (buffer != null) { writeFrame(buffer); } } } public Object makeFrame(Response res, int requestId) { return makeFrame(new ResponseHeader(requestId, res.getContractId(), res.getStructId()), res, ENVELOPE_RESPONSE); } public void sendBroadcastMessage(Message msg, byte toType, int toId) { if (getMyEntityId() != 0) { if (!commsLogIgnore(msg)) commsLog("%s [B] => %s (to %s:%d)", this, msg.dump(), TO_TYPES[toType], toId); final Object buffer = makeFrame(new MessageHeader(getMyEntityId(), toType, toId, msg.getContractId(), msg.getStructId()), msg, ENVELOPE_BROADCAST); if (buffer != null) { writeFrame(buffer); getDispatcher().messagesSentCounter.mark(); } } } public void sendMessage(Message msg, byte toType, int toId) { if (getMyEntityId() != 0) { if (!commsLogIgnore(msg)) commsLog("%s [M] => %s (to %s:%d)", this, msg.dump(), TO_TYPES[toType], toId); final Object buffer = makeFrame(new MessageHeader(getMyEntityId(), toType, toId, msg.getContractId(), msg.getStructId()), msg, ENVELOPE_MESSAGE); if (buffer != null) { writeFrame(buffer); getDispatcher().messagesSentCounter.mark(); } } } private volatile boolean autoFlush = true; public void setAutoFlush(boolean val) { autoFlush = val; } public void flush() { channel.flush(); } public ChannelFuture writeFrame(Object frame) { if (frame != null) { if (channel.isActive()) { lastSentTo.set(System.currentTimeMillis()); if (autoFlush) { return channel.writeAndFlush(frame); } else { return channel.write(frame); } } else { ReferenceCountUtil.release(frame); } } return null; } public static final String[] TO_TYPES = { "Unknown", "Topic", "Entity", "Alt" }; public void sendRelayedMessage(MessageHeader header, ByteBuf payload, boolean broadcast) { if (!commsLogIgnore(header.structId)) { commsLog("%s [M] ~> Message:%d %s (to %s:%d)", this, header.structId, getNameFor(header), TO_TYPES[header.toType], header.toId); } byte envelope = broadcast ? ENVELOPE_BROADCAST : ENVELOPE_MESSAGE; writeFrame(makeFrame(header, payload, envelope)); } public Async sendRelayedRequest(RequestHeader header, ByteBuf payload, Session originator, ResponseHandler handler) { final Async async = new Async(null, header, originator, handler); int origRequestId = async.header.requestId; int newRequestId = addPendingRequest(async); if (!commsLogIgnore(header.structId)) commsLog("%s [%d/%d] ~> Request:%d", this, newRequestId, origRequestId, header.structId); // making a new header lets us not worry about synchronizing the change the requestId RequestHeader newHeader = new RequestHeader(newRequestId, header.fromId, header.toId, header.fromType, header.timeout, header.version, header.contractId, header.structId); if (newHeader.toId == UNADDRESSED && theirType != TYPE_TETRAPOD) { newHeader.toId = theirId; } writeFrame(makeFrame(newHeader, payload, ENVELOPE_REQUEST)); return async; } public void sendRelayedResponse(ResponseHeader header, ByteBuf payload) { if (!commsLogIgnore(header.structId)) commsLog("%s [%d] ~> Response:%d", this, header.requestId, header.structId); writeFrame(makeFrame(header, payload, ENVELOPE_RESPONSE)); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { ctx.close(); // quieter logging for certain exceptions if (cause instanceof IOException) { if (cause instanceof SSLException) { logger.warn("{} {}", this, cause.getMessage()); return; } else if (cause.getMessage() != null) { if (cause.getMessage().equals("Connection reset by peer") || cause.getMessage().equals("Connection timed out")) { logger.info("{} {}", this, cause.getMessage()); return; } } } else if (cause instanceof DecoderException) { logger.info("{} {}", this, cause.getMessage()); return; } logger.error("{} : {} : {}", this, cause.getClass().getSimpleName(), cause.getMessage()); logger.error(cause.getMessage(), cause); } public synchronized boolean isConnected() { if (channel != null) { return channel.isActive(); } return false; } public void close() { channel.close(); } public void addSessionListener(Listener listener) { synchronized (listeners) { listeners.add(listener); } } public void removeSessionListener(Listener listener) { synchronized (listeners) { listeners.remove(listener); } } protected void fireSessionStartEvent() { logger.debug("{} Session Start", this); for (Listener l : getListeners()) { l.onSessionStart(this); } } protected void fireSessionStopEvent() { logger.debug("{} Session Stop", this); for (Listener l : getListeners()) { l.onSessionStop(this); } } private Listener[] getListeners() { synchronized (listeners) { return listeners.toArray(new Listener[0]); } } public synchronized void setMyEntityId(int entityId) { if (myId != entityId && isConnected()) { logger.debug("{} Setting my Entity {}", this, entityId); } this.myId = entityId; } public synchronized int getMyEntityId() { return myId; } public void setMyEntityType(byte type) { myType = type; } public synchronized void setTheirEntityId(int entityId) { this.theirId = entityId; } public synchronized int getTheirEntityId() { return theirId; } public synchronized byte getTheirEntityType() { return theirType; } public void setTheirEntityType(byte type) { theirType = type; } public int addPendingRequest(Async async) { int requestId = requestCounter.incrementAndGet(); pendingRequests.put(requestId, async); return requestId; } public void cancelAllPendingRequests() { for (Async a : pendingRequests.values()) { a.setResponse(ERROR_CONNECTION_CLOSED); } pendingRequests.clear(); } // /////////////////////////////////// RELAY ///////////////////////////////////// public synchronized void setRelayHandler(RelayHandler relayHandler) { this.relayHandler = relayHandler; } public String getPeerHostname() { return "Unknown"; } public boolean commsLog(String format, Object... args) { if (commsLog.isDebugEnabled()) { for (int i = 0; i < args.length; i++) { if (args[i] == this) { args[i] = String.format("%s:%d", getClass().getSimpleName().substring(0, 4), sessionNum); } } commsLog.debug(String.format(format, args)); } return true; } public String getNameFor(MessageHeader header) { return StructureFactory.getName(header.contractId, header.structId); } public boolean commsLogIgnore(Structure struct) { return commsLogIgnore(struct.getStructId()); } public boolean commsLogIgnore(int structId) { if (commsLog.isTraceEnabled()) return false; switch (structId) { case ServiceLogsRequest.STRUCT_ID: case ServiceLogsResponse.STRUCT_ID: case ServiceStatsMessage.STRUCT_ID: return true; } return !commsLog.isDebugEnabled(); } }
package mms.Pluginsystem.Impl; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.Enumeration; import java.util.LinkedList; import java.util.ResourceBundle; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import javafx.beans.binding.Bindings; import javafx.beans.property.DoubleProperty; import javafx.collections.ObservableList; import javafx.event.Event; import javafx.event.EventHandler; import javafx.event.EventType; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Pane; import javafx.scene.layout.StackPane; import javafx.scene.media.MediaPlayer; import javafx.scene.media.MediaView; import mms.Pluginsystem.ControlPlugin; import mms.Pluginsystem.MenuPlugin; import mms.Pluginsystem.Plugin; import mms.Pluginsystem.PluginHost; public class PluginController extends PluginHost implements Initializable { @FXML private StackPane stackPane; @FXML private MediaView mediaView; @FXML private MenuBar menuBar; @FXML private AnchorPane anchorPane; @FXML private MenuItem openFileMenuItem; private ControlPlugin controlPlugin; private boolean loadedControl = false, loadedMenu = false; /** * Initializes the controller class. * * @param url * @param rb */ @Override public void initialize(URL url, ResourceBundle rb) { DoubleProperty width = mediaView.fitWidthProperty(); DoubleProperty height = mediaView.fitHeightProperty(); width.bind(Bindings.selectDouble(mediaView.sceneProperty(), "width")); height.bind(Bindings.selectDouble(mediaView.sceneProperty(), "height")); //Load plugins start(); final PluginController manager = this; //Will be called on program exit Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { manager.stop(); } }); } public void start() { File[] files = new File("Plugins").listFiles(); if (files != null) { for (File f : files) { loadPlugin(f); } } //Check if one MenuPlugin is loaded, if not load default one if (!loadedMenu) { loadedPlugins.add(new DefaultMenuPlugin(this, menuBar)); } //Check if one ControlPlugin is loaded, if not load default one if (!loadedControl) { loadedPlugins.add(controlPlugin = new DefaultControlPlugin(this, anchorPane, mediaView)); } //Sort plugins (Controlplugin is first then menuPlugin then others) loadedPlugins.sort((Plugin o1, Plugin o2) -> { if (o1 instanceof ControlPlugin || o1 instanceof MenuPlugin && o2 instanceof Plugin) { return -1; } else { return 0; //TODO define loadorder for all other plugins! } }); loadedPlugins.stream().forEach(pi -> pi.start()); } public void stop() { //Stop reversed loadedPlugins.stream().collect(Collectors.toCollection(LinkedList::new)).descendingIterator().forEachRemaining(pi -> pi.stop()); } public void loadPlugin(File file) { try (JarFile jar = new JarFile(file)) { String entryName; Enumeration<JarEntry> entries = jar.entries(); //Adds jar to SystemClassPath addSoftwareLibrary(file); while (entries.hasMoreElements()) { entryName = entries.nextElement().getName(); if (entryName.endsWith(".class")) { Class cl; try (URLClassLoader loader = new URLClassLoader(new URL[]{file.toURI().toURL()})) { //Delete .class and replace / with . String className = entryName.substring(0, entryName.length() - 6).replace('/', '.'); //Load class cl = loader.loadClass(className); } //Check implemented interfaces (should implement our PluginInterface) if (ControlPlugin.class.isAssignableFrom(cl)) { if (!loadedControl) { controlPlugin = (ControlPlugin) cl.getDeclaredConstructor(PluginHost.class, AnchorPane.class, MediaView.class).newInstance(this, anchorPane, mediaView); loadedPlugins.add(controlPlugin); loadedControl = true; } else { //one ControlPlugin is already loaded! --> only one allowed throw new IllegalStateException("Only one ControlPlugin is allowed! (loaded twice)"); } } else if (MenuPlugin.class.isAssignableFrom(cl)) { if (!loadedMenu) { MenuPlugin plugin = (MenuPlugin) cl.getDeclaredConstructor(PluginHost.class, MenuBar.class).newInstance(this, menuBar); loadedPlugins.add(plugin); loadedMenu = true; } else { //one MenuPlugin is already loaded! --> only one allowed throw new IllegalStateException("Only one MenuPlugin is allowed! (loaded twice)"); } } else if (Plugin.class.isAssignableFrom(cl)) { loadedPlugins.add((Plugin) cl.getDeclaredConstructor(PluginHost.class).newInstance(this)); } } } } catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) { Logger.getLogger(PluginHost.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException ex) { Logger.getLogger(PluginController.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(PluginController.class.getName()).log(Level.SEVERE, null, ex); } } private void addSoftwareLibrary(File file) throws Exception { Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class}); method.setAccessible(true); method.invoke(ClassLoader.getSystemClassLoader(), new Object[]{file.toURI().toURL()}); } / @Override public void addToUIStack(Pane pane) { stackPane.getChildren().add(pane); } @Override public void setPlayer(MediaPlayer player) { MediaPlayer p; if ((p = mediaView.getMediaPlayer()) != null) { p.stop(); player.setVolume(mediaView.getMediaPlayer().getVolume()); } mediaView.setMediaPlayer(player); //Controlplugin is always a mediaplayerlistener! controlPlugin.onMediaPlayerChanged(player); playerListener.stream().forEach(plugin -> { plugin.onMediaPlayerChanged(player); }); } @Override public <T extends Event> void addUIEventHandler(EventType<T> eventType, EventHandler<? super T> eventHandler) { anchorPane.addEventHandler(eventType, eventHandler); } @Override public <T extends Event> void addUIEventFilter(EventType<T> eventType, EventHandler<? super T> eventFilter) { anchorPane.addEventFilter(eventType, eventFilter); } @Override public <T extends Event> void removeUIEventHandler(EventType<T> eventType, EventHandler<? super T> eventHandler) { anchorPane.removeEventHandler(eventType, eventHandler); } @Override public <T extends Event> void removeUIEventFilter(EventType<T> eventType, EventHandler<? super T> eventFilter) { anchorPane.removeEventFilter(eventType, eventFilter); } @Override public ObservableList<Menu> getMenus() { return menuBar.getMenus(); } / }
package model.supervised.naivebayes; import data.DataSet; import model.Predictable; import model.Trainable; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import utils.array.ArraySumUtil; import utils.random.RandomUtils; import utils.sort.SortIntDoubleUtils; import java.util.HashMap; public abstract class NaiveBayes implements Predictable, Trainable{ private static final Logger log = LogManager.getLogger(NaiveBayes.class); protected DataSet data = null; protected int featureLength = Integer.MIN_VALUE; protected HashMap<Integer, Object> indexClassMap = null; protected int classCount = Integer.MIN_VALUE; private double[] priors = null; // protected abstract double[] predictClassProbability(double[] features); protected abstract void naiveBayesTrain(); protected abstract void naiveBayesInit(); // @Override public double predict(double[] feature) { double[] probabilities = probs(feature); int[] indexes = RandomUtils.getIndexes(classCount); SortIntDoubleUtils.sort(indexes, probabilities); return indexes[indexes.length - 1]; } @Override public double[] probs(double[] feature) { double[] probabilities = predictClassProbability(feature); for (int i = 0; i < classCount; i++) { probabilities[i] += Math.log(priors[i]); } return ArraySumUtil.normalize(probabilities); } @Override public double score(double[] feature) { double[] probabilities = predictClassProbability(feature); double score = probabilities[1] - probabilities[0]; return score; } @Override public void train() { for (int category : indexClassMap.keySet()) { priors[category] = data.getCategoryProportion(category); } naiveBayesTrain(); } @Override public void initialize(DataSet d) { data = d; featureLength = d.getFeatureLength(); indexClassMap = d.getLabels().getIndexClassMap(); classCount = indexClassMap.size(); priors = new double[classCount]; naiveBayesInit(); log.info("Naive Bayes Model initializing, classCount: {}", classCount); } }
package api.webservice; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import api.beans.request.ChangePasswordTokenBeanRequest; import api.beans.request.DumpObjectRequest; import api.beans.request.InitTokenBeanRequest; import api.beans.request.InitUserPasswordTokenBeanRequest; import api.beans.response.KeyPairBeanResponse; import api.beans.response.RandomBeanResponse; import api.beans.response.SecretKeyBeanResponse; import api.beans.response.TokenInfoResponse; import api.beans.response.TokenMechanismsBeanResponse; import api.beans.response.DumpTokenBeanResponse; import api.beans.response.ListTokenBeanResponse; import api.webservice.implementation.TokenMechanismWebServiceImplementation; import api.webservice.implementation.TokenWebServiceImplementation; @Path("token") public class TokenWebService { @GET @Produces({ MediaType.APPLICATION_JSON }) @Path("info/{idToken}") public TokenInfoResponse tokenInfos(@Context HttpServletRequest req, @PathParam("idToken") int idToken, @QueryParam("select") List<String> select) { return new TokenWebServiceImplementation().tokenInfos(req, idToken, select); } @PUT @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @Path("init/{idToken}") public Response init(@Context HttpServletRequest req, InitTokenBeanRequest r, @PathParam("idToken") int idToken) { return new TokenWebServiceImplementation().init(req, r, idToken); } @PUT @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @Path("reset/{idToken}") public Response reset(@Context HttpServletRequest req, InitTokenBeanRequest r, @PathParam("idToken") int idToken) { return new TokenWebServiceImplementation().reset(req, r, idToken); } @PUT @Consumes({ MediaType.APPLICATION_JSON }) @Path("changePW/{idToken}") public Response changePassword(@Context HttpServletRequest req, ChangePasswordTokenBeanRequest r, @PathParam("idToken") int idToken) { return new TokenWebServiceImplementation().changePassword(req, r, idToken); } @PUT @Consumes({ MediaType.APPLICATION_JSON }) @Path("initUserPin/{idToken}") public Response initUserPin(@Context HttpServletRequest req, InitUserPasswordTokenBeanRequest r, @PathParam("idToken") int idToken) { return new TokenWebServiceImplementation().initUserPin(req, r, idToken); } @GET @Produces({ MediaType.APPLICATION_JSON }) @Path("mechanisms/{idToken}") public TokenMechanismsBeanResponse tokenMechanisms(@Context HttpServletRequest req, @PathParam("idToken") int idToken, @QueryParam("select") List<String> select) { return new TokenMechanismWebServiceImplementation().tokenMechanisms(req, idToken, select); } @GET @Produces({ MediaType.APPLICATION_JSON }) @Path("SecretKey/{idToken}") public SecretKeyBeanResponse genSecretKey(@Context HttpServletRequest req, @PathParam("idToken") int idToken) { return new TokenMechanismWebServiceImplementation().genSecretKey(req, idToken); } @GET @Produces({ MediaType.APPLICATION_JSON }) @Path("KeyPair/{idToken}") public KeyPairBeanResponse genKeyPair(@Context HttpServletRequest req, @PathParam("idToken") int idToken) { return new TokenMechanismWebServiceImplementation().genKeyPair(req, idToken); } @GET @Produces({ MediaType.APPLICATION_JSON }) @Path("random/{idToken}/{nbByte}") public RandomBeanResponse tokenGetRandom(@Context HttpServletRequest req, @PathParam("idToken") int idToken, @PathParam("nbByte") int nbByte) { return new TokenWebServiceImplementation().tokenGetRandom(req, idToken, nbByte); } @GET @Produces({ MediaType.APPLICATION_JSON }) @Path("object/{idToken}/") public ListTokenBeanResponse listObject(@Context HttpServletRequest req, @PathParam("idToken") int idToken) { return new TokenWebServiceImplementation().listObject(req, idToken); } @PUT @Produces({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_JSON }) @Path("object/dump/{idToken}/") public DumpTokenBeanResponse tokenDumpObject(@Context HttpServletRequest req, DumpObjectRequest rb, @PathParam("idToken") int idToken) { return new TokenWebServiceImplementation().tokenDumpObject(req, rb, idToken); } @DELETE @Path("object/{idToken}/{handleObject}") public Response tokenDumpObject(@Context HttpServletRequest req, @PathParam("idToken") int idToken, @PathParam("handleObject") int handleObject) { return new TokenWebServiceImplementation().deleteObject(req, idToken, handleObject); } }
package com.akiban.sql.pg; import com.akiban.ais.model.Column; import com.akiban.ais.model.UserTable; import com.akiban.qp.operator.QueryContext; import com.akiban.qp.persistitadapter.PValueRowDataCreator; import com.akiban.server.api.dml.scan.NewRow; import com.akiban.server.api.dml.scan.NiceRow; import com.akiban.server.rowdata.RowDef; import com.akiban.server.types.AkType; import com.akiban.server.types.FromObjectValueSource; import com.akiban.server.types.ToObjectValueTarget; import com.akiban.server.types.conversion.Converters; import com.akiban.server.types.util.ValueHolder; import com.akiban.server.types3.ErrorHandlingMode; import com.akiban.server.types3.TExecutionContext; import com.akiban.server.types3.TInstance; import com.akiban.server.types3.Types3Switch; import com.akiban.server.types3.mcompat.mtypes.MString; import com.akiban.server.types3.pvalue.PValue; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.nio.charset.UnsupportedCharsetException; import java.util.Arrays; import java.util.Collections; import java.util.List; public class CsvRowReader { private final RowDef rowDef; private final int[] fieldMap; private final boolean[] nullable; private final CsvFormat format; private final int delim, quote, escape, nl, cr; private final byte[] nullBytes; private final int tableId; private final boolean usePValues; private final PValue pstring; private final PValue[] pvalues; private final PValueRowDataCreator pvalueCreator; private final TExecutionContext[] executionContexts; private final FromObjectValueSource fromObject; private final ValueHolder holder; private final ToObjectValueTarget toObject; private AkType[] aktypes; private NewRow row; private enum State { ROW_START, FIELD_START, IN_FIELD, IN_QUOTE, AFTER_QUOTE }; private State state; private byte[] buffer = new byte[128]; private int fieldIndex, fieldLength; public CsvRowReader(UserTable table, List<Column> columns, CsvFormat format, QueryContext queryContext) { this.tableId = table.getTableId(); this.rowDef = table.rowDef(); this.fieldMap = new int[columns.size()]; this.nullable = new boolean[fieldMap.length]; for (int i = 0; i < fieldMap.length; i++) { Column column = columns.get(i); fieldMap[i] = column.getPosition(); nullable[i] = column.getNullable(); } this.format = format; this.delim = format.getDelimiterByte(); this.quote = format.getQuoteByte(); this.escape = format.getEscapeByte(); this.nl = format.getNewline(); this.cr = format.getReturn(); this.nullBytes = format.getNullBytes(); this.usePValues = Types3Switch.ON; if (usePValues) { pstring = new PValue(MString.VARCHAR.instance(Integer.MAX_VALUE, false)); pvalues = new PValue[columns.size()]; executionContexts = new TExecutionContext[pvalues.length]; List<TInstance> inputs = Collections.singletonList(pstring.tInstance()); for (int i = 0; i < pvalues.length; i++) { TInstance output = columns.get(i).tInstance(); pvalues[i] = new PValue(output); // TODO: Only needed until every place gets type from // PValueTarget, when there can just be one // TExecutionContext wrapping the QueryContext. executionContexts[i] = new TExecutionContext(null, inputs, output, queryContext, ErrorHandlingMode.WARN, ErrorHandlingMode.WARN, ErrorHandlingMode.WARN); } pvalueCreator = new PValueRowDataCreator(); fromObject = null; holder = null; toObject = null; aktypes = null; } else { fromObject = new FromObjectValueSource(); holder = new ValueHolder(); toObject = new ToObjectValueTarget(); aktypes = new AkType[columns.size()]; for (int i = 0; i < aktypes.length; i++) { aktypes[i] = columns.get(i).getType().akType(); } pstring = null; pvalues = null; pvalueCreator = null; executionContexts = null; } } public NewRow nextRow(InputStream inputStream) throws IOException { int lb = inputStream.read(); if (lb < 0) return null; row = new NiceRow(tableId, rowDef); state = State.ROW_START; fieldIndex = fieldLength = 0; while (true) { int b = lb; if (b < 0) b = inputStream.read(); else lb = -1; switch (state) { case ROW_START: if (b < 0) { return null; } else if ((b == cr) || (b == nl)) { continue; } else if (b == delim) { addField(false); state = State.FIELD_START; } else if (b == quote) { state = State.IN_QUOTE; } else { addToField(b); state = State.IN_FIELD; } break; case FIELD_START: if ((b < 0) || (b == cr) || (b == nl)) { addField(false); return row; } else if (b == delim) { addField(false); } else if (b == quote) { state = State.IN_QUOTE; } else { addToField(b); state = State.IN_FIELD; } break; case IN_FIELD: if ((b < 0) || (b == cr) || (b == nl)) { addField(false); return row; } else if (b == delim) { addField(false); state = State.FIELD_START; } else if (b == quote) { throw new IOException("QUOTE in the middle of a field"); } else { addToField(b); } break; case IN_QUOTE: if (b < 0) throw new IOException("EOF inside QUOTE"); else if (b == quote) { if (escape == quote) { // Must be doubled; peek next character. lb = inputStream.read(); if (lb == quote) { addToField(b); lb = -1; continue; } } state = State.AFTER_QUOTE; } else if (b == escape) { // Non-doubling escape. b = inputStream.read(); if (b < 0) throw new IOException("EOF after ESCAPE"); addToField(b); } else { addToField(b); } break; case AFTER_QUOTE: if ((b < 0) || (b == cr) || (b == nl)) { addField(true); return row; } else if (b == delim) { addField(true); state = State.FIELD_START; } else { throw new IOException("junk after quoted field"); } break; } } } private void addToField(int b) { if (fieldLength + 1 > buffer.length) { buffer = Arrays.copyOf(buffer, (buffer.length * 3) / 2); } buffer[fieldLength++] = (byte)b; } private void addField(boolean quoted) { if (!quoted && nullable[fieldIndex]) { // Check whether unquoted value matches the representation // of null, normally the empty string. if (fieldLength == nullBytes.length) { boolean match = true; for (int i = 0; i < fieldLength; i++) { if (buffer[i] != nullBytes[i]) { match = false; break; } } if (match) { row.put(fieldMap[fieldIndex++], null); fieldLength = 0; return; } } } int columnIndex = fieldMap[fieldIndex]; // bytes -> string -> parsed typed value -> Java object. String string; try { string = new String(buffer, 0, fieldLength, format.getEncoding()); } catch (UnsupportedEncodingException ex) { UnsupportedCharsetException nex = new UnsupportedCharsetException(format.getEncoding()); nex.initCause(ex); throw nex; } if (usePValues) { pstring.putString(string, null); PValue pvalue = pvalues[fieldIndex]; pvalue.tInstance().typeClass() .fromObject(executionContexts[fieldIndex], pstring, pvalue); pvalueCreator.put(pvalue, row, rowDef.getFieldDef(columnIndex), columnIndex); } else { fromObject.setExplicitly(string, AkType.VARCHAR); holder.expectType(aktypes[fieldIndex]); Converters.convert(fromObject, holder); row.put(columnIndex, toObject.convertFromSource(holder)); } fieldIndex++; fieldLength = 0; } }
package T145.magistics.blocks; import javax.annotation.Nullable; import T145.magistics.Magistics; import T145.magistics.api.logic.IFacing; import T145.magistics.api.variants.IVariant; import T145.magistics.lib.managers.InventoryManager; import T145.magistics.tiles.MTileInventory; import net.minecraft.block.Block; import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public abstract class MBlock<T extends Enum<T> & IVariant> extends Block implements ITileEntityProvider { public final PropertyEnum<T> VARIANT; public final T[] VARIANT_VALUES; protected static IProperty[] tempVariants; private class MBlockItem extends ItemBlock { public MBlockItem(Block block, boolean hasVariants) { super(block); setHasSubtypes(hasVariants); } @Override public int getMetadata(int meta) { return meta; } @Override public String getUnlocalizedName(ItemStack stack) { String name = super.getUnlocalizedName(); if (hasSubtypes) { name += "." + VARIANT_VALUES[stack.getMetadata()].getName(); } return name; } } public MBlock(String name, Material material, Class variants) { super(createProperties(material, variants)); if (variants == Object.class || variants == null) { VARIANT = null; VARIANT_VALUES = null; } else { VARIANT = PropertyEnum.create("variant", variants); VARIANT_VALUES = VARIANT.getValueClass().getEnumConstants(); setDefaultState(blockState.getBaseState().withProperty(VARIANT, VARIANT_VALUES[0])); } setRegistryName(new ResourceLocation(Magistics.MODID, name)); setUnlocalizedName(name); setCreativeTab(Magistics.TAB); GameRegistry.register(this); if (VARIANT != null && VARIANT_VALUES != null) { GameRegistry.register(new MBlockItem(this, true), getRegistryName()); for (T variant : VARIANT_VALUES) { TileEntity tile = createNewTileEntity(Minecraft.getMinecraft().world, variant.ordinal()); if (tile != null) { isBlockContainer = true; Class tileClass = tile.getClass(); GameRegistry.registerTileEntity(tileClass, tileClass.getSimpleName()); } } } else { GameRegistry.register(new MBlockItem(this, false), getRegistryName()); TileEntity tile = createNewTileEntity(Minecraft.getMinecraft().world, 0); if (isBlockContainer = tile != null) { Class tileClass = tile.getClass(); GameRegistry.registerTileEntity(tileClass, tileClass.getSimpleName()); } } } public MBlock(String name, Material material) { this(name, material, Object.class); } protected static Material createProperties(Material material, Class variants) { tempVariants = null; if (variants != Object.class) { tempVariants = new IProperty[] { PropertyEnum.create("variant", variants) }; } return material; } @Override @SideOnly(Side.CLIENT) public void getSubBlocks(Item item, CreativeTabs tab, NonNullList<ItemStack> list) { if (VARIANT != null) { for (T variant : VARIANT_VALUES) { list.add(new ItemStack(item, 1, variant.ordinal())); } } else { super.getSubBlocks(item, tab, list); } } @Override public int damageDropped(IBlockState state) { return getMetaFromState(state); } @Override public IBlockState getStateFromMeta(int meta) { if (VARIANT == null) { return super.getStateFromMeta(meta); } if (meta < VARIANT_VALUES.length) { return getDefaultState().withProperty(VARIANT, VARIANT_VALUES[meta]); } return getDefaultState(); } @Override public int getMetaFromState(IBlockState state) { return VARIANT == null ? super.getMetaFromState(state) : state.getValue(VARIANT).ordinal(); } @Override protected BlockStateContainer createBlockState() { if (VARIANT == null) { if (tempVariants == null) { return super.createBlockState(); } return new BlockStateContainer(this, tempVariants); } return new BlockStateContainer(this, new IProperty[] { VARIANT }); } public IProperty[] getVariants() { return new IProperty[] { VARIANT == null ? null : VARIANT }; } public boolean hasVariants() { return getVariants() != null; } public String getVariantName(IBlockState state) { if (VARIANT == null) { String name = state.getBlock().getUnlocalizedName(); return name.substring(name.indexOf(".") + 1); } return state.getValue(VARIANT).getName(); } public boolean isVariant(IBlockState state, IVariant type) { if (VARIANT == null) { return false; } return state.getValue(VARIANT) == type; } @Override public abstract TileEntity createNewTileEntity(World world, int meta); @Override public boolean hasTileEntity(IBlockState state) { return isBlockContainer; } @Override @Nullable public TileEntity createTileEntity(World world, IBlockState state) { if (isBlockContainer) { return ((ITileEntityProvider) this).createNewTileEntity(world, getMetaFromState(state)); } return null; } @Override public void onBlockPlacedBy(World world, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) { TileEntity tile = world.getTileEntity(pos); if (tile != null && tile instanceof IFacing) { ((IFacing) tile).setFacingFromEntity(placer); } } @Override public void breakBlock(World world, BlockPos pos, IBlockState state) { TileEntity tile = world.getTileEntity(pos); if (tile != null && tile instanceof MTileInventory) { InventoryManager.dropInventory((MTileInventory) tile, world, state, pos); } super.breakBlock(world, pos, state); } @Override public boolean eventReceived(IBlockState state, World world, BlockPos pos, int id, int param) { super.eventReceived(state, world, pos, id, param); TileEntity tile = world.getTileEntity(pos); return tile == null ? false : tile.receiveClientEvent(id, param); } }