answer
stringlengths
17
10.2M
package org.osiam.client.minimalUser; import java.util.Date; import org.osiam.resources.helper.JsonDateSerializer; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonSerialize; /** * represents the basic Data of a scim User * */ @JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY) @JsonIgnoreProperties({"link", "gender", "timezone", "verified"}) public class BasicUser { private String id; private String name; @JsonProperty("first_name") private String firstName; @JsonProperty("last_name") private String lastName; private String userName; private String email; private String locale; @JsonProperty("updated_time") @JsonSerialize(using = JsonDateSerializer.class) private Date updatedTime; private BasicUser() { } /** * * @return the id of the User */ public String getId(){ return id; } /** * * @return the formatted name property */ public String getName() { if(name == null){ name = ""; } return name; } /** * * @return the given name of the User */ public String getFirstName(){ if(firstName == null){ firstName = ""; } return firstName; } /** * * @return the last name of the User */ public String getLastName(){ if(lastName == null){ lastName = ""; } return lastName; } /** * * @return the primary email address of the user */ public String getEmail(){ if(email == null){ email = ""; } return email; } /** * * @return the userName of the User */ public String getUserName() { return userName; } /** * * @return the date where the USer was last updated */ public Date getUpdatedTime(){ return updatedTime; } /** * * @return the local setting of the user */ public String getLocale() { if(locale == null){ locale = ""; } return locale; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((email == null) ? 0 : email.hashCode()); result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); result = prime * result + ((locale == null) ? 0 : locale.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((updatedTime == null) ? 0 : updatedTime.hashCode()); result = prime * result + ((userName == null) ? 0 : userName.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; } BasicUser other = (BasicUser) obj; if (email == null) { if (other.email != null) { return false; } } else if (!email.equals(other.email)) { return false; } if (firstName == null) { if (other.firstName != null) { return false; } } else if (!firstName.equals(other.firstName)) { return false; } if (id == null) { if (other.id != null) { return false; } } else if (!id.equals(other.id)) { return false; } if (lastName == null) { if (other.lastName != null) { return false; } } else if (!lastName.equals(other.lastName)) { return false; } if (locale == null) { if (other.locale != null) { return false; } } else if (!locale.equals(other.locale)) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } if (updatedTime == null) { if (other.updatedTime != null) { return false; } } else if (!updatedTime.equals(other.updatedTime)) { return false; } if (userName == null) { if (other.userName != null) { return false; } } else if (!userName.equals(other.userName)) { return false; } return true; } }
package org.owasp.esapi.filters; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.owasp.esapi.ESAPI; /** * This filter wraps the incoming request and outgoing response and overrides * many methods with safer versions. Many of the safer versions simply validate * parts of the request or response for unwanted characters before allowing the * call to complete. Some examples of attacks that use these * vectors include request splitting, response splitting, and file download * injection. Attackers use techniques like CRLF injection and null byte injection * to confuse the parsing of requests and responses. */ public class SafeHTTPFilter implements Filter { /** * * @param request * @param response * @param chain * @throws java.io.IOException * @throws javax.servlet.ServletException */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { chain.doFilter(request, response); return; } HttpServletRequest hrequest = (HttpServletRequest)request; HttpServletResponse hresponse = (HttpServletResponse)response; ESAPI.httpUtilities().setCurrentHTTP(hrequest, hresponse); chain.doFilter(ESAPI.currentRequest(), ESAPI.currentResponse()); } public void destroy() { // no special action } /** * * @param filterConfig * @throws javax.servlet.ServletException */ public void init(FilterConfig filterConfig) throws ServletException { // no special action } }
package org.powertac.server; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Session; import javax.jms.TextMessage; import org.apache.log4j.Logger; import org.powertac.common.Broker; import org.powertac.common.XMLMessageConverter; import org.powertac.common.interfaces.BrokerMessageListener; import org.powertac.common.interfaces.BrokerProxy; import org.powertac.common.interfaces.VisualizerProxy; import org.powertac.common.repo.BrokerRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.core.MessageCreator; import org.springframework.stereotype.Service; @Service public class BrokerProxyService implements BrokerProxy { static private Logger log = Logger.getLogger(BrokerProxyService.class); @Autowired private JmsTemplate template; @Autowired private XMLMessageConverter converter; @Autowired private BrokerRepo brokerRepo; @Autowired private MessageRouter router; @Autowired private MessageListenerRegistrar registrar; @Autowired private VisualizerProxy visualizerProxyService; // Deferred messages during initialization boolean deferredBroadcast = false; ArrayList<Object> deferredMessages; public BrokerProxyService () { super(); deferredMessages = new ArrayList<Object>(); } /* * (non-Javadoc) * * @see * org.powertac.common.interfaces.BrokerProxy#sendMessage(org.powertac.common * .Broker, java.lang.Object) */ @Override public void sendMessage (Broker broker, Object messageObject) { // dispatch to visualizers, but only if we're actually going to send // to the broker. if (broker.isEnabled()) visualizerProxyService.forwardMessage(messageObject); localSendMessage(broker, messageObject); } // break out the actual sending to prevent visualizer getting multiple // copies of broadcast messages private void localSendMessage (Broker broker, Object messageObject) { // don't communicate with non-enabled brokers if (!broker.isEnabled()) { log.warn("broker " + broker.getUsername() + " is disabled"); return; } // route to local brokers if (broker.isLocal()) { broker.receiveMessage(messageObject); } else { final String text = converter.toXML(messageObject); log.info("sending text: \n" + text); final String queueName = broker.toQueueName(); template.send(queueName, new MessageCreator() { @Override public Message createMessage (Session session) throws JMSException { TextMessage message = session.createTextMessage(text); return message; } }); } } /* * (non-Javadoc) * * @see * org.powertac.common.interfaces.BrokerProxy#sendMessages(org.powertac.common * .Broker, java.util.List) */ @Override public void sendMessages (Broker broker, List<?> messageObjects) { for (Object message : messageObjects) { sendMessage(broker, message); } } /* * (non-Javadoc) * * @see * org.powertac.common.interfaces.BrokerProxy#broadcastMessage(java.lang.Object * ) */ @Override public void broadcastMessage (Object messageObject) { if (deferredBroadcast) { deferredMessages.add(messageObject); return; } // dispatch to visualizers visualizerProxyService.forwardMessage(messageObject); Collection<Broker> brokers = brokerRepo.list(); for (Broker broker : brokers) { // let's be JMS provider neutral and not take advance of special queues in // ActiveMQ // if we have JMS performance issue, we will look into optimization using // ActiveMQ special queues. localSendMessage(broker, messageObject); } } /* * (non-Javadoc) * * @see * org.powertac.common.interfaces.BrokerProxy#broadcastMessages(java.util. * List) */ @Override public void broadcastMessages (List<?> messageObjects) { for (Object message : messageObjects) { broadcastMessage(message); } } /* * (non-Javadoc) * * @see * org.powertac.common.interfaces.BrokerProxy#routeMessage(java.lang.Object) */ @Override public void routeMessage (Object message) { if (router.route(message)) { // dispatch to visualizers visualizerProxyService.forwardMessage(message); } } /* * (non-Javadoc) * * @see * org.powertac.common.interfaces.BrokerProxy#registerBrokerMarketListener * (org.powertac.common.interfaces.BrokerMessageListener) */ @Override public void registerBrokerMarketListener (BrokerMessageListener listener) { registrar.registerBrokerMarketListener(listener); } /* * (non-Javadoc) * * @see * org.powertac.common.interfaces.BrokerProxy#registerBrokerTariffListener * (org.powertac.common.interfaces.BrokerMessageListener) */ @Override public void registerBrokerTariffListener (BrokerMessageListener listener) { registrar.registerBrokerTariffListener(listener); } /* * (non-Javadoc) * * @see * org.powertac.common.interfaces.BrokerProxy#registerSimListener(org.powertac * .common.interfaces.BrokerMessageListener) */ @Override public void registerSimListener (BrokerMessageListener listener) { registrar.registerSimListener(listener); } /* * (non-Javadoc) * * @see * org.powertac.common.interfaces.BrokerProxy#setDeferredBroadcast(boolean) */ @Override public void setDeferredBroadcast (boolean b) { deferredBroadcast = b; } /* * (non-Javadoc) * * @see org.powertac.common.interfaces.BrokerProxy#broadcastDeferredMessages() */ @Override public void broadcastDeferredMessages () { deferredBroadcast = false; log.info("broadcasting " + deferredMessages.size() + " deferred messages"); broadcastMessages(deferredMessages); deferredMessages.clear(); } }
package org.redline_rpm; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; /** * Wrapper for observing data read from a NIO channel. This wrapper is * used for operations that must be notified of incoming IO data. */ public class ReadableChannelWrapper extends ChannelWrapper implements ReadableByteChannel { protected ReadableByteChannel channel; public ReadableChannelWrapper( final ReadableByteChannel channel) { this.channel = channel; } /** * Reads data from the channel and passes it to the consumer. This method * does not mutate the acutal data in the provided buffer, but makes it's * own copy to pass to the consumer. * * @param buffer the buffer to read into * @return the number of bytes read from the underlying channel * @throws IOException if an IO error occurrs */ public int read( final ByteBuffer buffer) throws IOException { final int read = channel.read( buffer); for ( Consumer< ?> consumer : consumers.values()) consumer.consume(( ByteBuffer) buffer.duplicate().flip()); return read; } /** * Close the underlying read channel and complete any operations in the * consumer. * * @throws IOException if an IO error occurrs */ public void close() throws IOException { channel.close(); super.close(); } /** * Boolean flag indicating whether the channel is open or closed. * * @return true if the channel is open, false if not */ public boolean isOpen() { return channel.isOpen(); } }
package org.shmztko.recorder; import java.util.List; import java.util.logging.Logger; import org.shmztko.accessor.PageAccessor; import org.shmztko.accessor.RemotePageAccessor; import org.shmztko.common.LogFactory; import org.shmztko.model.Award; import org.shmztko.model.Record; import org.shmztko.model.Statistic; import org.shmztko.model.User; import org.shmztko.parser.DartsLiveParser; import org.shmztko.utils.DateUtils; /** * DartsLive * @author ShimizuTakeo */ public class DartsLiveRecorder { private static final Logger LOG = LogFactory.getLogger(DartsLiveRecorder.class); private PageAccessor accessor; /** * @param accessor */ public void setPageAccessor(PageAccessor accessor) { this.accessor = accessor; } /** * * @param user */ public void record(User user) { if (accessor == null) { accessor = new RemotePageAccessor(user); } DartsLiveParser parser = new DartsLiveParser(accessor); List<Statistic> stats = parser.getYesterdayStats(); List<Award> awards = parser.getYesterdayAwards(); if (stats.isEmpty() && awards.isEmpty()) { LOG.info("No Statistcs or Awards to record."); return; } else { LOG.info("Found statistics or awards to record."); LOG.info("Statistics ¥t-> " + stats.size()); LOG.info("Awards ¥t->" + awards.size()); Record record = new Record(); record.setPlayedAt(DateUtils.getYesterday()); // MEMO:DBsave record.saveIt(); record.addStatistics(stats); record.addAwards(awards); user.addRecord(record); user.saveIt(); } } }
package org.spongepowered.api.text.title; import com.google.common.base.Objects; import org.spongepowered.api.text.Text; import java.util.Optional; import javax.annotation.Nullable; /** * Represents an immutable configuration for an in-game title. Instances of this * interface can be created through the {@link Builder} by calling * {@link #builder()}. * * <p>All properties of a title are optional - if they are not set it will use * the current default values from the client.</p> */ public final class Title { public static final Title EMPTY = new Title(); public static final Title CLEAR = new Title(null, null, null, null, null, null, true, false); public static final Title RESET = new Title(null, null, null, null, null, null, false, true); final Optional<Text> title; final Optional<Text> subtitle; final Optional<Text> actionBar; final Optional<Integer> fadeIn; final Optional<Integer> stay; final Optional<Integer> fadeOut; final boolean clear; final boolean reset; private Title() { this(null, null, null, null, null, null, false, false); } /** * Constructs a new immutable {@link Title} with the specified properties. * * @param title The main title of the title, or {@code null} for default * @param subtitle The subtitle of the title, or {@code null} for default * @param actionBar The action bar text of the title, or {@code null} for default * @param fadeIn The fade in time of the title, or {@code null} for default * @param stay The stay time of the title, or {@code null} for default * @param fadeOut The fade out time of the title, or {@code null} for * default * @param clear {@code true} if this title clears the currently displayed * one first * @param reset {@code true} if this title resets all settings to default * first */ Title(@Nullable Text title, @Nullable Text subtitle, @Nullable Text actionBar, @Nullable Integer fadeIn, @Nullable Integer stay, @Nullable Integer fadeOut, boolean clear, boolean reset) { this.title = Optional.ofNullable(title); this.subtitle = Optional.ofNullable(subtitle); this.actionBar = Optional.ofNullable(actionBar); this.fadeIn = Optional.ofNullable(fadeIn); this.stay = Optional.ofNullable(stay); this.fadeOut = Optional.ofNullable(fadeOut); this.clear = clear; this.reset = reset; } /** * Returns the title of this title configuration. * * @return The {@link Text} of the title, if it was configured */ public final Optional<Text> getTitle() { return this.title; } /** * Returns the subtitle of this title configuration. * * @return The {@link Text} of the subtitle, if it was configured */ public final Optional<Text> getSubtitle() { return this.subtitle; } /** * Returns the action bar text of this title configuration. * * @return The {@link Text} of the action bar, if it was configured */ public final Optional<Text> getActionBar() { return this.actionBar; } /** * Returns the specified time to fade in the title on the client. Once this * period of time is over, the title will stay for the amount of time from * {@link #getStay}. * * <p>The default value for Vanilla is 20 (1 second).</p> * * @return The amount of ticks (1/20 second) for the fade in effect */ public final Optional<Integer> getFadeIn() { return this.fadeIn; } /** * Returns the specified time how long the title should stay on the client. * Once this period of time is over, the title will fade out using the * duration specified from {@link #getFadeOut}. * * <p>The default value for Vanilla is 60 (3 second).</p> * * @return The amount of ticks (1/20 second) for the stay effect */ public final Optional<Integer> getStay() { return this.stay; } /** * Returns the specified time to fade out the title on the client. * * <p>The default value for Vanilla is 20 (1 second).</p> * * @return The amount of ticks (1/20 second) for the fade out effect */ public final Optional<Integer> getFadeOut() { return this.fadeOut; } /** * Returns whether this configuration is clearing the current title from the * screen. * * @return True if the current title will be removed from the client's * screen */ public final boolean isClear() { return this.clear; } /** * Returns whether this configuration is clearing the current title from the * screen and resetting the current configuration to the default values. * * <p>This is recommended when you want to make sure to display a single * title.</p> * * @return True if the current settings will be reset to the defaults */ public final boolean isReset() { return this.reset; } /** * Creates a new {@link Builder} using the configuration of this instance. * * @return A new builder to modify this Title configuration */ public Builder toBuilder() { return new Builder(this); } @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (!(o instanceof Title)) { return false; } Title that = (Title) o; return this.title.equals(that.title) && this.subtitle.equals(that.subtitle) && this.actionBar.equals(that.actionBar) && this.fadeIn.equals(that.fadeIn) && this.stay.equals(that.stay) && this.fadeOut.equals(that.fadeOut) && this.clear == that.clear && this.reset == that.reset; } @Override public int hashCode() { return Objects.hashCode(this.title, this.subtitle, this.actionBar, this.fadeIn, this.stay, this.fadeOut, this.clear, this.reset); } @Override public String toString() { return Objects.toStringHelper(this) .omitNullValues() .add("title", this.title.orElse(null)) .add("subtitle", this.subtitle.orElse(null)) .add("actionBar", this.actionBar.orElse(null)) .add("fadeIn", this.fadeIn.orElse(null)) .add("stay", this.stay.orElse(null)) .add("fadeOut", this.fadeOut.orElse(null)) .add("clear", this.clear) .add("reset", this.reset) .toString(); } /** * Represents a builder class to create immutable {@link Title} * configurations. * * @see Title */ public static final class Builder { @Nullable private Text title; @Nullable private Text subtitle; @Nullable private Text actionBar; @Nullable private Integer fadeIn; @Nullable private Integer stay; @Nullable private Integer fadeOut; private boolean clear; private boolean reset; /** * Constructs a new empty {@link Builder}. */ Builder() { } /** * Constructs a new {@link Builder} with the properties of the given * {@link Title} as initial values. * * @param title The title to copy the values from */ Builder(Title title) { this.title = title.title.orElse(null); this.subtitle = title.subtitle.orElse(null); this.actionBar = title.actionBar.orElse(null); this.fadeIn = title.fadeIn.orElse(null); this.stay = title.stay.orElse(null); this.fadeOut = title.fadeOut.orElse(null); this.clear = title.clear; this.reset = title.reset; } /** * Returns the current title of this builder. * * @return The current main title, or {@link Optional#empty()} if none * @see Title#getTitle() */ public final Optional<Text> getTitle() { return Optional.ofNullable(this.title); } /** * Sets the title to send to the player. * * @param title The text to use as the title, or {@code null} to reset * @return This title builder * @see Title#getTitle() */ public Builder title(@Nullable Text title) { this.title = title; return this; } /** * Returns the current subtitle of this builder. * * @return The current subtitle, or {@link Optional#empty()} if none * @see Title#getSubtitle() */ public final Optional<Text> getSubtitle() { return Optional.ofNullable(this.subtitle); } /** * Sets the subtitle to send to the player. * * @param subtitle The text to use as the subtitle, or {@code null} to * reset * @return This title builder * @see Title#getSubtitle() */ public Builder subtitle(@Nullable Text subtitle) { this.subtitle = subtitle; return this; } /** * Returns the current action bar text of this builder. * * @return The current action bar text, or {@link Optional#empty()} if none * @see Title#getActionBar() */ public final Optional<Text> getActionBar() { return Optional.ofNullable(this.actionBar); } /** * Sets the action bar text to send to the player. * * @param actionBar The text to use for the action bar, or {@code null} to * reset * @return This title builder * @see Title#getActionBar() */ public Builder actionBar(@Nullable Text actionBar) { this.actionBar = actionBar; return this; } /** * Returns the current fade in effect time of the title. * * @return The current fade in time, or {@link Optional#empty()} if none * @see Title#getFadeIn() */ public final Optional<Integer> getFadeIn() { return Optional.ofNullable(this.fadeIn); } /** * Sets the duration in ticks of the fade in effect of the title. Once * this period of time is over the title will stay for the amount of * time specified in {@link #stay(Integer)}. * * <p>The default value for Vanilla is 20 (1 second).</p> * * @param fadeIn The amount of ticks (1/20 second) for the fade in * effect, or {@code null} to reset * @return This title builder * @see Title#getFadeIn() */ public Builder fadeIn(@Nullable Integer fadeIn) { this.fadeIn = fadeIn; return this; } /** * Returns the current stay effect time of the title. * * @return The current stay time, or {@link Optional#empty()} if none * @see Title#getStay() */ public final Optional<Integer> getStay() { return Optional.ofNullable(this.stay); } /** * Sets the duration in ticks how long the title should stay on the * screen. Once this period of time is over the title will fade out * using the duration specified in {@link #fadeOut(Integer)}. * * <p>The default value for Vanilla is 60 (3 seconds).</p> * * @param stay The amount of ticks (1/20 second) to stay, or * {@code null} to reset * @return This title builder * @see Title#getStay() */ public Builder stay(@Nullable Integer stay) { this.stay = stay; return this; } /** * Returns the current fade out effect time of the title. * * @return The current fade out time, or {@link Optional#empty()} if * none * @see Title#getFadeOut() */ public final Optional<Integer> getFadeOut() { return Optional.ofNullable(this.fadeOut); } /** * Sets the duration in ticks of the fade out effect of the title. * * <p>The default value for Vanilla is 20 (1 second).</p> * * @param fadeOut The amount of ticks (1/20 second) for the fade out * effect, or {@code null} to reset * @return This title builder * @see Title#getFadeOut() */ public Builder fadeOut(@Nullable Integer fadeOut) { this.fadeOut = fadeOut; return this; } /** * Returns whether this builder is currently configured to clear. * * @return {@code true} if the title will clear * @see Title#isClear() */ public final boolean isClear() { return this.clear; } /** * Removes the currently displayed title from the player's screen. This * will keep the currently used display times and will only remove the * title. * * @return This title builder * @see Title#isClear() */ public Builder clear() { return clear(true); } /** * Sets whether the the currently displayed title should be removed from * the player's screen and will keep the currently used display times. * * @param clear Whether this title should clear * @return This title builder * @see Title#isClear() */ public Builder clear(boolean clear) { if (this.clear = clear) { this.title = null; // No need to send title if we clear it after // that again } return this; } /** * Returns whether this builder is currently configured to reset. * * @return {@code true} if the title will reset * @see Title#isReset() */ public final boolean isReset() { return this.reset; } /** * Removes the currently displayed title from the player's screen and * set the configuration back to the default values. * * @return This title builder * @see Title#isReset() */ public Builder reset() { return reset(true); } /** * Sets whether the currently displayed title should be removed from the * player's screen and the configuration set back to the default values. * * @param reset Whether this title should reset * @return This title builder * @see Title#isReset() */ public Builder reset(boolean reset) { if (this.reset = reset) { // No need for these if we reset it again after that this.title = null; this.subtitle = null; this.fadeIn = null; this.stay = null; this.fadeOut = null; } return this; } /** * Builds an immutable instance of the current configuration. * * @return An immutable {@link Title} with the currently configured * settings */ public Title build() { // If the title has no other properties and is either empty, just clears // or just resets we can return a special instance if (this.title == null && this.subtitle == null && this.actionBar == null && this.fadeIn == null && this.stay == null && this.fadeOut == null) { if (this.clear) { if (!this.reset) { return CLEAR; } } else if (this.reset) { return RESET; } else { return EMPTY; } } return new Title( this.title, this.subtitle, this.actionBar, this.fadeIn, this.stay, this.fadeOut, this.clear, this.reset); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Builder)) { return false; } Builder that = (Builder) o; return Objects.equal(this.title, that.title) && Objects.equal(this.subtitle, that.subtitle) && Objects.equal(this.actionBar, that.actionBar) && Objects.equal(this.fadeIn, that.fadeIn) && Objects.equal(this.stay, that.stay) && Objects.equal(this.fadeOut, that.fadeOut) && this.clear == that.clear && this.reset == that.reset; } @Override public int hashCode() { return Objects.hashCode(this.title, this.subtitle, this.actionBar, this.fadeIn, this.stay, this.fadeOut, this.clear, this.reset); } @Override public String toString() { return Objects.toStringHelper(this) .omitNullValues() .add("title", this.title) .add("subtitle", this.subtitle) .add("actionBar", this.actionBar) .add("fadeIn", this.fadeIn) .add("stay", this.stay) .add("fadeOut", this.fadeOut) .add("clear", this.clear) .add("reset", this.reset) .toString(); } } /** * Returns a {@link Title} that will simply do nothing when it is sent to * the client. * * @return An empty title instance */ public static Title of() { return EMPTY; } /** * Returns a {@link Title} that will display the given main title on the * player's screen. * * @param title The title to display * @return The created title */ public static Title of(Text title) { return builder().title(title).build(); } /** * Returns a {@link Title} that will display the given main and subtitle on * the player's screen. * * @param title The title to display * @param subtitle The subtitle to display * @return The created title */ public static Title of(Text title, Text subtitle) { return builder().title(title).subtitle(subtitle).build(); } /** * Returns a {@link Title} that will clear the currently displayed * {@link Title} from the player's screen. * * @return A title configuration that will clear */ public static Title clear() { return CLEAR; } /** * Returns a {@link Title} that will reset the current title back to default * values on the client. * * @return A title configuration that will reset */ public static Title reset() { return RESET; } /** * Creates a new {@link Title} configuration builder that will reset the * currently displayed Title on the client before displaying the new * configured one. * * @return A new {@link Builder} * @see #update */ public static Builder builder() { return update().reset(); } /** * Creates a new empty {@link Title} configuration builder. Unlike * {@link #builder} this won't reset the current Title on the client before * displaying the current one. This has less use cases but should be used if * just the previously sent Title should be updated. * * @return A new {@link Builder} * @see #builder */ public static Builder update() { return new Builder(); } }
package pl.domzal.junit.docker.rule; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.commons.lang.StringUtils; import org.junit.Rule; import org.junit.rules.ExternalResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.spotify.docker.client.DefaultDockerClient; import com.spotify.docker.client.DockerCertificateException; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.DockerClient.ListImagesParam; import com.spotify.docker.client.DockerClient.LogsParam; import com.spotify.docker.client.DockerException; import com.spotify.docker.client.DockerRequestException; import com.spotify.docker.client.ImageNotFoundException; import com.spotify.docker.client.LogStream; import com.spotify.docker.client.messages.ContainerConfig; import com.spotify.docker.client.messages.ContainerCreation; import com.spotify.docker.client.messages.ContainerInfo; import com.spotify.docker.client.messages.ContainerState; import com.spotify.docker.client.messages.HostConfig; import com.spotify.docker.client.messages.Image; import com.spotify.docker.client.messages.NetworkSettings; import com.spotify.docker.client.messages.PortBinding; import pl.domzal.junit.docker.rule.WaitForUnit.WaitForCondition; public class DockerRule extends ExternalResource { private static Logger log = LoggerFactory.getLogger(DockerRule.class); private static final int STOP_TIMEOUT = 5; private final DockerClient dockerClient; private ContainerCreation container; private final DockerRuleBuilder builder; private final String imageNameWithTag; private Map<String, List<PortBinding>> containerPorts; private DockerLogs dockerLogs; public DockerRule(DockerRuleBuilder builder) { this.builder = builder; this.imageNameWithTag = imageNameWithTag(builder.imageName()); try { dockerClient = DefaultDockerClient.fromEnv().build(); if (builder.imageAlwaysPull() || ! imageAvaliable(dockerClient, imageNameWithTag)) { dockerClient.pull(imageNameWithTag); } } catch (ImageNotFoundException e) { throw new ImagePullException(String.format("Image '%s' not found", imageNameWithTag), e); } catch (DockerCertificateException | DockerException | InterruptedException e) { throw new IllegalStateException(e); } } public static DockerRuleBuilder builder() { return new DockerRuleBuilder(); } @Override protected void before() throws Throwable { HostConfig hostConfig = HostConfig.builder() .publishAllPorts(builder.publishAllPorts()) .portBindings(builder.hostPortBindings()) .binds(builder.binds()) .extraHosts(builder.extraHosts()) .build(); ContainerConfig containerConfig = ContainerConfig.builder() .hostConfig(hostConfig) .image(imageNameWithTag) .env(builder.env()) .networkDisabled(false) .exposedPorts(builder.containerExposedPorts()) .entrypoint(builder.entrypoint()) .cmd(builder.cmd()).build(); try { this.container = dockerClient.createContainer(containerConfig); log.debug("rule before {}", container.id()); log.info("container {} created, id {}", imageNameWithTag, container.id()); dockerClient.startContainer(container.id()); log.debug("{} started", container.id()); attachLogs(dockerClient, container.id()); ContainerInfo inspectContainer = dockerClient.inspectContainer(container.id()); containerPorts = inspectContainer.networkSettings().ports(); if (builder.waitForMessage()!=null) { waitForMessage(); } logMappings(dockerClient); } catch (DockerRequestException e) { throw new IllegalStateException(e.message(), e); } catch (DockerException | InterruptedException e) { throw new IllegalStateException(e); } } private void attachLogs(DockerClient dockerClient, String containerId) throws IOException, InterruptedException { dockerLogs = new DockerLogs(dockerClient, containerId); if (builder.stdoutWriter()!=null) { dockerLogs.setStdoutWriter(builder.stdoutWriter()); } if (builder.stderrWriter()!=null) { dockerLogs.setStderrWriter(builder.stderrWriter()); } dockerLogs.start(); } private boolean imageAvaliable(DockerClient dockerClient, String imageName) throws DockerException, InterruptedException { String imageNameWithTag = imageNameWithTag(imageName); List<Image> listImages = dockerClient.listImages(ListImagesParam.danglingImages(false)); for (Image image : listImages) { if (image.repoTags().contains(imageNameWithTag)) { log.debug("image '{}' found", imageNameWithTag); return true; } } log.debug("image '{}' not found", imageNameWithTag); return false; } private String imageNameWithTag(String imageName) { if (! StringUtils.contains(imageName, ':')) { return imageName + ":latest"; } else { return imageName; } } private void waitForMessage() throws TimeoutException, InterruptedException { final String waitForMessage = builder.waitForMessage(); log.info("{} waiting for log message '{}'", container.id(), waitForMessage); new WaitForUnit(TimeUnit.SECONDS, builder.waitForMessageSeconds(), new WaitForCondition(){ @Override public boolean isConditionMet() { return getLog().contains(waitForMessage); } @Override public String timeoutMessage() { return String.format("Timeout waiting for '%s'", waitForMessage); } }).startWaiting(); log.debug("{} message '{}' found", container.id(), waitForMessage); } @Override protected void after() { log.debug("after {}", container.id()); try { dockerLogs.close(); ContainerState state = dockerClient.inspectContainer(container.id()).state(); log.debug("{} state {}", container.id(), state); if (state.running()) { dockerClient.stopContainer(container.id(), STOP_TIMEOUT); log.info("{} stopped", container.id()); } if (!builder.keepContainer()) { dockerClient.removeContainer(container.id(), true); log.info("{} deleted", container.id()); container = null; } } catch (DockerException e) { throw new IllegalStateException(e); } catch (InterruptedException e) { throw new IllegalStateException(e); } } public final String getDockerHost() { return dockerClient.getHost(); } /** * Get host dynamic port given container port was mapped to. * * @param containerPort Container port. Typically it matches Dockerfile EXPOSE directive. * @return Host port conteiner port is exposed on. */ public final String getExposedContainerPort(String containerPort) { String key = containerPort + "/tcp"; List<PortBinding> list = containerPorts.get(key); if (list == null || list.size() == 0) { throw new IllegalStateException(String.format("%s is not exposed", key)); } if (list.size() == 0) { throw new IllegalStateException(String.format("binding list for %s is empty", key)); } if (list.size() > 1) { throw new IllegalStateException(String.format("binding list for %s is longer than 1", key)); } return list.get(0).hostPort(); } private void logMappings(DockerClient dockerClient) throws DockerException, InterruptedException { ContainerInfo inspectContainer = dockerClient.inspectContainer(container.id()); NetworkSettings networkSettings = inspectContainer.networkSettings(); log.info("{} exposed ports: {}", container.id(), networkSettings.ports()); } /** * Stop and wait till given string will show in container output. * * @param searchString String to wait for in container output. * @param waitTime Wait time. * @throws TimeoutException On wait timeout. */ public void waitFor(final String searchString, int waitTime) throws TimeoutException, InterruptedException { new WaitForUnit(TimeUnit.SECONDS, waitTime, TimeUnit.SECONDS, 1, new WaitForCondition() { @Override public boolean isConditionMet() { return StringUtils.contains(getLog(), searchString); } @Override public String tickMessage() { return String.format("wait for '%s' in log", searchString); } @Override public String timeoutMessage() { return String.format("container log: \n%s", getLog()); } }) .startWaiting(); } /** * Wait for container exit. Please note this is blocking call. */ public void waitForExit() throws InterruptedException { try { dockerClient.waitContainer(container.id()); } catch (DockerException e) { throw new IllegalStateException(e); } } /** * Container log. */ public String getLog() { try (LogStream stream = dockerClient.logs(container.id(), LogsParam.stdout(), LogsParam.stderr());) { String fullLog = stream.readFully(); if (log.isTraceEnabled()) { log.trace("{} full log: {}", container.id(), StringUtils.replace(fullLog, "\n", "|")); } return fullLog; } catch (DockerException | InterruptedException e) { throw new IllegalStateException(e); } } /** * Id of container (null if it is not yet been created or has been stopped). */ public String getContainerId() { return (container!=null ? container.id() : null); } /** * {@link DockerClient} for direct container manipulation. */ DockerClient getDockerClient() { return dockerClient; } }
package pl.lepszetlumaczenia.tabele; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="rzeczowniki", schema="public") public class Rzeczownik { @Id @Column(name="kod_rzeczownika", nullable=false) private int kodReczownika; @Column(name="temat", nullable=false) private String temat; /** * Grupa deklinacyjna. Istnieje ok. 150 grup deklinacyjnych, * po tym identyfikatorze przeprowadzane jest przetwarzanie * do ostatecznej formy rzeczownika. */ @Column(name="grupa_deklin", nullable=false) private int grupaDeklinacyjna; /** * Pusty konstruktor klasy. */ public Rzeczownik() { } public int getKodReczownika() { return kodReczownika; } public void setKodReczownika(int kodReczownika) { this.kodReczownika = kodReczownika; } public String getTemat() { return temat; } public void setTemat(String temat) { this.temat = temat; } public int getGrupaDeklinacyjna() { return grupaDeklinacyjna; } public void setGrupaDeklinacyjna(int grupaDeklinacyjna) { this.grupaDeklinacyjna = grupaDeklinacyjna; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "Rzeczownik [kodReczownika=" + kodReczownika + ", temat=" + temat + ", grupaDeklinacyjna=" + grupaDeklinacyjna + "]"; } }
package se.su.it.svc.server.aspect; import org.apache.cxf.phase.PhaseInterceptorChain; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.slf4j.LoggerFactory; import se.su.it.svc.server.annotations.AuditHideReturnValue; import se.su.it.svc.server.annotations.AuditMethodDetails; import se.su.it.svc.server.audit.AuditEntity; import javax.servlet.http.HttpServletRequest; import java.lang.reflect.Method; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.List; @Aspect public class AuditAspect { private static final String STATE_INPROGRESS = "IN PROGRESS"; private static final String STATE_SUCCESS = "SUCCESS"; private static final String STATE_EXCEPTION = "EXCEPTION"; private static final String UNKNOWN = "<unknown>"; private static final String HIDDEN_VALUE = "******"; static final org.slf4j.Logger logger = LoggerFactory.getLogger(AuditAspect.class); @Before("execution(* (@javax.jws.WebService *).*(..))") public void auditBefore(JoinPoint joinPoint) throws Throwable { String id = getId(); Class targetClass = joinPoint.getTarget().getClass(); String methodName = joinPoint.getSignature().getName(); Object[] args = joinPoint.getArgs(); logger.info("["+id+"] Before: " + targetClass.getName() + "." + methodName + " with " + args.length + "params"); Method method = null; try { method = getMethod(targetClass, methodName, args); } catch (NoSuchMethodException e) { logger.warn("["+id+"] Could not get method for " + targetClass.getName() + "." + methodName); } // Create an AuditEntity based on the gathered information AuditEntity ae = AuditEntity.getInstance( new Timestamp(new Date().getTime()).toString(), methodName, objectsToString(args), UNKNOWN, STATE_INPROGRESS, getMethodDetails(method) ); logger.info("["+id+"] Received: "+ ae); } @AfterReturning( pointcut = "execution(* (@javax.jws.WebService *).*(..))", returning = "result") public void auditAfterReturning(JoinPoint joinPoint, Object result) throws Throwable { String id = getId(); Class targetClass = joinPoint.getTarget().getClass(); String methodName = joinPoint.getSignature().getName(); Object[] args = joinPoint.getArgs(); logger.info("["+id+"] After: " + targetClass.getName() + "." + methodName + " with " + args.length + "params"); Method method = null; try { method = getMethod(targetClass, methodName, args); } catch (NoSuchMethodException e) { logger.warn("["+id+"] Could not get method for " + targetClass.getName() + "." + methodName); } if (method != null && method.isAnnotationPresent(AuditHideReturnValue.class)) { result = HIDDEN_VALUE; } AuditEntity ae = AuditEntity.getInstance( new Timestamp(new Date().getTime()).toString(), methodName, objectsToString(args), result != null ? result.toString() : null, STATE_SUCCESS, getMethodDetails(method) ); logger.info("["+id+"] Returned: " + ae); } @AfterThrowing( pointcut = "execution(* (@javax.jws.WebService *).*(..))", throwing = "throwable") public void auditAfterThrowing(JoinPoint joinPoint, Throwable throwable) throws Throwable { String id = getId(); Class targetClass = joinPoint.getTarget().getClass(); String methodName = joinPoint.getSignature().getName(); Object[] args = joinPoint.getArgs(); logger.info("["+id+"] After exception: " + targetClass.getName() + "." + methodName + " with " + args.length + "params"); Method method = null; try { method = getMethod(targetClass, methodName, args); } catch (NoSuchMethodException e) { logger.warn("["+id+"] Could not get method for " + targetClass.getName() + "." + methodName); } AuditEntity ae = AuditEntity.getInstance( new Timestamp(new Date().getTime()).toString(), methodName, objectsToString(args), throwable != null ? throwable.toString() : null, STATE_EXCEPTION, getMethodDetails(method) ); logger.info("["+id+"] Exception: " + ae); } protected String objectsToString(Object[] objects) { if (objects == null) { return "null"; } StringBuilder sb = new StringBuilder(); sb.append("["); for (Object object : objects) { sb.append(object).append(", "); } if (sb.lastIndexOf(",") > 0) { sb.replace(sb.lastIndexOf(","), sb.length(), ""); } sb.append("]"); return sb.toString(); } protected String getId() { String id = ""; try { HttpServletRequest request = (HttpServletRequest) PhaseInterceptorChain.getCurrentMessage().get("HTTP.REQUEST"); id = request.getSession().getId(); } catch (Exception ex) { logger.debug("Failed to get id from session", ex); } return id; } private Method getMethod(Class target, String name, Object[] args) throws NoSuchMethodException { Class[] parameterTypes = new Class[args.length]; for(int i = 0; i < parameterTypes.length; i++) { parameterTypes[i] = args[i].getClass(); } return target.getMethod(name, parameterTypes); } /** * Generate MethodDetails from annotation on method to be able to describe * functions that will be invoked by this method * * @return the method details */ private List<String> getMethodDetails(Method method) { List<String> methodDetails = new ArrayList<String>(); if (method != null) { if (method.isAnnotationPresent(AuditMethodDetails.class)) { AuditMethodDetails annotation = method.getAnnotation(AuditMethodDetails.class); String details = annotation.details(); for(String s : details.split(",")) { methodDetails.add(s.trim()); } } } return methodDetails; } }
package studentcapture.datalayer.database; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import studentcapture.datalayer.database.Assignment.AssignmentWrapper; import studentcapture.datalayer.database.Course.CourseWrapper; import studentcapture.datalayer.database.Submission.SubmissionWrapper; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.sql.Types; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; @Repository public class User { private final String SQL_ADD_USR = "INSERT INTO users" + " (username, firstname, lastname, persnr, pswd)" + " VALUES (?, ?, ?, ?, ?)"; private final String SQL_GET_USR_BY_ID = "SELECT * FROM users WHERE userid = ?"; private final String SQL_USR_EXIST = "SELECT EXISTS (SELECT 1 FROM users " + "WHERE username = ? AND pswd = ?)"; private final String SQL_GET_PSWDS = ""; private final String SQL_RM_USR = ""; // This template should be used to send queries to the database @Autowired protected JdbcTemplate jdbcTemplate; @Autowired private Course course; @Autowired private Assignment assignment; @Autowired private Submission submission; /** * Add a new user to the User-table in the database. * * @param userName unique identifier for a person * @param fName First name of a user * @param lName Last name of a user * @param pNr Person-Number * @param pwd Password * @return true if success, else false. */ public boolean addUser(String userName, String fName, String lName, String pNr, String pwd) { // TODO: //Check that user doesn't exist // Generate salt // Create idSalt by combining salt with user name // register user info with idSalt. Object[] args = new Object[] {userName, fName,lName,pNr,pwd}; int[] types = new int[]{Types.VARCHAR,Types.VARCHAR,Types.VARCHAR, Types.CHAR,Types.VARCHAR}; try { jdbcTemplate.update(SQL_ADD_USR, args,types); } catch (DataIntegrityViolationException e) { System.out.println(e); return false; } return true; } /** * Remove a user from the User-table in the database. * * @param username unique identifier for a person * @return true if the remove succeed, else false. */ public String getUserID(String username){ String sql = "SELECT userID from users WHERE username = ?"; return jdbcTemplate.queryForObject(sql, new Object[]{username},String.class); } public boolean removeUser(String casID) { throw new UnsupportedOperationException(); } /** * Updates a user in the User-table in the database. Use Null-value for * those parameters that shouldn't update. * * @param fName First name of a user * @param lName Last name of a user * @param pNr Person-Number * @param pWord Password * @param casID unique identifier for a person * @return true if the update succeed, else false. */ public boolean updateUser(String fName, String lName, String pNr, String pWord, String casID) { throw new UnsupportedOperationException(); } /** * Returns a list with info of a user. * * @param userID unique identifier for a person * @return The list with info of a person. */ public HashMap<String,String> getUserByID(String userID) { String sql = "SELECT * FROM users WHERE userid = ?"; Object[] arg = new Object[]{Integer.parseInt(userID)}; HashMap<String,String> info = (HashMap<String,String>) jdbcTemplate.queryForObject(SQL_GET_USR_BY_ID, arg, new UserWrapper()); return info; } /** * Check if a user exist by the name and password. * @return true if user exist, otherwise false. */ public boolean userExist(String userName,String pswd) { return jdbcTemplate.queryForObject(SQL_USR_EXIST, new Object[] {userName,pswd}, Boolean.class); } public Optional<CourseAssignmentHierarchy> getCourseAssignmentHierarchy( String userID) { CourseAssignmentHierarchy hierarchy = new CourseAssignmentHierarchy(); int userId = Integer.parseInt(userID); try { addStudentHierarchy(hierarchy, userId); addTeacherHierarchy(hierarchy, userId); addUserToHierarchy(hierarchy, userId); } catch (IncorrectResultSizeDataAccessException e){ System.out.println("HEJ"); return Optional.empty(); } catch (DataAccessException e1){ e1.printStackTrace(); return Optional.empty(); } return Optional.of(hierarchy); } private static final String getUserStatement = "SELECT * FROM Users WHERE " + "UserId=?"; private void addUserToHierarchy(CourseAssignmentHierarchy hierarchy, int userId) { Map<String, Object> map = jdbcTemplate.queryForMap( getUserStatement, userId); hierarchy.userId = (int) map.get("UserId"); hierarchy.firstName = (String) map.get("FirstName"); hierarchy.lastName = (String) map.get("LastName"); } private static final String getTeacherHierarchyStatement = "SELECT * FROM " + "Participant AS par LEFT JOIN Course AS cou ON par.courseId=" + "cou.courseId LEFT JOIN Assignment AS ass ON cou.courseId=" + "ass.courseId LEFT JOIN Submission AS sub ON ass.assignmentId=" + "sub.assignmentId WHERE par.userId=? AND par.function='Teacher'"; private void addTeacherHierarchy(CourseAssignmentHierarchy hierarchy, int userId) { List<Map<String, Object>> rows = jdbcTemplate.queryForList( getTeacherHierarchyStatement, userId); for (Map<String, Object> row : rows) { CoursePackage currentCourse; String courseId = (String) row.get("CourseId"); try { currentCourse = hierarchy.teacherCourses.get(courseId); if(currentCourse==null) throw new NullPointerException(); } catch (NullPointerException e) { currentCourse = new CoursePackage(); currentCourse.course = course.getCourseWithWrapper(courseId); hierarchy.teacherCourses.put(courseId, currentCourse); } try { AssignmentPackage currentAssignment; int assignmentId = (int) row.get("AssignmentId"); try { currentAssignment = currentCourse.assignments.get(assignmentId); if (currentAssignment == null) { throw new NullPointerException(); } } catch (NullPointerException e) { currentAssignment = new AssignmentPackage(); currentAssignment.assignment = assignment .getAssignmentWithWrapper(assignmentId).get(); currentCourse.assignments.put(assignmentId, currentAssignment); } // TODO: unused variable SubmissionWrapper currentSubmission; Integer submissionId = (Integer) row.get("SubmissionId"); if (submissionId != null) { try { currentSubmission = currentAssignment .submissions.get(submissionId); } catch (Exception e) { currentSubmission = submission.getSubmissionWithWrapper( assignmentId,userId).get(); } } } catch (Exception e) { //TODO } } } private static final String getStudentHierarchyStatement = "SELECT * FROM " + "Participant AS par LEFT JOIN Course AS cou ON par.courseId=" + "cou.courseId LEFT JOIN Assignment AS ass ON cou.courseId=" + "ass.courseId LEFT JOIN Submission AS sub ON par.userId=" + "sub.studentId AND ass.assignmentId=sub.assignmentId WHERE " + "par.userId=? AND par.function='Student'"; private void addStudentHierarchy(CourseAssignmentHierarchy hierarchy, int userId) { List<Map<String, Object>> rows = jdbcTemplate.queryForList( getStudentHierarchyStatement, userId); for (Map<String, Object> row : rows) { CoursePackage currentCourse; String courseId = (String) row.get("CourseId"); try { currentCourse = hierarchy.studentCourses.get(courseId); if(currentCourse==null) throw new NullPointerException(); } catch (NullPointerException e) { currentCourse = new CoursePackage(); currentCourse.course = course.getCourseWithWrapper(courseId); hierarchy.studentCourses.put(courseId, currentCourse); } try { AssignmentPackage currentAssignment; int assignmentId = (int) row.get("AssignmentId"); try { currentAssignment = currentCourse.assignments.get(assignmentId); if(currentAssignment==null) throw new NullPointerException(); } catch (NullPointerException e) { currentAssignment = new AssignmentPackage(); currentAssignment.assignment = assignment .getAssignmentWithWrapper(assignmentId).get(); currentCourse.assignments.put(assignmentId, currentAssignment); } SubmissionWrapper currentSubmission = null; Integer submissionId = (Integer) row.get("SubmissionId"); if (submissionId != null) { try { currentSubmission = currentAssignment .submissions.get(submissionId); } catch (Exception e) { currentSubmission = submission.getSubmissionWithWrapper( assignmentId,userId).get(); currentAssignment.submissions.put(submissionId, currentSubmission); } } } catch (Exception e) { //TODO throw new RuntimeException("Unimplemented catch-block triggered"); } } } /** * Used to collect user information, and return a hashmap. */ protected class UserWrapper implements org.springframework.jdbc.core.RowMapper { @Override public Object mapRow(ResultSet rs, int i) throws SQLException { HashMap<String,String> info = new HashMap(); info.put("userid",rs.getString("userid")); info.put("username",rs.getString("username")); info.put("lastname",rs.getString("lastname")); info.put("persnr",rs.getString("persnr")); info.put("pswd",rs.getString("pswd")); return info; } } public static class CourseAssignmentHierarchy { public int userId; public String firstName; public String lastName; public Map<String, CoursePackage> teacherCourses; public Map<String, CoursePackage> studentCourses; public CourseAssignmentHierarchy() { teacherCourses = new HashMap<>(); studentCourses = new HashMap<>(); } } public class CoursePackage { public CourseWrapper course; public Map<Integer, AssignmentPackage> assignments; public CoursePackage() { assignments = new HashMap<>(); } } public class AssignmentPackage { public AssignmentWrapper assignment = null; public Map<Integer, SubmissionWrapper> submissions = null; } }
package techreborn.tiles; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.item.crafting.Ingredient; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.registry.ForgeRegistries; import org.apache.commons.lang3.tuple.Pair; import reborncore.api.tile.IInventoryProvider; import reborncore.common.powerSystem.TilePowerAcceptor; import reborncore.common.util.Inventory; import reborncore.common.util.ItemUtils; import techreborn.client.container.IContainerProvider; import techreborn.client.container.builder.BuiltContainer; import techreborn.client.container.builder.ContainerBuilder; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; public class TileAutoCraftingTable extends TilePowerAcceptor implements IContainerProvider, IInventoryProvider, ISidedInventory { ResourceLocation currentRecipe; public Inventory inventory = new Inventory(10, "TileAutoCraftingTable", 64, this); public int progress; public int maxProgress = 120; public int euTick = 10; public Pair<ResourceLocation, IRecipe> cachedRecipe; public void setCurrentRecipe(ResourceLocation recipe) { currentRecipe = recipe; } @Nullable public IRecipe getIRecipe() { if (currentRecipe == null) { return null; } if (cachedRecipe == null || !cachedRecipe.getLeft().equals(currentRecipe)) { IRecipe recipe = ForgeRegistries.RECIPES.getValue(currentRecipe); if (recipe != null) { cachedRecipe = Pair.of(currentRecipe, recipe); return recipe; } cachedRecipe = null; return null; } return cachedRecipe.getRight(); } @Override public void update() { super.update(); if(world.isRemote){ return; } IRecipe recipe = getIRecipe(); if (recipe != null) { if (progress >= maxProgress) { if (make(recipe)) { progress = 0; } } else { if (canMake(recipe)) { if (canUseEnergy(euTick)) { progress++; useEnergy(euTick); } } } } } public boolean canMake(IRecipe recipe) { if (recipe.canFit(3, 3)) { boolean missingOutput = false; int[] stacksInSlots = new int[9]; for (int i = 0; i < 9; i++) { stacksInSlots[i] = inventory.getStackInSlot(i).getCount(); } for (Ingredient ingredient : recipe.getIngredients()) { if (ingredient != Ingredient.EMPTY) { boolean foundIngredient = false; for (int i = 0; i < 9; i++) { ItemStack stack = inventory.getStackInSlot(i); if(stacksInSlots[i] > 0){ if (ingredient.apply(stack)) { foundIngredient = true; stacksInSlots[i] break; } } } if(!foundIngredient){ missingOutput = true; } } } if (!missingOutput) { if (hasOutputSpace(recipe.getRecipeOutput())) { return true; } } return false; } return false; } public boolean hasOutputSpace(ItemStack output) { ItemStack stack = inventory.getStackInSlot(9); if (stack.isEmpty()) { return true; } if (ItemUtils.isItemEqual(stack, output, true, true)) { if (stack.getMaxStackSize() < stack.getCount() + output.getCount()) { return true; } } return false; } public boolean make(IRecipe recipe) { if (canMake(recipe)) { for (Ingredient ingredient : recipe.getIngredients()) { for (int i = 0; i < 9; i++) { ItemStack stack = inventory.getStackInSlot(i); if (ingredient.apply(stack)) { stack.shrink(1); //TODO is this right? or do I need to use it as an actull crafting grid break; } } } ItemStack output = inventory.getStackInSlot(9); if (output.isEmpty()) { inventory.setInventorySlotContents(9, recipe.getRecipeOutput().copy()); } else { output.grow(recipe.getRecipeOutput().getCount()); } return true; } return false; } public boolean hasIngredient(Ingredient ingredient){ for (int i = 0; i < 9; i++) { ItemStack stack = inventory.getStackInSlot(i); if (ingredient.apply(stack)) { return true; } } return false; } public TileAutoCraftingTable() { super(); } @Override public double getBaseMaxPower() { return 10000; } @Override public double getBaseMaxOutput() { return 0; } @Override public double getBaseMaxInput() { return 32; } @Override public boolean canAcceptEnergy(EnumFacing enumFacing) { return true; } @Override public boolean canProvideEnergy(EnumFacing enumFacing) { return false; } @Override public BuiltContainer createContainer(EntityPlayer player) { return new ContainerBuilder("autocraftingTable").player(player.inventory).inventory().hotbar() .addInventory().tile(this) .slot(0, 28, 25).slot(1, 46, 25).slot(2, 64, 25) .slot(3, 28, 43).slot(4, 46, 43).slot(5, 64, 43) .slot(6, 28, 61).slot(7, 46, 61).slot(8, 64, 61) .outputSlot(9, 145, 42) .syncIntegerValue(this::getProgress, this::setProgress) .syncIntegerValue(this::getMaxProgress, this::setMaxProgress) .addInventory().create(); } @Override public boolean canBeUpgraded() { return false; } @Override public IInventory getInventory() { return inventory; } public int getProgress() { return progress; } public void setProgress(int progress) { this.progress = progress; } public int getMaxProgress() { if (maxProgress == 0) { maxProgress = 1; } return maxProgress; } public void setMaxProgress(int maxProgress) { this.maxProgress = maxProgress; } @Override public NBTTagCompound writeToNBT(NBTTagCompound tag) { if(currentRecipe != null){ tag.setString("currentRecipe", currentRecipe.toString()); } return super.writeToNBT(tag); } @Override public void readFromNBT(NBTTagCompound tag) { if(tag.hasKey("currentRecipe")){ currentRecipe = new ResourceLocation(tag.getString("currentRecipe")); } super.readFromNBT(tag); } public boolean isItemValidForRecipeSlot(IRecipe recipe, ItemStack stack, int slotID){ if(recipe == null){ return true; } int bestSlot = findBestSlotForStack(recipe, stack); if(bestSlot != -1){ return bestSlot == slotID; } return true; } public int findBestSlotForStack(IRecipe recipe, ItemStack stack){ if(recipe == null){ return -1; } List<Integer> possibleSlots = new ArrayList<>(); for (int i = 0; i < 9; i++) { ItemStack stackInSlot = inventory.getStackInSlot(i); Ingredient ingredient = recipe.getIngredients().get(i); if(ingredient != Ingredient.EMPTY && ingredient.apply(stack)){ if(stackInSlot.isEmpty()){ possibleSlots.add(i); } else if (stackInSlot.getItem() == stack.getItem() && stackInSlot.getItemDamage() == stack.getItemDamage()){ if(stackInSlot.getMaxStackSize() >= stackInSlot.getCount() + stack.getCount()){ possibleSlots.add(i); } } } } //Slot, count Pair<Integer, Integer> smallestCount = null; for(Integer slot : possibleSlots){ ItemStack slotStack = inventory.getStackInSlot(slot); if(slotStack.isEmpty()){ return slot; } if(smallestCount == null){ smallestCount = Pair.of(slot, slotStack.getCount()); } else if(smallestCount.getRight() >= slotStack.getCount()){ smallestCount = Pair.of(slot, slotStack.getCount()); } } if(smallestCount != null){ return smallestCount.getLeft(); } return -1; } @Override public boolean isItemValidForSlot(int index, ItemStack stack) { int bestSlot = findBestSlotForStack(getIRecipe(), stack); if(bestSlot != -1){ return index == bestSlot; } return super.isItemValidForSlot(index, stack); } @Override public boolean canInsertItem(int index, ItemStack itemStackIn, EnumFacing direction) { if(index == 9){ return false; } int bestSlot = findBestSlotForStack(getIRecipe(), itemStackIn); if(bestSlot != -1){ return index == bestSlot; } return false; } @Override public int[] getSlotsForFace(EnumFacing side) { return new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; } }
package uk.co.jemos.podam.api; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicReference; import net.jcip.annotations.Immutable; import net.jcip.annotations.ThreadSafe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.jemos.podam.common.AttributeStrategy; import uk.co.jemos.podam.common.PodamBooleanValue; import uk.co.jemos.podam.common.PodamByteValue; import uk.co.jemos.podam.common.PodamCharValue; import uk.co.jemos.podam.common.PodamCollection; import uk.co.jemos.podam.common.PodamConstants; import uk.co.jemos.podam.common.PodamConstructor; import uk.co.jemos.podam.common.PodamDoubleValue; import uk.co.jemos.podam.common.PodamFloatValue; import uk.co.jemos.podam.common.PodamIntValue; import uk.co.jemos.podam.common.PodamLongValue; import uk.co.jemos.podam.common.PodamShortValue; import uk.co.jemos.podam.common.PodamStrategyValue; import uk.co.jemos.podam.common.PodamStringValue; import uk.co.jemos.podam.exceptions.PodamMockeryException; /** * The PODAM factory implementation * * @author mtedone * * @since 1.0.0 * */ @ThreadSafe @Immutable public class PodamFactoryImpl implements PodamFactory { private static final String RESOLVING_COLLECTION_EXCEPTION_STR = "An exception occurred while resolving the collection"; private static final String MAP_CREATION_EXCEPTION_STR = "An exception occurred while creating a Map object"; private static final String RAWTYPES_STR = "rawtypes"; private static final String UNCHECKED_STR = "unchecked"; private static final String THE_ANNOTATION_VALUE_STR = "The annotation value: "; private static final Type[] NO_TYPES = new Type[0]; /** Application logger */ private static final Logger LOG = LoggerFactory .getLogger(PodamFactoryImpl.class.getName()); /** * External factory to delegate production this factory cannot handle * <p> * The default is {@link LoggingExternalFactory}. * </p> */ private final PodamFactory externalFactory; /** * The strategy to use to fill data. * <p> * The default is {@link RandomDataProviderStrategy}. * </p> */ private final DataProviderStrategy strategy; /** * A map to keep one object for each class. If memoization is enabled, the * factory will use this table to avoid creating objects of the same class * multiple times. */ private Map<Class<?>, Object> memoizationTable = new HashMap<Class<?>, Object>(); /** * Default constructor. */ public PodamFactoryImpl() { this(LoggingExternalFactory.getInstance(), RandomDataProviderStrategy.getInstance()); } /** * Constructor with non-default strategy * * @param strategy * The strategy to use to fill data */ public PodamFactoryImpl(DataProviderStrategy strategy) { this(LoggingExternalFactory.getInstance(), strategy); } /** * Constructor with non-default external factory * * @param externalFactory * External factory to delegate production this factory cannot * handle */ public PodamFactoryImpl(PodamFactory externalFactory) { this(externalFactory, RandomDataProviderStrategy.getInstance()); } /** * Full constructor. * * @param externalFactory * External factory to delegate production this factory cannot * handle * @param strategy * The strategy to use to fill data */ public PodamFactoryImpl(PodamFactory externalFactory, DataProviderStrategy strategy) { this.externalFactory = externalFactory; this.strategy = strategy; } /** * {@inheritDoc} */ @Override public <T> T manufacturePojo(Class<T> pojoClass) { return this.manufacturePojo(pojoClass, NO_TYPES); } /** * {@inheritDoc} */ @Override public <T> T manufacturePojo(Class<T> pojoClass, Type... genericTypeArgs) { Map<Class<?>, Integer> pojos = new HashMap<Class<?>, Integer>(); pojos.put(pojoClass, 0); try { return this.manufacturePojoInternal(pojoClass, pojos, genericTypeArgs); } catch (InstantiationException e) { throw new PodamMockeryException("", e); } catch (IllegalAccessException e) { throw new PodamMockeryException("", e); } catch (InvocationTargetException e) { throw new PodamMockeryException("", e); } catch (ClassNotFoundException e) { throw new PodamMockeryException("", e); } } /** * {@inheritDoc} */ @Override public DataProviderStrategy getStrategy() { return strategy; } private Type[] fillTypeArgMap(final Map<String, Type> typeArgsMap, final Class<?> pojoClass, final Type[] genericTypeArgs) { final TypeVariable<?>[] typeParameters = pojoClass.getTypeParameters(); if (typeParameters.length > genericTypeArgs.length) { String msg = pojoClass.getCanonicalName() + " is missing generic type arguments, expected " + typeParameters.length + " found " + Arrays.toString(genericTypeArgs); throw new IllegalStateException(msg); } int i; for (i = 0; i < typeParameters.length; i++) { typeArgsMap.put(typeParameters[i].getName(), genericTypeArgs[i]); } Type[] genericTypeArgsExtra; if (typeParameters.length < genericTypeArgs.length) { genericTypeArgsExtra = Arrays.copyOfRange(genericTypeArgs, i, genericTypeArgs.length); } else { genericTypeArgsExtra = null; } /* Adding types, which were specified during inheritance */ Class<?> clazz = pojoClass; while (clazz != null) { Type superType = clazz.getGenericSuperclass(); clazz = clazz.getSuperclass(); if (superType instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType) superType; Type[] actualParamTypes = paramType.getActualTypeArguments(); TypeVariable<?>[] paramTypes = clazz.getTypeParameters(); for (i = 0; i < actualParamTypes.length && i < paramTypes.length; i++) { if (actualParamTypes[i] instanceof Class) { typeArgsMap.put(paramTypes[i].getName(), actualParamTypes[i]); } } } } return genericTypeArgsExtra; } private Object createNewInstanceForClassWithoutConstructors( Class<?> pojoClass, Map<Class<?>, Integer> pojos, Class<?> clazz, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Object retValue = null; Constructor<?>[] constructors = clazz.getConstructors(); if (constructors.length == 0 || Modifier.isAbstract(clazz.getModifiers())) { final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); try { Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, genericTypeArgs); if (genericTypeArgsExtra != null) { LOG.warn("Lost generic type arguments {}", Arrays.toString(genericTypeArgsExtra)); } } catch (IllegalStateException e) { LOG.error( "An error occurred while filling the type argument in the map", e); return null; } // If no publicly accessible constructors are available, // the best we can do is to find a constructor (e.g. // getInstance()) Method[] declaredMethods = clazz.getDeclaredMethods(); // A candidate factory method is a method which returns the // Class type // The parameters to pass to the method invocation Object[] parameterValues = null; Object[] noParams = new Object[] {}; for (Method candidateConstructor : declaredMethods) { if (!Modifier.isStatic(candidateConstructor.getModifiers()) || !candidateConstructor.getReturnType().equals(clazz) || retValue != null) { continue; } parameterValues = new Object[candidateConstructor .getParameterTypes().length]; Type[] parameterTypes = candidateConstructor .getGenericParameterTypes(); if (parameterTypes.length == 0) { parameterValues = noParams; } else { // This is a factory method with arguments Annotation[][] parameterAnnotations = candidateConstructor .getParameterAnnotations(); int idx = 0; for (Type paramType : parameterTypes) { AtomicReference<Type[]> methodGenericTypeArgs = new AtomicReference<Type[]>(); Class<?> parameterType = resolveGenericParameter( paramType, typeArgsMap, methodGenericTypeArgs); List<Annotation> annotations = Arrays .asList(parameterAnnotations[idx]); String attributeName = null; // It's a Collection type if (Collection.class.isAssignableFrom(parameterType)) { Collection<? super Object> listType = resolveCollectionType(parameterType); Class<?> elementType; if (paramType instanceof ParameterizedType) { elementType = (Class<?>) methodGenericTypeArgs .get()[0]; } else { LOG.warn("Collection parameter {} type is non-generic." + "We will assume a Collection<Object> for you.", paramType); elementType = Object.class; } int nbrElements = strategy .getNumberOfCollectionElements(elementType); for (Annotation annotation : annotations) { if (annotation.annotationType().equals( PodamCollection.class)) { PodamCollection ann = (PodamCollection) annotation; nbrElements = ann.nbrElements(); } } for (int i = 0; i < nbrElements; i++) { Object attributeValue = manufactureAttributeValue( clazz, pojos, elementType, annotations, attributeName); listType.add(attributeValue); } parameterValues[idx] = listType; // It's a Map } else if (Map.class.isAssignableFrom(parameterType)) { Map<? super Object, ? super Object> mapType = resolveMapType(parameterType); Class<?> keyClass; Class<?> valueClass; if (paramType instanceof ParameterizedType) { keyClass = (Class<?>) methodGenericTypeArgs .get()[0]; valueClass = (Class<?>) methodGenericTypeArgs .get()[1]; } else { LOG.warn("Map parameter {} type is non-generic." + "We will assume a Map<Object,Object> for you.", paramType); keyClass = Object.class; valueClass = Object.class; } int nbrElements = strategy .getNumberOfCollectionElements(valueClass); for (Annotation annotation : annotations) { if (annotation.annotationType().equals( PodamCollection.class)) { PodamCollection ann = (PodamCollection) annotation; nbrElements = ann.nbrElements(); } } for (int i = 0; i < nbrElements; i++) { Object keyValue = manufactureAttributeValue( clazz, pojos, keyClass, annotations, attributeName); Object elementValue = manufactureAttributeValue( clazz, pojos, valueClass, annotations, attributeName); mapType.put(keyValue, elementValue); } parameterValues[idx] = mapType; } else { // It's any other object parameterValues[idx] = manufactureAttributeValue( clazz, pojos, parameterType, annotations, attributeName, typeArgsMap, genericTypeArgs); } idx++; } } try { retValue = candidateConstructor.invoke(clazz, parameterValues); LOG.info("Could create an instance using " + candidateConstructor); } catch (Exception t) { LOG.info( "PODAM could not create an instance for constructor: " + candidateConstructor + ". Will try another one...", t); } } } else { // There are public constructors. We want constructor with minumum // number of parameters to speed up the creation strategy.sort(constructors); for (Constructor<?> constructor : constructors) { try { Object[] constructorArgs = getParameterValuesForConstructor( constructor, pojoClass, pojos, genericTypeArgs); retValue = constructor.newInstance(constructorArgs); LOG.info("For class: " + clazz.getName() + " a valid constructor: " + constructor + " was found. PODAM will use it to create an instance."); break; } catch (Exception t) { LOG.info( "Couldn't create attribute with constructor: " + constructor + ". Will check if other constructors are available", t); } } } if (retValue == null) { retValue = externalFactory.manufacturePojo(clazz, genericTypeArgs); } if (retValue == null) { LOG.warn("For attribute {}[{}] PODAM could not possibly create" + " a value. It will be returned as null.", pojoClass, clazz); } return retValue; } /** * It resolves generic parameter type * * * @param paramType * The generic parameter type * @param typeArgsMap * A map of resolved types * @param methodGenericTypeArgs * Return value posible generic types of the generic parameter * type * @return value for class representing the generic parameter type */ private Class<?> resolveGenericParameter(Type paramType, Map<String, Type> typeArgsMap, AtomicReference<Type[]> methodGenericTypeArgs) { Class<?> parameterType = null; methodGenericTypeArgs.set(new Type[] {}); if (paramType instanceof TypeVariable<?>) { final TypeVariable<?> typeVariable = (TypeVariable<?>) paramType; final Type type = typeArgsMap.get(typeVariable.getName()); if (type != null) { parameterType = resolveGenericParameter(type, typeArgsMap, methodGenericTypeArgs); } } else if (paramType instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) paramType; parameterType = (Class<?>) pType.getRawType(); methodGenericTypeArgs.set(pType.getActualTypeArguments()); } else if (paramType instanceof WildcardType) { WildcardType wType = (WildcardType) paramType; Type[] bounds = wType.getLowerBounds(); String msg; if (bounds != null && bounds.length > 0) { msg = "Lower bounds:"; } else { bounds = wType.getUpperBounds(); msg = "Upper bounds:"; } if (bounds != null && bounds.length > 0) { LOG.debug(msg + Arrays.toString(bounds)); parameterType = resolveGenericParameter(bounds[0], typeArgsMap, methodGenericTypeArgs); } } else if (paramType instanceof Class) { parameterType = (Class<?>) paramType; } if (parameterType == null) { LOG.warn("Unrecognized type {}. Will use Object instead", paramType); parameterType = Object.class; } return parameterType; } private Object resolvePrimitiveValue(Class<?> primitiveClass, List<Annotation> annotations, AttributeMetadata attributeMetadata) { Object retValue = null; if (primitiveClass.equals(int.class)) { if (!annotations.isEmpty()) { retValue = getIntegerValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getInteger(attributeMetadata); } } else if (primitiveClass.equals(long.class)) { if (!annotations.isEmpty()) { retValue = getLongValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getLong(attributeMetadata); } } else if (primitiveClass.equals(float.class)) { if (!annotations.isEmpty()) { retValue = getFloatValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getFloat(attributeMetadata); } } else if (primitiveClass.equals(double.class)) { if (!annotations.isEmpty()) { retValue = getDoubleValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getDouble(attributeMetadata); } } else if (primitiveClass.equals(boolean.class)) { if (!annotations.isEmpty()) { retValue = getBooleanValueForAnnotation(annotations); } if (retValue == null) { retValue = strategy.getBoolean(attributeMetadata); } } else if (primitiveClass.equals(byte.class)) { if (!annotations.isEmpty()) { retValue = getByteValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getByte(attributeMetadata); } } else if (primitiveClass.equals(short.class)) { if (!annotations.isEmpty()) { retValue = getShortValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getShort(attributeMetadata); } } else if (primitiveClass.equals(char.class)) { if (!annotations.isEmpty()) { retValue = getCharacterValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getCharacter(attributeMetadata); } } return retValue; } /** * It returns the boolean value indicated in the annotation. * * @param annotations * The collection of annotations for the annotated attribute * @return The boolean value indicated in the annotation */ private Boolean getBooleanValueForAnnotation(List<Annotation> annotations) { Boolean retValue = null; for (Annotation annotation : annotations) { if (PodamBooleanValue.class.isAssignableFrom(annotation.getClass())) { PodamBooleanValue localStrategy = (PodamBooleanValue) annotation; retValue = localStrategy.boolValue(); break; } } return retValue; } private Byte getByteValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Byte retValue = null; for (Annotation annotation : annotations) { if (PodamByteValue.class.isAssignableFrom(annotation.getClass())) { PodamByteValue intStrategy = (PodamByteValue) annotation; String numValueStr = intStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Byte.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = "The precise value: " + numValueStr + " cannot be converted to a byte type. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { byte minValue = intStrategy.minValue(); byte maxValue = intStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getByteInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } private Short getShortValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Short retValue = null; for (Annotation annotation : annotations) { if (PodamShortValue.class.isAssignableFrom(annotation.getClass())) { PodamShortValue shortStrategy = (PodamShortValue) annotation; String numValueStr = shortStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Short.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = "The precise value: " + numValueStr + " cannot be converted to a short type. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { short minValue = shortStrategy.minValue(); short maxValue = shortStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getShortInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } /** * It creates and returns a random {@link Character} value * * @param annotations * The list of annotations which might customise the return value * * @param attributeMetadata * The attribute's metadata, if any, used for customisation * * @return A random {@link Character} value */ private Character getCharacterValueWithinRange( List<Annotation> annotations, AttributeMetadata attributeMetadata) { Character retValue = null; for (Annotation annotation : annotations) { if (PodamCharValue.class.isAssignableFrom(annotation.getClass())) { PodamCharValue annotationStrategy = (PodamCharValue) annotation; char charValue = annotationStrategy.charValue(); if (charValue != ' ') { retValue = charValue; } else { char minValue = annotationStrategy.minValue(); char maxValue = annotationStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getCharacterInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } private Integer getIntegerValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Integer retValue = null; for (Annotation annotation : annotations) { if (PodamIntValue.class.isAssignableFrom(annotation.getClass())) { PodamIntValue intStrategy = (PodamIntValue) annotation; String numValueStr = intStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Integer.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = THE_ANNOTATION_VALUE_STR + numValueStr + " could not be converted to an Integer. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { int minValue = intStrategy.minValue(); int maxValue = intStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getIntegerInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } private Float getFloatValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Float retValue = null; for (Annotation annotation : annotations) { if (PodamFloatValue.class.isAssignableFrom(annotation.getClass())) { PodamFloatValue floatStrategy = (PodamFloatValue) annotation; String numValueStr = floatStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Float.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = THE_ANNOTATION_VALUE_STR + numValueStr + " could not be converted to a Float. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { float minValue = floatStrategy.minValue(); float maxValue = floatStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getFloatInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } /** * It creates and returns a random {@link Double} value * * @param annotations * The list of annotations which might customise the return value * * @param attributeMetadata * The attribute's metadata, if any, used for customisation * * * @return a random {@link Double} value */ private Double getDoubleValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Double retValue = null; for (Annotation annotation : annotations) { if (PodamDoubleValue.class.isAssignableFrom(annotation.getClass())) { PodamDoubleValue doubleStrategy = (PodamDoubleValue) annotation; String numValueStr = doubleStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Double.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = THE_ANNOTATION_VALUE_STR + numValueStr + " could not be converted to a Double. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { double minValue = doubleStrategy.minValue(); double maxValue = doubleStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getDoubleInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } private Long getLongValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Long retValue = null; for (Annotation annotation : annotations) { if (PodamLongValue.class.isAssignableFrom(annotation.getClass())) { PodamLongValue longStrategy = (PodamLongValue) annotation; String numValueStr = longStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Long.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = THE_ANNOTATION_VALUE_STR + numValueStr + " could not be converted to a Long. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { long minValue = longStrategy.minValue(); long maxValue = longStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getLongInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } /** * It attempts to resolve the given class as a wrapper class and if this is * the case it assigns a random value * * * @param candidateWrapperClass * The class which might be a wrapper class * @param attributeMetadata * The attribute's metadata, if any, used for customisation * @return {@code null} if this is not a wrapper class, otherwise an Object * with the value for the wrapper class */ private Object resolveWrapperValue(Class<?> candidateWrapperClass, List<Annotation> annotations, AttributeMetadata attributeMetadata) { Object retValue = null; if (candidateWrapperClass.equals(Integer.class)) { if (!annotations.isEmpty()) { retValue = getIntegerValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getInteger(attributeMetadata); } } else if (candidateWrapperClass.equals(Long.class)) { if (!annotations.isEmpty()) { retValue = getLongValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getLong(attributeMetadata); } } else if (candidateWrapperClass.equals(Float.class)) { if (!annotations.isEmpty()) { retValue = getFloatValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getFloat(attributeMetadata); } } else if (candidateWrapperClass.equals(Double.class)) { if (!annotations.isEmpty()) { retValue = getDoubleValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getDouble(attributeMetadata); } } else if (candidateWrapperClass.equals(Boolean.class)) { if (!annotations.isEmpty()) { retValue = getBooleanValueForAnnotation(annotations); } if (retValue == null) { retValue = strategy.getBoolean(attributeMetadata); } } else if (candidateWrapperClass.equals(Byte.class)) { if (!annotations.isEmpty()) { retValue = getByteValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getByte(attributeMetadata); } } else if (candidateWrapperClass.equals(Short.class)) { if (!annotations.isEmpty()) { retValue = getShortValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getShort(attributeMetadata); } } else if (candidateWrapperClass.equals(Character.class)) { if (!annotations.isEmpty()) { retValue = getCharacterValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getCharacter(attributeMetadata); } } return retValue; } @SuppressWarnings({ UNCHECKED_STR, RAWTYPES_STR }) private <T> T resolvePojoWithoutSetters(Class<T> pojoClass, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { T retValue = null; Constructor<?>[] constructors = pojoClass.getConstructors(); if (constructors.length == 0) { retValue = (T) createNewInstanceForClassWithoutConstructors( pojoClass, pojos, pojoClass, genericTypeArgs); } else { // There are public constructors. We want constructor with minumum // number of parameters to speed up the creation strategy.sort(constructors); for (Constructor<?> constructor : constructors) { Object[] parameterValues = getParameterValuesForConstructor( constructor, pojoClass, pojos, genericTypeArgs); // Being a generic method we cannot be sure on the identity of // T, therefore the mismatch between the newInstance() return // value (Object) and T is acceptable, thus the SuppressWarning // annotation try { if (!constructor.isAccessible()) { constructor.setAccessible(true); } retValue = (T) constructor.newInstance(parameterValues); if (retValue instanceof Collection && ((Collection) retValue).isEmpty()) { LOG.info("We could create an instance with constructor: " + constructor + ", but collection is empty" + ". Will try with another one."); } else if (retValue instanceof Map && ((Map) retValue).isEmpty()) { LOG.info("We could create an instance with constructor: " + constructor + ", but map is empty" + ". Will try with another one."); } else { LOG.info("We could create an instance with constructor: " + constructor); break; } } catch (Exception t) { LOG.info("We couldn't create an instance for pojo: " + pojoClass + " for constructor: " + constructor + ". Will try with another one.", t); } } if (retValue == null) { retValue = externalFactory.manufacturePojo(pojoClass, genericTypeArgs); } } return retValue; } @SuppressWarnings(UNCHECKED_STR) private <T> T manufacturePojoInternal(Class<T> pojoClass, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { T retValue = null; // reuse object from memoization table if (strategy.isMemoizationEnabled()) { T objectToReuse = (T) memoizationTable.get(pojoClass); if (objectToReuse != null) { return objectToReuse; } } if (pojoClass.isPrimitive()) { // For JDK POJOs we can't retrieve attribute name List<Annotation> annotations = new ArrayList<Annotation>(); String noName = null; return (T) resolvePrimitiveValue(pojoClass, annotations, new AttributeMetadata(noName, pojoClass, annotations, pojoClass)); } if (pojoClass.isInterface() || Modifier.isAbstract(pojoClass.getModifiers())) { Class<T> specificClass = (Class<T>) strategy .getSpecificClass(pojoClass); if (!specificClass.equals(pojoClass)) { return this.manufacturePojoInternal(specificClass, pojos, genericTypeArgs); } else { if (Modifier.isAbstract(pojoClass.getModifiers())) { return (T) createNewInstanceForClassWithoutConstructors( pojoClass, pojos, pojoClass, genericTypeArgs); } else { return externalFactory.manufacturePojo(pojoClass, genericTypeArgs); } } } // If a public no-arg constructor can be found we use it, // otherwise we try to find a non-public one and we use that. If the // class does not have a no-arg constructor we search for a suitable // constructor. try { Constructor<?>[] constructors = pojoClass.getConstructors(); if (constructors == null || constructors.length == 0) { LOG.warn("No public constructors were found for {}. " + "We'll look for a default, non-public constructor.", pojoClass); Constructor<T> defaultConstructor = pojoClass .getDeclaredConstructor(new Class[] {}); LOG.info("Will use: " + defaultConstructor); // Security hack defaultConstructor.setAccessible(true); retValue = defaultConstructor.newInstance(); } else { retValue = resolvePojoWithoutSetters(pojoClass, pojos, genericTypeArgs); } } catch (SecurityException e) { throw new PodamMockeryException( "Security exception while applying introspection.", e); } catch (NoSuchMethodException e1) { LOG.info( "No default (public or non-public) constructors were found. " + "Also no other public constructors were found. " + "Your last hope is that we find a non-public, non-default constructor.", e1); Constructor<?>[] constructors = pojoClass.getDeclaredConstructors(); if (constructors == null || constructors.length == 0) { throw new IllegalStateException( "The POJO " + pojoClass + " appears without constructors. How is this possible? "); } LOG.info("Will use: " + constructors[0]); // It uses the first public constructor found Object[] parameterValuesForConstructor = getParameterValuesForConstructor( constructors[0], pojoClass, pojos, genericTypeArgs); constructors[0].setAccessible(true); retValue = (T) constructors[0] .newInstance(parameterValuesForConstructor); } // update memoization table with new object // the reference is stored before properties are set so that recursive // properties can use it if (strategy.isMemoizationEnabled()) { memoizationTable.put(pojoClass, retValue); } /* Construction failed, no point to continue */ if (retValue == null) { return null; } if (retValue instanceof Collection && ((Collection<?>)retValue).size() == 0) { fillCollection((Collection<? super Object>)retValue, pojos, genericTypeArgs); } else if (retValue instanceof Map && ((Map<?,?>)retValue).size() == 0) { fillMap((Map<? super Object,? super Object>)retValue, pojos, genericTypeArgs); } Class<?>[] parameterTypes = null; Class<?> attributeType = null; ClassInfo classInfo = PodamUtils.getClassInfo(pojoClass, strategy.getExcludedAnnotations()); // According to JavaBeans standards, setters should have only // one argument Object setterArg = null; for (Method setter : classInfo.getClassSetters()) { List<Annotation> pojoAttributeAnnotations = retrieveFieldAnnotations( pojoClass, setter); String attributeName = PodamUtils .extractFieldNameFromSetterMethod(setter); parameterTypes = setter.getParameterTypes(); if (parameterTypes.length != 1) { throw new IllegalStateException("A " + pojoClass.getSimpleName() + "." + setter.getName() + "() should have only one argument"); } // A class which has got an attribute to itself (e.g. // recursive hierarchies) attributeType = parameterTypes[0]; // If an attribute has been annotated with // PodamAttributeStrategy, it takes the precedence over any // other strategy. Additionally we don't pass the attribute // metadata for value customisation; if user went to the extent // of specifying a PodamAttributeStrategy annotation for an // attribute they are already customising the value assigned to // that attribute. PodamStrategyValue attributeStrategyAnnotation = containsAttributeStrategyAnnotation(pojoAttributeAnnotations); if (null != attributeStrategyAnnotation) { AttributeStrategy<?> attributeStrategy = attributeStrategyAnnotation .value().newInstance(); if (LOG.isDebugEnabled()) { LOG.debug("The attribute: " + attributeName + " will be filled using the following strategy: " + attributeStrategy); } setterArg = returnAttributeDataStrategyValue(attributeType, attributeStrategy); } else { final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, genericTypeArgs); if (genericTypeArgsExtra != null) { LOG.warn("Lost generic type arguments {}", Arrays.toString(genericTypeArgsExtra)); } Type[] typeArguments = new Type[] {}; // If the parameter is a generic parameterized type resolve // the actual type arguments if (setter.getGenericParameterTypes()[0] instanceof ParameterizedType) { final ParameterizedType attributeParameterizedType = (ParameterizedType) setter .getGenericParameterTypes()[0]; typeArguments = attributeParameterizedType .getActualTypeArguments(); } else if (setter.getGenericParameterTypes()[0] instanceof TypeVariable) { final TypeVariable<?> typeVariable = (TypeVariable<?>) setter .getGenericParameterTypes()[0]; Type type = typeArgsMap.get(typeVariable.getName()); if (type instanceof ParameterizedType) { final ParameterizedType attributeParameterizedType = (ParameterizedType) type; typeArguments = attributeParameterizedType .getActualTypeArguments(); attributeType = (Class<?>) attributeParameterizedType .getRawType(); } else { attributeType = (Class<?>) type; } } AtomicReference<Type[]> typeGenericTypeArgs = new AtomicReference<Type[]>(new Type[] {}); for (int i = 0; i < typeArguments.length; i++) { if (typeArguments[i] instanceof TypeVariable) { Class<?> resolvedType = resolveGenericParameter(typeArguments[i], typeArgsMap, typeGenericTypeArgs); if (!Collection.class.isAssignableFrom(resolvedType) && !Map.class.isAssignableFrom(resolvedType)) { typeArguments[i] = resolvedType; } } } setterArg = manufactureAttributeValue(pojoClass, pojos, attributeType, pojoAttributeAnnotations, attributeName, typeArgsMap, typeArguments); if (null == setterArg) { setterArg = externalFactory.manufacturePojo(attributeType); } } if (setterArg != null) { try { setter.invoke(retValue, setterArg); } catch(IllegalAccessException e) { LOG.warn("{} is not accessible. Setting it to accessible." + " However this is a security hack and your code" + " should really adhere to JavaBeans standards.", setter.toString()); setter.setAccessible(true); setter.invoke(retValue, setterArg); } } else { LOG.warn("Couldn't find a suitable value for attribute {}[{}]" + ". It will be left to null.", pojoClass, attributeType); } } return retValue; } private Object manufactureAttributeValue(Class<?> pojoClass, Map<Class<?>, Integer> pojos, Class<?> attributeType, List<Annotation> annotations, String attributeName, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Map<String, Type> nullTypeArgsMap = new HashMap<String, Type>(); return manufactureAttributeValue(pojoClass, pojos, attributeType, annotations, attributeName, nullTypeArgsMap, genericTypeArgs); } @SuppressWarnings(RAWTYPES_STR) private Object manufactureAttributeValue(Class<?> pojoClass, Map<Class<?>, Integer> pojos, Class<?> attributeType, List<Annotation> annotations, String attributeName, Map<String, Type> typeArgsMap, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Object attributeValue = null; Class<?> realAttributeType; if (genericTypeArgs.length > 0 && genericTypeArgs[0] instanceof Class && attributeType.isAssignableFrom((Class) genericTypeArgs[0])) { realAttributeType = (Class) genericTypeArgs[0]; } else { realAttributeType = attributeType; } AttributeMetadata attributeMetadata = new AttributeMetadata( attributeName, realAttributeType, annotations, pojoClass); // Primitive type if (realAttributeType.isPrimitive()) { attributeValue = resolvePrimitiveValue(realAttributeType, annotations, attributeMetadata); // Wrapper type } else if (isWrapper(realAttributeType)) { attributeValue = resolveWrapperValue(realAttributeType, annotations, attributeMetadata); // String type } else if (realAttributeType.equals(String.class)) { attributeValue = resolveStringValue(annotations, attributeMetadata); } else if (realAttributeType.getName().startsWith("[")) { // Array type attributeValue = resolveArrayElementValue(realAttributeType, pojos, annotations, pojoClass, attributeName, typeArgsMap); // Otherwise it's a different type of Object (including // the Object class) } else if (Collection.class.isAssignableFrom(realAttributeType)) { // Collection type try { attributeValue = resolveCollectionValueWhenCollectionIsPojoAttribute( pojoClass, pojos, realAttributeType, attributeName, annotations, typeArgsMap, genericTypeArgs); } catch(IllegalArgumentException e) { LOG.info("Cannot manufacture list {}, will try strategy", realAttributeType); } } else if (Map.class.isAssignableFrom(realAttributeType)) { // Map type try { attributeValue = resolveMapValueWhenMapIsPojoAttribute(pojoClass, pojos, realAttributeType, attributeName, annotations, typeArgsMap, genericTypeArgs); } catch(IllegalArgumentException e) { LOG.info("Cannot manufacture map {}, will try strategy", realAttributeType); } } else if (realAttributeType.isEnum()) { // Enum type int enumConstantsLength = realAttributeType.getEnumConstants().length; if (enumConstantsLength > 0) { int enumIndex = strategy.getIntegerInRange(0, enumConstantsLength, attributeMetadata) % enumConstantsLength; attributeValue = realAttributeType.getEnumConstants()[enumIndex]; } } else if (realAttributeType.isAssignableFrom(Class.class)) { if (genericTypeArgs.length > 0 && genericTypeArgs[0] != null) { AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>(new Type[] {}); attributeValue = resolveGenericParameter(genericTypeArgs[0], typeArgsMap, elementGenericTypeArgs); } else { LOG.error("{} is missing generic type argument", realAttributeType); } } // For any other type, we use the PODAM strategy if (attributeValue == null) { Integer depth = pojos.get(realAttributeType); if (depth == null) { depth = -1; } if (depth <= strategy.getMaxDepth(pojoClass)) { pojos.put(realAttributeType, depth + 1); if (realAttributeType.getName().startsWith("java.") || realAttributeType.getName().startsWith("javax.")) { // For classes in the Java namespace we attempt the no-args // or the // factory constructor strategy attributeValue = createNewInstanceForClassWithoutConstructors( pojoClass, pojos, realAttributeType, genericTypeArgs); } else { attributeValue = this.manufacturePojoInternal( realAttributeType, pojos, genericTypeArgs); } pojos.put(realAttributeType, depth); } else { LOG.warn("Loop in {} production detected.", realAttributeType); attributeValue = externalFactory.manufacturePojo( realAttributeType, genericTypeArgs); } } return attributeValue; } private String resolveStringValue(List<Annotation> annotations, AttributeMetadata attributeMetadata) throws InstantiationException, IllegalAccessException { String retValue = null; if (annotations == null || annotations.isEmpty()) { retValue = strategy.getStringValue(attributeMetadata); } else { for (Annotation annotation : annotations) { if (!PodamStringValue.class.isAssignableFrom(annotation .getClass())) { continue; } // A specific value takes precedence over the length PodamStringValue podamAnnotation = (PodamStringValue) annotation; if (podamAnnotation.strValue() != null && podamAnnotation.strValue().length() > 0) { retValue = podamAnnotation.strValue(); } else { retValue = strategy.getStringOfLength( podamAnnotation.length(), attributeMetadata); } } if (retValue == null) { retValue = strategy.getStringValue(attributeMetadata); } } return retValue; } /** * It returns an default value for a {@link Field} matching the attribute * name or null if a field was not found. * * @param pojoClass * The class supposed to contain the field * @param attributeName * The field name * * @return an instance of {@link Field} matching the attribute name or * null if a field was not found. */ private <T> T getDefaultFieldValue(Class<?> pojoClass, String attributeName) { T retValue = null; try { Field field = getField(pojoClass, attributeName); if (field == null) { throw new NoSuchFieldException( "It was not possible to retrieve field: " + attributeName); } // It allows to invoke Field.get on private fields field.setAccessible(true); // TODO: we probably already have instantiated the pojoClass, // it will be better to pass pojoInstance instead of pojoClass Object newInstance = pojoClass.newInstance(); retValue = (T) field.get(newInstance); } catch (Exception e) { LOG.info( "The field didn't exist or we couldn't call an empty constructor.", e); } return retValue; } /** * It returns a {@link Field} matching the attribute name or null if a field * was not found. * * @param pojoClass * The class supposed to contain the field * @param attributeName * The field name * * @return a {@link Field} matching the attribute name or null if a field * was not found. */ private Field getField(Class<?> pojoClass, String attributeName) { Field field = null; Class<?> clazz = pojoClass; while (clazz != null) { try { field = clazz.getDeclaredField(attributeName); break; } catch (NoSuchFieldException e) { LOG.info("A field could not be found for attribute name: " + attributeName, e); clazz = clazz.getSuperclass(); } } return field; } /** * It returns a {@link PodamStrategyValue} if one was specified, or * {@code null} otherwise. * * @param annotations * The list of annotations * @return {@code true} if the list of annotations contains at least one * {@link PodamStrategyValue} annotation. */ private PodamStrategyValue containsAttributeStrategyAnnotation( List<Annotation> annotations) { PodamStrategyValue retValue = null; for (Annotation annotation : annotations) { if (PodamStrategyValue.class .isAssignableFrom(annotation.getClass())) { retValue = (PodamStrategyValue) annotation; break; } } return retValue; } /** * It returns {@code true} if this class is a wrapper class, {@code false} * otherwise * * @param candidateWrapperClass * The class to check * @return {@code true} if this class is a wrapper class, {@code false} * otherwise */ private boolean isWrapper(Class<?> candidateWrapperClass) { return candidateWrapperClass.equals(Byte.class) ? true : candidateWrapperClass.equals(Boolean.class) ? true : candidateWrapperClass.equals(Character.class) ? true : candidateWrapperClass.equals(Short.class) ? true : candidateWrapperClass .equals(Integer.class) ? true : candidateWrapperClass .equals(Long.class) ? true : candidateWrapperClass .equals(Float.class) ? true : candidateWrapperClass .equals(Double.class) ? true : false; } /** * Given the original class and the setter method, it returns all * annotations for the field or an empty collection if no custom annotations * were found on the field * * @param clazz * The class containing the annotated attribute * @param setter * The setter method * @return all annotations for the field * @throws NoSuchFieldException * If the field could not be found * @throws SecurityException * if a security exception occurred */ private List<Annotation> retrieveFieldAnnotations(Class<?> clazz, Method setter) { Class<?> workClass = clazz; List<Annotation> retValue = new ArrayList<Annotation>(); // Checks if the field has got any custom annotations String attributeName = PodamUtils .extractFieldNameFromSetterMethod(setter); Field setterField = null; while (workClass != null) { try { setterField = workClass.getDeclaredField(attributeName); break; } catch (NoSuchFieldException e) { LOG.info( "A field for " + attributeName + " could not be found", e); workClass = workClass.getSuperclass(); } } if (setterField != null) { Annotation[] annotations = setterField.getAnnotations(); if (annotations != null && annotations.length != 0) { retValue = Arrays.asList(annotations); } } return retValue; } @SuppressWarnings({ UNCHECKED_STR }) private Collection<? super Object> resolveCollectionValueWhenCollectionIsPojoAttribute( Class<?> pojoClass, Map<Class<?>, Integer> pojos, Class<?> collectionType, String attributeName, List<Annotation> annotations, Map<String, Type> typeArgsMap, Type... genericTypeArgs) { // This needs to be generic because collections can be of any type Collection<? super Object> retValue = getDefaultFieldValue(pojoClass, attributeName); if (null == retValue) { retValue = resolveCollectionType(collectionType); } try { Class<?> typeClass = null; AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); if (genericTypeArgs == null || genericTypeArgs.length == 0) { LOG.warn("The collection attribute: " + attributeName + " does not have a type. We will assume Object for you"); // Support for non-generified collections typeClass = Object.class; } else { Type actualTypeArgument = genericTypeArgs[0]; typeClass = resolveGenericParameter(actualTypeArgument, typeArgsMap, elementGenericTypeArgs); } fillCollection(pojoClass, pojos, attributeName, annotations, retValue, typeClass, elementGenericTypeArgs.get()); } catch (SecurityException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (IllegalArgumentException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (InstantiationException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (IllegalAccessException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (ClassNotFoundException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (InvocationTargetException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } return retValue; } private void fillCollection(Collection<? super Object> collection, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); Class<?> pojoClass = collection.getClass(); Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, genericTypeArgs); if (genericTypeArgsExtra != null && genericTypeArgsExtra.length > 0) { LOG.warn("Lost generic type arguments {}", Arrays.toString(genericTypeArgsExtra)); } String attributeName = null; Annotation[] annotations = collection.getClass().getAnnotations(); Class<?> collectionClass = pojoClass; AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); Type[] typeParams = collectionClass.getTypeParameters(); while (typeParams.length < 1) { Type type = collectionClass.getGenericSuperclass(); collectionClass = resolveGenericParameter(type, typeArgsMap, elementGenericTypeArgs); typeParams = elementGenericTypeArgs.get(); } Class<?> elementTypeClass = resolveGenericParameter(typeParams[0], typeArgsMap, elementGenericTypeArgs); fillCollection(pojoClass, pojos, attributeName, Arrays.asList(annotations), collection, elementTypeClass, elementGenericTypeArgs.get()); } private void fillCollection(Class<?> pojoClass, Map<Class<?>, Integer> pojos, String attributeName, List<Annotation> annotations, Collection<? super Object> collection, Class<?> collectionElementType, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { // If the user defined a strategy to fill the collection elements, // we use it PodamCollection collectionAnnotation = null; AttributeStrategy<?> elementStrategy = null; for (Annotation annotation : annotations) { if (PodamCollection.class.isAssignableFrom(annotation.getClass())) { collectionAnnotation = (PodamCollection) annotation; break; } } int nbrElements = strategy .getNumberOfCollectionElements(collectionElementType); if (null != collectionAnnotation) { nbrElements = collectionAnnotation.nbrElements(); elementStrategy = collectionAnnotation.collectionElementStrategy() .newInstance(); } for (int i = 0; i < nbrElements; i++) { // The default if (null != elementStrategy && ObjectStrategy.class.isAssignableFrom(elementStrategy .getClass()) && Object.class.equals(collectionElementType)) { LOG.debug("Element strategy is ObjectStrategy and collection element is of type Object: using the ObjectStrategy strategy"); collection.add(elementStrategy.getValue()); } else if (null != elementStrategy && !ObjectStrategy.class.isAssignableFrom(elementStrategy .getClass())) { LOG.debug("Collection elements will be filled using the following strategy: " + elementStrategy); Object strategyValue = returnAttributeDataStrategyValue( collectionElementType, elementStrategy); collection.add(strategyValue); } else { collection.add(manufactureAttributeValue(pojoClass, pojos, collectionElementType, annotations, attributeName, genericTypeArgs)); } } } private Map<? super Object, ? super Object> resolveMapValueWhenMapIsPojoAttribute( Class<?> pojoClass, Map<Class<?>, Integer> pojos, Class<?> attributeType, String attributeName, List<Annotation> annotations, Map<String, Type> typeArgsMap, Type... genericTypeArgs) { Map<? super Object, ? super Object> retValue = getDefaultFieldValue(pojoClass, attributeName); if (null == retValue) { retValue = resolveMapType(attributeType); } try { Class<?> keyClass = null; Class<?> elementClass = null; AtomicReference<Type[]> keyGenericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); if (genericTypeArgs == null || genericTypeArgs.length == 0) { LOG.warn("Map attribute: " + attributeName + " is non-generic. We will assume a Map<Object, Object> for you."); keyClass = Object.class; elementClass = Object.class; } else { // Expected only key, value type if (genericTypeArgs.length != 2) { throw new IllegalStateException( "In a Map only key value generic type are expected."); } Type[] actualTypeArguments = genericTypeArgs; keyClass = resolveGenericParameter(actualTypeArguments[0], typeArgsMap, keyGenericTypeArgs); elementClass = resolveGenericParameter(actualTypeArguments[1], typeArgsMap, elementGenericTypeArgs); } MapArguments mapArguments = new MapArguments(); mapArguments.setPojoClass(pojoClass); mapArguments.setPojos(pojos); mapArguments.setAttributeName(attributeName); mapArguments.setAnnotations(annotations); mapArguments.setMapToBeFilled(retValue); mapArguments.setKeyClass(keyClass); mapArguments.setElementClass(elementClass); mapArguments.setKeyGenericTypeArgs(keyGenericTypeArgs.get()); mapArguments .setElementGenericTypeArgs(elementGenericTypeArgs.get()); fillMap(mapArguments); } catch (InstantiationException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } catch (IllegalAccessException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } catch (SecurityException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } catch (ClassNotFoundException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } catch (InvocationTargetException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } return retValue; } private void fillMap(Map<? super Object, ? super Object> map, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); Class<?> pojoClass = map.getClass(); Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, genericTypeArgs); if (genericTypeArgsExtra != null && genericTypeArgsExtra.length > 0) { LOG.warn("Lost generic type arguments {}", Arrays.toString(genericTypeArgsExtra)); } Annotation[] annotations = pojoClass.getAnnotations(); String attributeName = null; Class<?> mapClass = pojoClass; AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); Type[] typeParams = mapClass.getTypeParameters(); while (typeParams.length < 2) { Type type = mapClass.getGenericSuperclass(); mapClass = resolveGenericParameter(type, typeArgsMap, elementGenericTypeArgs); typeParams = elementGenericTypeArgs.get(); } AtomicReference<Type[]> keyGenericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); Class<?> keyClass = resolveGenericParameter(typeParams[0], typeArgsMap, keyGenericTypeArgs); Class<?> elementClass = resolveGenericParameter(typeParams[1], typeArgsMap, elementGenericTypeArgs); MapArguments mapArguments = new MapArguments(); mapArguments.setPojoClass(pojoClass); mapArguments.setPojos(pojos); mapArguments.setAttributeName(attributeName); mapArguments.setAnnotations(Arrays.asList(annotations)); mapArguments.setMapToBeFilled(map); mapArguments.setKeyClass(keyClass); mapArguments.setElementClass(elementClass); mapArguments.setKeyGenericTypeArgs(keyGenericTypeArgs.get()); mapArguments .setElementGenericTypeArgs(elementGenericTypeArgs.get()); fillMap(mapArguments); } private void fillMap(MapArguments mapArguments) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { // If the user defined a strategy to fill the collection elements, // we use it PodamCollection collectionAnnotation = null; AttributeStrategy<?> keyStrategy = null; AttributeStrategy<?> elementStrategy = null; for (Annotation annotation : mapArguments.getAnnotations()) { if (PodamCollection.class.isAssignableFrom(annotation.getClass())) { collectionAnnotation = (PodamCollection) annotation; break; } } int nbrElements = strategy.getNumberOfCollectionElements(mapArguments .getElementClass()); if (null != collectionAnnotation) { nbrElements = collectionAnnotation.nbrElements(); keyStrategy = collectionAnnotation.mapKeyStrategy().newInstance(); elementStrategy = collectionAnnotation.mapElementStrategy() .newInstance(); } for (int i = 0; i < nbrElements; i++) { Object keyValue = null; Object elementValue = null; MapKeyOrElementsArguments valueArguments = new MapKeyOrElementsArguments(); valueArguments.setPojoClass(mapArguments.getPojoClass()); valueArguments.setPojos(mapArguments.getPojos()); valueArguments.setAttributeName(mapArguments.getAttributeName()); valueArguments.setAnnotations(mapArguments.getAnnotations()); valueArguments.setKeyOrValueType(mapArguments.getKeyClass()); valueArguments.setElementStrategy(keyStrategy); valueArguments.setGenericTypeArgs(mapArguments .getKeyGenericTypeArgs()); keyValue = getMapKeyOrElementValue(valueArguments); valueArguments = new MapKeyOrElementsArguments(); valueArguments.setPojoClass(mapArguments.getPojoClass()); valueArguments.setPojos(mapArguments.getPojos()); valueArguments.setAttributeName(mapArguments.getAttributeName()); valueArguments.setAnnotations(mapArguments.getAnnotations()); valueArguments.setKeyOrValueType(mapArguments.getElementClass()); valueArguments.setElementStrategy(elementStrategy); valueArguments.setGenericTypeArgs(mapArguments .getElementGenericTypeArgs()); elementValue = getMapKeyOrElementValue(valueArguments); Map<? super Object, ? super Object> map = mapArguments.getMapToBeFilled(); /* ConcurrentHashMap doesn't allow null values */ if (elementValue != null || !(map instanceof ConcurrentHashMap)) { map.put(keyValue, elementValue); } } } private Object getMapKeyOrElementValue( MapKeyOrElementsArguments keyOrElementsArguments) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Object retValue = null; if (null != keyOrElementsArguments.getElementStrategy() && ObjectStrategy.class.isAssignableFrom(keyOrElementsArguments .getElementStrategy().getClass()) && Object.class.equals(keyOrElementsArguments .getKeyOrValueType())) { LOG.debug("Element strategy is ObjectStrategy and Map key or value type is of type Object: using the ObjectStrategy strategy"); retValue = keyOrElementsArguments.getElementStrategy().getValue(); } else if (null != keyOrElementsArguments.getElementStrategy() && !ObjectStrategy.class .isAssignableFrom(keyOrElementsArguments .getElementStrategy().getClass())) { LOG.debug("Map key or value will be filled using the following strategy: " + keyOrElementsArguments.getElementStrategy()); retValue = returnAttributeDataStrategyValue( keyOrElementsArguments.getKeyOrValueType(), keyOrElementsArguments.getElementStrategy()); } else { retValue = manufactureAttributeValue( keyOrElementsArguments.getPojoClass(), keyOrElementsArguments.getPojos(), keyOrElementsArguments.getKeyOrValueType(), keyOrElementsArguments.getAnnotations(), keyOrElementsArguments.getAttributeName(), keyOrElementsArguments.getGenericTypeArgs()); } return retValue; } private Object resolveArrayElementValue(Class<?> attributeType, Map<Class<?>, Integer> pojos, List<Annotation> annotations, Class<?> pojoClass, String attributeName, Map<String, Type> typeArgsMap) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Class<?> componentType = attributeType.getComponentType(); AtomicReference<Type[]> genericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); if (null != attributeName) { try { final Type genericType = pojoClass.getDeclaredField( attributeName).getGenericType(); if (genericType instanceof GenericArrayType) { final Type type = ((GenericArrayType) genericType) .getGenericComponentType(); if (type instanceof TypeVariable<?>) { final Type typeVarType = typeArgsMap .get(((TypeVariable<?>) type).getName()); componentType = resolveGenericParameter(typeVarType, typeArgsMap, genericTypeArgs); } } } catch (NoSuchFieldException e) { LOG.info("Cannot get the declared field type for field " + attributeName + " of class " + pojoClass.getName(), e); } } // If the user defined a strategy to fill the collection elements, // we use it PodamCollection collectionAnnotation = null; AttributeStrategy<?> elementStrategy = null; for (Annotation annotation : annotations) { if (PodamCollection.class.isAssignableFrom(annotation.getClass())) { collectionAnnotation = (PodamCollection) annotation; break; } } int nbrElements; if (null != collectionAnnotation) { nbrElements = collectionAnnotation.nbrElements(); elementStrategy = collectionAnnotation.collectionElementStrategy() .newInstance(); } else { nbrElements = strategy.getNumberOfCollectionElements(attributeType); } Object arrayElement = null; Object array = Array.newInstance(componentType, nbrElements); for (int i = 0; i < nbrElements; i++) { // The default if (null != elementStrategy && ObjectStrategy.class .isAssignableFrom(collectionAnnotation .collectionElementStrategy()) && Object.class.equals(componentType)) { LOG.debug("Element strategy is ObjectStrategy and array element is of type Object: using the ObjectStrategy strategy"); arrayElement = elementStrategy.getValue(); } else if (null != elementStrategy && !ObjectStrategy.class .isAssignableFrom(collectionAnnotation .collectionElementStrategy())) { LOG.debug("Array elements will be filled using the following strategy: " + elementStrategy); arrayElement = returnAttributeDataStrategyValue(componentType, elementStrategy); } else { arrayElement = manufactureAttributeValue(pojoClass, pojos, componentType, annotations, attributeName, typeArgsMap, genericTypeArgs.get()); } Array.set(array, i, arrayElement); } return array; } /** * Given a collection type it returns an instance * <p> * <ul> * <li>The default type for a {@link List} is an {@link ArrayList}</li> * <li>The default type for a {@link Queue} is a {@link LinkedList}</li> * <li>The default type for a {@link Set} is a {@link HashSet}</li> * </ul> * * </p> * * @param collectionType * The collection type * * @return an instance of the collection type */ @SuppressWarnings({ RAWTYPES_STR, UNCHECKED_STR }) private Collection<? super Object> resolveCollectionType( Class<?> collectionType) { Collection<? super Object> retValue = null; // Default list and set are ArrayList and HashSet. If users // wants a particular collection flavour they have to initialise // the collection if (Queue.class.isAssignableFrom(collectionType)) { if (collectionType.isAssignableFrom(LinkedList.class)) { retValue = new LinkedList(); } } else if (Set.class.isAssignableFrom(collectionType)) { if (collectionType.isAssignableFrom(HashSet.class)) { retValue = new HashSet(); } } else { if (collectionType.isAssignableFrom(ArrayList.class)) { retValue = new ArrayList(); } } if (null == retValue) { throw new IllegalArgumentException("Collection type: " + collectionType + " not supported"); } return retValue; } /** * It manufactures and returns a default instance for each map type * * <p> * The default implementation for a {@link ConcurrentMap} is * {@link ConcurrentHashMap} * </p> * * <p> * The default implementation for a {@link SortedMap} is a {@link TreeMap} * </p> * * <p> * The default Map is none of the above was recognised is a {@link HashMap} * </p> * * @param mapType * The attribute type implementing Map * @return A default instance for each map type * */ @SuppressWarnings({ UNCHECKED_STR, RAWTYPES_STR }) private Map<? super Object, ? super Object> resolveMapType( Class<?> mapType) { Map<? super Object, ? super Object> retValue = null; if (SortedMap.class.isAssignableFrom(mapType)) { if (mapType.isAssignableFrom(TreeMap.class)) { retValue = new TreeMap(); } } else if (ConcurrentMap.class.isAssignableFrom(mapType)) { if (mapType.isAssignableFrom(ConcurrentHashMap.class)) { retValue = new ConcurrentHashMap(); } } else { if (mapType.isAssignableFrom(HashMap.class)) { retValue = new HashMap(); } } if (null == retValue) { throw new IllegalArgumentException("Map type: " + mapType + " not supported"); } return retValue; } private Object[] getParameterValuesForConstructor( Constructor<?> constructor, Class<?> pojoClass, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); Type[] genericTypeArgsExtra = null; genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, genericTypeArgs); Annotation[][] parameterAnnotations = constructor .getParameterAnnotations(); Object[] parameterValues = new Object[constructor.getParameterTypes().length]; // Found a constructor with @PodamConstructor annotation Class<?>[] parameterTypes = constructor.getParameterTypes(); int idx = 0; for (Class<?> parameterType : parameterTypes) { List<Annotation> annotations = Arrays .asList(parameterAnnotations[idx]); String attributeName = null; if (Collection.class.isAssignableFrom(parameterType)) { Collection<? super Object> collection = resolveCollectionType(parameterType); Type type = constructor.getGenericParameterTypes()[idx]; Class<?> collectionElementType; AtomicReference<Type[]> collectionGenericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); if (type instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) type; Type actualTypeArgument = pType.getActualTypeArguments()[0]; collectionElementType = resolveGenericParameter( actualTypeArgument, typeArgsMap, collectionGenericTypeArgs); } else { LOG.warn("Collection parameter {} type is non-generic." + "We will assume a Collection<Object> for you.", type); collectionElementType = Object.class; } Type[] genericTypeArgsAll = mergeTypeArrays( collectionGenericTypeArgs.get(), genericTypeArgsExtra); fillCollection(pojoClass, pojos, attributeName, annotations, collection, collectionElementType, genericTypeArgsAll); parameterValues[idx] = collection; } else if (Map.class.isAssignableFrom(parameterType)) { Map<? super Object, ? super Object> mapType = resolveMapType(parameterType); Type type = constructor.getGenericParameterTypes()[idx]; Class<?> keyClass; Class<?> elementClass; AtomicReference<Type[]> keyGenericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); if (type instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) type; Type[] actualTypeArguments = pType.getActualTypeArguments(); keyClass = resolveGenericParameter(actualTypeArguments[0], typeArgsMap, keyGenericTypeArgs); elementClass = resolveGenericParameter( actualTypeArguments[1], typeArgsMap, elementGenericTypeArgs); } else { LOG.warn("Map parameter {} type is non-generic." + "We will assume a Map<Object,Object> for you.", type); keyClass = Object.class; elementClass = Object.class; } Type[] genericTypeArgsAll = mergeTypeArrays( elementGenericTypeArgs.get(), genericTypeArgsExtra); MapArguments mapArguments = new MapArguments(); mapArguments.setPojoClass(pojoClass); mapArguments.setPojos(pojos); mapArguments.setAttributeName(attributeName); mapArguments.setAnnotations(annotations); mapArguments.setMapToBeFilled(mapType); mapArguments.setKeyClass(keyClass); mapArguments.setElementClass(elementClass); mapArguments.setKeyGenericTypeArgs(keyGenericTypeArgs.get()); mapArguments.setElementGenericTypeArgs(genericTypeArgsAll); fillMap(mapArguments); parameterValues[idx] = mapType; } else { parameterValues[idx] = manufactureAttributeValue(pojoClass, pojos, parameterType, annotations, attributeName, typeArgsMap, genericTypeArgs); } idx++; } return parameterValues; } /** * Utility method to merge two arrays * * @param original * The main array * @param extra * The additional array, optionally may be null * @return A merged array of original and extra arrays */ private Type[] mergeTypeArrays(Type[] original, Type[] extra) { Type[] merged; if (extra != null) { merged = new Type[original.length + extra.length]; System.arraycopy(original, 0, merged, 0, original.length); System.arraycopy(extra, 0, merged, original.length, extra.length); } else { merged = original; } return merged; } private Object returnAttributeDataStrategyValue(Class<?> attributeType, AttributeStrategy<?> attributeStrategy) throws InstantiationException, IllegalAccessException { Object retValue = null; Method attributeStrategyMethod = null; try { attributeStrategyMethod = attributeStrategy.getClass().getMethod( PodamConstants.PODAM_ATTRIBUTE_STRATEGY_METHOD_NAME, new Class<?>[] {}); if (!attributeType.isAssignableFrom(attributeStrategyMethod .getReturnType())) { String errMsg = "The type of the Podam Attribute Strategy is not " + attributeType.getName() + " but " + attributeStrategyMethod.getReturnType().getName() + ". An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg); } retValue = attributeStrategy.getValue(); } catch (SecurityException e) { throw new IllegalStateException( "A security issue occurred while retrieving the Podam Attribute Strategy details", e); } catch (NoSuchMethodException e) { throw new IllegalStateException( "It seems the Podam Attribute Annotation is of the wrong type", e); } return retValue; } }
package uristqwerty.CraftGuide; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import net.minecraft.client.Minecraft; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import uristqwerty.CraftGuide.api.StackInfo; import uristqwerty.CraftGuide.api.StackInfoSource; import uristqwerty.CraftGuide.api.Util; public class CommonUtilities { public static Field getPrivateField(Class fromClass, String... names) throws NoSuchFieldException { Field field = null; for(String name: names) { try { field = fromClass.getDeclaredField(name); field.setAccessible(true); return field; } catch(NoSuchFieldException e) { } } if(names.length == 1) { throw new NoSuchFieldException("Could not find a field named " + names[0]); } else { String nameStr = "[" + names[0]; for(int i = 1; i < names.length; i++) { nameStr += ", " + names[i]; } throw new NoSuchFieldException("Could not find a field with any of the following names: " + nameStr + "]"); } } public static <T> Object getPrivateValue(Class<T> objectClass, T object, String... names) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field field = getPrivateField(objectClass, names); return field.get(object); } public static String itemName(ItemStack item) { String idText = ""; if(Minecraft.getMinecraft().gameSettings.advancedItemTooltips) { if(item.getHasSubtypes()) { idText = String.format(" (%s #%04d/%d)", Item.itemRegistry.getNameForObject(item.getItem()), Item.getIdFromItem(item.getItem()), getItemDamage(item)); } else { idText = String.format(" (%s #%04d)", Item.itemRegistry.getNameForObject(item.getItem()), Item.getIdFromItem(item.getItem())); } } return item.getDisplayName() + idText; } public static List<String> itemNames(ItemStack item) { ArrayList<String> list = new ArrayList<String>(); if(getItemDamage(item) == CraftGuide.DAMAGE_WILDCARD && item.getHasSubtypes()) { ArrayList<ItemStack> subItems = new ArrayList(); item.getItem().getSubItems(item.getItem(), null, subItems); for(ItemStack stack: subItems) { list.add(itemName(stack)); } } else { list.add(itemName(item)); } return list; } public static int countItemNames(ItemStack item) { if(getItemDamage(item) == CraftGuide.DAMAGE_WILDCARD && item.getHasSubtypes()) { ArrayList temp = new ArrayList(); item.getItem().getSubItems(item.getItem(), null, temp); return temp.size(); } else { return 1; } } public static int countItemNames(Object item) { if(item instanceof ItemStack) { return countItemNames((ItemStack)item); } else if(item instanceof List) { int count = 0; for(Object o: (List)item) { count += countItemNames(o); } return count; } else { return 0; } } private static class Pair<T1, T2> { T1 first; T2 second; public Pair(T1 a, T2 b) { first = a; second = b; } @Override public int hashCode() { // Null hashes arbitrarily chosen by keyboard mashing. int firsthash = first == null? 5960343 : first.hashCode(); int secondhash = second == null? 1186323 : second.hashCode(); return firsthash ^ Integer.rotateLeft(secondhash, 13); } @Override public boolean equals(Object obj) { if(!(obj instanceof Pair)) return false; Pair other = (Pair)obj; return (first == null? other.first == null : first.equals(other.first)) && (second == null? other.second == null : second.equals(other.second)); } } private static Map<Pair<Item, Integer>, List<String>> textCache = new HashMap<Pair<Item, Integer>, List<String>>(); static void clearTooltipCache() { textCache.clear(); } private static List<String> cachedExtendedItemStackText(ItemStack stack) { Pair<Item, Integer> key = new Pair(stack.getItem(), stack.getItemDamage()); List<String> tooltip = textCache.get(key); if(tooltip == null) { tooltip = new ArrayList(genExtendedItemStackText(stack)); textCache.put(key, tooltip); } return tooltip; } public static List<String> getExtendedItemStackText(Object item) { List<String> text = getPossiblyCachedExtendedItemText(item); if(item instanceof List && ((List)item).size() > 1) { int count = CommonUtilities.countItemNames(item); text.add("\u00a77" + (count - 1) + " other type" + (count > 2? "s" : "") + " of item accepted"); } return text; } private static List<String> getPossiblyCachedExtendedItemText(Object item) { if(item instanceof ItemStack || (item instanceof List && ((List)item).get(0) instanceof ItemStack)) { ItemStack stack = item instanceof ItemStack? (ItemStack)item : (ItemStack)((List)item).get(0); if(stack.hasTagCompound()) return genExtendedItemStackText(stack); else return new ArrayList(cachedExtendedItemStackText(stack)); } else { return getItemStackText(item); } } private static List<String> genExtendedItemStackText(ItemStack stack) { List<String> text = getItemStackText(stack); appendStackInfo(text, stack); return text; } private static void appendStackInfo(List<String> text, ItemStack stack) { Iterator<StackInfoSource> iterator = StackInfo.sources.iterator(); while(iterator.hasNext()) { StackInfoSource infoSource = iterator.next(); try { String info = infoSource.getInfo(stack); if(info != null) { text.add(info); } } catch(LinkageError e) { CraftGuideLog.log(e); iterator.remove(); } catch(Exception e) { CraftGuideLog.log(e); } } } public static boolean searchExtendedItemStackText(Object item, String text) { for(String line: getExtendedItemStackText(item)) { if(line != null && line.toLowerCase().contains(text)) { return true; } } return false; } private static List<String> getItemStackText(Object item) { if(item instanceof List) { return getItemStackText(((List)item).get(0)); } else if(item instanceof ItemStack) { return Util.instance.getItemStackText((ItemStack)item); } else { return null; } } static Field itemDamageField = null; static { try { itemDamageField = getPrivateField(ItemStack.class, "itemDamage", "field_77991_e", "e"); } catch(NoSuchFieldException e) { e.printStackTrace(); } } public static int getItemDamage(ItemStack stack) { if(stack.getItem() != null) { return stack.getItemDamage(); } else { if(itemDamageField != null) { try { return itemDamageField.getInt(stack); } catch(IllegalArgumentException e) { e.printStackTrace(); } catch(IllegalAccessException e) { e.printStackTrace(); } } return 0; } } public static boolean checkItemStackMatch(ItemStack first, ItemStack second) { if(first == null || second == null) { return first == second; } return first.getItem() == second.getItem() && ( getItemDamage(first) == CraftGuide.DAMAGE_WILDCARD || getItemDamage(second) == CraftGuide.DAMAGE_WILDCARD || getItemDamage(first) == getItemDamage(second) ); } }
package me.nallar.nmsprepatcher; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.base.Splitter; // The prepatcher adds method declarations in superclasses, // so javac can compile the patch classes if they need to use a method/field they // add on an instance other than this class PrePatcher { private static final Logger log = Logger.getLogger("PatchLogger"); private static final Pattern privatePattern = Pattern.compile("^(\\s+?)private", Pattern.MULTILINE); private static final Pattern extendsPattern = Pattern.compile("^public.*?\\s+?extends\\s+?([\\S^<]+?)(?:<(\\S+)>)?[\\s]+?(?:implements [^}]+?)?\\{", Pattern.MULTILINE); private static final Pattern genericMethodPattern = Pattern.compile("@Generic\\s+?(public\\s+?(\\S*?)?\\s+?(\\S*?)\\s*?\\S+?\\s*?\\()[^\\{]*\\)\\s*?\\{", Pattern.DOTALL | Pattern.MULTILINE); private static final Pattern declareMethodPattern = Pattern.compile("@Declare\\s+?(public\\s+?(?:(?:synchronized|static) )*(\\S*?)?\\s+?(\\S*?)\\s*?\\S+?\\s*?\\([^\\{]*\\)\\s*?\\{)", Pattern.DOTALL | Pattern.MULTILINE); private static final Pattern declareVariablePattern = Pattern.compile("@Declare\\s+?(public [^;\r\n]+?)_( = [^;\r\n]+?)?;", Pattern.DOTALL | Pattern.MULTILINE); private static final Pattern packageVariablePattern = Pattern.compile("\n ? ?([^ ]+ ? ?[^ ]+);"); private static final Pattern innerClassPattern = Pattern.compile("[^\n]public (?:static )?class ([^ \n]+)[ \n]", Pattern.MULTILINE); private static void recursiveSearch(File patchDirectory, File sourceDirectory, Map<File, String> patchClasses, Map<File, String> generics) { for (File file : patchDirectory.listFiles()) { if (file.isDirectory()) { recursiveSearch(file, sourceDirectory, patchClasses, generics); continue; } if (!file.getName().endsWith(".java")) { continue; } String contents = readFile(file); if (contents == null) { log.log(Level.SEVERE, "Failed to read " + file); continue; } Matcher extendsMatcher = extendsPattern.matcher(contents); if (!extendsMatcher.find()) { if (contents.contains(" extends")) { log.warning("Didn't match extends matcher for " + file); } continue; } String shortClassName = extendsMatcher.group(1); String className = null; for (String line : Splitter.on('\n').split(contents)) { if (line.endsWith('.' + shortClassName + ';')) { className = line.substring(7, line.length() - 1); } } if (className == null) { log.info("Unable to find class " + shortClassName + " for " + file); continue; } File sourceFile = new File(sourceDirectory, className.replace('.', '/') + ".java"); if (!sourceFile.exists()) { log.severe("Can't find " + sourceFile + " for " + file + ", not patching."); continue; } String generic = extendsMatcher.group(2); if (generic != null) { generics.put(sourceFile, generic); } String current = patchClasses.get(sourceFile); patchClasses.put(sourceFile, (current == null ? "" : current) + contents); } } public static void patch(File patchDirectory, File sourceDirectory) { if (!patchDirectory.isDirectory()) { throw new IllegalArgumentException("Not a directory! " + patchDirectory + ", " + sourceDirectory); } Map<File, String> patchClasses = new HashMap<File, String>(); Map<File, String> generics = new HashMap<File, String>(); recursiveSearch(patchDirectory, sourceDirectory, patchClasses, generics); for (Map.Entry<File, String> classPatchEntry : patchClasses.entrySet()) { String contents = classPatchEntry.getValue(); File sourceFile = classPatchEntry.getKey(); String shortClassName = sourceFile.getName(); shortClassName = shortClassName.substring(shortClassName.lastIndexOf('/') + 1); shortClassName = shortClassName.substring(0, shortClassName.indexOf('.')); String sourceString = readFile(sourceFile).trim().replace("\t", " "); int previousIndex = sourceString.indexOf("\n//PREPATCH\n"); int cutIndex = previousIndex == -1 ? sourceString.lastIndexOf('}') : previousIndex; StringBuilder source = new StringBuilder(sourceString.substring(0, cutIndex)).append("\n//PREPATCH\n"); Matcher matcher = declareMethodPattern.matcher(contents); while (matcher.find()) { String type = matcher.group(2); String ret = "null"; // TODO: Add more types. if ("static".equals(type)) { type = matcher.group(3); } if ("boolean".equals(type)) { ret = "false"; } else if ("void".equals(type)) { ret = ""; } else if ("long".equals(type)) { ret = "0L"; } else if ("int".equals(type)) { ret = "0"; } else if ("float".equals(type)) { ret = "0f"; } else if ("double".equals(type)) { ret = "0.0"; } String decl = matcher.group(1) + "return " + ret + ";}"; if (source.indexOf(decl) == -1) { source.append(decl).append('\n'); } } Matcher variableMatcher = declareVariablePattern.matcher(contents); while (variableMatcher.find()) { String var = variableMatcher.group(1); source.append(var.replace(" final ", " ")).append(";\n"); } source.append("\n}"); sourceString = source.toString(); String generic = generics.get(sourceFile); if (generic != null) { sourceString = sourceString.replaceAll("class " + shortClassName + "(<[^>]>)?", "class " + shortClassName + '<' + generic + '>'); } Matcher genericMatcher = genericMethodPattern.matcher(contents); while (genericMatcher.find()) { String original = genericMatcher.group(1); String withoutGenerics = original.replace(' ' + generic + ' ', " Object "); int index = sourceString.indexOf(withoutGenerics); if (index == -1) { continue; } int endIndex = sourceString.indexOf("\n }", index); String body = sourceString.substring(index, endIndex); sourceString = sourceString.replace(body, body.replace(withoutGenerics, original).replace("return ", "return (" + generic + ") ")); } // TODO: Fix package -> public properly later. sourceString = sourceString.replace("\nfinal ", " "); sourceString = sourceString.replace(" final ", " "); sourceString = sourceString.replace("\nclass", "\npublic class"); sourceString = sourceString.replace("\n " + shortClassName, "\n public " + shortClassName); sourceString = sourceString.replace("\n protected " + shortClassName, "\n public " + shortClassName); sourceString = sourceString.replace("private class", "public class"); sourceString = sourceString.replace("protected class", "public class"); sourceString = privatePattern.matcher(sourceString).replaceAll("$1protected"); if (contents.contains("\n@Public")) { sourceString = sourceString.replace("protected ", "public "); } sourceString = sourceString.replace("protected void save(", "public void save("); Matcher packageMatcher = packageVariablePattern.matcher(sourceString); StringBuffer sb = new StringBuffer(); while (packageMatcher.find()) { packageMatcher.appendReplacement(sb, "\n public " + packageMatcher.group(1) + ';'); } packageMatcher.appendTail(sb); sourceString = sb.toString(); Matcher innerClassMatcher = innerClassPattern.matcher(sourceString); while (innerClassMatcher.find()) { String name = innerClassMatcher.group(1); sourceString = sourceString.replace(" " + name + '(', " public " + name + '('); } try { writeFile(sourceFile, sourceString.replace(" ", "\t")); } catch (IOException e) { log.log(Level.SEVERE, "Failed to save " + sourceFile, e); } } } private static String readFile(File file) { Scanner fileReader = null; try { fileReader = new Scanner(file, "UTF-8").useDelimiter("\\A"); return fileReader.next().replace("\r\n", "\n"); } catch (FileNotFoundException ignored) { } finally { if (fileReader != null) { fileReader.close(); } } return null; } private static void writeFile(File file, String contents) throws IOException { FileWriter fileWriter = new FileWriter(file); try { fileWriter.write(contents); } finally { fileWriter.close(); } } }
package org.exist.xquery.functions.validation; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import org.exist.dom.QName; import org.exist.memtree.MemTreeBuilder; import org.exist.memtree.NodeImpl; import org.exist.storage.BrokerPool; import org.exist.validation.ValidationReport; import org.exist.validation.Validator; import org.exist.xquery.BasicFunction; import org.exist.xquery.Cardinality; import org.exist.xquery.FunctionSignature; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.BooleanValue; import org.exist.xquery.value.FunctionParameterSequenceType; import org.exist.xquery.value.FunctionReturnSequenceType; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceType; import org.exist.xquery.value.Type; import org.exist.xquery.value.ValueSequence; /** * XQuery function for validation of XML instance documents * using grammars like XSDs and DTDs. * * @author Dannes Wessels (dizzzz@exist-db.org) */ public class Validation extends BasicFunction { private static final String deprecated1="Use the validation:jaxp-parse(), " + "validation:jaxv() or validation:jing() functions."; private static final String deprecated2="Use the validation:jaxp-parse-report(), " + "validation:jaxv-report() or validation:jing-report() functions."; private static final String simpleFunctionTxt= "Validate xml. " + "The grammar files (DTD, XML Schema) are resolved using the global "+ "catalog file(s)."; private static final String extendedFunctionTxt= "Validate document by using a specific grammar."; private final Validator validator; private final BrokerPool brokerPool; // Setup function signature public final static FunctionSignature deprecated[] = { new FunctionSignature( new QName("validate", ValidationModule.NAMESPACE_URI, ValidationModule.PREFIX), simpleFunctionTxt, new SequenceType[]{ new FunctionParameterSequenceType("instance", Type.ITEM, Cardinality.EXACTLY_ONE, "The document referenced as xs:anyURI or a node (element or returned by fn:doc())") }, new FunctionReturnSequenceType(Type.BOOLEAN, Cardinality.EXACTLY_ONE, Shared.simplereportText), deprecated1 ), new FunctionSignature( new QName("validate", ValidationModule.NAMESPACE_URI, ValidationModule.PREFIX), extendedFunctionTxt, new SequenceType[]{ new FunctionParameterSequenceType("instance", Type.ITEM, Cardinality.EXACTLY_ONE, "The document referenced as xs:anyURI or a node (element or returned by fn:doc())"), new FunctionParameterSequenceType("grammar", Type.ANY_URI, Cardinality.EXACTLY_ONE, "The reference to an OASIS catalog file (.xml), "+ "a collection (path ends with '/') or a grammar document. "+ "Supported grammar documents extensions are \".dtd\" \".xsd\" "+ "\".rng\" \".rnc\" \".sch\" and \".nvdl\".") }, new FunctionReturnSequenceType(Type.NODE, Cardinality.EXACTLY_ONE, Shared.simplereportText), deprecated1 ), new FunctionSignature( new QName("validate-report", ValidationModule.NAMESPACE_URI, ValidationModule.PREFIX), simpleFunctionTxt+" An xml report is returned.", new SequenceType[]{ new FunctionParameterSequenceType("instance", Type.ITEM, Cardinality.EXACTLY_ONE, "The document referenced as xs:anyURI or a node (element or returned by fn:doc())") }, new FunctionReturnSequenceType(Type.NODE, Cardinality.EXACTLY_ONE, Shared.xmlreportText), deprecated2 ), new FunctionSignature( new QName("validate-report", ValidationModule.NAMESPACE_URI, ValidationModule.PREFIX), extendedFunctionTxt+" An xml report is returned.", new SequenceType[]{ new FunctionParameterSequenceType("instance", Type.ITEM, Cardinality.EXACTLY_ONE, "The document referenced as xs:anyURI or a node (element or returned by fn:doc())"), new FunctionParameterSequenceType("grammar", Type.ITEM, Cardinality.EXACTLY_ONE, "The reference to an OASIS catalog file (.xml), "+ "a collection (path ends with '/') or a grammar document. "+ "Supported grammar documents extensions are \".dtd\" \".xsd\" "+ "\".rng\" \".rnc\" \".sch\" and \".nvdl\". The parameter can be passed as an xs:anyURI or a" + "document node.") }, new FunctionReturnSequenceType(Type.NODE, Cardinality.EXACTLY_ONE, Shared.xmlreportText), deprecated2 ) }; public Validation(XQueryContext context, FunctionSignature signature) { super(context, signature); brokerPool = context.getBroker().getBrokerPool(); validator = new Validator(brokerPool); } /** * @throws org.exist.xquery.XPathException * @see BasicFunction#eval(Sequence[], Sequence) */ public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { // Check input parameters if (args.length != 1 && args.length != 2) { return Sequence.EMPTY_SEQUENCE; } InputStream is = null; ValidationReport report = new ValidationReport(); try { // args[0] is = Shared.getInputStream(args[0].itemAt(0), context); if(args.length == 1) { // Validate using system catalog report=validator.validate(is); } else { // Validate using resource specified in second parameter String url=Shared.getUrl(args[1].itemAt(0)); report=validator.validate(is, url); } } catch (MalformedURLException ex) { LOG.error(ex.getMessage()); report.setException(ex); } catch (IOException ex) { LOG.error(ex); report.setException(ex); } catch (Throwable ex) { LOG.error(ex); report.setException(ex); } finally { // Force release stream if(is != null){ try { is.close(); } catch (Exception ex) { LOG.debug("Attemted to close stream. ignore.", ex); } } } // Create response if (isCalledAs("validate") || isCalledAs("jing")) { Sequence result = new ValueSequence(); result.add(new BooleanValue(report.isValid())); return result; } else /* isCalledAs("validate-report") || isCalledAs("jing-report") */{ MemTreeBuilder builder = context.getDocumentBuilder(); NodeImpl result = Shared.writeReport(report, builder); return result; } } }
package org.jets3t.servlets.gatekeeper; import java.security.Principal; import javax.servlet.http.HttpSession; /** * Stores information about an HTTP client that submitted a request to the Gatekeeper. * <p> * The information available about a client will depend on the server and client configuration, * such as whether the client is identified with an existing HttpSession or Principal. It must * be assumed that much of the information stored in this class will have a null value in many * cases. * * @author James Murty */ public class ClientInformation { private String remoteAddress = null; private String remoteHost = null; private String remoteUser = null; private int remotePort = -1; private HttpSession session = null; private Principal userPrincipal = null; public ClientInformation(String remoteAddress, String remoteHost, String remoteUser, int remotePort, HttpSession session, Principal userPrincipal) { this.remoteAddress = remoteAddress; this.remoteHost = remoteHost; this.remoteUser = remoteUser; this.remotePort = remotePort; this.session = session; this.userPrincipal = userPrincipal; } public String getRemoteAddress() { return remoteAddress; } public String getRemoteHost() { return remoteHost; } public int getRemotePort() { return remotePort; } public String getRemoteUser() { return remoteUser; } public HttpSession getSession() { return session; } public Principal getUserPrincipal() { return userPrincipal; } }
package org.mtransit.parser.ca_windsor_transit_bus; import java.util.HashMap; public class Stops { public static HashMap<String, String> ALL_STOPS; static { HashMap<String, String> allStops = new HashMap<String, String>(); allStops.put("stop_code", "stop_id"); // stop_name allStops.put("1000", "1"); // Windsor Transit Terminal allStops.put("1002", "2"); // Ouellette at Chatham allStops.put("1004", "3"); // Ouellette at Park allStops.put("1006", "4"); // Ouellette at Wyandotte allStops.put("1008", "5"); // Ouellette at Elliott allStops.put("1010", "6"); // Ouellette at Erie allStops.put("1012", "7"); // Ouellette at Pine allStops.put("1014", "8"); // Ouellette at Giles allStops.put("1016", "9"); // Ouellette at Montrose allStops.put("1018", "10"); // Ouellette at Ellis allStops.put("1020", "11"); // Ouellette at Shepherd allStops.put("1022", "12"); // Ouellette at Hanna allStops.put("1024", "13"); // Tecumseh E at Ouellette allStops.put("1027", "14"); // Tecumseh E at McDougall allStops.put("1029", "15"); // Howard at Tecumseh E allStops.put("1031", "16"); // Howard at Logan allStops.put("1033", "17"); // Howard at Foch allStops.put("1036", "18"); // Howard at Memorial allStops.put("1037", "19"); // Howard at Eugenie allStops.put("1040", "20"); // Howard at McDougall allStops.put("1043", "21"); // Howard at Edinborough allStops.put("1045", "22"); // Howard at Charles allStops.put("1047", "23"); // Howard at Grand Marais allStops.put("1049", "24"); // Howard at Roundhouse allStops.put("1050", "25"); // Sydney at Windsor Commons allStops.put("1051", "26"); // Devonshire Mall at Moxies allStops.put("1048", "27"); // Howard at Devonshire Mall allStops.put("1046", "28"); // Howard at Grand Marais allStops.put("1044", "29"); // Howard at Charles allStops.put("1042", "30"); // Howard at Edinborough allStops.put("1041", "31"); // Howard at McDougall allStops.put("1039", "32"); // Howard at Hildegard allStops.put("1038", "33"); // Howard at Eugenie allStops.put("1035", "34"); // Howard at Lens allStops.put("1034", "35"); // Howard at Foch allStops.put("1032", "36"); // Howard at Logan allStops.put("1030", "37"); // Tecumseh E at Howard allStops.put("1028", "38"); // Tecumseh E at McDougall allStops.put("1026", "39"); // Tecumseh E at Goyeau allStops.put("1025", "40"); // Ouellette at Tecumseh E allStops.put("1023", "41"); // Ouellette at Hanna allStops.put("1021", "42"); // Ouellette at Shepherd allStops.put("1019", "43"); // Ouellette at Ellis allStops.put("1017", "44"); // Ouellette at Montrose allStops.put("1015", "45"); // Ouellette at Giles allStops.put("1013", "46"); // Ouellette at Pine allStops.put("1011", "47"); // Ouellette at Erie allStops.put("1009", "48"); // Ouellette at Ouellette Manor allStops.put("1007", "49"); // Ouellette at Elliott allStops.put("1005", "50"); // Ouellette at Wyandotte allStops.put("1003", "51"); // Ouellette at Park allStops.put("1001", "52"); // Chatham at Ouellette allStops.put("1881", "53"); // Marentette at Division allStops.put("1879", "54"); // Marentette at Foster allStops.put("2114", "55"); // Marentette at Sydney allStops.put("2109", "56"); // E.C. Row Ave at Devon allStops.put("2110", "57"); // Marentette at E.C. Row Ave allStops.put("2111", "58"); // Marentette at Sydney allStops.put("1052", "59"); // College Ave. at Community Centre allStops.put("1053", "60"); // College at South allStops.put("1054", "61"); // College at Prince allStops.put("1056", "62"); // Prince at Barrymore allStops.put("1057", "63"); // Prince at Mulford allStops.put("1058", "64"); // Prince at Vaughan allStops.put("1059", "65"); // Prince at Glenfield allStops.put("1060", "66"); // Prince at Whitney allStops.put("1062", "67"); // Felix at Tecumseh allStops.put("1063", "68"); // Felix at Manchester allStops.put("1064", "69"); // Felix at Girardot allStops.put("1065", "70"); // Felix at Millen allStops.put("1067", "71"); // Felix at College allStops.put("1069", "72"); // Felix at Linwood allStops.put("1071", "73"); // Mill at Donnelly allStops.put("1073", "74"); // Mill at Sandwich allStops.put("1075", "75"); // Sandwich at Detroit allStops.put("1055", "76"); // Sandwich at University allStops.put("1078", "77"); // University at Huron Church allStops.put("1080", "78"); // University at Patricia allStops.put("1082", "79"); // University at California allStops.put("1085", "80"); // University at Randolph allStops.put("1087", "81"); // University at Partington allStops.put("1089", "82"); // University at Campbell allStops.put("2136", "83"); // University at Curry allStops.put("1092", "84"); // University at Cameron allStops.put("1094", "85"); // University at Wellington allStops.put("1096", "86"); // University at Crawford allStops.put("1098", "87"); // University at Caron allStops.put("1100", "88"); // University at Bruce allStops.put("2137", "89"); // University at Church allStops.put("1101", "90"); // Victoria at University allStops.put("1103", "91"); // Windsor Transit Terminal allStops.put("1106", "92"); // Tecumseh at Howard allStops.put("1109", "93"); // Tecumseh at Marentette allStops.put("1111", "94"); // Tecumseh at Parent allStops.put("1113", "95"); // Tecumseh at Forest allStops.put("1115", "96"); // Tecumseh at Parkwood allStops.put("1117", "97"); // Tecumseh at Moy allStops.put("1119", "98"); // Tecumseh at Lincoln allStops.put("1121", "99"); // Tecumseh at Kildare allStops.put("1123", "100"); // Tecumseh at Byng allStops.put("1125", "101"); // Tecumseh at Walker allStops.put("1128", "102"); // Tecumseh at Cadillac allStops.put("1130", "103"); // Tecumseh at Chandler allStops.put("1132", "104"); // Tecumseh at Meldrum allStops.put("1134", "105"); // Tecumseh at Central allStops.put("1135", "106"); // Tecumseh at Aubin allStops.put("1137", "107"); // Tecumseh at George allStops.put("1139", "108"); // Tecumseh at Rossini allStops.put("1142", "109"); // Tecumseh at Francois allStops.put("1144", "110"); // Tecumseh at Pillette allStops.put("1146", "111"); // Tecumseh at Norman allStops.put("1148", "112"); // Tecumseh at Westminster allStops.put("1150", "113"); // Tecumseh at Ford allStops.put("1152", "114"); // Rivard at Tecumseh allStops.put("1153", "115"); // Rivard at Adstoll allStops.put("1156", "116"); // Rivard at Rose allStops.put("1157", "117"); // Rose at Jos St. Louis allStops.put("1161", "118"); // Rose atLloyd George allStops.put("1163", "119"); // Roseville at Thornberry allStops.put("1165", "120"); // Roseville at Thornberry allStops.put("1167", "121"); // Roseville at Charlie Brooks allStops.put("1169", "122"); // Roseville at Tecumseh allStops.put("1171", "123"); // Tecumseh Rd. at Eastpark Plaza allStops.put("1173", "124"); // Tecumseh Mall Rear Entrance allStops.put("1175", "125"); // Tecumseh at Lauzon Parkway allStops.put("1177", "126"); // Tecumseh at Annie allStops.put("1179", "127"); // Tecumseh at Lauzon allStops.put("1181", "128"); // Tecumseh at Canadian Tire allStops.put("1183", "129"); // Tecumseh at Rafih allStops.put("1185", "130"); // Tecumseh at Penang allStops.put("1187", "131"); // Tecumseh at Metro Plaza allStops.put("1189", "132"); // Forest Glade at Tecumseh allStops.put("1191", "133"); // Forest Glade at Esplanade allStops.put("1193", "134"); // Forest Glade at Ridge allStops.put("1195", "135"); // Forest Glade at Wildwood allStops.put("1197", "136"); // Forest Glade at Mulberry allStops.put("1205", "137"); // Forest Glade at Elmwood allStops.put("1204", "138"); // Wildwood at Rosebriar allStops.put("1202", "139"); // Wildwood at Hemlock allStops.put("1201", "140"); // Wildwood at Midfield allStops.put("1200", "141"); // Wildwood at Forest Glade allStops.put("1199", "142"); // Wildwood at Beachdale allStops.put("1198", "143"); // Wildwood at Apple allStops.put("1196", "144"); // Wildwood at Forest Glade allStops.put("1194", "145"); // Forest Glade at Ridge allStops.put("1192", "146"); // Forest Glade at Eastcourt allStops.put("1190", "147"); // Forest Glade at Tecumseh allStops.put("1188", "148"); // Tecumseh at Forest Glade allStops.put("1186", "149"); // Tecumseh at Penang allStops.put("1184", "150"); // Tecumseh at Rafih allStops.put("1182", "151"); // Tecumseh at Food Basics allStops.put("1180", "152"); // Tecumseh at Lauzon allStops.put("1178", "153"); // Tecumseh at Annie allStops.put("1176", "154"); // Tecumseh at Lauzon Parkway allStops.put("1174", "155"); // Tecumseh Mall Rear Entrance allStops.put("1172", "156"); // Tecumseh at Walmart allStops.put("1170", "157"); // Roseville at Tecumseh allStops.put("1168", "158"); // Roseville at Charlie Brooks allStops.put("1166", "159"); // Roseville at Thornberry allStops.put("1164", "160"); // Roseville at Thornberry allStops.put("1162", "161"); // Rose at Jefferson allStops.put("1160", "162"); // Rose at Clemenceau allStops.put("1158", "163"); // Rose at Rivard allStops.put("1155", "164"); // Rivard at Adstoll allStops.put("2139", "165"); // Rivard at Tecumseh allStops.put("1151", "166"); // Tecumseh at Ford allStops.put("1149", "167"); // Tecumseh at Buckingham allStops.put("1147", "168"); // Tecumseh at Westminster allStops.put("1145", "169"); // Tecumseh at Norman allStops.put("1143", "170"); // Tecumseh at Pillette allStops.put("1141", "171"); // Tecumseh at Ellrose allStops.put("1203", "172"); // Tecumseh at Francois allStops.put("1140", "173"); // Tecumseh at Rossini allStops.put("1138", "174"); // Tecumseh at George allStops.put("1136", "175"); // Tecumseh at Westcott allStops.put("1133", "176"); // Tecumseh at Central allStops.put("1131", "177"); // Tecumseh at Meldrum allStops.put("1129", "178"); // Tecumseh at Chandler allStops.put("1127", "179"); // Tecumseh at Hickory allStops.put("1126", "180"); // Tecumseh at Factoria allStops.put("1124", "181"); // Tecumseh at Turner allStops.put("1122", "182"); // Tecumseh at Durham allStops.put("1120", "183"); // Tecumseh at Kildare allStops.put("1118", "184"); // Tecumseh at Lincoln allStops.put("1114", "185"); // Tecumseh at Hall allStops.put("1112", "186"); // Tecumseh at Benjamin allStops.put("1110", "187"); // Tecumseh at Parent allStops.put("1107", "188"); // Tecumseh a Windsor Health Centre allStops.put("1105", "189"); // Tecumseh at Howard allStops.put("1104", "190"); // University at Ouellette allStops.put("1102", "191"); // Transit Terminal at Chatham allStops.put("1099", "192"); // University at Bruce allStops.put("1097", "193"); // University at Caron allStops.put("1095", "194"); // University at Crawford allStops.put("1093", "195"); // University at Elm allStops.put("1091", "196"); // University at Cameron allStops.put("1090", "197"); // University at Curry allStops.put("1088", "198"); // University at Campbell allStops.put("1086", "199"); // University at Bridge allStops.put("1084", "200"); // University at Randolph allStops.put("1083", "201"); // University at Askin allStops.put("1081", "202"); // University at Patricia allStops.put("1079", "203"); // University at Huron Church allStops.put("1077", "204"); // Riverside at Rosedale allStops.put("1074", "205"); // Sandwich at Detroit allStops.put("1072", "206"); // Mill at Sandwich allStops.put("1070", "207"); // Mill at Wyandotte allStops.put("1068", "208"); // Felix at Linwood allStops.put("1066", "209"); // College at Felix allStops.put("1375", "210"); // Tecumseh Mall Rear Entrance allStops.put("1374", "211"); // Lauzon Parkway at Lauzon Line allStops.put("1372", "212"); // Lauzon at Tranby allStops.put("1370", "213"); // Lauzon at Trinity Towers allStops.put("1368", "214"); // Lauzon at Little River allStops.put("1076", "215"); // Little River at Adair allStops.put("1363", "216"); // Little River Acres at Little Riv allStops.put("1361", "217"); // Little River Acres at East Moor allStops.put("1359", "218"); // Little River Acres at Cottage allStops.put("1355", "219"); // Little River Acres at Aire allStops.put("1354", "220"); // Little RiverAcres at LittleRiver allStops.put("1352", "221"); // Riverdale at St. Rose allStops.put("1350", "222"); // Riverdale at Jerome allStops.put("1348", "223"); // Riverdale at Wyandotte allStops.put("1346", "224"); // Riverdale at Menard allStops.put("1344", "225"); // Riverdale at Riverside allStops.put("1342", "226"); // Riverside at Marina allStops.put("1340", "227"); // Riverside at Solidarity Towers allStops.put("1338", "228"); // Riverside at Riverside Towers allStops.put("1336", "229"); // Riverside at Shoreline Towers allStops.put("1334", "230"); // Riverside at Dieppe allStops.put("1329", "231"); // Riverside Dr. E. at Lauzon allStops.put("1327", "232"); // Lauzon at Cecile allStops.put("1325", "233"); // Lauzon at Cedarview allStops.put("1323", "234"); // Lauzon at Wyandotte allStops.put("1321", "235"); // Wyandotte at Matthew Brady allStops.put("1319", "236"); // Wyandotte at Fairview allStops.put("1316", "237"); // Wyandotte at Vernon allStops.put("1314", "238"); // Wyandotte at St. Rose allStops.put("Sto125649", "239"); // Wyandotte at Metro allStops.put("1312", "240"); // Wyandotte at Janisse allStops.put("1309", "241"); // Wyandotte at Homedale allStops.put("1310", "242"); // Wyandotte at Patrice allStops.put("1307", "243"); // Wyandotte at Jefferson allStops.put("1304", "244"); // Wyandotte at Reedmere allStops.put("1302", "245"); // Wyandotte at Villaire allStops.put("1299", "246"); // Wyandotte at Ford allStops.put("1297", "247"); // Wyandotte at Westminster allStops.put("1295", "248"); // Wyandotte at Dawson allStops.put("1293", "249"); // Wyandotte at Pillette allStops.put("1291", "250"); // Wyandotte at Jos. Janisse allStops.put("1289", "251"); // Wyandotte at Rossini allStops.put("1287", "252"); // Wyandotte at George allStops.put("1285", "253"); // Wyandotte at Sterling allStops.put("1283", "254"); // Wyandotte at Strabane allStops.put("1281", "255"); // Wyandotte at Belleview allStops.put("1279", "256"); // Wyandotte at Drouillard allStops.put("1277", "257"); // Wyandotte at St. Luke allStops.put("1275", "258"); // Wyandotte at Walker allStops.put("1272", "259"); // Wyandotte at Devonshire allStops.put("1271", "260"); // Wyandotte at Chilver allStops.put("1268", "261"); // Wyandotte at Gladstone allStops.put("1266", "262"); // Wyandotte at Hall allStops.put("1264", "263"); // Wyandotte at Langlois allStops.put("1260", "264"); // Wyandotte at Marentette allStops.put("1259", "265"); // Wyandotte at Louis allStops.put("1256", "266"); // Wyandotte at Glengarry allStops.put("1254", "267"); // Wyandotte at McDougall allStops.put("1252", "268"); // Wyandotte at Goyeau allStops.put("1249", "269"); // Wyandotte at Ouellette allStops.put("1247", "270"); // Wyandotte at Victoria allStops.put("1244", "271"); // Wyandotte at Bruce allStops.put("1242", "272"); // Wyandotte at Janette allStops.put("1240", "273"); // Wyandotte at Crawford allStops.put("1238", "274"); // Wyandotte at Wellington allStops.put("1236", "275"); // Wyandotte at McKay allStops.put("1234", "276"); // Wyandotte at Campbell allStops.put("1232", "277"); // Wyandotte at Bridge allStops.put("1230", "278"); // Wyandotte at Randolph allStops.put("1229", "279"); // Wyandotte at California allStops.put("1227", "280"); // Wyandotte at Patricia allStops.put("1223", "281"); // Wyandotte at Rosedale allStops.put("1221", "282"); // Wyandotte at Mill allStops.put("1220", "283"); // Mill at Peter allStops.put("1218", "284"); // Sandwich at Brock allStops.put("1216", "285"); // Sandwich at Chippawa allStops.put("1214", "286"); // Sandwich at South allStops.put("1212", "287"); // Sandwich at Watkins allStops.put("1210", "288"); // Prince at Peter allStops.put("1209", "289"); // Prince at King allStops.put("1208", "290"); // College at Prince allStops.put("1207", "291"); // College at South allStops.put("1206", "292"); // College Ave. at Community Centre allStops.put("1116", "293"); // Prince at King allStops.put("1211", "294"); // Prince at Peter allStops.put("1213", "295"); // Sandwich at Watkins allStops.put("1215", "296"); // Sandwich at South allStops.put("1217", "297"); // Sandwich at Chippawa allStops.put("1219", "298"); // Sandwich at Brock allStops.put("1222", "299"); // Wyandotte at Mill allStops.put("1224", "300"); // Wyandotte at Rosedale allStops.put("1226", "301"); // Wyandotte at Huron Church allStops.put("1228", "302"); // Wyandotte at Sunset allStops.put("1231", "303"); // Wyandotte at Randolph allStops.put("1233", "304"); // Wyandotte at Bridge allStops.put("1235", "305"); // Wyandotte at Campbell allStops.put("1237", "306"); // Wyandotte at McKay allStops.put("1239", "307"); // Wyandotte at Wellington allStops.put("1241", "308"); // Wyandotte at Crawford allStops.put("1243", "309"); // Wyandotte at Caron allStops.put("1245", "310"); // Wyandotte at Bruce allStops.put("1248", "311"); // Wyandotte at Victoria allStops.put("1250", "312"); // Wyandotte at Ouellette allStops.put("1251", "313"); // Wyandotte at Dufferin allStops.put("1253", "314"); // Wyandotte at Windsor allStops.put("1255", "315"); // Wyandotte at McDougall allStops.put("1257", "316"); // Wyandotte at Glengarry allStops.put("1258", "317"); // Wyandotte at Aylmer allStops.put("1261", "318"); // Wyandotte at Marentette allStops.put("1263", "319"); // Wyandotte at Parent allStops.put("1265", "320"); // Wyandotte at Marion allStops.put("1267", "321"); // Wyandotte at Hall allStops.put("1269", "322"); // Wyandotte at Gladstone allStops.put("1270", "323"); // Wyandotte at Lincoln allStops.put("1273", "324"); // Wyandotte at Devonshire allStops.put("1274", "325"); // Wyandotte at Monmouth allStops.put("1276", "326"); // Wyandotte at Walker allStops.put("1278", "327"); // Wyandotte at Albert allStops.put("1280", "328"); // Wyandotte at Drouillard allStops.put("1282", "329"); // Wyandotte at Belleview allStops.put("1284", "330"); // Wyandotte at Strabane allStops.put("1286", "331"); // Wyandotte at Sterling allStops.put("1288", "332"); // Wyandotte at George allStops.put("1290", "333"); // Wyandotte at Rossini allStops.put("1292", "334"); // Wyandotte at Jos. Janisse allStops.put("1294", "335"); // Wyandotte at Pillette allStops.put("1296", "336"); // Wyandotte at Raymo allStops.put("1298", "337"); // Wyandotte at Westminster allStops.put("1300", "338"); // Wyandotte at Ford allStops.put("1301", "339"); // Wyandotte at Prado allStops.put("1303", "340"); // Wyandotte at St. Louis allStops.put("1306", "341"); // Wyandotte at Jefferson allStops.put("1308", "342"); // Wyandotte at Victor allStops.put("1311", "343"); // Wyandotte at St. Marys allStops.put("1315", "344"); // Wyandotte at St. Rose allStops.put("1317", "345"); // Wyandotte at Edward allStops.put("1318", "346"); // Wyandotte at Fairview allStops.put("1320", "347"); // Wyandotte at Matthew Brady allStops.put("1324", "348"); // Lauzon at Wyandotte allStops.put("1326", "349"); // Lauzon at Cedarview allStops.put("1328", "350"); // Lauzon at Clairview allStops.put("1330", "351"); // Lauzon at Riverside allStops.put("1333", "352"); // Riverside at Watson allStops.put("1337", "353"); // Riverside at Bayview Towers allStops.put("1339", "354"); // Riverside at St Clair Towers allStops.put("1341", "355"); // Riverside at Island View Towers allStops.put("1343", "356"); // Riverside at Westchester allStops.put("1345", "357"); // Riverdale at Cedarview allStops.put("1347", "358"); // Riverdale at Menard allStops.put("1349", "359"); // Riverdale at Wyandotte allStops.put("1351", "360"); // Riverdale at Jerome allStops.put("1353", "361"); // Riverdale at St. Rose allStops.put("1356", "362"); // Little River Acres at Abbey allStops.put("1358", "363"); // Little River Acres at Aire allStops.put("1360", "364"); // Little RiverAcres at Copperfield allStops.put("1362", "365"); // Little River Acres at East Moor allStops.put("1364", "366"); // Little RiverAcres at LittleRiver allStops.put("1365", "367"); // Little River at Laporte allStops.put("1366", "368"); // Lauzon Road at Edgar allStops.put("1367", "369"); // Lauzon Rd. at ABC Day Nursery allStops.put("1369", "370"); // Lauzon at Tranby allStops.put("1371", "371"); // Lauzon Parkway at Lauzon Line allStops.put("1373", "372"); // Lauzon Parkway at VIA Tracks allStops.put("1524", "373"); // Transit Centre Front Entrance allStops.put("1504", "374"); // N. Service at Central allStops.put("1502", "375"); // Grand Marais at Allyson allStops.put("1500", "376"); // Grand Marais at Tourangeau allStops.put("1498", "377"); // Grand Marais at Bernard allStops.put("1496", "378"); // Grand Marais at Pillette allStops.put("1494", "379"); // Pillette at Adstoll allStops.put("1492", "380"); // Pillette at Tecumseh allStops.put("1490", "381"); // Pillette at Guy allStops.put("1488", "382"); // Pillette at Milloy allStops.put("1486", "383"); // Pillette at Alice allStops.put("1484", "384"); // Pillette at Reginald allStops.put("1580", "385"); // Seminole at Pillette allStops.put("1578", "386"); // Seminole at Ellrose allStops.put("1576", "387"); // Seminole at Bernard allStops.put("1481", "388"); // George at Seminole allStops.put("1479", "389"); // George at Reginald allStops.put("1477", "390"); // George at Alice allStops.put("1475", "391"); // George at Milloy allStops.put("1313", "392"); // George at Guy allStops.put("1471", "393"); // Hickory at Tecumseh allStops.put("1469", "394"); // Hickory at Milloy allStops.put("1467", "395"); // Drouillard at Alice allStops.put("1465", "396"); // Drouillard at Reginald allStops.put("1463", "397"); // Drouillard at Seminole allStops.put("1462", "398"); // Drouillard at Metcalfe allStops.put("1460", "399"); // Drouillard at Franklin allStops.put("1458", "400"); // Drouillard at Ontario allStops.put("1456", "401"); // Richmond at Drouillard allStops.put("1454", "402"); // Richmond at St. Luke allStops.put("1453", "403"); // Richmond at Walker allStops.put("1450", "404"); // Richmond at Monmouth allStops.put("1448", "405"); // Richmond at Chilver allStops.put("1446", "406"); // Richmond at Lincoln allStops.put("1445", "407"); // Erie at Lincoln allStops.put("1443", "408"); // Erie at Moy allStops.put("1442", "409"); // Erie at Marion allStops.put("1440", "410"); // Erie at Elsmere allStops.put("1436", "411"); // Erie at Louis allStops.put("1434", "412"); // Erie at Howard allStops.put("1432", "413"); // Erie at McDougall allStops.put("1426", "414"); // Erie at Goyeau allStops.put("1428", "415"); // Erie at Ouellette allStops.put("1424", "416"); // Crawford at Wyandotte allStops.put("1423", "417"); // Crawford at Elliott allStops.put("1421", "418"); // Crawford at College allStops.put("1419", "419"); // Crawford at Erie allStops.put("1417", "420"); // Crawford at Grove allStops.put("1414", "421"); // Crawford at Tecumseh allStops.put("1412", "422"); // Tecumseh at Crawford allStops.put("1411", "423"); // Tecumseh at McKay allStops.put("1407", "424"); // Tecumseh at Campbell allStops.put("1406", "425"); // Tecumseh at Bridge allStops.put("1404", "426"); // Tecumseh at Randolph allStops.put("1402", "427"); // Tecumseh at California allStops.put("1400", "428"); // Tecumseh at Northway allStops.put("1398", "429"); // Tecumseh at Huron Church allStops.put("1396", "430"); // Tecumseh at Felix allStops.put("1376", "431"); // College Ave. at Community Centre allStops.put("1377", "432"); // South at College allStops.put("1378", "433"); // South at Wells allStops.put("1379", "434"); // Girardot at South allStops.put("1380", "435"); // Girardot at Strathmore allStops.put("1383", "436"); // Connaught at Chappell allStops.put("1386", "437"); // Sun Valley at Greenview allStops.put("1388", "438"); // Sun Valley at Malden allStops.put("1389", "439"); // Brunet at Industrial allStops.put("1391", "440"); // Industrial at Ambassador allStops.put("1392", "441"); // Ambassador at Urgent Care allStops.put("1393", "442"); // Ambassador at Malden allStops.put("1394", "443"); // Daytona at Malden allStops.put("1395", "444"); // Daytona at Totten allStops.put("1397", "445"); // Northway at Algonquin allStops.put("1399", "446"); // Tecumseh at Northway allStops.put("1401", "447"); // Tecumseh at California allStops.put("1403", "448"); // Tecumseh at Randolph allStops.put("1405", "449"); // Tecumseh at Bridge allStops.put("1408", "450"); // Tecumseh at Campbell allStops.put("1410", "451"); // Tecumseh at Curry allStops.put("1413", "452"); // Crawford at Tecumseh allStops.put("1416", "453"); // Crawford at Grove allStops.put("1418", "454"); // Crawford at Erie allStops.put("1420", "455"); // Crawford at College allStops.put("1422", "456"); // Crawford at Elliott allStops.put("1425", "457"); // Crawford at Wyandotte allStops.put("1429", "458"); // Erie at Ouellette allStops.put("1430", "459"); // Erie at Goyeau allStops.put("1431", "460"); // Erie at McDougall allStops.put("1435", "461"); // Erie at Howard allStops.put("1437", "462"); // Erie at Louis allStops.put("1438", "463"); // Erie at Elsmere allStops.put("1441", "464"); // Erie at Marion allStops.put("1444", "465"); // Erie at Hall allStops.put("1914", "466"); // Gladstone at Erie allStops.put("1447", "467"); // Richmond at Lincoln allStops.put("1449", "468"); // Richmond at Kildare allStops.put("1451", "469"); // Richmond at Argyle allStops.put("1452", "470"); // Richmond at Walker allStops.put("1455", "471"); // Richmond at St. Luke allStops.put("1457", "472"); // Richmond at Drouillard allStops.put("1459", "473"); // Drouillard at Ontario allStops.put("1461", "474"); // Drouillard at Franklin allStops.put("1322", "475"); // Drouillard at Metcalfe allStops.put("1464", "476"); // Drouillard at Seminole allStops.put("1466", "477"); // Drouillard at Reginald allStops.put("1468", "478"); // Drouillard at Alice allStops.put("1470", "479"); // Drouillard at Milloy allStops.put("1472", "480"); // Drouillard at Tecumseh allStops.put("1474", "481"); // George at Tecumseh allStops.put("1331", "482"); // George at Guy allStops.put("1476", "483"); // George at Milloy allStops.put("1478", "484"); // George at Alice allStops.put("1480", "485"); // George at Reginald allStops.put("1572", "486"); // Seminole at George allStops.put("1574", "487"); // Seminole at Rossini allStops.put("1577", "488"); // Seminole at Francois allStops.put("1483", "489"); // Seminole at Pillette allStops.put("1485", "490"); // Pillette at Reginald allStops.put("1487", "491"); // Pillette at Alice allStops.put("1489", "492"); // Pillette at Milloy allStops.put("1491", "493"); // Pillette at Guy allStops.put("1493", "494"); // Pillette at Tecumseh allStops.put("1495", "495"); // Pillette at Adstoll allStops.put("1497", "496"); // Pillette at Grand Marais allStops.put("1501", "497"); // Pillette at Plymouth allStops.put("1503", "498"); // Plymouth at Robert allStops.put("1505", "499"); // Plymouth at Tourangeau allStops.put("1506", "500"); // Plymouth at Grand Marais allStops.put("1507", "501"); // Central at Temple allStops.put("1508", "502"); // Mannheim at Deziel allStops.put("1509", "503"); // St. Etienne at Kautex allStops.put("1510", "504"); // Kautex at Deziel allStops.put("1511", "505"); // Deziel at Mannheim allStops.put("1512", "506"); // Deziel at Central allStops.put("1513", "507"); // Rhodes at Wheelton allStops.put("1514", "508"); // Rhodes at Electricity allStops.put("1515", "509"); // Rhodes at Jamieson allStops.put("1516", "510"); // Rhodes at Enwin allStops.put("1517", "511"); // Rhodes at Pillette allStops.put("1518", "512"); // Rhodes at Fuller Construction allStops.put("1335", "513"); // Rhodes at Jefferson allStops.put("1357", "514"); // Jefferson at E.C. Row allStops.put("1519", "515"); // North Service at Jefferson allStops.put("1520", "516"); // North Service at Clemenceau allStops.put("1521", "517"); // North Service at Tracks allStops.put("1522", "518"); // North Service Road at Pillette allStops.put("1332", "519"); // Service Road at Electrical Union allStops.put("2051", "520"); // Transit Terminal at Chatham allStops.put("1656", "521"); // Essex Way at Meadowbrook allStops.put("1660", "522"); // Cantelon at Kew allStops.put("1659", "523"); // Cantelon at Lauzon Parkway allStops.put("1658", "524"); // Forest Glade at Lauzon Parkway allStops.put("1657", "525"); // Forest Glade at Lauzon allStops.put("1655", "526"); // Beachdale at Chestnut allStops.put("1653", "527"); // Esplanade at Beachdale allStops.put("1651", "528"); // Esplanade at Ridge allStops.put("1649", "529"); // Esplanade at Lilac allStops.put("1647", "530"); // Lilac at Lauzon allStops.put("1645", "531"); // Lauzon Road at Hawthorne allStops.put("1643", "532"); // Lauzon Road at Yolanda allStops.put("1639", "533"); // Clemenceau at Rose allStops.put("1637", "534"); // Clemenceau at Joinville allStops.put("1635", "535"); // Clemenceau at Haig allStops.put("1633", "536"); // Clemenceau at Grand allStops.put("1631", "537"); // Clemenceau at Roosevelt allStops.put("1629", "538"); // Queen Elizabeth at Clemenceau allStops.put("1626", "539"); // Queen Elizabeth at Grandview allStops.put("1623", "540"); // Queen Elizabeth at Clarence allStops.put("1621", "541"); // Rivard at Queen Elizabeth allStops.put("1619", "542"); // Rivard at Library allStops.put("1617", "543"); // Rivard at Grand allStops.put("1615", "544"); // Rivard at Haig allStops.put("1613", "545"); // Rivard at Joinville allStops.put("1611", "546"); // Rivard at Rose allStops.put("1609", "547"); // Ford at Empress allStops.put("1607", "548"); // Ford at Coronation allStops.put("1605", "549"); // Ford at Lassaline allStops.put("1603", "550"); // Ford at Reginald allStops.put("1601", "551"); // South National at Ford allStops.put("1599", "552"); // South National at Ferndale allStops.put("1597", "553"); // South National at Balfour allStops.put("1595", "554"); // Jefferson at South National allStops.put("1593", "555"); // Jefferson at Edgar allStops.put("1591", "556"); // Jefferson at Raymond allStops.put("1589", "557"); // Jefferson at Ontario allStops.put("1588", "558"); // Pillette at Wyandotte allStops.put("1586", "559"); // Pillette at Ontario allStops.put("1584", "560"); // Pillette at South National allStops.put("1582", "561"); // Pillette at Metcalfe allStops.put("1573", "562"); // Seminole at George allStops.put("1570", "563"); // Seminole at Central allStops.put("1568", "564"); // Seminole at Chandler allStops.put("1566", "565"); // Seminole at Drouillard allStops.put("1564", "566"); // Seminole at Albert allStops.put("1562", "567"); // Seminole at Walker allStops.put("1560", "568"); // Ottawa at Monmouth allStops.put("1557", "569"); // Ottawa at Kildare allStops.put("1555", "570"); // Ottawa at Lincoln allStops.put("1552", "571"); // Ottawa at Gladstone allStops.put("1550", "572"); // Ottawa at Hall allStops.put("1548", "573"); // Ottawa at Benjamin allStops.put("1545", "574"); // Parent at Ottawa allStops.put("1543", "575"); // Giles at Elsmere allStops.put("1541", "576"); // Giles at Louis allStops.put("1539", "577"); // Giles at Howard allStops.put("1536", "578"); // Giles at McDougall allStops.put("1534", "579"); // Giles at Windsor allStops.put("1532", "580"); // Giles at Ouellette allStops.put("1529", "581"); // Transit Windsor Terminal allStops.put("1531", "582"); // Giles at Ouellette allStops.put("1533", "583"); // Giles at Goyeau allStops.put("1535", "584"); // Giles at McDougall allStops.put("1538", "585"); // Giles at Howard allStops.put("1542", "586"); // Giles at Marentette allStops.put("1544", "587"); // Giles at Parent allStops.put("1546", "588"); // Ottawa at Parent allStops.put("1549", "589"); // Ottawa at Pierre allStops.put("1551", "590"); // Ottawa at Moy allStops.put("1553", "591"); // Ottawa at Gladstone allStops.put("1554", "592"); // Ottawa at Lincoln allStops.put("1556", "593"); // Ottawa at Kildare allStops.put("1559", "594"); // Ottawa at Walker allStops.put("1561", "595"); // Seminole at Walker allStops.put("1563", "596"); // Seminole at Albert allStops.put("1565", "597"); // Seminole at Drouillard allStops.put("1567", "598"); // Seminole at Chandler allStops.put("1569", "599"); // Seminole at Central allStops.put("1571", "600"); // Seminole at Westcott allStops.put("1579", "601"); // Pillette at Seminole allStops.put("1581", "602"); // Pillette at Metcalfe allStops.put("1583", "603"); // Pillette at South National allStops.put("1585", "604"); // Pillette at Ontario allStops.put("1587", "605"); // Pillette at Wyandotte allStops.put("1590", "606"); // Jefferson at Ontario allStops.put("1592", "607"); // Jefferson at Raymond allStops.put("1594", "608"); // Jefferson at Edgar allStops.put("1596", "609"); // South National at Jefferson allStops.put("1598", "610"); // South National at Balfour allStops.put("1600", "611"); // South National at Ferndale allStops.put("1602", "612"); // South National at Ford allStops.put("1604", "613"); // Ford at Reginald allStops.put("1606", "614"); // Ford at Lassaline allStops.put("1608", "615"); // Ford at Coronation allStops.put("1610", "616"); // Ford at Empress allStops.put("1612", "617"); // Rivard at Joinville allStops.put("1614", "618"); // Rivard at Haig allStops.put("1616", "619"); // Rivard at Grand allStops.put("1618", "620"); // Rivard at Ambassador Church allStops.put("1620", "621"); // Rivard at Queen Elizabeth allStops.put("1622", "622"); // Queen Elizabeth at Clarence allStops.put("1625", "623"); // Queen Elizabeth at Harmony allStops.put("1628", "624"); // Queen Elizabeth at Clemenceau allStops.put("1630", "625"); // Clemenceau at Roosevelt allStops.put("1632", "626"); // Clemenceau at Grand allStops.put("1634", "627"); // Clemenceau at Haig allStops.put("1636", "628"); // Clemenceau at Joinville allStops.put("1159", "629"); // Rose at Clemenceau allStops.put("1642", "630"); // Lauzon Rd. at Yolanda allStops.put("1644", "631"); // Lauzon Rd. at Hawthorne allStops.put("1646", "632"); // Hawthorne at Sycamore allStops.put("1648", "633"); // Meadowbrook at Hawthorne allStops.put("1650", "634"); // Meadowbrook at Parkside Estates allStops.put("1652", "635"); // Meadowbrook at Optimist Park allStops.put("1654", "636"); // Meadowbrook at Essex Way allStops.put("2063", "637"); // Giles at Parent allStops.put("1661", "638"); // Walker at Ontario allStops.put("1662", "639"); // Walker at Ontario allStops.put("2064", "640"); // Parent at Giles allStops.put("1734", "641"); // St. Clair College Front Entrance allStops.put("1817", "642"); // Cousineau at Highway 3 allStops.put("1816", "643"); // Cousineau at Mount Royal allStops.put("1814", "644"); // Cousineau at Casgrain allStops.put("1813", "645"); // Cousineau at Country Club allStops.put("1809", "646"); // Country Club at Hunt Club allStops.put("1807", "647"); // Country Club at Shade Tree allStops.put("1804", "648"); // Country Club at Lake Trail allStops.put("1800", "649"); // Howard at North Talbot allStops.put("1799", "650"); // Howard at Wallace allStops.put("1797", "651"); // Howard at Ducharme allStops.put("1794", "652"); // Howard at Morand allStops.put("1792", "653"); // Cabana at Howard allStops.put("1791", "654"); // Cabana at Huntington allStops.put("1788", "655"); // Cabana at Dougall allStops.put("1786", "656"); // Dougall at Granada allStops.put("1784", "657"); // Dougall at Medina allStops.put("1782", "658"); // Dougall at Beals allStops.put("1387", "659"); // Dougall at Liberty allStops.put("1780", "660"); // Dougall at Norfolk allStops.put("1777", "661"); // Dougall at Nottingham Walmart allStops.put("1390", "662"); // Dougall Town Centre allStops.put("1775", "663"); // Dougall at West Grand allStops.put("1773", "664"); // Dougall at South Cameron allStops.put("1771", "665"); // Eugenie at Dougall allStops.put("1769", "666"); // Dougall at Rose Bowl allStops.put("1767", "667"); // Dougall at Dougall Square allStops.put("1763", "668"); // Dougall at Brentwood allStops.put("1761", "669"); // Dougall at Wear allStops.put("1759", "670"); // Tecumseh at York allStops.put("1757", "671"); // Bruce at Hanna allStops.put("1753", "672"); // Bruce at Shepherd allStops.put("1751", "673"); // Bruce at Clinton allStops.put("1749", "674"); // Bruce at Giles allStops.put("1747", "675"); // Bruce at Pine allStops.put("1745", "676"); // Bruce at Erie allStops.put("1433", "677"); // Bruce at Caroline allStops.put("1743", "678"); // Bruce at Elliott allStops.put("1742", "679"); // Bruce at Wyandotte allStops.put("1740", "680"); // Bruce at Park allStops.put("1738", "681"); // Bruce at University allStops.put("1737", "682"); // Transit Terminal at Chatham allStops.put("1739", "683"); // Janette at Park allStops.put("1741", "684"); // Janette at Wyandotte allStops.put("1382", "685"); // Janette at Elliott allStops.put("1384", "686"); // Janette at Caroline allStops.put("1385", "687"); // Erie at Janette allStops.put("1744", "688"); // Erie at Church allStops.put("1746", "689"); // Dougall at Pine allStops.put("1748", "690"); // Dougall at Giles allStops.put("1750", "691"); // Dougall at Montrose allStops.put("1752", "692"); // Dougall at Ellis allStops.put("1754", "693"); // Dougall at Shepherd allStops.put("1756", "694"); // Dougall at Hanna allStops.put("1758", "695"); // Dougall at Tecumseh allStops.put("1760", "696"); // Dougall at Wear allStops.put("1762", "697"); // Dougall at Jackson Park allStops.put("1764", "698"); // Dougall at Windsor Sportsmen allStops.put("1766", "699"); // Dougall at Dorwin Plaza allStops.put("1768", "700"); // Dougall at Dougall Plaza allStops.put("1770", "701"); // Eugenie at Pellisier allStops.put("1774", "702"); // Dougall at South Cameron allStops.put("1776", "703"); // Dougall at West Grand allStops.put("1778", "704"); // Dougall at Nottingham Walmart allStops.put("1779", "705"); // Dougall at Norfolk allStops.put("1781", "706"); // Dougall at Liberty allStops.put("1783", "707"); // Dougall at Beals allStops.put("1785", "708"); // Dougall at Medina allStops.put("1787", "709"); // Dougall at Granada allStops.put("1789", "710"); // Cabana at Dougall allStops.put("1790", "711"); // Cabana at Huntington allStops.put("1793", "712"); // Cabana at Howard allStops.put("1795", "713"); // Howard at Morand allStops.put("1796", "714"); // Howard at Ducharme allStops.put("1798", "715"); // Howard at Wallace allStops.put("1801", "716"); // Howard at Neal allStops.put("1803", "717"); // Country Club at Tournament allStops.put("1806", "718"); // Country Club at Rodfam allStops.put("1808", "719"); // Country Club at Hunt Club allStops.put("1810", "720"); // Country Club at Cousineau allStops.put("1812", "721"); // Cousineau at Casgrain allStops.put("1815", "722"); // Cousineau at Mt. Royal allStops.put("1732", "723"); // Cousineau at Highway 3 allStops.put("1997", "724"); // Sixth Concession at North Talbot allStops.put("1993", "725"); // Sixth Concession at Holburn allStops.put("1991", "726"); // Holburn at Spago allStops.put("1989", "727"); // Ducharme at Holburn allStops.put("1987", "728"); // Ducharme at Canberra allStops.put("1985", "729"); // Ducharme at Periwinkle allStops.put("1983", "730"); // Ducharme at Fontana allStops.put("1981", "731"); // Ducharme at Lavender allStops.put("1979", "732"); // Ducharme at Walker allStops.put("1977", "733"); // Walker at Provincial allStops.put("1975", "734"); // Walker at 7th Concession allStops.put("1973", "735"); // Walker at Walker Crossings allStops.put("1971", "736"); // Walker at Canadian Tire allStops.put("1969", "737"); // Walker at Ferrari Plaza allStops.put("1968", "738"); // Airport at Front Entrance allStops.put("1966", "739"); // Walker at Division allStops.put("1964", "740"); // Walker at Moxlay allStops.put("1963", "741"); // Walker at Airport allStops.put("1961", "742"); // Walker at Melinda allStops.put("1959", "743"); // Walker at Calderwood allStops.put("1957", "744"); // Walker at Lappan allStops.put("1955", "745"); // Walker at Foster allStops.put("1953", "746"); // Walker at Seymour allStops.put("1951", "747"); // Walker at Sydney allStops.put("1949", "748"); // Walker at Digby allStops.put("1947", "749"); // Walker at Parkdale allStops.put("1945", "750"); // Walker at Grand Marais allStops.put("1943", "751"); // Walker at St. Julien allStops.put("1941", "752"); // Walker at Somme allStops.put("1939", "753"); // Ypres at Turner allStops.put("1937", "754"); // Ypres at Kildare allStops.put("1935", "755"); // Ypres at Lincoln allStops.put("1933", "756"); // Lincoln at Vimy allStops.put("1931", "757"); // Lincoln at Lens allStops.put("1929", "758"); // Lincoln at Tecumseh allStops.put("1805", "759"); // Lincoln at Mohawk allStops.put("1927", "760"); // Lincoln at Seneca allStops.put("1925", "761"); // Lincoln at ETR Rail Tracks allStops.put("1923", "762"); // Lincoln at Shepherd allStops.put("1921", "763"); // Lincoln at Ottawa allStops.put("1919", "764"); // Lincoln at Ontario allStops.put("1917", "765"); // Lincoln at Richmond allStops.put("1915", "766"); // Lincoln at Erie allStops.put("1913", "767"); // Lincoln at Niagara allStops.put("1911", "768"); // Lincoln at Cataraqui allStops.put("1909", "769"); // Lincoln at Wyandotte allStops.put("1907", "770"); // Lincoln at Assumption allStops.put("1811", "771"); // Riverside at Gladstone allStops.put("1905", "772"); // Riverside at Hall allStops.put("1802", "773"); // Riverside at Langlois allStops.put("1903", "774"); // Riverside at Parent allStops.put("1901", "775"); // Riverside at Aylmer allStops.put("1899", "776"); // Riverside at McDougall allStops.put("1898", "777"); // Riverside at Goyeau allStops.put("1896", "778"); // Ferry at Riverside allStops.put("1894", "779"); // Transit Terminal Church at Pitt allStops.put("1895", "780"); // Riverside at Ouellette allStops.put("1897", "781"); // Riverside at McDougall allStops.put("1900", "782"); // Riverside at Aylmer allStops.put("1902", "783"); // Riverside at Parent allStops.put("1818", "784"); // Riverside at Langlois allStops.put("1904", "785"); // Riverside at Hall allStops.put("1864", "786"); // Riverside at Gladstone allStops.put("1906", "787"); // Gladstone at Assumption allStops.put("1908", "788"); // Gladstone at Wyandotte allStops.put("1910", "789"); // Gladstone at Cataraqui allStops.put("1912", "790"); // Gladstone at Niagara allStops.put("1916", "791"); // Gladstone at Richmond allStops.put("1918", "792"); // Gladstone at Giles allStops.put("1920", "793"); // Gladstone at Ottawa allStops.put("1865", "794"); // Gladstone at Ellis allStops.put("1922", "795"); // Shepherd at Lincoln allStops.put("1924", "796"); // Lincoln at ETR Rail Tracks allStops.put("1926", "797"); // Lincoln at Seneca allStops.put("1928", "798"); // Lincoln at Tecumseh allStops.put("1930", "799"); // Lincoln at Lens allStops.put("1932", "800"); // Lincoln at Vimy allStops.put("1934", "801"); // Lincoln at Ypres allStops.put("1936", "802"); // Ypres at Kildare allStops.put("1938", "803"); // Ypres at Turner allStops.put("1940", "804"); // Walker at Somme allStops.put("1942", "805"); // Walker at St. Julien allStops.put("1944", "806"); // Walker at Grand Marais allStops.put("1946", "807"); // Walker at Parkdale allStops.put("1948", "808"); // Walker at Digby allStops.put("1950", "809"); // Walker at Sydney allStops.put("1952", "810"); // Walker at Seymour allStops.put("1954", "811"); // Walker at Foster allStops.put("1956", "812"); // Walker at Lappan allStops.put("1958", "813"); // Walker at Calderwood allStops.put("1960", "814"); // Walker at Melinda allStops.put("1962", "815"); // Walker at Ledyard allStops.put("1772", "816"); // Walker at Moxley allStops.put("1965", "817"); // Walker at Division allStops.put("1967", "818"); // Walker at Home Depot Plaza allStops.put("1970", "819"); // Walker at Canada Post allStops.put("1972", "820"); // Walker at Best Buy allStops.put("1974", "821"); // Walker at Costco allStops.put("1976", "822"); // Walker at Legacy Park allStops.put("1978", "823"); // Walker at Provincial allStops.put("1980", "824"); // Walker at Ducharme allStops.put("1982", "825"); // Walker at Highway 401 allStops.put("1984", "826"); // Walker at U-Haul allStops.put("1986", "827"); // Walker at North Talbot allStops.put("1988", "828"); // North Talbot at Halford allStops.put("1990", "829"); // North Talbot at Burke allStops.put("1992", "830"); // North Talbot at Dumouchelle allStops.put("1994", "831"); // North Talbot at Old West allStops.put("1995", "832"); // North Talbot at Pioneer allStops.put("2052", "833"); // Ferry at Riverside allStops.put("2055", "834"); // Glengarry at University allStops.put("2057", "835"); // Glengarry at Wyandotte allStops.put("2059", "836"); // Howard at Elliott allStops.put("2065", "837"); // Parent at Ottawa allStops.put("2066", "838"); // Parent at Ellis allStops.put("2068", "839"); // Parent at Shepherd allStops.put("2070", "840"); // Parent at Hanna allStops.put("1108", "841"); // Tecumseh at Marentette allStops.put("2075", "842"); // Eugenie at Howard allStops.put("2076", "843"); // Eugenie at Lillian allStops.put("2080", "844"); // South Pacific at Parent allStops.put("2082", "845"); // South Pacific at Jeremiah allStops.put("2084", "846"); // Southdale at South Pacific allStops.put("2086", "847"); // Southdale at Southridge allStops.put("2088", "848"); // Slater at Southdale allStops.put("2092", "849"); // Slater at Grand Marais allStops.put("2094", "850"); // Grand Marais at Southdale allStops.put("2096", "851"); // Grand Marais at Garvey allStops.put("2098", "852"); // Grand Marais at South Pacific allStops.put("2100", "853"); // Grand Marais at Langlois allStops.put("2102", "854"); // N. Service Rd.at Langlois allStops.put("2104", "855"); // N. Service Rd. at Conservation allStops.put("2106", "856"); // Conservation at E.C. Row Ave allStops.put("2108", "857"); // E.C. Row Ave at Parkwood allStops.put("1765", "858"); // Sydney at Windsor Commons allStops.put("1877", "859"); // Devonshire Mall at Moxies allStops.put("2113", "860"); // Marentette at EC Row Ave allStops.put("2112", "861"); // E.C. Row Ave at Devon allStops.put("2105", "862"); // E.C Row Ave at Conservation allStops.put("2103", "863"); // N. Service Rd.at Jennifer allStops.put("2101", "864"); // N. Service Rd. at Langlois allStops.put("2099", "865"); // Grand Marais at Langlois allStops.put("2097", "866"); // Grand Marais at South Pacific allStops.put("2095", "867"); // Grand Marais at Garvey allStops.put("2093", "868"); // Slater at Hartford allStops.put("2089", "869"); // Slater at Southdale allStops.put("2087", "870"); // Southdale at Bramley allStops.put("2085", "871"); // South Pacific at Southdale allStops.put("2083", "872"); // South Pacific at Jeremiah allStops.put("2081", "873"); // South Pacific at Parent allStops.put("2079", "874"); // Eugenie at South Pacific allStops.put("2077", "875"); // Eugenie at Remington allStops.put("2074", "876"); // Howard at Tecumseh allStops.put("2073", "877"); // Parent at Tecumseh allStops.put("2071", "878"); // Parent at Hanna allStops.put("2069", "879"); // Parent at Shepherd allStops.put("2067", "880"); // Parent at Ellis allStops.put("2061", "881"); // Howard at Erie allStops.put("2060", "882"); // Howard at Elliott allStops.put("2058", "883"); // Aylmer at Wyandotte allStops.put("2056", "884"); // Aylmer at Assumption allStops.put("2054", "885"); // Chatham at Glengarry allStops.put("2053", "886"); // Chatham at Goyeau allStops.put("2116", "887"); // Windsor Transit Terminal allStops.put("2117", "888"); // Goyeau at Pitt allStops.put("2118", "889"); // City Hall Square allStops.put("2119", "890"); // Canada Tunnel Plaza Duty Free allStops.put("2126", "891"); // Congress at Beaubien allStops.put("2127", "892"); // Congress at Randolph allStops.put("2132", "893"); // Griswold at Congress allStops.put("2129", "894"); // Washington at Jefferson allStops.put("2130", "895"); // Fort at Cass allStops.put("2131", "896"); // Cass at Lafayette allStops.put("2135", "897"); // Rosa Parks Transit Center allStops.put("2120", "898"); // McDougall at University Avenue allStops.put("1755", "899"); // Chatham at Goyeau allStops.put("1831", "900"); // Chatham at Ouellette allStops.put("2134", "901"); // Michigan at Washington allStops.put("2124", "902"); // Tunnel Platform at Mariner's allStops.put("2122", "903"); // McDougall at Wyandotte allStops.put("1665", "904"); // Riverside at Caron allStops.put("1525", "905"); // Crawford at Riverside allStops.put("1527", "906"); // Crawford at University allStops.put("1528", "907"); // Crawford at University allStops.put("1526", "908"); // Crawford at Riverside allStops.put("1664", "909"); // Riverside at Caron allStops.put("1893", "910"); // Legacy Park at Sears Home allStops.put("1892", "911"); // Division at Walker allStops.put("1537", "912"); // Division at Bliss allStops.put("1890", "913"); // Division at Woodward allStops.put("1889", "914"); // Division at Conservation Area allStops.put("1887", "915"); // Division at Clarke allStops.put("1876", "916"); // Howard at Kenilworth allStops.put("1874", "917"); // Howard at Maguire allStops.put("1871", "918"); // Cabana at Dougall allStops.put("1540", "919"); // Cabana at Granada allStops.put("1869", "920"); // Cabana at McGraw allStops.put("1547", "921"); // Cabana at Casgrain allStops.put("1867", "922"); // Cabana at Dominion allStops.put("1863", "923"); // Geraedts at St. Clair Residence allStops.put("1736", "924"); // Geraedts at St. Clair Residence allStops.put("1862", "925"); // Cabana at Geraedts allStops.put("1860", "926"); // Cabana at Randolph allStops.put("1638", "927"); // Cabana at Askin allStops.put("1858", "928"); // Cabana at Northway allStops.put("1627", "929"); // Todd Lane at Tenth allStops.put("1854", "930"); // Todd Lane at Ninth allStops.put("1624", "931"); // Todd Lane at Oxley allStops.put("1852", "932"); // Todd Lane at Canada allStops.put("1850", "933"); // Todd Lane at Fifth allStops.put("1848", "934"); // Todd Lane at Third allStops.put("1847", "935"); // Malden at Orford allStops.put("1845", "936"); // Malden at Delmar allStops.put("1843", "937"); // Sprucewood at Malden allStops.put("1575", "938"); // Sprucewood at Newman allStops.put("1841", "939"); // Sprucewood at Woodmont allStops.put("1839", "940"); // Sprucewood at Abbott allStops.put("1837", "941"); // Sprucewood at Kingsley allStops.put("1558", "942"); // Sprucewood at Matchette allStops.put("1833", "943"); // Marigold at Weaver allStops.put("1830", "944"); // Matchette at Titcombe allStops.put("1828", "945"); // Matchette at Armanda allStops.put("1826", "946"); // Matchette at Carmichael allStops.put("1824", "947"); // Matchette at Chappell allStops.put("1822", "948"); // Prince at Vaughan allStops.put("1821", "949"); // Prince at Mulford allStops.put("1820", "950"); // Prince at Wells allStops.put("1819", "951"); // College Ave. at Community Centre allStops.put("1823", "952"); // Matchette at Chappell allStops.put("1825", "953"); // Matchette at Carmichael allStops.put("1827", "954"); // Matchette at Broadway allStops.put("1829", "955"); // Matchette at Titcombe allStops.put("1835", "956"); // Sprucewood at Matchette allStops.put("1836", "957"); // Sprucewood at Kingsley allStops.put("1838", "958"); // Sprucewood at Abbott allStops.put("1840", "959"); // Sprucewood at Woodmont allStops.put("1482", "960"); // Sprucewood at Newman allStops.put("1842", "961"); // Sprucewood at Malden allStops.put("1844", "962"); // Malden at Delmar allStops.put("1846", "963"); // Malden at Todd Lane allStops.put("1849", "964"); // Todd Lane at Elmdale allStops.put("1851", "965"); // Todd Lane at Wayne allStops.put("1853", "966"); // Todd Lane at Canada allStops.put("1499", "967"); // Todd Lane at Bishop allStops.put("1855", "968"); // Todd Lane at Ninth allStops.put("1856", "969"); // Todd Lane at Tenth allStops.put("1857", "970"); // Cabana at Northway allStops.put("1523", "971"); // Cabana at Borrelli allStops.put("1859", "972"); // Cabana at Southwinds allStops.put("1861", "973"); // Cabana at Roxborough allStops.put("1866", "974"); // Cabana at Geraedts allStops.put("1868", "975"); // Cabana at Longfellow allStops.put("1473", "976"); // Cabana at Casgrain allStops.put("1870", "977"); // Cabana at McGraw allStops.put("1415", "978"); // Cabana at Granada allStops.put("1872", "979"); // Howard at Cabana allStops.put("1873", "980"); // Howard at Maguire allStops.put("1875", "981"); // Howard at Kenilworth allStops.put("1880", "982"); // Marentette at Foster allStops.put("1882", "983"); // Marentette at Division allStops.put("1883", "984"); // Provincial at Clarke allStops.put("1409", "985"); // Provincial at Cabana allStops.put("1884", "986"); // Provincial at Humane Society allStops.put("1885", "987"); // Provincial at Sixth Concession allStops.put("1886", "988"); // Provincial at Lone Pine allStops.put("1888", "989"); // Provincial at Monarch Basics allStops.put("1891", "990"); // Provincial at Legacy Park allStops.put("1663", "991"); // Windsor Transit Terminal allStops.put("1667", "992"); // Riverside at Oak allStops.put("1669", "993"); // Riverside at McKay allStops.put("1671", "994"); // Campbell at Riverside allStops.put("1673", "995"); // Campbell at University allStops.put("1305", "996"); // Campbell at Martindale allStops.put("1675", "997"); // Campbell at Wyandotte allStops.put("1677", "998"); // Campbell at Rooney allStops.put("1679", "999"); // Campbell at College allStops.put("1681", "1000"); // Campbell at Adanac allStops.put("1683", "1001"); // Campbell at Grove allStops.put("1685", "1002"); // Campbell at Taylor allStops.put("1687", "1003"); // Campbell at Pelletier allStops.put("1689", "1004"); // Campbell at Tecumseh allStops.put("1690", "1005"); // Campbell at Everts allStops.put("1692", "1006"); // Campbell at Curry allStops.put("1694", "1007"); // Dominion at Totten allStops.put("1696", "1008"); // Dominion at Arcadia allStops.put("1698", "1009"); // Dominion at McKay allStops.put("1700", "1010"); // Dominion at Ojibway allStops.put("1702", "1011"); // Dominion at Holy Names allStops.put("1703", "1012"); // Dominion at Northwood allStops.put("1706", "1013"); // Dominion at E.C. Row allStops.put("1708", "1014"); // Dominion at Labelle allStops.put("1711", "1015"); // Dominion at Grand Marais allStops.put("1713", "1016"); // Dominion at Norfolk allStops.put("1715", "1017"); // Dominion at Richardie allStops.put("1717", "1018"); // Dominion at Beals allStops.put("1719", "1019"); // Dominion at Roselawn allStops.put("1721", "1020"); // Dominion at Cabana allStops.put("1723", "1021"); // Mount Royal at Cabana allStops.put("1725", "1022"); // Mount Royal at Villa Maria North allStops.put("1726", "1023"); // Mount Royal at Villa Maria South allStops.put("1728", "1024"); // Mount Royal at Mitchell allStops.put("1730", "1025"); // Mount Royal at Cousineau allStops.put("1735", "1026"); // Glenwood at Cabana allStops.put("1246", "1027"); // Glenwood at St. Gabriel allStops.put("1733", "1028"); // Beals at Roxborough allStops.put("1731", "1029"); // Beals at Rankin allStops.put("1729", "1030"); // Rankin at Liberty allStops.put("1727", "1031"); // Norfolk at Rankin allStops.put("1724", "1032"); // Norfolk at California allStops.put("1722", "1033"); // California at Grand Marais allStops.put("1720", "1034"); // Grand Marais at Northway allStops.put("1718", "1035"); // Labelle at Northway allStops.put("1716", "1036"); // Labelle at California allStops.put("1714", "1037"); // Labelle at St. Patricks allStops.put("1710", "1038"); // Labelle at Orion allStops.put("1709", "1039"); // Labelle at Everts allStops.put("1707", "1040"); // Labelle at Dominion allStops.put("1705", "1041"); // Dominion at E.C. Row allStops.put("1704", "1042"); // Dominion at Northwood allStops.put("1701", "1043"); // Dominion at Holy Names allStops.put("1699", "1044"); // Dominion at Ojibway allStops.put("1697", "1045"); // Dominion at McKay allStops.put("1695", "1046"); // Dominion at Arcadia allStops.put("1693", "1047"); // Campbell at Totten allStops.put("1691", "1048"); // Campbell at Curry allStops.put("1154", "1049"); // Campbell at Mark allStops.put("1688", "1050"); // Campbell at Tecumseh allStops.put("1686", "1051"); // Campbell at Pelletier allStops.put("1684", "1052"); // Campbell at Taylor allStops.put("1682", "1053"); // Campbell at Grove allStops.put("1680", "1054"); // Campbell at Adanac allStops.put("1678", "1055"); // Campbell at College allStops.put("1676", "1056"); // Campbell at Rooney allStops.put("1674", "1057"); // Campbell at Wyandotte allStops.put("1381", "1058"); // Campbell at Martindale allStops.put("1672", "1059"); // Campbell at University allStops.put("1670", "1060"); // Campbell at Riverside allStops.put("1668", "1061"); // Riverside at McKay allStops.put("1666", "1062"); // Riverside at Oak allStops.put("1998", "1063"); // Tecumseh Mall Rear Entrance allStops.put("2007", "1064"); // Lauzon Rd. at Lilac allStops.put("1999", "1065"); // Lauzon at Vince allStops.put("2000", "1066"); // Lauzon at Forest Glade allStops.put("2001", "1067"); // Forest Glade at Meadowbrook allStops.put("2002", "1068"); // Anchor at Twin Oaks allStops.put("2003", "1069"); // Anchor at Green Shield allStops.put("2004", "1070"); // Anchor at CS Wind allStops.put("2006", "1071"); // Anchor at Jamison Entrance allStops.put("2005", "1072"); // Banwell at Wildwood allStops.put("2022", "1073"); // Banwell at Palmetto allStops.put("2024", "1074"); // Banwell at Tecumseh allStops.put("2028", "1075"); // McHugh at Questa allStops.put("2030", "1076"); // McHugh at Trappers allStops.put("2031", "1077"); // McHugh at Venetian allStops.put("2033", "1078"); // McHugh at Clover allStops.put("2034", "1079"); // McHugh at Cypress allStops.put("2039", "1080"); // WFCU Centre Main Entrance allStops.put("2041", "1081"); // McHugh at Darfield allStops.put("2043", "1082"); // Lauzon Rd. at McHugh allStops.put("2050", "1083"); // McHugh at Lauzon allStops.put("2049", "1084"); // McHugh at Darfield allStops.put("2048", "1085"); // WFCU Centre Main Entrance allStops.put("2046", "1086"); // McHugh at Cypress allStops.put("2045", "1087"); // McHugh at Clover allStops.put("2042", "1088"); // Clover at Firgrove allStops.put("2040", "1089"); // Clover at Little River allStops.put("2037", "1090"); // Little River at Pearson allStops.put("2035", "1091"); // Little River at Chateau allStops.put("2032", "1092"); // Little River at Banwell allStops.put("2029", "1093"); // Little River at Jarvis allStops.put("2027", "1094"); // Cora Greenwood at Little River allStops.put("2025", "1095"); // Cora Green at Castle Hill allStops.put("2023", "1096"); // Cora Green at Dillon allStops.put("2021", "1097"); // Cora Green at Riverside allStops.put("2020", "1098"); // Riverside at Jarvis allStops.put("2019", "1099"); // Greenpark at Amalfi allStops.put("2018", "1100"); // Wyandotte at Greenpark allStops.put("2017", "1101"); // Wyandotte at Clover allStops.put("2016", "1102"); // Wyandotte at Florence allStops.put("2015", "1103"); // Wyandotte at Martinique allStops.put("2014", "1104"); // Wyandotte at Greendale allStops.put("2013", "1105"); // Wyandotte at Westchester allStops.put("2012", "1106"); // Wyandotte at Isack allStops.put("2011", "1107"); // Wyandotte at Riverside Plaza allStops.put("2010", "1108"); // Wyandotte at Watson allStops.put("2009", "1109"); // Lauzon Rd. at Wyandotte allStops.put("2008", "1110"); // Lauzon Road at St. Rose allStops.put("2047", "1111"); // McHugh at Mickey Renuad Way allStops.put("2038", "1112"); // McHugh at Micky Renaud Way allStops.put("2140", "1113"); // St Clair Front Entrance allStops.put("2141", "1114"); // Montgomery at Surrey allStops.put("2142", "1115"); // Montgomery at Eastbourne allStops.put("2143", "1116"); // Heritage at Winfield allStops.put("2144", "1117"); // Heritage at Winfield allStops.put("2145", "1118"); // Heritage at Rushwood allStops.put("2146", "1119"); // Heritage at Rushwood allStops.put("2147", "1120"); // Heritage at Sandwich West allStops.put("2148", "1121"); // Sandwich West at Lovell allStops.put("2149", "1122"); // Sandwich West at Durocher allStops.put("2150", "1123"); // Sandwich West at D'Amore allStops.put("2151", "1124"); // Sandwich West at Mary allStops.put("2152", "1125"); // Sandwich West at Huron Church allStops.put("2153", "1126"); // Huron Church at Skinner allStops.put("2154", "1127"); // Huron Church at Cousineau allStops.put("2155", "1128"); // Normandy at Huron Church allStops.put("2156", "1129"); // Normandy at Twelfth allStops.put("2157", "1130"); // Normandy at Tenth allStops.put("2158", "1131"); // Normandy at Seventh allStops.put("2159", "1132"); // Ellis at Normandy allStops.put("2160", "1133"); // Delmar at Trinity allStops.put("2161", "1134"); // Malden at Normandy allStops.put("2162", "1135"); // Malden at Morton allStops.put("2163", "1136"); // Malden at Edgemore allStops.put("2164", "1137"); // Malden at Outram allStops.put("2165", "1138"); // Malden at Monty allStops.put("2166", "1139"); // Malden at Rosati allStops.put("2167", "1140"); // Malden at Bouffard allStops.put("2168", "1141"); // Vollmer Centre Front Entrance allStops.put("2169", "1142"); // Mike Raymond at Malden allStops.put("2170", "1143"); // Malden at Laurier allStops.put("2171", "1144"); // Malden at Bouffard allStops.put("2172", "1145"); // Malden at Rosati allStops.put("2173", "1146"); // Reaume at Malden allStops.put("2174", "1147"); // Reaume at Woodbridge allStops.put("2175", "1148"); // Reaume at Deerview allStops.put("2176", "1149"); // Reaume at Piruzza allStops.put("2177", "1150"); // Reaume at Matchette allStops.put("2178", "1151"); // Matchette at Monty allStops.put("2179", "1152"); // Matchette at Minto allStops.put("2180", "1153"); // Morton at Matchette allStops.put("2181", "1154"); // Morton at Quick allStops.put("2182", "1155"); // Morton at Wales allStops.put("2183", "1156"); // Morton at Ramblewood allStops.put("2184", "1157"); // Morton at Ramblewood allStops.put("2185", "1158"); // Morton at Ojibway allStops.put("2186", "1159"); // Front at River allStops.put("2187", "1160"); // Front at Antaya allStops.put("2188", "1161"); // Front at Reaume allStops.put("2189", "1162"); // Front at Riverview allStops.put("2190", "1163"); // Front at Bouffard allStops.put("2191", "1164"); // Front at Huron allStops.put("2192", "1165"); // Front at Laurier allStops.put("2193", "1166"); // Front at Adams allStops.put("2194", "1167"); // Front at Boismier allStops.put("2195", "1168"); // International at Front allStops.put("2196", "1169"); // Michigan at International allStops.put("2197", "1170"); // Michigan at Fields allStops.put("2198", "1171"); // Michigan at Delaware allStops.put("2199", "1172"); // Michigan at Laurier allStops.put("2200", "1173"); // Laurier at Hazel allStops.put("2201", "1174"); // Laurier at Alfred allStops.put("2202", "1175"); // Laurier at Mayfair allStops.put("2203", "1176"); // Laurier at Marquette allStops.put("2204", "1177"); // Laurier at Matchette allStops.put("2205", "1178"); // Laurier at First allStops.put("2206", "1179"); // Laurier at Selkirk allStops.put("2207", "1180"); // Laurier at Tacoma allStops.put("2208", "1181"); // Laurier at Malden allStops.put("2209", "1182"); // Malden at Reaume allStops.put("2210", "1183"); // Malden at Valiant allStops.put("2211", "1184"); // Malden at Stuart allStops.put("2212", "1185"); // Malden at Edgemore allStops.put("2213", "1186"); // Malden at Grillo allStops.put("2214", "1187"); // Malden at Normandy allStops.put("2215", "1188"); // Delmar at Trinity allStops.put("2216", "1189"); // Ellis at Normandy allStops.put("2217", "1190"); // Normandy at Seventh allStops.put("2218", "1191"); // Normandy at Tenth allStops.put("2219", "1192"); // Normandy at Thirteenth allStops.put("2220", "1193"); // Normandy at Huron Church allStops.put("2221", "1194"); // Huron Church at Disputed allStops.put("2222", "1195"); // Huron Church at Skinner allStops.put("2223", "1196"); // Sandwich West at Huron Church allStops.put("2224", "1197"); // Sandwich West at Mary allStops.put("2225", "1198"); // Sandwich West at D'Amore allStops.put("2226", "1199"); // Sandwich West at Durocher allStops.put("2227", "1200"); // Sandwich West at Lovell allStops.put("2228", "1201"); // Heritage at Sandwich West allStops.put("2229", "1202"); // Heritage at Rushwood allStops.put("2230", "1203"); // Heritage at Rushwood allStops.put("2231", "1204"); // Heritage at Blackthorn allStops.put("2232", "1205"); // Heritage at Sixth Concession allStops.put("2233", "1206"); // Sixth Concession at Montgomery ALL_STOPS = allStops; } }
package ru.job4j.transfers; import java.util.ArrayList; import java.util.List; import java.util.TreeMap; public class Bank { /** * A collection that indicates that each user can have a list of bank accounts. */ private TreeMap<User, ArrayList<Account>> bank = new TreeMap<>(); /** * The method of adding a user to the collection. * * @param user - user. */ public void addUser(User user) { this.bank.putIfAbsent(user, new ArrayList<>()); } /** * The method deletes the user from the collection. * * @param user - user. */ public void delete(User user) { this.bank.remove(user); } /** * The method adds an account to the user in the collection. * * @param user - user. * @param account - account. */ public void add(User user, Account account) { this.bank.get(user).add(account); } /** * Get method. * * @param user - user. * @param account - account. * @return - index of account. */ private Account getActualAccount(User user, Account account) { Account index = null; ArrayList<Account> list = this.bank.get(user); if (user.getName() != null && user.getPassport() != null && account.getRequisites() != null) { index = list.get(list.indexOf(account)); } return index; } /** * The method deletes the account from the user. * * @param user - user. * @param account - account. */ public void deleteAccount(User user, Account account) { this.bank.get(user).remove(account); } /** * Get method. * * @param user - user. * @return - collection user. */ public List<Account> getUserAccounts(User user) { List<Account> list = this.bank.get(user); if (user.getName() == null || user.getPassport() == null) { list = null; } return list; } /** * The method checks to determine the possibility of making money transfers. * * @param srcPassport - first passport. * @param srcRequisite - first requisite. * @param destPassport - destination passport. * @param dstRequisite - destination requisite. * @param amount - amount. * @return - boolean result. */ public boolean transferMoney(String srcPassport, String srcRequisite, String destPassport, String dstRequisite, double amount) { User sourceUser = getUserByPassport(srcPassport); User destinationUser = getUserByPassport(destPassport); Account sourceAccount = getAccount(sourceUser, srcRequisite); Account destinationAccount = getAccount(destinationUser, dstRequisite); boolean rsl = false; if (sourceUser != null && destinationUser != null && sourceAccount != null && destinationAccount != null) { rsl = sourceAccount.transfer(destinationAccount, amount); } return rsl; } /** * Method checks the user's account. * * @param sourceUser - user. * @param srcRequisite - requisite. * @return - account. */ private Account getAccount(User sourceUser, String srcRequisite) { Account rsl = null; for (Account account : this.getUserAccounts(sourceUser)) { if (srcRequisite.equals(account.getRequisites())) { rsl = account; } } return rsl; } /** * Method checks for compliance with the passport. * * @param srcPassport - passport ID. * @return - passport. */ private User getUserByPassport(String srcPassport) { User rsl = null; for (User user : bank.keySet()) { if (srcPassport.equals(user.getPassport())) { rsl = user; } } return rsl; } @Override public String toString() { return "Bank{" + "accounts=" + bank + "}"; } }
package org.pentaho.di.verticabulkload; import java.io.IOException; import java.io.InterruptedIOException; import java.io.PipedInputStream; import java.sql.SQLException; import java.util.ArrayList; import java.util.concurrent.Executors; import org.pentaho.di.core.Const; import org.pentaho.di.core.database.Database; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; import com.vertica.jdbc.VerticaConnection; import com.vertica.jdbc.VerticaCopyStream; import org.pentaho.di.verticabulkload.nativebinary.ColumnSpec; import org.pentaho.di.verticabulkload.nativebinary.ColumnType; import org.pentaho.di.verticabulkload.nativebinary.StreamEncoder; public class VerticaBulkLoader extends BaseStep implements StepInterface { private static Class<?> PKG = VerticaBulkLoader.class; // for i18n purposes, needed by Translator2!! private VerticaBulkLoaderMeta meta; private VerticaBulkLoaderData data; public VerticaBulkLoader( StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans ) { super( stepMeta, stepDataInterface, copyNr, transMeta, trans ); } @Override public boolean processRow( StepMetaInterface smi, StepDataInterface sdi ) throws KettleException { meta = (VerticaBulkLoaderMeta) smi; data = (VerticaBulkLoaderData) sdi; Object[] r = getRow(); // this also waits for a previous step to be // finished. if ( r == null ) { // no more input to be expected... try { data.close(); } catch ( IOException ioe ) { throw new KettleStepException( "Error releasing resources", ioe ); } return false; } if ( first ) { first = false; data.outputRowMeta = getInputRowMeta().clone(); meta.getFields( data.outputRowMeta, getStepname(), null, null, this ); RowMetaInterface tableMeta = meta.getTableRowMetaInterface(); if ( !meta.specifyFields() ) { // Just take the whole input row data.insertRowMeta = getInputRowMeta().clone(); data.selectedRowFieldIndices = new int[data.insertRowMeta.size()]; data.colSpecs = new ArrayList<ColumnSpec>( data.insertRowMeta.size() ); for ( int insertFieldIdx = 0; insertFieldIdx < data.insertRowMeta.size(); insertFieldIdx++ ) { data.selectedRowFieldIndices[insertFieldIdx] = insertFieldIdx; ValueMetaInterface inputValueMeta = data.insertRowMeta.getValueMeta( insertFieldIdx ); ValueMetaInterface insertValueMeta = inputValueMeta.clone(); ValueMetaInterface targetValueMeta = tableMeta.getValueMeta( insertFieldIdx ); insertValueMeta.setName( targetValueMeta.getName() ); data.insertRowMeta.setValueMeta( insertFieldIdx, insertValueMeta ); ColumnSpec cs = getColumnSpecFromField( inputValueMeta, insertValueMeta, targetValueMeta ); data.colSpecs.add( insertFieldIdx, cs ); } } else { int numberOfInsertFields = meta.getFieldDatabase().length; data.insertRowMeta = new RowMeta(); data.colSpecs = new ArrayList<ColumnSpec>( numberOfInsertFields ); // Cache the position of the selected fields in the row array data.selectedRowFieldIndices = new int[numberOfInsertFields]; for ( int insertFieldIdx = 0; insertFieldIdx < numberOfInsertFields; insertFieldIdx++ ) { String inputFieldName = meta.getFieldStream()[insertFieldIdx]; int inputFieldIdx = getInputRowMeta().indexOfValue( inputFieldName ); if ( inputFieldIdx < 0 ) { throw new KettleStepException( BaseMessages.getString( PKG, "VerticaBulkLoader.Exception.FieldRequired", inputFieldName ) ); //$NON-NLS-1$ } data.selectedRowFieldIndices[insertFieldIdx] = inputFieldIdx; String insertFieldName = meta.getFieldDatabase()[insertFieldIdx]; ValueMetaInterface inputValueMeta = getInputRowMeta().getValueMeta( inputFieldIdx ); if ( inputValueMeta == null ) { throw new KettleStepException( BaseMessages.getString( PKG, "VerticaBulkLoader.Exception.FailedToFindField", meta.getFieldStream()[insertFieldIdx] ) ); //$NON-NLS-1$ } ValueMetaInterface insertValueMeta = inputValueMeta.clone(); insertValueMeta.setName( insertFieldName ); data.insertRowMeta.addValueMeta( insertValueMeta ); ValueMetaInterface targetValueMeta = tableMeta.searchValueMeta( insertFieldName ); ColumnSpec cs = getColumnSpecFromField( inputValueMeta, insertValueMeta, targetValueMeta ); data.colSpecs.add( insertFieldIdx, cs ); } } try { data.pipedInputStream = new PipedInputStream(); if ( data.colSpecs == null || data.colSpecs.isEmpty() ) { return false; } data.encoder = new StreamEncoder( data.colSpecs, data.pipedInputStream ); initializeWorker(); data.encoder.writeHeader(); } catch ( IOException ioe ) { throw new KettleStepException( "Error creating stream encoder", ioe ); } } try { Object[] outputRowData = writeToOutputStream( r ); if ( outputRowData != null ) { putRow( data.outputRowMeta, outputRowData ); // in case we want it // go further... incrementLinesOutput(); } if ( checkFeedback( getLinesRead() ) ) { if ( log.isBasic() ) { logBasic( "linenr " + getLinesRead() ); } //$NON-NLS-1$ } } catch ( KettleException e ) { logError( "Because of an error, this step can't continue: ", e ); setErrors( 1 ); stopAll(); setOutputDone(); // signal end to receiver(s) return false; } catch ( IOException e ) { e.printStackTrace(); } return true; } private ColumnSpec getColumnSpecFromField( ValueMetaInterface inputValueMeta, ValueMetaInterface insertValueMeta, ValueMetaInterface targetValueMeta ) { logBasic( "Mapping input field " + inputValueMeta.getName() + " (" + inputValueMeta.getTypeDesc() + ")" + " to target column " + insertValueMeta.getName() + " (" + targetValueMeta.getOriginalColumnTypeName() + ") " ); String targetColumnTypeName = targetValueMeta.getOriginalColumnTypeName().toUpperCase(); if ( targetColumnTypeName.equals( "INTEGER" ) || targetColumnTypeName.equals( "BIGINT" ) ) { return new ColumnSpec( ColumnSpec.ConstantWidthType.INTEGER_64 ); } else if ( targetColumnTypeName.equals( "BOOLEAN" ) ) { return new ColumnSpec( ColumnSpec.ConstantWidthType.BOOLEAN ); } else if ( targetColumnTypeName.equals( "FLOAT" ) || targetColumnTypeName.equals( "DOUBLE PRECISION" ) ) { return new ColumnSpec( ColumnSpec.ConstantWidthType.FLOAT ); } else if ( targetColumnTypeName.equals( "CHAR" ) ) { return new ColumnSpec( ColumnSpec.UserDefinedWidthType.CHAR, targetValueMeta.getLength() ); } else if ( targetColumnTypeName.equals( "VARCHAR" ) ) { return new ColumnSpec( ColumnSpec.VariableWidthType.VARCHAR, targetValueMeta.getLength() ); } else if ( targetColumnTypeName.equals( "DATE" ) ) { if ( inputValueMeta.isDate() == false ) { throw new IllegalArgumentException( "Field " + inputValueMeta.getName() + " must be a Date compatible type to match target column " + insertValueMeta.getName() ); } else { return new ColumnSpec( ColumnSpec.ConstantWidthType.DATE ); } } else if ( targetColumnTypeName.equals( "TIME" ) ) { if ( inputValueMeta.isDate() == false ) { throw new IllegalArgumentException( "Field " + inputValueMeta.getName() + " must be a Date compatible type to match target column " + insertValueMeta.getName() ); } else { return new ColumnSpec( ColumnSpec.ConstantWidthType.TIME ); } } else if ( targetColumnTypeName.equals( "TIMETZ" ) ) { if ( inputValueMeta.isDate() == false ) { throw new IllegalArgumentException( "Field " + inputValueMeta.getName() + " must be a Date compatible type to match target column " + insertValueMeta.getName() ); } else { return new ColumnSpec( ColumnSpec.ConstantWidthType.TIMETZ ); } } else if ( targetColumnTypeName.equals( "TIMESTAMP" ) ) { if ( inputValueMeta.isDate() == false ) { throw new IllegalArgumentException( "Field " + inputValueMeta.getName() + " must be a Date compatible type to match target column " + insertValueMeta.getName() ); } else { return new ColumnSpec( ColumnSpec.ConstantWidthType.TIMESTAMP ); } } else if ( targetColumnTypeName.equals( "TIMESTAMPTZ" ) ) { if ( inputValueMeta.isDate() == false ) { throw new IllegalArgumentException( "Field " + inputValueMeta.getName() + " must be a Date compatible type to match target column " + insertValueMeta.getName() ); } else { return new ColumnSpec( ColumnSpec.ConstantWidthType.TIMESTAMPTZ ); } } else if ( targetColumnTypeName.equals( "INTERVAL" ) || targetColumnTypeName.equals( "INTERVAL DAY TO SECOND" ) ) { if ( inputValueMeta.isDate() == false ) { throw new IllegalArgumentException( "Field " + inputValueMeta.getName() + " must be a Date compatible type to match target column " + insertValueMeta.getName() ); } else { return new ColumnSpec( ColumnSpec.ConstantWidthType.INTERVAL ); } } else if ( targetColumnTypeName.equals( "BINARY" ) ) { return new ColumnSpec( ColumnSpec.VariableWidthType.VARBINARY, targetValueMeta.getLength() ); } else if ( targetColumnTypeName.equals( "VARBINARY" ) ) { return new ColumnSpec( ColumnSpec.VariableWidthType.VARBINARY, targetValueMeta.getLength() ); } else if ( targetColumnTypeName.equals( "NUMERIC" ) ) { return new ColumnSpec( ColumnSpec.PrecisionScaleWidthType.NUMERIC, targetValueMeta.getLength(), targetValueMeta .getPrecision() ); } throw new IllegalArgumentException( "Column type " + targetColumnTypeName + " not supported." ); //$NON-NLS-1$ } private void initializeWorker() { final String dml = buildCopyStatementSqlString(); data.workerThread = Executors.defaultThreadFactory().newThread( new Runnable() { @Override public void run() { try { VerticaCopyStream stream = new VerticaCopyStream( (VerticaConnection) ( data.db.getConnection() ), dml ); stream.start(); stream.addStream( data.pipedInputStream ); setLinesRejected( stream.getRejects().size() ); stream.execute(); long rowsLoaded = stream.finish(); if ( getLinesOutput() != rowsLoaded ) { logMinimal( String.format( "%d records loaded out of %d records sent.", rowsLoaded, getLinesOutput() ) ); } data.db.disconnect(); } catch ( SQLException e ) { if ( e.getCause() instanceof InterruptedIOException ) { logBasic( "SQL statement interrupted by halt of transformation" ); } else { logError( "SQL Error during statement execution.", e ); setErrors( 1 ); stopAll(); setOutputDone(); // signal end to receiver(s) } } } } ); data.workerThread.start(); } private String buildCopyStatementSqlString() { final DatabaseMeta databaseMeta = data.db.getDatabaseMeta(); StringBuilder sb = new StringBuilder( 150 ); sb.append( "COPY " ); sb.append( databaseMeta.getQuotedSchemaTableCombination( environmentSubstitute( meta.getSchemaName() ), environmentSubstitute( meta.getTableName() ) ) ); sb.append( " (" ); final RowMetaInterface fields = data.insertRowMeta; for ( int i = 0; i < fields.size(); i++ ) { if ( i > 0 ) { sb.append( ", " ); } ColumnType columnType = data.colSpecs.get( i ).type; ValueMetaInterface valueMeta = fields.getValueMeta( i ); switch ( columnType ) { case NUMERIC: sb.append( "TMPFILLERCOL" ).append( i ).append( " FILLER VARCHAR(1000), " ); // Force columns to be quoted: sb.append( databaseMeta.getStartQuote() + valueMeta.getName() + databaseMeta.getEndQuote() ); sb.append( " AS CAST(" ).append( "TMPFILLERCOL" ).append( i ).append( " AS NUMERIC" ); sb.append( ")" ); break; default: // Force columns to be quoted: sb.append( databaseMeta.getStartQuote() + valueMeta.getName() + databaseMeta.getEndQuote() ); break; } } sb.append( ")" ); sb.append( " FROM STDIN NATIVE " ); if ( !Const.isEmpty( meta.getExceptionsFileName() ) ) { sb.append( "EXCEPTIONS E'" ).append( meta.getExceptionsFileName().replace( "'", "\\'" ) ).append( "' " ); } if ( !Const.isEmpty( meta.getRejectedDataFileName() ) ) { sb.append( "REJECTED DATA E'" ).append( meta.getRejectedDataFileName().replace( "'", "\\'" ) ).append( "' " ); } // TODO: Should eventually get a preference for this, but for now, be backward compatible. sb.append( "ENFORCELENGTH " ); if ( meta.isAbortOnError() ) { sb.append( "ABORT ON ERROR " ); } if ( meta.isDirect() ) { sb.append( "DIRECT " ); } if ( !Const.isEmpty( meta.getStreamName() ) ) { sb.append( "STREAM NAME E'" ).append( environmentSubstitute( meta.getStreamName() ).replace( "'", "\\'" ) ) .append( "' " ); } // XXX: I believe the right thing to do here is always use NO COMMIT since we want Kettle's configuration to drive. // NO COMMIT does not seem to work even when the transformation setting 'make the transformation database // transactional' is on // sb.append("NO COMMIT"); logDebug( "copy stmt: " + sb.toString() ); return sb.toString(); } private Object[] writeToOutputStream( Object[] r ) throws KettleException, IOException { assert ( r != null ); Object[] insertRowData = r; Object[] outputRowData = r; if ( meta.specifyFields() ) { insertRowData = new Object[data.selectedRowFieldIndices.length]; for ( int idx = 0; idx < data.selectedRowFieldIndices.length; idx++ ) { insertRowData[idx] = r[data.selectedRowFieldIndices[idx]]; } } try { data.encoder.writeRow( data.insertRowMeta, insertRowData ); } catch ( IOException e ) { if ( !data.isStopped() ) { throw new KettleException( "I/O Error during row write.", e ); } } return outputRowData; } @Override public boolean init( StepMetaInterface smi, StepDataInterface sdi ) { meta = (VerticaBulkLoaderMeta) smi; data = (VerticaBulkLoaderData) sdi; if ( super.init( smi, sdi ) ) { try { data.databaseMeta = meta.getDatabaseMeta(); data.db = new Database( this, meta.getDatabaseMeta() ); data.db.shareVariablesWith( this ); if ( getTransMeta().isUsingUniqueConnections() ) { synchronized ( getTrans() ) { data.db.connect( getTrans().getThreadName(), getPartitionID() ); } } else { data.db.connect( getPartitionID() ); } if ( log.isBasic() ) { logBasic( "Connected to database [" + meta.getDatabaseMeta() + "]" ); } data.db.setAutoCommit( false ); return true; } catch ( KettleException e ) { logError( "An error occurred intialising this step: " + e.getMessage() ); stopAll(); setErrors( 1 ); } } return false; } @Override public void stopRunning( StepMetaInterface stepMetaInterface, StepDataInterface stepDataInterface ) throws KettleException { setStopped( true ); if ( data.workerThread != null ) { synchronized ( data.workerThread ) { if ( data.workerThread.isAlive() && !data.workerThread.isInterrupted() ) { try { data.workerThread.interrupt(); data.workerThread.join(); } catch ( InterruptedException e ) { // Checkstyle:OFF: } // Checkstyle:ONN: } } } super.stopRunning( stepMetaInterface, stepDataInterface ); } @Override public void dispose( StepMetaInterface smi, StepDataInterface sdi ) { meta = (VerticaBulkLoaderMeta) smi; data = (VerticaBulkLoaderData) sdi; // allow data to be garbage collected immediately: data.colSpecs = null; data.encoder = null; setOutputDone(); try { if ( getErrors() > 0 ) { data.db.rollback(); } } catch ( KettleDatabaseException e ) { logError( "Unexpected error rolling back the database connection.", e ); } if ( data.workerThread != null ) { try { data.workerThread.join(); } catch ( InterruptedException e ) { // Checkstyle:OFF: } // Checkstyle:ONN: } if ( data.db != null ) { data.db.disconnect(); } super.dispose( smi, sdi ); } }
package fault.java.metrics; import fault.java.Status; import fault.java.utils.TimeProvider; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.Random; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; public class ActionMetricsTest { @Mock private TimeProvider timeProvider; private ActionMetrics actionMetrics; @Before public void setUp() { MockitoAnnotations.initMocks(this); when(timeProvider.currentTimeMillis()).thenReturn(0L); this.actionMetrics = new ActionMetrics(1000, timeProvider); } @Test public void testMetricsReportsNoErrorsIfNoErrorsOrTimeouts() { when(timeProvider.currentTimeMillis()).thenReturn(1000L, 1000L); actionMetrics.reportActionResult(Status.SUCCESS); assertEquals(0, actionMetrics.getFailuresForTimePeriod(1000)); } @Test public void testMetricsReportCorrectFailureCount() { int errorCount = new Random().nextInt(100); for (int i = 0; i < errorCount; ++i) { when(timeProvider.currentTimeMillis()).thenReturn(500L); actionMetrics.reportActionResult(Status.ERROR); } when(timeProvider.currentTimeMillis()).thenReturn(1999L); assertEquals(errorCount, actionMetrics.getFailuresForTimePeriod(1000)); } @Test public void testMetricsReportsNoSuccessesIfNoSuccesses() { when(timeProvider.currentTimeMillis()).thenReturn(1000L, 1000L, 1000L); actionMetrics.reportActionResult(Status.ERROR); actionMetrics.reportActionResult(Status.TIMED_OUT); assertEquals(0, actionMetrics.getSuccessesForTimePeriod(1000)); } @Test public void testMetricsReportCorrectSuccessCount() { int successCount = new Random().nextInt(100); for (int i = 0; i < successCount; ++i) { when(timeProvider.currentTimeMillis()).thenReturn(500L); actionMetrics.reportActionResult(Status.SUCCESS); } when(timeProvider.currentTimeMillis()).thenReturn(1999L); assertEquals(successCount, actionMetrics.getSuccessesForTimePeriod(1000)); } @Test public void testMixedResultsCorrectReporting() { int errorCount = 0; int successCount = 0; int timeoutCount = 0; Random random = new Random(); for (int i = 0; i < 100; ++i) { if (random.nextBoolean()) { when(timeProvider.currentTimeMillis()).thenReturn(500L); actionMetrics.reportActionResult(Status.ERROR); ++errorCount; } if (random.nextBoolean()) { when(timeProvider.currentTimeMillis()).thenReturn(500L); actionMetrics.reportActionResult(Status.SUCCESS); ++successCount; } if (random.nextBoolean()) { when(timeProvider.currentTimeMillis()).thenReturn(500L); actionMetrics.reportActionResult(Status.TIMED_OUT); ++timeoutCount; } } when(timeProvider.currentTimeMillis()).thenReturn(1999L, 1999L, 1999L); assertEquals(successCount, actionMetrics.getSuccessesForTimePeriod(1000)); assertEquals(errorCount, actionMetrics.getErrorsForTimePeriod(1000)); assertEquals(timeoutCount, actionMetrics.getTimeoutsForTimePeriod(1000)); } @Test public void testMetricsOnlyReportForTimePeriod() { for (int i = 1; i < 4; ++i) { long timestamp = 500L * i; when(timeProvider.currentTimeMillis()).thenReturn(timestamp, timestamp, timestamp); actionMetrics.reportActionResult(Status.ERROR); actionMetrics.reportActionResult(Status.SUCCESS); actionMetrics.reportActionResult(Status.TIMED_OUT); } when(timeProvider.currentTimeMillis()).thenReturn(2000L, 2000L, 2000L); assertEquals(3, actionMetrics.getSuccessesForTimePeriod(2000)); assertEquals(2, actionMetrics.getSuccessesForTimePeriod(1000)); assertEquals(3, actionMetrics.getErrorsForTimePeriod(2000)); assertEquals(2, actionMetrics.getErrorsForTimePeriod(1000)); assertEquals(3, actionMetrics.getTimeoutsForTimePeriod(2000)); assertEquals(2, actionMetrics.getTimeoutsForTimePeriod(1000)); } }
package uk.org.il2ssd.jfx; import javafx.scene.Parent; import javafx.scene.control.TextInputControl; import org.loadui.testfx.GuiTest; import uk.org.il2ssd.Core; import java.util.concurrent.TimeUnit; import static org.loadui.testfx.controls.Commons.nodeLabeledBy; import static org.loadui.testfx.controls.TextInputControls.clearTextIn; /** * GUI Test Controller */ public class Il2SsdGuiTest extends GuiTest { // Server IP and port static String ipAddress = "ghserver"; static String port = "21003"; // Node identifiers static String ipAddressLabel = "IP Address:"; static String portLabel = "Port:"; static String consoleTab = "Console"; static String settingsTab = "Settings"; static String consoleTextArea = ".text-area"; static String connectButton = "\uf090 Connect"; static String disconnectButton = "\uf08b Disconnect"; static String fileMenu = "File"; static String exitMenuItem = "Exit"; @Override protected Parent getRootNode() { return Core.getStage().getScene().getRoot(); } public void enterSettings() { this.click(settingsTab); clearTextIn((TextInputControl) nodeLabeledBy(ipAddressLabel)); this.click(nodeLabeledBy(ipAddressLabel)).type(ipAddress); clearTextIn((TextInputControl) nodeLabeledBy(portLabel)); this.click(nodeLabeledBy(portLabel)).type(port); } public void connect() { this.click(connectButton); this.sleep(1, TimeUnit.SECONDS); } public void disconnect() { this.click(disconnectButton); this.sleep(1, TimeUnit.SECONDS); } }
package tests; import static org.junit.Assert.assertTrue; // checking the values import gui.GUI; import gui.volumetab.VolumeTab; import java.awt.Component; import java.awt.Container; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Stack; import javax.swing.JSlider; import javax.swing.JTextField; import org.junit.Test; // needed for annotation import org.junit.runner.Result; import org.junit.runner.notification.Failure; // printing the failures import util.SortAlgorithm; // Everytime an error occurs, please write a Test for this (take a look at Software Engineering). /** * Test Class for some simple stuff. * * @author Dominik Ridder * */ public class Testcase { /** * Main class for executing the JUnit Testcases. This main is normally not * used, because there is a better way for running all Tests with an * build.xml and ant. * * @param agrs * This parameter is currently unused. */ public static void main(String[] agrs) { Result rc = new Result(); rc = org.junit.runner.JUnitCore.runClasses(Testcase.class); System.out.printf("%d tests were executed, %d of them with failures\n", rc.getRunCount(), rc.getFailureCount()); if (!rc.wasSuccessful()) { List<Failure> fList = rc.getFailures(); for (Failure f : fList) { System.out.println(f.getTestHeader()); System.out.println(f.getMessage()); } } } /** * Tests if the Attributes are displayed after opening a Volume. * <p> * These are the steps of the tests: * <p> * - Create GUI * <p> * - Select VolumeTab * <p> * - Set Path and create Volume * <p> * (Wait max 5 seconds for opening the Volume) * <p> * - Check if the OutputArea is empty */ @Test public void VisibleAttributes() { GUI g = new GUI(true, false); VolumeTab voltab = (VolumeTab) g.getCurrentTab(); voltab.setPath("/opt/dridder_local/TestDicoms/AllDicoms/B0092/14_wm_gre_rx=PA"); voltab.createVolume(); int millisec = 5000; // 5 sec max waitForVolumeCreation(voltab, millisec); assertTrue(!voltab.isOutputAreaEmpty()); } /** * This Test should check if the sorting algorithm is working properly. */ @Test public void CheckSort() { String unsorted = "/opt/dridder_local/Datadir/Testcase/Unsorted"; String sorted = "/opt/dridder_local/Datadir/Testcase/Sorted"; SortAlgorithm sorter = new SortAlgorithm(); sorter.setCreateNiftis(false); sorter.setFilesOptionCopy(); sorter.setKeepImageName(false); sorter.setProtocolDigits(0); sorter.setImgDigits(0); sorter.useSubfolders(false); for (int i = 0; i < 2; i++) { // Check once with existant source and once without assertTrue("Testdata not Found: "+unsorted+".", new File(unsorted).exists()); sorter.searchAndSortIn(unsorted, sorted); File subjectDir = new File(sorted+"/B0316"); assertTrue("Subject Directory B0316 was not created.", subjectDir.exists()); int dircount = 0; int dcmcount = 0; for (File potDirectory : subjectDir.listFiles()) { if (potDirectory.isDirectory()) { dircount++; for (File dcm : potDirectory.listFiles()) { if (dcm.getName().endsWith(".dcm")) { dcmcount++; } } } } assertTrue("Subject Directory B0316 should contain 10 directorys.", dircount == 8); assertTrue("Subject Directory B0316 should contain 14 dicoms.", dcmcount == 9); } // Clean up Sorted directory Stack<File> todelete = new Stack<File>(); for (File subfile : new File(sorted).listFiles()) { todelete.push(subfile); } while(todelete.size() != 0) { File next = todelete.pop(); if (next.isDirectory() && next.listFiles().length != 0) { todelete.push(next); // Retry later for (File subfile : next.listFiles()) { todelete.push(subfile); } } else { boolean worked = next.delete(); if (!worked) { break; } } } assertTrue("Error while deleting sorted directory.", new File(sorted).listFiles().length == 0); } /** * Test which tries to detect slidebar and textfield equality for slice and * echo. This includes mainly 3 tests: * <p> * o Slice and Echo equality given after instanciating the volume? * <p> * o Does a slider change effect the textfield? * <p> * o Does a textfield change effect the slider? */ @Test public void Slide2Textfield() { String volPath = "/opt/dridder_local/Datadir/Sorted/B0316/16_wm_gre_b0"; int millisec = 5000; boolean forceEnd = true; boolean visible = false; GUI g = new GUI(forceEnd, visible); VolumeTab voltab = (VolumeTab) g.getCurrentTab(); // Setting up gui and volume voltab.setPath(volPath); voltab.createVolume(); waitForVolumeCreation(voltab, millisec); if (voltab.isCreatingVolume()) { assertTrue("Volume creation timeout.", false); return; } // Finding the components String[] names = {"SliceIndex", "EchoIndex", "SliceSlider", "EchoSlider"}; ArrayList<Component> components = new ArrayList<>(); Stack<Component> searchThrough = new Stack<Component>(); for (String compName : names) { searchThrough.push(voltab); while(searchThrough.size() > 0) { Component comp = searchThrough.pop(); if (comp instanceof Container) { for (Component child : ((Container) comp).getComponents()) { searchThrough.push(child); } } if (compName.equals(comp.getName())) { components.add(comp); break; } } } // Did we found all components? if (components.size() != 4) { assertTrue("Components Not Found.", false); return; } // Typecasting JTextField sliceIndex = (JTextField) components.get(0); JTextField echoIndex = (JTextField) components.get(1); JSlider sliceSlider = (JSlider) components.get(2); JSlider echoSlider = (JSlider) components.get(3); // Should be equal after creation assertTrue("Slice error after creation.", Integer.parseInt(sliceIndex.getText()) == sliceSlider.getValue()); assertTrue("Echo error after creation.", Integer.parseInt(echoIndex.getText()) == echoSlider.getValue()); // Testing slidebar to field sliceSlider.setValue(80); echoSlider.setValue(3); assertTrue("Slice Slider to Textfield error.", Integer.parseInt(sliceIndex.getText()) == sliceSlider.getValue()); assertTrue("Echo Slider to Textfield error.", Integer.parseInt(echoIndex.getText()) == echoSlider.getValue()); // Testing field to slidebar sliceIndex.setText("40"); echoIndex.setText("2"); sliceIndex.setCaretPosition(1); // Invoke caret change event echoIndex.setCaretPosition(1); assertTrue("Slice Textfield to Slider error.", Integer.parseInt(sliceIndex.getText()) == sliceSlider.getValue()); assertTrue("Echo Textfield to Slider error.", Integer.parseInt(echoIndex.getText()) == echoSlider.getValue()); } public void waitForVolumeCreation(VolumeTab voltab, int duration) { double start = System.currentTimeMillis(); while (voltab.isCreatingVolume()) { // Finished Creation? if (System.currentTimeMillis() - start > duration) { break; // Timeout } else { try { Thread.sleep(300); // Wait } catch (InterruptedException e) { e.printStackTrace(); } } } } }
// LociUploader.java package loci.plugins; import java.awt.TextField; import java.util.Vector; import ij.*; import ij.gui.GenericDialog; import ij.plugin.PlugIn; import ij.process.*; import ij.io.FileInfo; import loci.formats.*; import loci.ome.upload.*; /** * ImageJ plugin for uploading images to an OME server. * * @author Melissa Linkert linket at wisc.edu */ public class LociUploader implements PlugIn { // -- Fields -- private String server; private String user; private String pass; // -- PlugIn API methods -- public synchronized void run(String arg) { // check that we can safely execute the plugin if (Util.checkVersion() && Util.checkLibraries(true, true, true, false)) { promptForLogin(); uploadStack(); } else { } } // -- Helper methods -- /** Open a dialog box that prompts for a username, password, and server. */ private void promptForLogin() { GenericDialog prompt = new GenericDialog("Login to OME"); prompt.addStringField("Server: ", Prefs.get("uploader.server", ""), 120); prompt.addStringField("Username: ", Prefs.get("uploader.user", ""), 120); prompt.addStringField("Password: ", "", 120); ((TextField) prompt.getStringFields().get(2)).setEchoChar('*'); prompt.showDialog(); server = prompt.getNextString(); user = prompt.getNextString(); pass = prompt.getNextString(); Prefs.set("uploader.server", server); Prefs.set("uploader.user", user); } /** Log in to the OME server and upload the current image stack. */ private void uploadStack() { try { IJ.showStatus("Starting upload..."); OMEUploader ul = new OMEUploader(server, user, pass); ImagePlus imp = WindowManager.getCurrentImage(); if (imp == null) { IJ.error("No open images!"); IJ.showStatus(""); return; } ImageStack is = imp.getImageStack(); Vector pixels = new Vector(); FileInfo fi = imp.getOriginalFileInfo(); OMEXMLMetadataStore store = new OMEXMLMetadataStore(); // if we opened this stack with the Bio-Formats importer, then the // appropriate OME-XML is in fi.description if (fi.description != null && fi.description.endsWith("</OME>")) { store.createRoot(fi.description); } else { store.createRoot(); int pixelType = FormatReader.UINT8; switch (imp.getBitDepth()) { case 16: pixelType = FormatReader.UINT16; break; case 32: pixelType = FormatReader.FLOAT; break; } store.setPixels( new Integer(imp.getWidth()), new Integer(imp.getHeight()), new Integer(imp.getNSlices()), new Integer(imp.getNChannels()), new Integer(imp.getNFrames()), new Integer(pixelType), new Boolean(!fi.intelByteOrder), "XYCZT", // TODO : figure out a way to calculate the dimension order null, null); store.setImage(fi.fileName, null, fi.info, null); } boolean little = !store.getBigEndian(null).booleanValue(); for (int i=0; i<is.getSize(); i++) { IJ.showStatus("Reading plane " + (i+1) + "/" + is.getSize()); Object pix = is.getProcessor(i + 1).getPixels(); if (pix instanceof byte[]) { pixels.add((byte[]) pix); } else if (pix instanceof short[]) { short[] s = (short[]) pix; byte[] b = new byte[s.length * 2]; for (int j=0; j<s.length; j++) { byte[] a = DataTools.shortToBytes(s[j], little); b[i*2] = a[0]; b[i*2 + 1] = a[1]; } pixels.add(b); } else if (pix instanceof int[]) { int[] j = (int[]) pix; int channels = is.getProcessor(i+1) instanceof ColorProcessor ? 3 : 1; byte[] b = new byte[j.length * channels]; for (int k=0; k<j.length; k++) { byte[] a = DataTools.intToBytes(j[k], little); b[k*3] = a[0]; b[k*3 + 1] = a[1]; b[k*3 + 2] = a[2]; } pixels.add(b); } else if (pix instanceof float[]) { float[] f = (float[]) pix; byte[] b = new byte[f.length * 4]; for (int j=0; j<f.length; j++) { int k = Float.floatToIntBits(f[j]); byte[] a = DataTools.intToBytes(k, little); b[i*4] = a[0]; b[i*4 + 1] = a[1]; b[i*4 + 2] = a[2]; b[i*4 + 3] = a[3]; } pixels.add(b); } } byte[][] planes = new byte[pixels.size()][]; for (int i=0; i<pixels.size(); i++) { planes[i] = (byte[]) pixels.get(i); } IJ.showStatus("Sending data to server..."); ul.uploadPlanes(planes, 0, planes.length - 1, 1, store, true); ul.logout(); IJ.showStatus("Upload finished."); } catch (UploadException e) { IJ.error("Upload failed:\n" + e); } } }
package org.spine3.base; import com.google.common.escape.Escaper; import com.google.common.escape.Escapers; import com.google.common.primitives.Ints; import com.google.common.primitives.Longs; import com.google.protobuf.Message; import org.spine3.json.Json; import java.lang.reflect.Type; import java.util.List; import java.util.Map; import static com.google.common.base.Preconditions.checkNotNull; import static org.spine3.base.StringifierRegistry.getStringifier; /** * Utility class for working with {@code Stringifier}s. * * @author Alexander Yevsyukov * @author Illia Shepilov */ public class Stringifiers { private Stringifiers() { // Disable instantiation of this utility class. } /** * Converts the passed value to the string representation. * * <p>Use this method for converting non-generic objects. For generic objects, * please use {@link #toString(Object, Type)}. * * @param object the object to convert * @param <T> the type of the object * @return the string representation of the passed object */ public static <T> String toString(T object) { checkNotNull(object); return toString(object, object.getClass()); } /** * Converts the passed value to the string representation. * * <p>This method must be used of the passed object is a generic type. * * @param object to object to convert * @param typeOfT the type of the passed object * @param <T> the type of the object to convert * @return the string representation of the passed object * @throws MissingStringifierException if passed value cannot be converted */ @SuppressWarnings("unchecked") // It is OK because the type is checked before cast. public static <T> String toString(T object, Type typeOfT) { checkNotNull(object); checkNotNull(typeOfT); final Stringifier<T> stringifier = getStringifier(typeOfT); final String result = stringifier.convert(object); return result; } /** * Converts string value to the specified type. * * @param str the string to convert * @param typeOfT the type into which to convert the string * @param <T> the type of the value to return * @return the parsed value from string * @throws MissingStringifierException if passed value cannot be converted */ public static <T> T fromString(String str, Type typeOfT) { checkNotNull(str); checkNotNull(typeOfT); final Stringifier<T> stringifier = getStringifier(typeOfT); final T result = stringifier.reverse() .convert(str); return result; } /** * Obtains {@code Stringifier} for the map with default delimiter for the passed map elements. * * @param keyClass the class of keys are maintained by this map * @param valueClass the class of mapped values * @param <K> the type of keys are maintained by this map * @param <V> the type of the values stored in this map * @return the stringifier for the map */ public static <K, V> Stringifier<Map<K, V>> mapStringifier(Class<K> keyClass, Class<V> valueClass) { checkNotNull(keyClass); checkNotNull(valueClass); final Stringifier<Map<K, V>> mapStringifier = new MapStringifier<>(keyClass, valueClass); return mapStringifier; } /** * Obtains {@code Stringifier} for the map with custom delimiter for the passed map elements. * * @param keyClass the class of keys are maintained by this map * @param valueClass the class of mapped values * @param delimiter the delimiter for the passed map elements via string * @param <K> the type of keys are maintained by this map * @param <V> the type of mapped values * @return the stringifier for the map */ public static <K, V> Stringifier<Map<K, V>> mapStringifier(Class<K> keyClass, Class<V> valueClass, char delimiter) { checkNotNull(keyClass); checkNotNull(valueClass); checkNotNull(delimiter); final Stringifier<Map<K, V>> mapStringifier = new MapStringifier<>(keyClass, valueClass, delimiter); return mapStringifier; } /** * Obtains {@code Stringifier} for the integers values. * * @return the stringifier for the integer values */ public static Stringifier<Integer> integerStringifier() { final Stringifier<Integer> integerStringifier = new IntegerStringifier(); return integerStringifier; } /** * Obtains {@code Stringifier} for the long values * * @return the stringifier for the long values */ public static Stringifier<Long> longStringifier() { final Stringifier<Long> integerStringifier = new LongStringifier(); return integerStringifier; } /** * Obtains {@code Stringifier} for the string values. * * <p>It does not make any modifications to {@code String}. * * @return the stringifier for the string values */ static Stringifier<String> noopStringifier() { final Stringifier<String> stringStringifier = new NoopStringifier(); return stringStringifier; } /** * Obtains {@code Stringifier} for list with default delimiter for the passed list elements. * * @param elementClass the class of the list elements * @param <T> the type of the elements in this list * @return the stringifier for the list */ public static <T> Stringifier<List<T>> listStringifier(Class<T> elementClass) { checkNotNull(elementClass); final Stringifier<List<T>> listStringifier = new ListStringifier<>(elementClass); return listStringifier; } /** * Obtains {@code Stringifier} for list with the custom delimiter for the passed list elements. * * @param elementClass the class of the list elements * @param delimiter the delimiter or the list elements passed via string * @param <T> the type of the elements in this list * @return the stringifier for the list */ public static <T> Stringifier<List<T>> listStringifier(Class<T> elementClass, char delimiter) { checkNotNull(elementClass); checkNotNull(delimiter); final Stringifier<List<T>> listStringifier = new ListStringifier<>(elementClass, delimiter); return listStringifier; } /** * Obtains the default {@code Stringifier} for the {@code Message} classes. * * @param messageClass the message class * @param <T> the type of the message * @return the default stringifier */ static <T extends Message> Stringifier<T> defaultStringifier(Class<T> messageClass) { checkNotNull(messageClass); final DefaultMessageStringifier<T> defaultStringifier = new DefaultMessageStringifier<>(messageClass); return defaultStringifier; } /** * Creates the {@code Escaper} which escapes contained '\' and passed characters. * * @param charToEscape the char to escape * @return the constructed escaper */ static Escaper createEscaper(char charToEscape) { final String escapedChar = "\\" + charToEscape; final Escaper result = Escapers.builder() .addEscape('\"', "\\\"") .addEscape(charToEscape, escapedChar) .build(); return result; } /** * The {@code Stringifier} for the {@code String} values. * * <p>Always returns the original {@code String} passed as an argument. */ private static class NoopStringifier extends Stringifier<String> { @Override protected String toString(String obj) { return obj; } @Override protected String fromString(String s) { return s; } } /** * The {@code Stringifier} for the long values. */ private static class LongStringifier extends Stringifier<Long> { @Override protected String toString(Long obj) { return Longs.stringConverter() .reverse() .convert(obj); } @Override protected Long fromString(String s) { return Longs.stringConverter() .convert(s); } } /** * The {@code Stringifier} for the integer values. */ private static class IntegerStringifier extends Stringifier<Integer> { @Override protected String toString(Integer obj) { return Ints.stringConverter() .reverse() .convert(obj); } @Override protected Integer fromString(String s) { return Ints.stringConverter() .convert(s); } } /** * The default {@code Stringifier} for the {@code Message} classes. * * <p>The sample of the usage: * {@code * // The message * final Human human = Human.newBuilder.setHairColor("black") .setEyesColor("blue").build(); * * final Stringifier<Human> humanStringifer = StringifierRegistry.getStringifier(Human.class); * * // The result is {"eyesColor" : "blue", "hairColor" : "black"} * final String json = humanStringifer.reverse().convert(humanStringifier); * * // human.equals(humanFromJson) == true; * final Human humanFromJson = humanStringifier.convert(json); * } * * @param <T> the message type */ private static class DefaultMessageStringifier<T extends Message> extends Stringifier<T> { private final Class<T> messageClass; private DefaultMessageStringifier(Class<T> messageType) { super(); this.messageClass = messageType; } @Override protected String toString(T obj) { return Json.toJson(obj); } @Override protected T fromString(String s) { return Json.fromJson(s, messageClass); } } }
package org.spine3.validate; import com.google.protobuf.Message; import com.google.protobuf.Timestamp; import org.spine3.base.CommandId; import org.spine3.base.EventId; import org.spine3.protobuf.TypeUrl; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static org.spine3.base.Identifiers.EMPTY_ID; import static org.spine3.base.Identifiers.idToString; /** * This class provides general validation routines. * * @author Alexander Yevsyukov */ public class Validate { private static final String MUST_BE_A_POSITIVE_VALUE = "%s must be a positive value"; private Validate() { } /** * Verifies if the passed message object is its default state and is not {@code null}. * * @param object the message to inspect * @return true if the message is in the default state, false otherwise */ public static boolean isDefault(Message object) { checkNotNull(object); final boolean result = object.getDefaultInstanceForType() .equals(object); return result; } /** * Verifies if the passed message object is not its default state and is not {@code null}. * * @param object the message to inspect * @return true if the message is not in the default state, false otherwise */ public static boolean isNotDefault(Message object) { checkNotNull(object); final boolean result = !isDefault(object); return result; } public static <M extends Message> M checkNotDefault(M object, @Nullable Object errorMessage) { checkNotNull(object); checkState(isNotDefault(object), errorMessage); return object; } @SuppressWarnings("OverloadedVarargsMethod") public static <M extends Message> M checkNotDefault(M object, String errorMessageTemplate, Object... errorMessageArgs) { checkNotNull(object); checkState(isNotDefault(object), errorMessageTemplate, errorMessageArgs); return object; } public static <M extends Message> M checkNotDefault(M object) { checkNotNull(object); checkNotDefault(object, "The message is in the default state: %s", TypeUrl.of(object) .getTypeName()); return object; } public static <M extends Message> M checkDefault(M object, @Nullable Object errorMessage) { checkNotNull(object); checkState(isDefault(object), errorMessage); return object; } @SuppressWarnings("OverloadedVarargsMethod") public static <M extends Message> M checkDefault(M object, String errorMessageTemplate, Object... errorMessageArgs) { checkNotNull(object); checkState(isDefault(object), errorMessageTemplate, errorMessageArgs); return object; } public static <M extends Message> M checkDefault(M object) { checkNotNull(object); if (!isDefault(object)) { final String typeName = TypeUrl.of(object) .getTypeName(); final String errorMessage = "The message is not in the default state: " + typeName; throw new IllegalStateException(errorMessage); } return object; } public static void checkParameter(boolean expression, String parameterName, String errorMessageFormat) { if (!expression) { final String errorMessage = String.format(errorMessageFormat, parameterName); throw new IllegalArgumentException(errorMessage); } } public static String checkNotEmptyOrBlank(String stringToCheck, String fieldName) { checkNotNull(stringToCheck, fieldName + " must not be null."); checkParameter(!stringToCheck.isEmpty(), fieldName, "%s must not be an empty string."); checkParameter(stringToCheck.trim() .length() > 0, fieldName, "%s must not be a blank string."); return stringToCheck; } public static Timestamp checkPositive(Timestamp timestamp, String argumentName) { checkNotNull(timestamp, argumentName); checkParameter(timestamp.getSeconds() > 0, argumentName, "%s must have a positive number of seconds."); checkParameter(timestamp.getNanos() >= 0, argumentName, "%s must not have a negative number of nanoseconds."); return timestamp; } public static void checkPositive(long value) { checkPositive(value, ""); } public static void checkPositive(long value, String argumentName) { checkParameter(value > 0L, argumentName, MUST_BE_A_POSITIVE_VALUE); } public static void checkPositiveOrZero(long value) { checkArgument(value >= 0); } public static EventId checkValid(EventId id) { checkNotNull(id); checkNotEmptyOrBlank(id.getUuid(), "event ID"); return id; } public static CommandId checkValid(CommandId id) { checkNotNull(id); final String idStr = idToString(id); checkArgument(!idStr.equals(EMPTY_ID), "Command ID must not be an empty string."); return id; } }
package org.smbarbour.mcu; import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.AWTException; import java.awt.BorderLayout; import java.awt.MenuItem; import java.awt.PopupMenu; import java.awt.SystemTray; import java.awt.TrayIcon; import javax.swing.JLabel; import javax.swing.JButton; import javax.swing.SwingConstants; import java.awt.Component; import javax.swing.Box; import java.awt.Font; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JCheckBox; import javax.swing.BoxLayout; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextPane; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Iterator; import java.util.List; import java.util.Properties; import org.smbarbour.mcu.MCUApp; import org.smbarbour.mcu.util.MCUpdater; import org.smbarbour.mcu.util.Module; import org.smbarbour.mcu.util.ServerList; import org.smbarbour.mcu.util.ServerListPacket; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.swing.JProgressBar; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.util.ResourceBundle; import javax.swing.JList; import javax.swing.AbstractListModel; import javax.swing.JToolBar; import javax.swing.ImageIcon; public class MainForm extends MCUApp { private static final ResourceBundle Customization = ResourceBundle.getBundle("customization"); //$NON-NLS-1$ private static final String VERSION = "v1.31"; private static MainForm window; private Properties config = new Properties(); private JFrame frmMain; final MCUpdater mcu = new MCUpdater(); private final JTextPane browser = new JTextPane(); private final JTextArea console = new JTextArea(); private ServerList selected; private final JPanel pnlModList = new JPanel(); private JLabel lblStatus; private JProgressBar progressBar; private JList serverList; private SLListModel slModel; private JButton btnLaunchMinecraft; private boolean minimized; private TrayIcon trayIcon; public ResourceBundle getCustomization(){ return Customization; } /** * Create the application. */ public MainForm() { window = this; initialize(); window.frmMain.setVisible(true); mcu.setParent(window); } public Properties getConfig() { return config; } public void writeConfig(Properties newConfig) { File configFile = new File(mcu.getArchiveFolder() + MCUpdater.sep + "config.properties"); try { configFile.getParentFile().mkdirs(); newConfig.store(new FileOutputStream(configFile), "User-specific configuration options"); config = newConfig; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private void createDefaultConfig(File configFile) { Properties newConfig = new Properties(); newConfig.setProperty("minimumMemory", "512M"); newConfig.setProperty("maximumMemory", "1G"); newConfig.setProperty("currentConfig", ""); newConfig.setProperty("packRevision",""); newConfig.setProperty("suppressUpdates", "false"); try { configFile.getParentFile().mkdirs(); newConfig.store(new FileOutputStream(configFile), "User-specific configuration options"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public boolean validateConfig(Properties current) { boolean hasChanged = false; if (current.getProperty("minimumMemory") == null) { current.setProperty("minimumMemory", "512M"); hasChanged = true; } if (current.getProperty("maximumMemory") == null) { current.setProperty("maximumMemory", "1G"); hasChanged = true; } if (current.getProperty("currentConfig") == null) { current.setProperty("currentConfig", ""); hasChanged = true; } if (current.getProperty("packRevision") == null) { current.setProperty("packRevision",""); hasChanged = true; } if (current.getProperty("suppressUpdates") == null) { current.setProperty("suppressUpdates", "false"); hasChanged = true; } return hasChanged; } /** * Initialize the contents of the frame. */ void initialize() { File configFile = new File(mcu.getArchiveFolder() + MCUpdater.sep + "config.properties"); if (!configFile.exists()) { createDefaultConfig(configFile); } try { config.load(new FileInputStream(configFile)); if (!validateConfig(config)) { writeConfig(config); } } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } frmMain = new JFrame(); frmMain.setTitle("[No Server Selected] - MCUpdater " + MainForm.VERSION); frmMain.setResizable(false); frmMain.setBounds(100, 100, 1175, 592); frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel pnlFooter = new JPanel(); frmMain.getContentPane().add(pnlFooter, BorderLayout.SOUTH); pnlFooter.setLayout(new BorderLayout(0, 0)); JPanel pnlButtons = new JPanel(); pnlFooter.add(pnlButtons, BorderLayout.EAST); JButton btnUpdate = new JButton("Update"); btnUpdate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new Thread() { public void run() { mcu.getMCVersion(); int saveConfig = JOptionPane.showConfirmDialog(null, "Do you want to save a backup of your existing configuration?", "MCUpdater", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if(saveConfig == JOptionPane.YES_OPTION){ setLblStatus("Creating backup"); setProgressBar(10); Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String backDesc = (String) JOptionPane.showInputDialog(null,"Enter description for backup:", "MCUpdater", JOptionPane.QUESTION_MESSAGE, null, null, ("Automatic backup: " + sdf.format(cal.getTime()))); mcu.saveConfig(backDesc); } else if(saveConfig == JOptionPane.CANCEL_OPTION){ return; } config.setProperty("currentConfig", selected.getServerId()); config.setProperty("packRevision", selected.getRevision()); writeConfig(config); List<Module> toInstall = new ArrayList<Module>(); List<Component> selects = new ArrayList<Component>(Arrays.asList(pnlModList.getComponents())); Iterator<Component> it = selects.iterator(); setLblStatus("Preparing module list"); setProgressBar(20); while(it.hasNext()) { Component baseEntry = it.next(); System.out.println(baseEntry.getClass().toString()); if(baseEntry.getClass().toString().equals("class org.smbarbour.mcu.JModuleCheckBox")) { JModuleCheckBox entry = (JModuleCheckBox) baseEntry; if(entry.isSelected()){ toInstall.add(entry.getModule()); } } } try { setLblStatus("Installing mods"); setProgressBar(25); mcu.installMods(selected, toInstall); if (selected.isGenerateList()) { setLblStatus("Writing servers.dat"); setProgressBar(90); mcu.writeMCServerFile(selected.getName(), selected.getAddress()); } setLblStatus("Finished"); setProgressBar(100); } catch (FileNotFoundException fnf) { JOptionPane.showMessageDialog(null, fnf.getMessage(), "MCUpdater", JOptionPane.ERROR_MESSAGE); } } }.start(); } }); pnlButtons.add(btnUpdate); btnLaunchMinecraft = new JButton("Launch Minecraft"); btnLaunchMinecraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { File launcher = new File(mcu.getMCFolder() + MCUpdater.sep + "minecraft.jar"); if(!launcher.exists()) { try { URL launcherURL = new URL("http://s3.amazonaws.com/MinecraftDownload/launcher/minecraft.jar"); ReadableByteChannel rbc = Channels.newChannel(launcherURL.openStream()); FileOutputStream fos = new FileOutputStream(launcher); fos.getChannel().transferFrom(rbc, 0, 1 << 24); } catch (MalformedURLException mue) { mue.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } File outFile = new File(mcu.getArchiveFolder() + MCUpdater.sep + "client-log.txt"); outFile.delete(); btnLaunchMinecraft.setEnabled(false); LauncherThread thread = LauncherThread.launch(launcher, config.getProperty("minimumMemory"), config.getProperty("maximumMemory"), Boolean.parseBoolean(config.getProperty("suppressUpdates")), outFile, console); thread.register( window, btnLaunchMinecraft ); thread.start(); } }); pnlButtons.add(btnLaunchMinecraft); JPanel pnlStatus = new JPanel(); pnlFooter.add(pnlStatus, BorderLayout.CENTER); pnlStatus.setLayout(new BorderLayout(0, 0)); lblStatus = new JLabel("Idle"); lblStatus.setHorizontalAlignment(SwingConstants.LEFT); pnlStatus.add(lblStatus); JPanel panel = new JPanel(); pnlStatus.add(panel, BorderLayout.EAST); panel.setLayout(new BorderLayout(0, 0)); progressBar = new JProgressBar(); panel.add(progressBar); progressBar.setStringPainted(true); Component TopStrut = Box.createVerticalStrut(5); panel.add(TopStrut, BorderLayout.NORTH); Component BottomStrut = Box.createVerticalStrut(5); panel.add(BottomStrut, BorderLayout.SOUTH); Component horizontalStrut = Box.createHorizontalStrut(5); pnlFooter.add(horizontalStrut, BorderLayout.WEST); JPanel pnlLeft = new JPanel(); frmMain.getContentPane().add(pnlLeft, BorderLayout.WEST); pnlLeft.setLayout(new BorderLayout(0, 0)); JLabel lblServers = new JLabel("Servers"); lblServers.setHorizontalAlignment(SwingConstants.CENTER); lblServers.setFont(new Font("Dialog", Font.BOLD, 14)); pnlLeft.add(lblServers, BorderLayout.NORTH); slModel = new SLListModel(); serverList = new JList(); serverList.setModel(slModel); serverList.setCellRenderer(new ServerListCellRenderer()); serverList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { changeSelectedServer(((ServerListPacket)serverList.getSelectedValue()).getEntry()); if (selected.getServerId().equals(config.getProperty("currentConfig")) && !(selected.getRevision().equals(config.getProperty("packRevision")))) { JOptionPane.showMessageDialog(null, "Your configuration is out of sync with the server. Updating is necessary.", "MCUpdater", JOptionPane.WARNING_MESSAGE); } } } }); JScrollPane serverScroller = new JScrollPane(serverList); pnlLeft.add(serverScroller, BorderLayout.CENTER); JPanel pnlRight = new JPanel(); frmMain.getContentPane().add(pnlRight, BorderLayout.EAST); pnlRight.setLayout(new BorderLayout(0, 0)); JPanel pnlChangesTitle = new JPanel(); pnlChangesTitle.setLayout(new BorderLayout(0,0)); JLabel lblChanges = new JLabel("Modules"); lblChanges.setHorizontalAlignment(SwingConstants.CENTER); lblChanges.setFont(new Font("Dialog", Font.BOLD, 14)); pnlChangesTitle.add(lblChanges, BorderLayout.CENTER); pnlRight.add(pnlChangesTitle, BorderLayout.NORTH); Component hstrut_ChangesLeft = Box.createHorizontalStrut(75); pnlChangesTitle.add(hstrut_ChangesLeft, BorderLayout.WEST); Component hstrut_ChangesRight = Box.createHorizontalStrut(75); pnlChangesTitle.add(hstrut_ChangesRight, BorderLayout.EAST); JScrollPane modScroller = new JScrollPane(pnlModList); pnlRight.add(modScroller, BorderLayout.CENTER); pnlModList.setLayout(new BoxLayout(pnlModList, BoxLayout.Y_AXIS)); browser.setEditable(false); browser.setContentType("text/html"); browser.addHyperlinkListener(new HyperlinkListener(){ @Override public void hyperlinkUpdate(HyperlinkEvent he) { if (he.getEventType() == HyperlinkEvent.EventType.ACTIVATED){ try { MCUpdater.openLink(he.getURL().toURI()); } catch (Exception e) { e.printStackTrace(); } } } }); JTabbedPane tabs = new JTabbedPane(); browser.setText("<HTML><BODY>There are no servers currently defined.</BODY></HTML>"); JScrollPane browserScrollPane = new JScrollPane(browser); browserScrollPane.setViewportBorder(null); browser.setBorder(null); tabs.add("News",browserScrollPane); console.setText("MCUpdater starting..."); console.setBorder(null); console.setLineWrap(true); console.setEditable(false); Font f = new Font("Monospaced",Font.PLAIN,11); console.setFont(f); JScrollPane consoleScrollPane = new JScrollPane(console); consoleScrollPane.setViewportBorder(null); consoleScrollPane.setAutoscrolls(true); consoleScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); consoleScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); tabs.add("Console",consoleScrollPane); frmMain.getContentPane().add(tabs, BorderLayout.CENTER); JToolBar toolBar = new JToolBar(); toolBar.setFloatable(false); frmMain.getContentPane().add(toolBar, BorderLayout.NORTH); JButton btnManageServers = new JButton(""); btnManageServers.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ServerManager sm = new ServerManager(window); sm.setVisible(true); } }); btnManageServers.setToolTipText("Manage Servers"); btnManageServers.setIcon(new ImageIcon(MainForm.class.getResource("/icons/server_database.png"))); toolBar.add(btnManageServers); JButton btnOptions = new JButton(""); btnOptions.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ClientConfig cc = new ClientConfig(window); cc.setVisible(true); } }); btnOptions.setToolTipText("Options"); btnOptions.setIcon(new ImageIcon(MainForm.class.getResource("/icons/application_edit.png"))); toolBar.add(btnOptions); JButton btnBackups = new JButton(""); btnBackups.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { BackupManager bm = new BackupManager(window); bm.setVisible(true); } }); btnBackups.setIcon(new ImageIcon(MainForm.class.getResource("/icons/folder_database.png"))); btnBackups.setToolTipText("Backups"); toolBar.add(btnBackups); Component horizontalGlue = Box.createHorizontalGlue(); toolBar.add(horizontalGlue); JLabel lblNewLabel = new JLabel("minecraft.jar version: " + mcu.getMCVersion()); toolBar.add(lblNewLabel); Component horizontalStrut_1 = Box.createHorizontalStrut(5); toolBar.add(horizontalStrut_1); File serverFile = new File(mcu.getArchiveFolder() + MCUpdater.sep + "mcuServers.dat"); String packUrl = Customization.getString("InitialServer.text"); while(!serverFile.exists() && !(serverFile.length() > 0)){ if(packUrl.isEmpty()) { packUrl = (String) JOptionPane.showInputDialog(null, "No default server defined.\nPlease enter URL to ServerPack.xml: ", "MCUpdater", JOptionPane.INFORMATION_MESSAGE, null, null, "http: } try { Document serverHeader = MCUpdater.readXmlFromUrl(packUrl); Element docEle = serverHeader.getDocumentElement(); ServerList sl = new ServerList(docEle.getAttribute("id"), docEle.getAttribute("name"), packUrl, docEle.getAttribute("newsUrl"), docEle.getAttribute("iconUrl"), docEle.getAttribute("version"), docEle.getAttribute("serverAddress"), mcu.parseBoolean(docEle.getAttribute("generateList")), docEle.getAttribute("revision")); List<ServerList> servers = new ArrayList<ServerList>(); servers.add(sl); mcu.writeServerList(servers); } catch (Exception x) { x.printStackTrace(); packUrl = ""; } } updateServerList(); int selectIndex = ((SLListModel)serverList.getModel()).getEntryIdByTag(config.getProperty("currentConfig")); serverList.setSelectedIndex(selectIndex); initTray(); } protected void changeSelectedServer(ServerList entry) { try { selected = entry; browser.setPage(entry.getNewsUrl()); frmMain.setTitle(entry.getName() + " - MCUpdater " + MainForm.VERSION); List<Module> modules = mcu.loadFromURL(entry.getPackUrl(), entry.getServerId()); Iterator<Module> itMods = modules.iterator(); pnlModList.setVisible(false); pnlModList.removeAll(); while(itMods.hasNext()) { Module modEntry = itMods.next(); JModuleCheckBox chkModule = new JModuleCheckBox(modEntry.getName()); if(modEntry.getInJar()) { chkModule.setFont(chkModule.getFont().deriveFont(Font.BOLD)); } chkModule.setModule(modEntry); if(modEntry.getRequired()) { chkModule.setSelected(true); chkModule.setEnabled(false); } if(modEntry.getIsDefault()) { chkModule.setSelected(true); } pnlModList.add(chkModule); } pnlModList.setVisible(true); this.frmMain.repaint(); } catch (IOException ioe) { ioe.printStackTrace(); } } public void updateServerList() { serverList.setVisible(false); slModel.clear(); List<ServerList> servers = mcu.loadServerList(Customization.getString("InitialServer.text")); if (servers != null) { Iterator<ServerList> it = servers.iterator(); //boolean flag = false; while(it.hasNext()) { ServerList entry = it.next(); slModel.add(new ServerListPacket(entry, mcu)); } } serverList.setVisible(true); } @Override public void setLblStatus(String text) { lblStatus.setText(text); } @Override public void setProgressBar(int value) { progressBar.setValue(value); } private void initTray() { if( !SystemTray.isSupported() ) { System.out.println("System tray is NOT supported :("); return; } final String label = "MCUpdater "+VERSION; trayIcon = new TrayIcon(new ImageIcon(MainForm.class.getResource("/icons/briefcase.png")).getImage(),label); final SystemTray tray = SystemTray.getSystemTray(); final PopupMenu menu = new PopupMenu(); final MenuItem restoreItem = new MenuItem("Restore MCU"); restoreItem.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { restore(); } }); final MenuItem killItem = new MenuItem("Kill Minecraft"); killItem.setEnabled(false); menu.add(restoreItem); menu.add(killItem); trayIcon.setPopupMenu(menu); try { tray.add(trayIcon); } catch (AWTException e) { trayIcon = null; e.printStackTrace(); } } public void minimize(boolean auto) { if( trayIcon == null ) { // only minimize if we have a way to come back return; } // TODO: add preference whether to autohide or not frmMain.setVisible(false); minimized = true; } public void restore() { if( !minimized ) { return; } frmMain.setVisible(true); } } class JModuleCheckBox extends JCheckBox { private static final long serialVersionUID = 8124564072878896685L; private Module entry; public JModuleCheckBox(String name) { super(name); } public void setModule(Module entry) { this.entry=entry; } public Module getModule() { return entry; } } class SLListModel extends AbstractListModel { private static final long serialVersionUID = -6829288390151952427L; List<ServerListPacket> model; public SLListModel() { model = new ArrayList<ServerListPacket>(); } public int getEntryIdByTag(String tag) { int foundId = 0; Iterator<ServerListPacket> it = model.iterator(); int searchId = 0; while (it.hasNext()) { ServerListPacket entry = it.next(); if (tag.equals(entry.getEntry().getServerId())) { foundId = searchId; break; } searchId++; } return foundId; } @Override public int getSize() { return model.size(); } @Override public Object getElementAt(int index) { return model.toArray()[index]; } public void add(ServerListPacket element) { model.add(element); fireContentsChanged(this, 0, getSize()); } public Iterator<ServerListPacket> iterator() { return model.iterator(); } public boolean removeElement(ServerListPacket element) { boolean removed = model.remove(element); if (removed) { fireContentsChanged(this, 0, getSize()); } return removed; } public void clear() { model.clear(); fireContentsChanged(this, 0, getSize()); } }
package org.jetel.component; import java.io.IOException; import org.jetel.data.DataRecord; import org.jetel.data.Defaults; import org.jetel.data.DynamicRecordBuffer; import org.jetel.data.RecordKey; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.ConfigurationProblem; import org.jetel.exception.ConfigurationStatus; import org.jetel.exception.XMLConfigurationException; import org.jetel.graph.InputPort; import org.jetel.graph.Node; import org.jetel.graph.Result; import org.jetel.graph.TransformationGraph; import org.jetel.metadata.DataRecordMetadata; import org.jetel.util.property.ComponentXMLAttributes; import org.jetel.util.string.StringUtils; import org.w3c.dom.Element; /** * <h3>Dedup Component</h3> * * <!-- Removes duplicates (based on specified key) from data flow of sorted records--> * * <table border="1"> * <th>Component:</th> * <tr><td><h4><i>Name:</i></h4></td> * <td>Dedup</td></tr> * <tr><td><h4><i>Category:</i></h4></td> * <td></td></tr> * <tr><td><h4><i>Description:</i></h4></td> * <td>Dedup (remove duplicate records) from sorted incoming records based on specified key.<br> * The key is name (or combination of names) of field(s) from input record. * It keeps either First or Last record from the group based on the parameter <emp>{keep}</emp> specified. * All duplicated records are rejected to the second optional port.</td></tr> * <tr><td><h4><i>Inputs:</i></h4></td> * <td>[0]- input records</td></tr> * <tr><td><h4><i>Outputs:</i></h4></td> * <td>[0]- result of deduplication</td></tr> * <td>[0]- all rejected records</td></tr> * <tr><td><h4><i>Comment:</i></h4></td> * <td></td></tr> * </table> * <br> * <table border="1"> * <th>XML attributes:</th> * <tr><td><b>type</b></td><td>"DEDUP"</td></tr> * <tr><td><b>id</b></td><td>component identification</td> * <tr><td><b>dedupKey</b></td><td>field names separated by :;| {colon, semicolon, pipe} or can be empty, then all records belong to one group</td> * <tr><td><b>keep</b></td><td>one of "First|Last|Unique" {the fist letter is sufficient, if not defined, then First}</td></tr> * <tr><td><b>equalNULL</b><br><i>optional</i></td><td>specifies whether two fields containing NULL values are considered equal. Default is TRUE.</td></tr> * <tr><td><b>noDupRecord</b><br><i>optional</i></td><td>number of duplicate record to be written to out port. Default is 1.</td></tr> * </table> * * <h4>Example:</h4> * <pre>&lt;Node id="DISTINCT" type="DEDUP" dedupKey="Name" keep="First"/&gt;</pre> * * @author dpavlis * @since April 4, 2002 * @revision $Revision$ */ public class Dedup extends Node { private static final String XML_KEEP_ATTRIBUTE = "keep"; private static final String XML_DEDUPKEY_ATTRIBUTE = "dedupKey"; private static final String XML_EQUAL_NULL_ATTRIBUTE = "equalNULL"; private static final String XML_NO_DUP_RECORD_ATTRIBUTE = "noDupRecord"; /** Description of the Field */ public final static String COMPONENT_TYPE = "DEDUP"; private final static int READ_FROM_PORT = 0; private final static int WRITE_TO_PORT = 0; private final static int REJECTED_PORT = 1; private final static int KEEP_FIRST = 1; private final static int KEEP_LAST = -1; private final static int KEEP_UNIQUE = 0; private final static int DEFAULT_NO_DUP_RECORD = 1; private int keep; private String[] dedupKeys; private RecordKey recordKey; private boolean equalNULLs = true; private boolean hasRejectedPort; private int noDupRecord = DEFAULT_NO_DUP_RECORD; // number of duplicate record to be written to out port //runtime variables int current; int previous; boolean isFirst; InputPort inPort; DataRecord[] records; /** *Constructor for the Dedup object * * @param id unique id of the component * @param dedupKeys definitio of key fields used to compare records * @param keep (1 - keep first; 0 - keep unique; -1 - keep last) */ public Dedup(String id, String[] dedupKeys, int keep) { super(id); this.keep = keep; this.dedupKeys = dedupKeys; } /** * Gets the change attribute of the Dedup object * * @param a Description of the Parameter * @param b Description of the Parameter * @return The change value */ private final boolean isChange(DataRecord a, DataRecord b) { if(recordKey != null) { return (recordKey.compare(a, b) != 0); } else { return false; } } @Override public Result execute() throws Exception { isFirst = true; // special treatment for 1st record inPort = getInputPort(READ_FROM_PORT); records = new DataRecord[2]; records[0] = new DataRecord(inPort.getMetadata()); records[0].init(); records[1] = new DataRecord(inPort.getMetadata()); records[1].init(); current = 1; previous = 0; if (dedupKeys == null) { writeAllRecordsToOutPort(); } else { switch(keep) { case KEEP_FIRST: executeFirst(); break; case KEEP_LAST: executeLast(); break; case KEEP_UNIQUE: executeUnique(); break; } } broadcastEOF(); return runIt ? Result.FINISHED_OK : Result.ABORTED; } /** * Execution a de-duplication with first function. * * @throws IOException * @throws InterruptedException */ private void executeFirst() throws IOException, InterruptedException { int groupItems = 0; while (records[current] != null && runIt) { records[current] = inPort.readRecord(records[current]); if (records[current] != null) { if (isFirst) { writeOutRecord(records[current]); groupItems++; isFirst = false; } else { if (isChange(records[current], records[previous])) { writeOutRecord(records[current]); groupItems = 1; } else { if (groupItems < noDupRecord) { writeOutRecord(records[current]); groupItems++; } else { writeRejectedRecord(records[current]); } } } // swap indexes current = current ^ 1; previous = previous ^ 1; } } } /** * Execution a de-duplication with last function. * * @throws IOException * @throws InterruptedException */ public void executeLast() throws IOException, InterruptedException { RingRecordBuffer ringBuffer = new RingRecordBuffer(noDupRecord, inPort.getMetadata()); ringBuffer.init(); while (records[current] != null && runIt) { records[current] = inPort.readRecord(records[current]); if (records[current] != null) { if (isFirst) { isFirst = false; } else { if (isChange(records[current], records[previous])) { ringBuffer.flushRecords(); ringBuffer.clear(); } } ringBuffer.writeRecord(records[current]); // swap indexes current = current ^ 1; previous = previous ^ 1; } } ringBuffer.flushRecords(); ringBuffer.free(); } /** * Execution a de-duplication with unique function. * * @throws IOException * @throws InterruptedException */ public void executeUnique() throws IOException, InterruptedException { int groupItems = 0; while (records[current] != null && runIt) { records[current] = inPort.readRecord(records[current]); if (records[current] != null) { if (isFirst) { isFirst = false; } else { if (isChange(records[current], records[previous])) { if (groupItems == 1) { writeOutRecord(records[previous]); } else { writeRejectedRecord(records[previous]); } groupItems = 0; } else { writeRejectedRecord(records[previous]); } } groupItems++; // swap indexes current = current ^ 1; previous = previous ^ 1; } else { if (!isFirst) { if(groupItems == 1) { writeOutRecord(records[previous]); } else { writeRejectedRecord(records[previous]); } } } } } /** * Write all records to output port. * Uses when all records belong to one group. * * @throws IOException * @throws InterruptedException */ private void writeAllRecordsToOutPort() throws IOException, InterruptedException { while (runIt && (records[0] = inPort.readRecord(records[0])) != null) { writeOutRecord(records[0]); } } /** * Tries to write given record to the rejected port, if is connected. * @param record * @throws InterruptedException * @throws IOException */ private void writeRejectedRecord(DataRecord record) throws IOException, InterruptedException { if(hasRejectedPort) { writeRecord(REJECTED_PORT, record); } } /** * Writes given record to the out port. * * @param record * @throws InterruptedException * @throws IOException */ private void writeOutRecord(DataRecord record) throws IOException, InterruptedException { writeRecord(WRITE_TO_PORT, record); } /** * Description of the Method * * @exception ComponentNotReadyException * Description of the Exception * @since April 4, 2002 */ public void init() throws ComponentNotReadyException { if(isInitialized()) return; super.init(); if(dedupKeys != null) { recordKey = new RecordKey(dedupKeys, getInputPort(READ_FROM_PORT).getMetadata()); recordKey.init(); // for DEDUP component, specify whether two fields with NULL value indicator set // are considered equal recordKey.setEqualNULLs(equalNULLs); } hasRejectedPort = (getOutPorts().size() == 2); if (noDupRecord < 1) { throw new ComponentNotReadyException(this, StringUtils.quote(XML_NO_DUP_RECORD_ATTRIBUTE) + " must be positive number."); } } /** * Description of the Method * * @return Description of the Returned Value * @since May 21, 2002 */ @Override public void toXML(Element xmlElement) { super.toXML(xmlElement); // dedupKeys attribute if (dedupKeys != null) { String keys = this.dedupKeys[0]; for (int i=1; i<this.dedupKeys.length; i++) { keys += Defaults.Component.KEY_FIELDS_DELIMITER + this.dedupKeys[i]; } xmlElement.setAttribute(XML_DEDUPKEY_ATTRIBUTE,keys); } // keep attribute switch(this.keep){ case KEEP_FIRST: xmlElement.setAttribute(XML_KEEP_ATTRIBUTE, "First"); break; case KEEP_LAST: xmlElement.setAttribute(XML_KEEP_ATTRIBUTE, "Last"); break; case KEEP_UNIQUE: xmlElement.setAttribute(XML_KEEP_ATTRIBUTE, "Unique"); break; } // equal NULL attribute xmlElement.setAttribute(XML_EQUAL_NULL_ATTRIBUTE, String.valueOf(equalNULLs)); if (noDupRecord != DEFAULT_NO_DUP_RECORD) { xmlElement.setAttribute(XML_NO_DUP_RECORD_ATTRIBUTE, String.valueOf(noDupRecord)); } } /** * Description of the Method * * @param nodeXML Description of Parameter * @return Description of the Returned Value * @since May 21, 2002 */ public static Node fromXML(TransformationGraph graph, Element xmlElement) throws XMLConfigurationException { ComponentXMLAttributes xattribs = new ComponentXMLAttributes(xmlElement, graph); Dedup dedup; try { String dedupKey = xattribs.getString(XML_DEDUPKEY_ATTRIBUTE, null); dedup=new Dedup(xattribs.getString(XML_ID_ATTRIBUTE), dedupKey != null ? dedupKey.split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX) : null, xattribs.getString(XML_KEEP_ATTRIBUTE).matches("^[Ff].*") ? KEEP_FIRST : xattribs.getString(XML_KEEP_ATTRIBUTE).matches("^[Ll].*") ? KEEP_LAST : KEEP_UNIQUE); if (xattribs.exists(XML_EQUAL_NULL_ATTRIBUTE)){ dedup.setEqualNULLs(xattribs.getBoolean(XML_EQUAL_NULL_ATTRIBUTE)); } if (xattribs.exists(XML_NO_DUP_RECORD_ATTRIBUTE)){ dedup.setNumberRecord(xattribs.getInteger(XML_NO_DUP_RECORD_ATTRIBUTE)); } } catch (Exception ex) { throw new XMLConfigurationException(COMPONENT_TYPE + ":" + xattribs.getString(XML_ID_ATTRIBUTE," unknown ID ") + ":" + ex.getMessage(),ex); } return dedup; } /** Description of the Method */ @Override public ConfigurationStatus checkConfig(ConfigurationStatus status) { super.checkConfig(status); checkInputPorts(status, 1, 1); checkOutputPorts(status, 1, 2); checkMetadata(status, getInputPort(READ_FROM_PORT).getMetadata(), getOutMetadata()); try { init(); } catch (ComponentNotReadyException e) { ConfigurationProblem problem = new ConfigurationProblem(e.getMessage(), ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL); if(!StringUtils.isEmpty(e.getAttributeName())) { problem.setAttributeName(e.getAttributeName()); } status.add(problem); } finally { free(); } return status; } public String getType(){ return COMPONENT_TYPE; } public void setEqualNULLs(boolean equal){ this.equalNULLs=equal; } public void setNumberRecord(int numberRecord) { this.noDupRecord = numberRecord; } private class RingRecordBuffer { private DynamicRecordBufferExt recordBuffer; private long sizeOfBuffer; // max number of records presented in buffer // state (number of records) before or after call any of method private DataRecordMetadata metadata; /** * @param sizeOfBuffer max number of records presented in buffer * @param metadata metadat of records that will be stored in buffer. */ public RingRecordBuffer(long sizeOfBuffer, DataRecordMetadata metadata) { this.sizeOfBuffer = sizeOfBuffer; this.metadata = metadata; } /** * Initializes the buffer. Must be called before any write or read operation * is performed. */ public void init() { recordBuffer = new DynamicRecordBufferExt(); recordBuffer.init(); } /** * Closes buffer, removes temporary file (is exists). */ public void free() { try { recordBuffer.close(); } catch (IOException e) { //do nothing } } /** * Adds record to the ring buffer - when buffer is full then the oldest * record in buffer is removed and pass to writeRejectedRecord() method. * @param record record that will be added to the ring buffer * @throws IOException * @throws InterruptedException */ public void writeRecord(DataRecord record) throws IOException, InterruptedException { recordBuffer.writeRecord(record); if (recordBuffer.getBufferedRecords() > sizeOfBuffer) { if (!recordBuffer.hasData()) { recordBuffer.swapBuffers(); } DataRecord rejectedRecord = new DataRecord(metadata); rejectedRecord.init(); rejectedRecord = recordBuffer.readRecord(rejectedRecord); writeRejectedRecord(rejectedRecord); } } /** * Flush all records from buffer to out port. * @throws IOException * @throws InterruptedException */ public void flushRecords() throws IOException, InterruptedException { DataRecord record = new DataRecord(metadata); record.init(); while (recordBuffer.getBufferedRecords() > 0) { if (!recordBuffer.hasData()) { recordBuffer.swapBuffers(); } record = recordBuffer.readRecord(record); writeOutRecord(record); } } /** * Clears the buffer. Temp file (if it was created) remains * unchanged size-wise */ public void clear() { recordBuffer.clear(); } } private class DynamicRecordBufferExt extends DynamicRecordBuffer { public DynamicRecordBufferExt() { super(Defaults.Graph.BUFFERED_EDGE_INTERNAL_BUFFER_SIZE); } /** * Remove data from writeDataBuffer and put it to readDataBuffer. */ public void swapBuffers() { swapWriteBufferToReadBuffer(); } } }
import java.util.Hashtable; import java.util.Map; import javax.xml.transform.*; import javax.xml.transform.stream.StreamSource; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.wizards.common.FileAccess; public class CGLayout extends ConfigSetItem { public String cp_Name; public String cp_FSName; private Map templates; private void createTemplates(XMultiServiceFactory xmsf) throws Exception { templates = new Hashtable(3); TransformerFactory tf = TransformerFactory.newInstance(); String workPath = getSettings().workPath; FileAccess fa = new FileAccess(xmsf); String stylesheetPath = fa.getURL(getSettings().workPath,"layouts/"+cp_FSName); String[] files = fa.listFiles(stylesheetPath,false); for (int i = 0; i<files.length; i++) if (FileAccess.getExtension(files[i]).equals("xsl")) templates.put(FileAccess.getFilename(files[i]), tf.newTemplates( new StreamSource(files[i]) )); } public Object[] getImageUrls() { Object[] sRetUrls = new Object[1]; sRetUrls[0] = FileAccess.connectURLs(getSettings().workPath, "layouts/" + cp_FSName + ".png"); return sRetUrls; } public Map getTemplates(XMultiServiceFactory xmsf) throws Exception { // TODO uncomment... // if (templates==null) createTemplates(xmsf); return templates; } }
package roart.predictor; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import roart.config.MyMyConfig; import roart.model.ResultItemTable; import roart.model.ResultItemTableRow; import roart.model.StockItem; import roart.pipeline.PipelineConstants; public abstract class Predictor { protected static Logger log = LoggerFactory.getLogger(Predictor.class); protected String title; protected MyMyConfig conf; protected int category; protected Map<String, Object[]> resultMap; public Predictor(MyMyConfig conf, String string, int category) { this.title = string; this.conf = conf; this.category = category; } abstract public boolean isEnabled(); public Object[] getResultItemTitle() { Object[] titleArray = new Object[1]; titleArray[0] = title; return titleArray; } abstract public Object[] getResultItem(StockItem stock); public Object calculate(Double[] array) { return null; } public List<Integer> getTypeList() { return null; } public Map<Integer, String> getMapTypes() { return null; } public Map<Integer, List<ResultItemTableRow>> otherTables() { return null; } public Map<String, Object> getResultMap() { return null; } public Map<String, Object> getLocalResultMap() { Map<String, Object> map = new HashMap<>(); map.put(PipelineConstants.CATEGORY, category); map.put(PipelineConstants.CATEGORYTITLE, title); map.put(PipelineConstants.RESULT, resultMap); return map; } public abstract String predictorName(); }
package util.ui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JOptionPane; import server.GameServer; @SuppressWarnings("serial") public class PublishButton extends JButton implements ActionListener { private GameServer theServer; public PublishButton(String theName) { super(theName); this.addActionListener(this); this.setEnabled(false); } public void setServer(GameServer theServer) { this.theServer = theServer; this.setEnabled(true); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == this) { if (theServer != null) { if (!theServer.getMatch().getGame().getRepositoryURL().contains("127.0.0.1")) { String theMatchKey = theServer.startPublishingToSpectatorServer("http://matches.ggp.org/"); if (theMatchKey != null) { String theURL = "http://matches.ggp.org/matches/" + theMatchKey + "/viz.html"; System.out.println("Publishing to: " + theURL); int nChoice = JOptionPane.showConfirmDialog(this, "Publishing successfully. Would you like to open the spectator view in a browser?", "Publishing Match Online", JOptionPane.YES_NO_OPTION); if (nChoice == JOptionPane.YES_OPTION) { try { java.awt.Desktop.getDesktop().browse(java.net.URI.create(theURL)); } catch (Exception ee) { ee.printStackTrace(); } } } else { JOptionPane.showMessageDialog(this, "Unknown problem when publishing match.", "Publishing Match Online", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(this, "Could not publish a game that is only stored locally.", "Publishing Match Online", JOptionPane.ERROR_MESSAGE); } setEnabled(false); } } } }
package org.diirt.pods.web; import java.io.InputStream; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.websocket.CloseReason; import javax.websocket.EndpointConfig; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import org.diirt.pods.common.ChannelTranslation; import org.diirt.pods.common.ChannelTranslator; import org.diirt.pods.common.Configuration; import org.epics.pvmanager.CompositeDataSource; import org.epics.pvmanager.PVManager; import org.epics.pvmanager.PVReader; import org.epics.pvmanager.PV; import org.epics.pvmanager.PVReaderEvent; import org.epics.pvmanager.PVReaderListener; import org.epics.pvmanager.PVWriter; import org.epics.pvmanager.PVWriterEvent; import org.epics.pvmanager.PVWriterListener; import static org.epics.pvmanager.formula.ExpressionLanguage.*; import org.epics.pvmanager.loc.LocalDataSource; import org.epics.pvmanager.sim.SimulationDataSource; import org.epics.util.time.TimeDuration; /** * * @author carcassi */ @ServerEndpoint(value = "/socket", encoders = {MessageEncoder.class}, decoders = {MessageDecoder.class}) public class WSEndpoint { // TODO: understand lifecycle of whole web application and put // configuration there, including closing datasources. static { CompositeDataSource datasource = new CompositeDataSource(); datasource.putDataSource("sim", new SimulationDataSource()); datasource.putDataSource("loc", new LocalDataSource()); PVManager.setDefaultDataSource(datasource); ChannelTranslator temp = null; try (InputStream input = Configuration.getFileAsStream("pods/web/mappings.xml", new WSEndpoint(), "mappings.default.xml")) { temp = ChannelTranslator.loadTranslator(input); } catch (Exception ex) { Logger.getLogger(WSEndpoint.class.getName()).log(Level.SEVERE, "Couldn't load DIIRT_HOME/pods/web/mappings", ex); } channelTranslator = temp; } private static Logger log = Logger.getLogger(WSEndpoint.class.getName()); private static final ChannelTranslator channelTranslator; // XXX: need to understand how state can actually be used private final Map<Integer, PVReader<?>> pvs = new ConcurrentHashMap<Integer, PVReader<?>>(); @OnMessage public void onMessage(Session session, Message message) { switch (message.getMessage()) { case SUBSCRIBE: onSubscribe(session, (MessageSubscribe) message); return; case UNSUBSCRIBE: onUnsubscribe(session, (MessageUnsubscribe) message); return; default: throw new UnsupportedOperationException("Message '" + message.getMessage() + "' not yet supported"); } } private void onSubscribe(final Session session, final MessageSubscribe message) { // TODO: check id already used double maxRate = 1; if (message.getMaxRate() != -1) { maxRate = message.getMaxRate(); } ChannelTranslation translation = channelTranslator.translate(message.getPv()); PVReader<?> reader; if (message.isReadOnly()) { reader = PVManager.read(formula(translation.getFormula())) .readListener(new ReadOnlyListener(session, message)) .maxRate(TimeDuration.ofHertz(maxRate)); } else { ReadWriteListener readWriteListener = new ReadWriteListener(session, message); reader = PVManager.readAndWrite(formula(translation.getFormula())) .readListener(readWriteListener) .writeListener(readWriteListener) .asynchWriteAndMaxReadRate(TimeDuration.ofHertz(maxRate)); } pvs.put(message.getId(), reader); } private void onUnsubscribe(Session session, MessageUnsubscribe message) { PVReader<?> pv = pvs.get(message.getId()); if (pv != null) { pv.close(); } } @OnOpen public void onOpen(Session session, EndpointConfig config) { System.out.println(session.getRequestURI() + ": OPEN"); } @OnClose public void onClose(Session session, CloseReason reason) { for (Map.Entry<Integer, PVReader<?>> entry : pvs.entrySet()) { PVReader<?> pvReader = entry.getValue(); pvReader.close(); } closed = true; } private volatile boolean closed = false; @OnError public void onError(Session session, Throwable cause) { System.out.println(session.getRequestURI() + ": ERROR"); cause.printStackTrace(); } private class ReadOnlyListener implements PVReaderListener<Object> { private final Session session; private final MessageSubscribe message; public ReadOnlyListener(Session session, MessageSubscribe message) { this.session = session; this.message = message; } @Override public void pvChanged(PVReaderEvent<Object> event) { if (closed) { log.log(Level.SEVERE, "Getting event after pv was closed for " + event.getPvReader().getName()); event.getPvReader().close(); return; } if (event.isConnectionChanged()) { session.getAsyncRemote().sendObject(new MessageConnectionEvent(message.getId(), event.getPvReader().isConnected(), false)); } if (event.isValueChanged()) { session.getAsyncRemote().sendObject(new MessageValueEvent(message.getId(), event.getPvReader().getValue())); } if (event.isExceptionChanged()) { session.getAsyncRemote().sendObject(new MessageErrorEvent(message.getId(), event.getPvReader().lastException().getMessage())); } } } private static PV<Object, Object> pv(PVWriter<Object> reader) { @SuppressWarnings("unchecked") PV<Object, Object> pv = (PV<Object, Object>) reader; return pv; } private class ReadWriteListener implements PVReaderListener<Object>, PVWriterListener<Object> { private final Session session; private final MessageSubscribe message; public ReadWriteListener(Session session, MessageSubscribe message) { this.session = session; this.message = message; } @Override public void pvChanged(PVReaderEvent<Object> event) { if (closed) { log.log(Level.SEVERE, "Getting event after pv was closed for " + event.getPvReader().getName()); event.getPvReader().close(); return; } if (event.isValueChanged()) { session.getAsyncRemote().sendObject(new MessageValueEvent(message.getId(), event.getPvReader().getValue())); } if (event.isExceptionChanged()) { session.getAsyncRemote().sendObject(new MessageErrorEvent(message.getId(), event.getPvReader().lastException().getMessage())); } } @Override public void pvChanged(PVWriterEvent<Object> event) { if (closed) { log.log(Level.SEVERE, "Getting event after pv was closed for " + event.getPvWriter()); event.getPvWriter().close(); return; } if (event.isConnectionChanged()) { session.getAsyncRemote().sendObject(new MessageConnectionEvent(message.getId(), pv(event.getPvWriter()).isConnected(), event.getPvWriter().isWriteConnected())); } if (event.isWriteSucceeded()) { session.getAsyncRemote().sendObject(new MessageWriteCompletedEvent(message.getId())); } if (event.isWriteFailed()) { session.getAsyncRemote().sendObject(new MessageWriteCompletedEvent(message.getId(), event.getPvWriter().lastWriteException().getMessage())); } if (event.isExceptionChanged()) { session.getAsyncRemote().sendObject(new MessageErrorEvent(message.getId(), event.getPvWriter().lastWriteException().getMessage())); } } } }
package com.shc.webgl4j.client; import com.google.gwt.canvas.client.Canvas; import com.google.gwt.canvas.dom.client.ImageData; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.dom.client.CanvasElement; import com.google.gwt.dom.client.Element; import com.google.gwt.typedarrays.shared.ArrayBufferView; import com.google.gwt.typedarrays.shared.Float32Array; import com.google.gwt.typedarrays.shared.Int32Array; import com.google.gwt.typedarrays.shared.TypedArrays; import com.google.gwt.user.client.ui.Image; /** * @author Sri Harsha Chilakapati */ public final class WebGL10 { public static final int GL_ACTIVE_ATTRIBUTES = 0x8B89; public static final int GL_ACTIVE_TEXTURE = 0x84E0; public static final int GL_ACTIVE_UNIFORMS = 0x8B86; public static final int GL_ALIASED_LINE_WIDTH_RANGE = 0x846E; public static final int GL_ALIASED_POINT_SIZE_RANGE = 0x846D; public static final int GL_ALPHA = 0x1906; public static final int GL_ALPHA_BITS = 0x0D55; public static final int GL_ALWAYS = 0x0207; public static final int GL_ARRAY_BUFFER = 0x8892; public static final int GL_ARRAY_BUFFER_BINDING = 0x8894; public static final int GL_ATTACHED_SHADERS = 0x8B85; public static final int GL_BACK = 0x0405; public static final int GL_BLEND = 0x0BE2; public static final int GL_BLEND_COLOR = 0x8005; public static final int GL_BLEND_DST_ALPHA = 0x80CA; public static final int GL_BLEND_DST_RGB = 0x80C8; public static final int GL_BLEND_EQUATION = 0x8009; public static final int GL_BLEND_EQUATION_ALPHA = 0x883D; public static final int GL_BLEND_EQUATION_RGB = 0x8009; public static final int GL_BLEND_SRC_ALPHA = 0x80CB; public static final int GL_BLEND_SRC_RGB = 0x80C9; public static final int GL_BLUE_BITS = 0x0D54; public static final int GL_BOOL = 0x8B56; public static final int GL_BOOL_VEC2 = 0x8B57; public static final int GL_BOOL_VEC3 = 0x8B58; public static final int GL_BOOL_VEC4 = 0x8B59; public static final int GL_BROWSER_DEFAULT_WEBGL = 0x9244; public static final int GL_BUFFER_SIZE = 0x8764; public static final int GL_BUFFER_USAGE = 0x8765; public static final int GL_BYTE = 0x1400; public static final int GL_CCW = 0x0901; public static final int GL_CLAMP_TO_EDGE = 0x812F; public static final int GL_COLOR_ATTACHMENT0 = 0x8CE0; public static final int GL_COLOR_BUFFER_BIT = 0x4000; public static final int GL_COLOR_CLEAR_VALUE = 0x0C22; public static final int GL_COLOR_WRITEMASK = 0x0C23; public static final int GL_COMPILE_STATUS = 0x8B81; public static final int GL_COMPRESSED_TEXTURE_FORMATS = 0x86A3; public static final int GL_CONSTANT_ALPHA = 0x8003; public static final int GL_CONSTANT_COLOR = 0x8001; public static final int GL_CONTEXT_LOST_WEBGL = 0x9242; public static final int GL_CULL_FACE = 0x0B44; public static final int GL_CULL_FACE_MODE = 0x0B45; public static final int GL_CURRENT_PROGRAM = 0x8B8D; public static final int GL_CURRENT_VERTEX_ATTRIB = 0x8626; public static final int GL_CW = 0x0900; public static final int GL_DECR = 0x1E03; public static final int GL_DECR_WRAP = 0x8508; public static final int GL_DELETE_STATUS = 0x8B80; public static final int GL_DEPTH_ATTACHMENT = 0x8D00; public static final int GL_DEPTH_BITS = 0x0D56; public static final int GL_DEPTH_BUFFER_BIT = 0x0100; public static final int GL_DEPTH_CLEAR_VALUE = 0x0B73; public static final int GL_DEPTH_COMPONENT = 0x1902; public static final int GL_DEPTH_COMPONENT16 = 0x81A5; public static final int GL_DEPTH_FUNC = 0x0B74; public static final int GL_DEPTH_RANGE = 0x0B70; public static final int GL_DEPTH_STENCIL = 0x84F9; public static final int GL_DEPTH_STENCIL_ATTACHMENT = 0x821A; public static final int GL_DEPTH_TEST = 0x0B71; public static final int GL_DEPTH_WRITEMASK = 0x0B72; public static final int GL_DITHER = 0x0BD0; public static final int GL_DONT_CARE = 0x1100; public static final int GL_DST_ALPHA = 0x0304; public static final int GL_DST_COLOR = 0x0306; public static final int GL_DYNAMIC_DRAW = 0x88E8; public static final int GL_ELEMENT_ARRAY_BUFFER = 0x8893; public static final int GL_ELEMENT_ARRAY_BUFFER_BINDING = 0x8895; public static final int GL_EQUAL = 0x0202; public static final int GL_FASTEST = 0x1101; public static final int GL_FLOAT = 0x1406; public static final int GL_FLOAT_MAT2 = 0x8B5A; public static final int GL_FLOAT_MAT3 = 0x8B5B; public static final int GL_FLOAT_MAT4 = 0x8B5C; public static final int GL_FLOAT_VEC2 = 0x8B50; public static final int GL_FLOAT_VEC3 = 0x8B51; public static final int GL_FLOAT_VEC4 = 0x8B52; public static final int GL_FRAGMENT_SHADER = 0x8B30; public static final int GL_FRAMEBUFFER = 0x8D40; public static final int GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8CD1; public static final int GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8CD0; public static final int GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8CD3; public static final int GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8CD2; public static final int GL_FRAMEBUFFER_BINDING = 0x8CA6; public static final int GL_FRAMEBUFFER_COMPLETE = 0x8CD5; public static final int GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8CD6; public static final int GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS = 0x8CD9; public static final int GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8CD7; public static final int GL_FRAMEBUFFER_UNSUPPORTED = 0x8CDD; public static final int GL_FRONT = 0x0404; public static final int GL_FRONT_AND_BACK = 0x0408; public static final int GL_FRONT_FACE = 0x0B46; public static final int GL_FUNC_ADD = 0x8006; public static final int GL_FUNC_REVERSE_SUBTRACT = 0x800B; public static final int GL_FUNC_SUBTRACT = 0x800A; public static final int GL_GENERATE_MIPMAP_HINT = 0x8192; public static final int GL_GEQUAL = 0x0206; public static final int GL_GREATER = 0x0204; public static final int GL_GREEN_BITS = 0x0D53; public static final int GL_HIGH_FLOAT = 0x8DF2; public static final int GL_HIGH_INT = 0x8DF5; public static final int GL_IMPLEMENTATION_COLOR_READ_FORMAT = 0x8B9B; public static final int GL_IMPLEMENTATION_COLOR_READ_TYPE = 0x8B9A; public static final int GL_INCR = 0x1E02; public static final int GL_INCR_WRAP = 0x8507; public static final int GL_INT = 0x1404; public static final int GL_INT_VEC2 = 0x8B53; public static final int GL_INT_VEC3 = 0x8B54; public static final int GL_INT_VEC4 = 0x8B55; public static final int GL_INVALID_ENUM = 0x0500; public static final int GL_INVALID_FRAMEBUFFER_OPERATION = 0x0506; public static final int GL_INVALID_OPERATION = 0x0502; public static final int GL_INVALID_VALUE = 0x0501; public static final int GL_INVERT = 0x150A; public static final int GL_KEEP = 0x1E00; public static final int GL_LEQUAL = 0x0203; public static final int GL_LESS = 0x0201; public static final int GL_LINEAR = 0x2601; public static final int GL_LINEAR_MIPMAP_LINEAR = 0x2703; public static final int GL_LINEAR_MIPMAP_NEAREST = 0x2701; public static final int GL_LINES = 0x0001; public static final int GL_LINE_LOOP = 0x0002; public static final int GL_LINE_STRIP = 0x0003; public static final int GL_LINE_WIDTH = 0x0B21; public static final int GL_LINK_STATUS = 0x8B82; public static final int GL_LOW_FLOAT = 0x8DF0; public static final int GL_LOW_INT = 0x8DF3; public static final int GL_LUMINANCE = 0x1909; public static final int GL_LUMINANCE_ALPHA = 0x190A; public static final int GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8B4D; public static final int GL_MAX_CUBE_MAP_TEXTURE_SIZE = 0x851C; public static final int GL_MAX_FRAGMENT_UNIFORM_VECTORS = 0x8DFD; public static final int GL_MAX_RENDERBUFFER_SIZE = 0x84E8; public static final int GL_MAX_TEXTURE_IMAGE_UNITS = 0x8872; public static final int GL_MAX_TEXTURE_SIZE = 0x8872; public static final int GL_MAX_VARYING_VECTORS = 0x8DFC; public static final int GL_MAX_VERTEX_ATTRIBS = 0x8869; public static final int GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8B4C; public static final int GL_MAX_VERTEX_UNIFORM_VECTORS = 0x8DFB; public static final int GL_MAX_VIEWPORT_DIMS = 0x0D3A; public static final int GL_MEDIUM_FLOAT = 0x8DF1; public static final int GL_MEDIUM_INT = 0x8DF4; public static final int GL_MIRRORED_REPEAT = 0x8370; public static final int GL_NEAREST = 0x2600; public static final int GL_NEAREST_MIPMAP_LINEAR = 0x2702; public static final int GL_NEAREST_MIPMAP_NEAREST = 0x2700; public static final int GL_NEVER = 0x0200; public static final int GL_NICEST = 0x1102; public static final int GL_NONE = 0x0000; public static final int GL_NOTEQUAL = 0x0205; public static final int GL_NOERROR = 0x0000; public static final int GL_ONE = 0x0001; public static final int GL_ONE_MINUS_CONSTANT_ALPHA = 0x8004; public static final int GL_ONE_MINUS_CONSTANT_COLOR = 0x8002; public static final int GL_ONE_MINUS_DST_ALPHA = 0x0305; public static final int GL_ONE_MINUS_DST_COLOR = 0x0307; public static final int GL_ONE_MINUS_SRC_ALPHA = 0x0303; public static final int GL_ONE_MINUS_SRC_COLOR = 0x0301; public static final int GL_OUT_OF_MEMORY = 0x0505; public static final int GL_PACK_ALIGNMENT = 0x0D05; public static final int GL_POINTS = 0x0000; public static final int GL_POLYGON_OFFSET_FACTOR = 0x8038; public static final int GL_POLYGON_OFFSET_FILL = 0x8037; public static final int GL_POLYGON_OFFSET_UNITS = 0x2A00; public static final int GL_RED_BITS = 0x0D52; public static final int GL_RENDERBUFFER = 0x8D41; public static final int GL_RENDERBUFFER_ALPHA_SIZE = 0x8D53; public static final int GL_RENDERBUFFER_BINDING = 0x8CA7; public static final int GL_RENDERBUFFER_BLUE_SIZE = 0x8D52; public static final int GL_RENDERBUFFER_DEPTH_SIZE = 0x8D54; public static final int GL_RENDERBUFFER_GREEN_SIZE = 0x8D51; public static final int GL_RENDERBUFFER_HEIGHT = 0x8D43; public static final int GL_RENDERBUFFER_INTERNAL_FORMAT = 0x8D44; public static final int GL_RENDERBUFFER_RED_SIZE = 0x8D50; public static final int GL_RENDERBUFFER_STENCIL_SIZE = 0x8D55; public static final int GL_RENDERBUFFER_WIDTH = 0x8D42; public static final int GL_RENDERER = 0x1F01; public static final int GL_REPEAT = 0x2901; public static final int GL_REPLACE = 0x1E01; public static final int GL_RGB = 0x1907; public static final int GL_RGB565 = 0x8D62; public static final int GL_RGB5_A1 = 0x8057; public static final int GL_RGBA = 0x1908; public static final int GL_RGBA4 = 0x8056; public static final int GL_SAMPLER_2D = 0x8B5E; public static final int GL_SAMPLER_CUBE = 0x8B60; public static final int GL_SAMPLES = 0x80A9; public static final int GL_SAMPLE_ALPHA_TO_COVERAGE = 0x809E; public static final int GL_SAMPLE_BUFFERS = 0x80A8; public static final int GL_SAMPLE_COVERAGE = 0x80A0; public static final int GL_SAMPLE_COVERAGE_INVERT = 0x80AB; public static final int GL_SAMPLE_COVERAGE_VALUE = 0x80AA; public static final int GL_SCISSOR_BOX = 0x0C10; public static final int GL_SCISSOR_TEST = 0x0C11; public static final int GL_SHADER_TYPE = 0x8B4F; public static final int GL_SHADING_LANGUAGE_VERSION = 0x8B8C; public static final int GL_SHORT = 0x1402; public static final int GL_SRC_ALPHA = 0x0302; public static final int GL_SRC_ALPHA_SATURATE = 0x0308; public static final int GL_SRC_COLOR = 0x0300; public static final int GL_STATIC_DRAW = 0x88E4; public static final int GL_STENCIL_ATTACHMENT = 0x8D20; public static final int GL_STENCIL_BACK_FAIL = 0x8801; public static final int GL_STENCIL_BACK_FUNC = 0x8800; public static final int GL_STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802; public static final int GL_STENCIL_BACK_PASS_DEPTH_PASS = 0x8803; public static final int GL_STENCIL_BACK_REF = 0x8CA3; public static final int GL_STENCIL_BACK_VALUE_MASK = 0x8CA4; public static final int GL_STENCIL_BACK_WRITEMASK = 0x8CA5; public static final int GL_STENCIL_BITS = 0x0D57; public static final int GL_STENCIL_BUFFER_BIT = 0x0400; public static final int GL_STENCIL_CLEAR_VALUE = 0x0B91; public static final int GL_STENCIL_FAIL = 0x0B94; public static final int GL_STENCIL_FUNC = 0x0B92; public static final int GL_STENCIL_INDEX = 0x1901; public static final int GL_STENCIL_INDEX8 = 0x8D48; public static final int GL_STENCIL_PASS_DEPTH_FAIL = 0x0B95; public static final int GL_STENCIL_PASS_DEPTH_PASS = 0x0B96; public static final int GL_STENCIL_REF = 0x0B97; public static final int GL_STENCIL_TEST = 0x0B90; public static final int GL_STENCIL_VALUE_MASK = 0x0B93; public static final int GL_STENCIL_WRITEMASK = 0x0B98; public static final int GL_STREAM_DRAW = 0x88E0; public static final int GL_SUBPIXEL_BITS = 0x0D50; public static final int GL_TEXTURE = 0x1702; public static final int GL_TEXTURE0 = 0x84C0; public static final int GL_TEXTURE1 = 0x84C1; public static final int GL_TEXTURE2 = 0x84C2; public static final int GL_TEXTURE3 = 0x84C3; public static final int GL_TEXTURE4 = 0x84C4; public static final int GL_TEXTURE5 = 0x84C5; public static final int GL_TEXTURE6 = 0x84C6; public static final int GL_TEXTURE7 = 0x84C7; public static final int GL_TEXTURE8 = 0x84C8; public static final int GL_TEXTURE9 = 0x84C9; public static final int GL_TEXTURE10 = 0x84CA; public static final int GL_TEXTURE11 = 0x84CB; public static final int GL_TEXTURE12 = 0x84CC; public static final int GL_TEXTURE13 = 0x84CD; public static final int GL_TEXTURE14 = 0x84CE; public static final int GL_TEXTURE15 = 0x84CF; public static final int GL_TEXTURE16 = 0x84D0; public static final int GL_TEXTURE17 = 0x84D1; public static final int GL_TEXTURE18 = 0x84D2; public static final int GL_TEXTURE19 = 0x84D3; public static final int GL_TEXTURE20 = 0x84D4; public static final int GL_TEXTURE21 = 0x84D5; public static final int GL_TEXTURE22 = 0x84D6; public static final int GL_TEXTURE23 = 0x84D7; public static final int GL_TEXTURE24 = 0x84D8; public static final int GL_TEXTURE25 = 0x84D9; public static final int GL_TEXTURE26 = 0x84DA; public static final int GL_TEXTURE27 = 0x84DB; public static final int GL_TEXTURE28 = 0x84DC; public static final int GL_TEXTURE29 = 0x84DD; public static final int GL_TEXTURE30 = 0x84DE; public static final int GL_TEXTURE31 = 0x84DF; public static final int GL_TEXTURE_2D = 0x0DE1; public static final int GL_TEXTURE_BINDING_2D = 0x8069; public static final int GL_TEXTURE_BINDING_CUBE_MAP = 0x8514; public static final int GL_TEXTURE_CUBE_MAP = 0x8513; public static final int GL_TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516; public static final int GL_TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518; public static final int GL_TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851A; public static final int GL_TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515; public static final int GL_TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517; public static final int GL_TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519; public static final int GL_TEXTURE_MAG_FILTER = 0x2800; public static final int GL_TEXTURE_MIN_FILTER = 0x2801; public static final int GL_TEXTURE_WRAP_S = 0x2802; public static final int GL_TEXTURE_WRAP_T = 0x2803; public static final int GL_TRIANGLES = 0x0004; public static final int GL_TRIANGLE_FAN = 0x0006; public static final int GL_TRIANGLE_STRIP = 0x0005; public static final int GL_UNPACK_ALIGNMENT = 0x0CF5; public static final int GL_UNPACK_COLORSPACE_CONVERSION_WEBGL = 0x9243; public static final int GL_UNPACK_FLIP_Y_WEBGL = 0x9240; public static final int GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL = 0x9241; public static final int GL_UNSIGNED_BYTE = 0x1401; public static final int GL_UNSIGNED_INT = 0x1405; public static final int GL_UNSIGNED_SHORT = 0x1403; public static final int GL_UNSIGNED_SHORT_4_4_4_4 = 0x8033; public static final int GL_UNSIGNED_SHORT_5_5_5_1 = 0x8034; public static final int GL_UNSIGNED_SHORT_5_6_5 = 0x8363; public static final int GL_VALIDATE_STATUS = 0x8B83; public static final int GL_VENDOR = 0x1F00; public static final int GL_VERSION = 0x1F02; public static final int GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889F; public static final int GL_VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622; public static final int GL_VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886A; public static final int GL_VERTEX_ATTRIB_ARRAY_POINTER = 0x8645; public static final int GL_VERTEX_ATTRIB_ARRAY_SIZE = 0x8623; public static final int GL_VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624; public static final int GL_VERTEX_ATTRIB_ARRAY_TYPE = 0x8625; public static final int GL_VERTEX_SHADER = 0x8B31; public static final int GL_VIEWPORT = 0x0BA2; public static final int GL_ZERO = 0x0000; /* Prevent instantiation */ private WebGL10() { } public static WebGLContext createContext(Canvas canvas) { return createContext(canvas.getCanvasElement()); } public static WebGLContext createContext(Canvas canvas, WebGLContext.Attributes attributes) { return createContext(canvas.getCanvasElement(), attributes); } public static WebGLContext createContext(CanvasElement canvas) { return createContext(canvas, null); } public static native boolean isSupported() /*-{ try { var canvas = $doc.createElement('canvas'); return !!( $wnd.WebGLRenderingContext && (canvas.getContext('webgl') || canvas.getContext('experimental-webgl'))); } catch (e) { $wnd.console.log(e); return false; } }-*/; public static boolean isContextCompatible() { return WebGLContext.getCurrent() != null && WebGLContext.getCurrent().getVersion() >= 1.0; } private static void checkContextCompatibility() { if (!isContextCompatible()) throw new IllegalStateException("The context should be created before invoking the GL functions"); } public static void glActiveTexture(int texture) { checkContextCompatibility(); nglActiveTexture(texture); } public static void glAttachShader(int programID, int shaderID) { checkContextCompatibility(); JavaScriptObject program = WebGLObjectMap.get().toProgram(programID); JavaScriptObject shader = WebGLObjectMap.get().toShader(shaderID); nglAttachShader(program, shader); } public static void glBindAttribLocation(int programID, int index, String name) { checkContextCompatibility(); nglBindAttribLocation(WebGLObjectMap.get().toProgram(programID), index, name); } public static void glBindBuffer(int target, int buffer) { checkContextCompatibility(); nglBindBuffer(target, WebGLObjectMap.get().toBuffer(buffer)); } public static void glBindFramebuffer(int target, int frameBuffer) { checkContextCompatibility(); nglBindFramebuffer(target, WebGLObjectMap.get().toFramebuffer(frameBuffer)); } public static void glBindRenderbuffer(int target, int renderBuffer) { checkContextCompatibility(); nglBindRenderbuffer(target, WebGLObjectMap.get().toRenderBuffer(renderBuffer)); } public static void glBindTexture(int target, int textureID) { checkContextCompatibility(); nglBindTexture(target, WebGLObjectMap.get().toTexture(textureID)); } public static void glBlendColor(float r, float g, float b, float a) { checkContextCompatibility(); nglBlendColor(r, g, b, a); } public static void glBlendEquation(int mode) { checkContextCompatibility(); nglBlendEquation(mode); } public static void glBlendEquationSeparate(int modeRGB, int modeAlpha) { checkContextCompatibility(); nglBlendEquationSeparate(modeRGB, modeAlpha); } public static void glBlendFunc(int srcFactor, int dstFactor) { checkContextCompatibility(); nglBlendFunc(srcFactor, dstFactor); } public static void glBlendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) { checkContextCompatibility(); nglBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha); } public static void glBufferData(int target, float[] data, int usage) { checkContextCompatibility(); nglBufferData(target, data, usage); } public static void glBufferData(int target, int[] data, int usage) { checkContextCompatibility(); nglBufferData(target, data, usage); } public static void glBufferData(int target, short[] data, int usage) { checkContextCompatibility(); nglBufferData(target, data, usage); } public static void glBufferData(int target, ArrayBufferView data, int usage) { checkContextCompatibility(); nglBufferData(target, data, usage); } public static void glBufferSubData(int target, int offset, long size, float[] data) { checkContextCompatibility(); nglBufferSubData(target, offset, size, data); } public static void glBufferSubData(int target, int offset, long size, int[] data) { checkContextCompatibility(); nglBufferSubData(target, offset, size, data); } public static void glBufferSubData(int target, int offset, long size, short[] data) { checkContextCompatibility(); nglBufferSubData(target, offset, size, data); } public static void glBufferSubData(int target, int offset, long size, ArrayBufferView data) { checkContextCompatibility(); nglBufferSubData(target, offset, size, data); } public static int glCheckFramebufferStatus(int target) { checkContextCompatibility(); return nglCheckFramebufferStatus(target); } public static void glClear(int masks) { checkContextCompatibility(); nglClear(masks); } public static void glClearColor(float r, float g, float b, float a) { checkContextCompatibility(); nglClearColor(r, g, b, a); } public static void glClearDepth(float depth) { checkContextCompatibility(); nglClearDepth(depth); } public static void glClearStencil(int stencil) { checkContextCompatibility(); nglClearStencil(stencil); } public static void glColorMask(boolean red, boolean green, boolean blue, boolean alpha) { checkContextCompatibility(); nglColorMask(red, green, blue, alpha); } public static void glCompileShader(int shaderID) { checkContextCompatibility(); nglCompileShader(WebGLObjectMap.get().toShader(shaderID)); } public static void glCompressedTexImage2D(int target, int level, int internalFormat, int border, long imageSize, Image image) { glCompressedTexImage2D(target, level, internalFormat, border, imageSize, image.getElement()); } public static void glCompressedTexImage2D(int target, int level, int internalFormat, long width, long height, int border, long imageSize, ArrayBufferView pixels) { checkContextCompatibility(); nglCompressedTexImage2D(target, level, internalFormat, width, height, border, imageSize, pixels); } public static void glCompressedTexImage2D(int target, int level, int internalFormat, int border, long imageSize, JavaScriptObject JavaScriptObject) { checkContextCompatibility(); nglCompressedTexImage2D(target, level, internalFormat,border, imageSize, JavaScriptObject); } public static void glCompressedTexSubImage2D(int target, int level, int xOffset, int yOffset, int format, long imageSize, Image image) { glCompressedTexSubImage2D(target, level, xOffset, yOffset, format, imageSize, image.getElement()); } public static void glCompressedTexSubImage2D(int target, int level, int xOffset, int yOffset, int format, long imageSize, JavaScriptObject data) { checkContextCompatibility(); nglCompressedTexSubImage2D(target, level, xOffset, yOffset, format, imageSize, data); } public static void glCompressedTexSubImage2D(int target, int level, int xOffset, int yOffset, long width, long height, int format, long imageSize, ArrayBufferView data) { checkContextCompatibility(); nglCompressedTexSubImage2D(target, level, xOffset, yOffset, width, height, format, imageSize, data); } public static void glCopyTexImage2D(int target, int level, int internalFormat, int x, int y, long width, long height, int border) { checkContextCompatibility(); nglCopyTexImage2D(target, level, internalFormat, x, y, width, height, border); } public static void glCopyTexSubImage2D(int target, int level, int xOffset, int yOffset, int x, int y, long width, long height) { checkContextCompatibility(); nglCopyTexSubImage2D(target, level, xOffset, yOffset, x, y, width, height); } public static int glCreateBuffer() { checkContextCompatibility(); return WebGLObjectMap.get().createBuffer(nglCreateBuffer()); } public static int glCreateFramebuffer() { checkContextCompatibility(); return WebGLObjectMap.get().createFramebuffer(nglCreateFramebuffer()); } public static int glCreateProgram() { checkContextCompatibility(); return WebGLObjectMap.get().createProgram(nglCreateProgram()); } public static int glCreateRenderbuffer() { checkContextCompatibility(); return WebGLObjectMap.get().createRenderBuffer(nglCreateRenderbuffer()); } public static int glCreateShader(int type) { checkContextCompatibility(); return WebGLObjectMap.get().createShader(nglCreateShader(type)); } public static int glCreateTexture() { checkContextCompatibility(); return WebGLObjectMap.get().createTexture(nglCreateTexture()); } public static void glCullFace(int mode) { checkContextCompatibility(); nglCullFace(mode); } public static void glDeleteBuffer(int bufferID) { checkContextCompatibility(); nglDeleteBuffer(WebGLObjectMap.get().toBuffer(bufferID)); WebGLObjectMap.get().deleteBuffer(bufferID); } public static void glDeleteFramebuffer(int frameBufferID) { checkContextCompatibility(); nglDeleteFramebuffer(WebGLObjectMap.get().toFramebuffer(frameBufferID)); WebGLObjectMap.get().deleteFramebuffer(frameBufferID); } public static void glDeleteProgram(int programID) { checkContextCompatibility(); nglDeleteProgram(WebGLObjectMap.get().toProgram(programID)); WebGLObjectMap.get().deleteProgram(programID); } public static void glDeleteRenderbuffer(int renderBufferID) { checkContextCompatibility(); nglDeleteRenderbuffer(WebGLObjectMap.get().toRenderBuffer(renderBufferID)); WebGLObjectMap.get().deleteRenderBuffer(renderBufferID); } public static void glDeleteShader(int shaderID) { checkContextCompatibility(); nglDeleteShader(WebGLObjectMap.get().toShader(shaderID)); WebGLObjectMap.get().deleteShader(shaderID); } public static void glDeleteTexture(int textureID) { checkContextCompatibility(); nglDeleteTexture(WebGLObjectMap.get().toTexture(textureID)); WebGLObjectMap.get().deleteTexture(textureID); } public static void glDepthFunc(int func) { checkContextCompatibility(); nglDepthFunc(func); } public static void glDepthMask(boolean flag) { checkContextCompatibility(); nglDepthMask(flag); } public static void glDepthRange(double nearVal, double farVal) { checkContextCompatibility(); nglDepthRange(nearVal, farVal); } public static void glDetachShader(int programID, int shaderID) { checkContextCompatibility(); nglDetachShader(WebGLObjectMap.get().toProgram(programID), WebGLObjectMap.get().toShader(shaderID)); } public static void glDisable(int disableCap) { checkContextCompatibility(); nglDisable(disableCap); } public static void glDisableVertexAttribArray(int index) { checkContextCompatibility(); nglDisableVertexAttribArray(index); } public static void glDrawArrays(int mode, int first, int count) { checkContextCompatibility(); nglDrawArrays(mode, first, count); } public static void glDrawElements(int mode, int count, int type, int offset) { checkContextCompatibility(); nglDrawElements(mode, count, type, offset); } public static void glEnable(int enableCap) { checkContextCompatibility(); nglEnable(enableCap); } public static void glEnableVertexAttribArray(int index) { checkContextCompatibility(); nglEnableVertexAttribArray(index); } public static void glFinish() { checkContextCompatibility(); nglFinish(); } public static void glFlush() { checkContextCompatibility(); nglFlush(); } public static void glFramebufferRenderbuffer(int target, int attachment, int renderbufferTarget, int renderBuffer) { checkContextCompatibility(); nglFramebufferRenderbuffer(target, attachment, renderbufferTarget, WebGLObjectMap.get().toRenderBuffer(renderBuffer)); } public static void glFramebufferTexture2D(int target, int attachment, int textureTarget, int texture, int level) { checkContextCompatibility(); nglFramebufferTexture2D(target, attachment, textureTarget, WebGLObjectMap.get().toTexture(texture), level); } public static void glFrontFace(int mode) { checkContextCompatibility(); nglFrontFace(mode); } public static void glGenerateMipmap(int target) { checkContextCompatibility(); nglGenerateMipmap(target); } public static ActiveInfo glGetActiveAttrib(int programID, int index) { checkContextCompatibility(); return nglGetActiveAttrib(WebGLObjectMap.get().toProgram(programID), index); } public static ActiveInfo glGetActiveUniform(int programID, int index) { checkContextCompatibility(); return nglGetActiveUniform(WebGLObjectMap.get().toProgram(programID), index); } public static int[] glGetAttachedShaders(int programID) { checkContextCompatibility(); JavaScriptObject[] nativeArray = nglGetAttachedShaders(WebGLObjectMap.get().toProgram(programID)); int[] transformedArray = new int[nativeArray.length]; for (int i = 0; i < nativeArray.length; i++) transformedArray[i] = WebGLObjectMap.get().createShader(nativeArray[i]); return transformedArray; } public static int glGetAttribLocation(int programID, String name) { checkContextCompatibility(); return nglGetAttribLocation(WebGLObjectMap.get().toProgram(programID), name); } public static Element glGetCanvas() { checkContextCompatibility(); return nglGetCanvas(); } public static WebGLContext.Attributes glGetContextAttributes() { checkContextCompatibility(); return nglGetContextAttributes(); } public static int glGetDrawingBufferHeight() { checkContextCompatibility(); return nglGetDrawingBufferHeight(); } public static int glGetDrawingBufferWidth() { checkContextCompatibility(); return nglGetDrawingBufferWidth(); } public static int glGetError() { checkContextCompatibility(); return nglGetError(); } public static JavaScriptObject glGetExtension(String name) { checkContextCompatibility(); return nglGetExtension(name); } public static int glGetFramebufferAttachmentParameter(int target, int attachment, int pname) { checkContextCompatibility(); return nglGetFramebufferAttachmentParameter(target, attachment, pname); } public static <T extends JavaScriptObject> T glGetParameter(int pname) { checkContextCompatibility(); return nglGetParameter(pname); } public static int glGetParameteri(int pname) { checkContextCompatibility(); return nglGetParameteri(pname); } public static boolean glGetParameterb(int pname) { checkContextCompatibility(); return nglGetParameterb(pname); } public static int[] glGetParameterii(int pname) { checkContextCompatibility(); return nglGetParameterii(pname); } public static float[] glGetParameterff(int pname) { checkContextCompatibility(); return nglGetParameterff(pname); } public static boolean[] glGetParameterbb(int pname) { checkContextCompatibility(); return nglGetParameterbb(pname); } public static String glGetParameters(int pname) { checkContextCompatibility(); return nglGetParameters(pname); } public static String glGetProgramInfoLog(int programID) { checkContextCompatibility(); return nglGetProgramInfoLog(WebGLObjectMap.get().toProgram(programID)); } public static int glGetProgramParameteri(int programID, int pname) { checkContextCompatibility(); return nglGetProgramParameteri(WebGLObjectMap.get().toProgram(programID), pname); } public static boolean glGetProgramParameterb(int programID, int pname) { checkContextCompatibility(); return nglGetProgramParameterb(WebGLObjectMap.get().toProgram(programID), pname); } public static int glGetRenderbufferParameter(int target, int pname) { checkContextCompatibility(); return nglGetRenderbufferParameter(target, pname); } public static String glGetShaderInfoLog(int shaderID) { checkContextCompatibility(); return nglGetShaderInfoLog(WebGLObjectMap.get().toShader(shaderID)); } public static int glGetShaderParameteri(int shaderID, int pname) { checkContextCompatibility(); return nglGetShaderParameteri(WebGLObjectMap.get().toShader(shaderID), pname); } public static boolean glGetShaderParameterb(int shaderID, int pname) { checkContextCompatibility(); return nglGetShaderParameterb(WebGLObjectMap.get().toShader(shaderID), pname); } public static ShaderPrecisionFormat glGetShaderPrecisionFormat(int shaderType, int precisionType) { checkContextCompatibility(); return nglGetShaderPrecisionFormat(shaderType, precisionType); } public static String glGetShaderSource(int shaderID) { checkContextCompatibility(); return nglGetShaderSource(WebGLObjectMap.get().toShader(shaderID)); } public static String[] glGetSupportedExtensions() { checkContextCompatibility(); return nglGetSupportedExtensions(); } public static int glGetTexParameter(int textureID, int pname) { checkContextCompatibility(); return nglGetTexParameter(WebGLObjectMap.get().toTexture(textureID), pname); } public static boolean glGetUniformb(int programID, int location) { return glGetUniformbv(programID, location)[0]; } public static boolean[] glGetUniformbv(int programID, int location) { checkContextCompatibility(); return nglGetUniformbv(WebGLObjectMap.get().toProgram(programID), WebGLObjectMap.get().toUniform(programID, location)); } public static float glGetUniformf(int programID, int location) { return glGetUniformfv(programID, location)[0]; } public static float[] glGetUniformfv(int programID, int location) { checkContextCompatibility(); return nglGetUniformfv(WebGLObjectMap.get().toProgram(programID), WebGLObjectMap.get().toUniform(programID, location)); } public static int glGetUniformi(int programID, int location) { return glGetUniformiv(programID, location)[0]; } public static int[] glGetUniformiv(int programID, int location) { checkContextCompatibility(); return nglGetUniformiv(WebGLObjectMap.get().toProgram(programID), WebGLObjectMap.get().toUniform(programID, location)); } public static int glGetUniformLocation(int programID, String name) { checkContextCompatibility(); return WebGLObjectMap.get().createUniform(nglGetUniformLocation(WebGLObjectMap.get().toProgram(programID), name)); } public static boolean glGetVertexAttribb(int index, int pname) { checkContextCompatibility(); return nglGetVertexAttribb(index, pname); } public static float glGetVertexAttribf(int index, int pname) { return glGetVertexAttribfv(index, pname)[0]; } public static float[] glGetVertexAttribfv(int index, int pname) { checkContextCompatibility(); return nglGetVertexAttribfv(index, pname); } public static int glGetVertexAttribi(int index, int pname) { checkContextCompatibility(); return nglGetVertexAttribi(index, pname); } public static int glGetVertexAttribOffset(int index, int pname) { checkContextCompatibility(); return nglGetVertexAttribOffset(index, pname); } public static void glHint(int target, int mode) { checkContextCompatibility(); nglHint(target, mode); } public static boolean glIsBuffer(int bufferID) { checkContextCompatibility(); return nglIsBuffer(WebGLObjectMap.get().toBuffer(bufferID)); } public static boolean glIsContextLost() { checkContextCompatibility(); return nglIsContextLost(); } public static boolean glIsEnabled(int enableCap) { checkContextCompatibility(); return nglIsEnabled(enableCap); } public static boolean glIsFramebuffer(int framebufferID) { checkContextCompatibility(); return nglIsFramebuffer(WebGLObjectMap.get().toFramebuffer(framebufferID)); } public static boolean glIsProgram(int programID) { checkContextCompatibility(); return nglIsProgram(WebGLObjectMap.get().toProgram(programID)); } public static boolean glIsRenderbuffer(int renderbufferID) { checkContextCompatibility(); return nglIsRenderbuffer(WebGLObjectMap.get().toRenderBuffer(renderbufferID)); } public static boolean glIsShader(int shaderID) { checkContextCompatibility(); return nglIsShader(WebGLObjectMap.get().toShader(shaderID)); } public static boolean glIsTexture(int textureID) { checkContextCompatibility(); return nglIsTexture(WebGLObjectMap.get().toTexture(textureID)); } public static void glLineWidth(int width) { checkContextCompatibility(); nglLineWidth(width); } public static void glLinkProgram(int programID) { checkContextCompatibility(); nglLinkProgram(WebGLObjectMap.get().toProgram(programID)); } public static void glPixelStorei(int pname, int param) { checkContextCompatibility(); nglPixelStorei(pname, param); } public static void glPolygonOffset(double factor, double units) { checkContextCompatibility(); nglPolygonOffset(factor, units); } public static void glReadPixels(int x, int y, int w, int h, int format, int type, ArrayBufferView pixels) { checkContextCompatibility(); nglReadPixels(x, y, w, h, format, type, pixels); } public static void glRenderbufferStorage(int target, int internalFormat, int width, int height) { checkContextCompatibility(); nglRenderbufferStorage(target, internalFormat, width, height); } public static void glSampleCoverage(float value, boolean invert) { checkContextCompatibility(); nglSampleCoverage(value, invert); } public static void glScissor(int x, int y, int w, int h) { checkContextCompatibility(); nglScissor(x, y, w, h); } public static void glShaderSource(int shaderID, String source) { checkContextCompatibility(); nglShaderSource(WebGLObjectMap.get().toShader(shaderID), source); } public static void glStencilFunc(int func, int ref, int mask) { checkContextCompatibility(); nglStencilFunc(func, ref, mask); } public static void glStencilFuncSeparate(int face, int func, int ref, int mask) { checkContextCompatibility(); nglStencilFuncSeparate(face, func, ref, mask); } public static void glStencilMask(int mask) { checkContextCompatibility(); nglStencilMask(mask); } public static void glStencilMaskSeparate(int face, int mask) { checkContextCompatibility(); nglStencilMaskSeparate(face, mask); } public static void glStencilOp(int sFail, int dpFail, int dpPass) { checkContextCompatibility(); nglStencilOp(sFail, dpFail, dpPass); } public static void glStencilOpSeparate(int face, int fail, int zFail, int zPass) { checkContextCompatibility(); nglStencilOpSeparate(face, fail, zFail, zPass); } public static void glTexImage2D(int target, int level, int internalFormat, int format, int type, Image pixels) { checkContextCompatibility(); nglTexImage2D(target, level, internalFormat, format, type, pixels.getElement()); } public static void glTexImage2D(int target, int level, int internalFormat, int format, int type, ImageData pixels) { checkContextCompatibility(); nglTexImage2D(target, level, internalFormat, format, type, pixels); } public static void glTexImage2D(int target, int level, int internalFormat, int width, int height, int border, int format, int type, ArrayBufferView pixels) { checkContextCompatibility(); nglTexImage2D(target, level, internalFormat, width, height, border, format, type, pixels); } public static void glTexImage2D(int target, int level, int internalFormat, int format, int type, JavaScriptObject pixels) { checkContextCompatibility(); nglTexImage2D(target, level, internalFormat, format, type, pixels); } public static void glTexParameterf(int target, int pname, float value) { checkContextCompatibility(); nglTexParameterf(target, pname, value); } public static void glTexParameteri(int target, int pname, int value) { checkContextCompatibility(); nglTexParameteri(target, pname, value); } public static void glTexSubImage2D(int target, int level, int xOffset, int yOffset, int width, int height, int format, int type, ArrayBufferView pixels) { checkContextCompatibility(); nglTexSubImage2D(target, level, xOffset, yOffset, width, height, format, type, pixels); } public static void glTexSubImage2D(int target, int level, int xOffset, int yOffset, int width, int height, int format, int type, JavaScriptObject pixels) { checkContextCompatibility(); nglTexSubImage2D(target, level, xOffset, yOffset, width, height, format, type, pixels); } public static void glTexSubImage2D(int target, int level, int xOffset, int yOffset, int width, int height, int format, int type, Image pixels) { glTexSubImage2D(target, level, xOffset, yOffset, width, height, format, type, pixels.getElement()); } public static void glTexSubImage2D(int target, int level, int xOffset, int yOffset, int width, int height, int format, int type, ImageData pixels) { glTexSubImage2D(target, level, xOffset, yOffset, width, height, format, type, (JavaScriptObject) pixels); } public static void glTexSubImage2D(int target, int level, int xOffset, int yOffset, int width, int height, int format, int type, Canvas pixels) { glTexSubImage2D(target, level, xOffset, yOffset, width, height, format, type, pixels.getElement()); } public static void glUniform1f(int location, float x) { checkContextCompatibility(); nglUniform1f(WebGLObjectMap.get().toUniform(location), x); } public static void glUniform1fv(int location, Float32Array x) { checkContextCompatibility(); nglUniform1fv(WebGLObjectMap.get().toUniform(location), x); } public static void glUniform1i(int location, int x) { checkContextCompatibility(); nglUniform1i(WebGLObjectMap.get().toUniform(location), x); } public static void glUniform1iv(int location, Int32Array x) { checkContextCompatibility(); nglUniform1iv(WebGLObjectMap.get().toUniform(location), x); } public static void glUniform2f(int location, float x, float y) { checkContextCompatibility(); nglUniform2f(WebGLObjectMap.get().toUniform(location), x, y); } public static void glUniform2fv(int location, Float32Array xy) { checkContextCompatibility(); nglUniform2fv(WebGLObjectMap.get().toUniform(location), xy); } public static void glUniform2i(int location, int x, int y) { checkContextCompatibility(); nglUniform2i(WebGLObjectMap.get().toUniform(location), x, y); } public static void glUniform2iv(int location, Int32Array xy) { checkContextCompatibility(); nglUniform2iv(WebGLObjectMap.get().toUniform(location), xy); } public static void glUniform3f(int location, float x, float y, float z) { checkContextCompatibility(); nglUniform3f(WebGLObjectMap.get().toUniform(location), x, y, z); } public static void glUniform3fv(int location, Float32Array xy) { checkContextCompatibility(); nglUniform3fv(WebGLObjectMap.get().toUniform(location), xy); } public static void glUniform3i(int location, int x, int y, int z) { checkContextCompatibility(); nglUniform3i(WebGLObjectMap.get().toUniform(location), x, y, z); } public static void glUniform3iv(int location, Int32Array xy) { checkContextCompatibility(); nglUniform3iv(WebGLObjectMap.get().toUniform(location), xy); } public static void glUniform4f(int location, float x, float y, float z, float w) { checkContextCompatibility(); nglUniform4f(WebGLObjectMap.get().toUniform(location), x, y, z, w); } public static void glUniform4fv(int location, Float32Array xy) { checkContextCompatibility(); nglUniform4fv(WebGLObjectMap.get().toUniform(location), xy); } public static void glUniform4i(int location, int x, int y, int z, int w) { checkContextCompatibility(); nglUniform4i(WebGLObjectMap.get().toUniform(location), x, y, z, w); } public static void glUniform4iv(int location, Int32Array xy) { checkContextCompatibility(); nglUniform4iv(WebGLObjectMap.get().toUniform(location), xy); } public static void glUniformMatrix2fv(int location, boolean transpose, float[] value) { Float32Array array = TypedArrays.createFloat32Array(value.length); array.set(value); glUniformMatrix2fv(location, transpose, array); } public static void glUniformMatrix2fv(int location, boolean transpose, Float32Array value) { checkContextCompatibility(); nglUniformMatrix2fv(WebGLObjectMap.get().toUniform(location), transpose, value); } public static void glUniformMatrix3fv(int location, boolean transpose, float[] value) { Float32Array array = TypedArrays.createFloat32Array(value.length); array.set(value); glUniformMatrix3fv(location, transpose, array); } public static void glUniformMatrix3fv(int location, boolean transpose, Float32Array value) { checkContextCompatibility(); nglUniformMatrix3fv(WebGLObjectMap.get().toUniform(location), transpose, value); } public static void glUniformMatrix4fv(int location, boolean transpose, float[] value) { Float32Array array = TypedArrays.createFloat32Array(value.length); array.set(value); glUniformMatrix4fv(location, transpose, array); } public static void glUniformMatrix4fv(int location, boolean transpose, Float32Array value) { checkContextCompatibility(); nglUniformMatrix4fv(WebGLObjectMap.get().toUniform(location), transpose, value); } public static void glUseProgram(int programID) { checkContextCompatibility(); WebGLObjectMap.get().currentProgram = programID; nglUseProgram(WebGLObjectMap.get().toProgram(programID)); } public static void glValidateProgram(int programID) { checkContextCompatibility(); nglValidateProgram(WebGLObjectMap.get().toProgram(programID)); } public static void glVertexAttribPointer(int index, int size, int type, boolean normalized, long stride, long offset) { checkContextCompatibility(); nglVertexAttribPointer(index, size, type, normalized, stride, offset); } public static void glVertexAttrib1f(int index, float x) { checkContextCompatibility(); nglVertexAttrib1f(index, x); } public static void glVertexAttrib1fv(int index, ArrayBufferView values) { checkContextCompatibility(); nglVertexAttrib1fv(index, values); } public static void glVertexAttrib1fv(int index, JavaScriptObject values) { checkContextCompatibility(); nglVertexAttrib1fv(index, values); } public static void glVertexAttrib1fv(int index, float[] values) { Float32Array float32Array = TypedArrays.createFloat32Array(values.length); float32Array.set(values); glVertexAttrib1fv(index, float32Array); } public static void glVertexAttrib2f(int index, float x, float y) { checkContextCompatibility(); nglVertexAttrib2f(index, x, y); } public static void glVertexAttrib2fv(int index, ArrayBufferView values) { checkContextCompatibility(); nglVertexAttrib2fv(index, values); } public static void glVertexAttrib2fv(int index, JavaScriptObject values) { checkContextCompatibility(); nglVertexAttrib2fv(index, values); } public static void glVertexAttrib2fv(int index, float[] values) { Float32Array float32Array = TypedArrays.createFloat32Array(values.length); float32Array.set(values); glVertexAttrib2fv(index, float32Array); } public static void glVertexAttrib3f(int index, float x, float y, float z) { checkContextCompatibility(); nglVertexAttrib3f(index, x, y, z); } public static void glVertexAttrib3fv(int index, ArrayBufferView values) { checkContextCompatibility(); nglVertexAttrib3fv(index, values); } public static void glVertexAttrib3fv(int index, JavaScriptObject values) { checkContextCompatibility(); nglVertexAttrib3fv(index, values); } public static void glVertexAttrib3fv(int index, float[] values) { Float32Array float32Array = TypedArrays.createFloat32Array(values.length); float32Array.set(values); glVertexAttrib3fv(index, float32Array); } public static void glVertexAttrib4f(int index, float x, float y, float z, float w) { checkContextCompatibility(); nglVertexAttrib4f(index, x, y, z, w); } public static void glVertexAttrib4fv(int index, ArrayBufferView values) { checkContextCompatibility(); nglVertexAttrib4fv(index, values); } public static void glVertexAttrib4fv(int index, JavaScriptObject values) { checkContextCompatibility(); nglVertexAttrib4fv(index, values); } public static void glVertexAttrib4fv(int index, float[] values) { Float32Array float32Array = TypedArrays.createFloat32Array(values.length); float32Array.set(values); glVertexAttrib4fv(index, float32Array); } public static void glViewport(int x, int y, int w, int h) { checkContextCompatibility(); nglViewport(x, y, w, h); } private static native void nglActiveTexture(int texture) /*-{ $wnd.gl.activeTexture(texture); }-*/; private static native int nglAttachShader(JavaScriptObject programID, JavaScriptObject shaderID) /*-{ $wnd.gl.attachShader(programID, shaderID); }-*/; private static native void nglBindAttribLocation(JavaScriptObject programID, int index, String name) /*-{ $wnd.gl.bindAttribLocation(programID, index, name); }-*/; private static native void nglBindBuffer(int target, JavaScriptObject buffer) /*-{ if (buffer == 0) buffer = null; $wnd.gl.bindBuffer(target, buffer); }-*/; private static native void nglBindFramebuffer(int target, JavaScriptObject frameBuffer) /*-{ if (frameBuffer == 0) frameBuffer = null; $wnd.gl.bindFramebuffer(target, frameBuffer); }-*/; private static native void nglBindRenderbuffer(int target, JavaScriptObject renderBuffer) /*-{ if (renderBuffer == 0) renderBuffer = null; $wnd.gl.bindRenderbuffer(target, renderBuffer); }-*/; private static native void nglBindTexture(int target, JavaScriptObject textureID) /*-{ if (textureID == 0) textureID = null; $wnd.gl.bindTexture(target, textureID); }-*/; private static native void nglBlendColor(float r, float g, float b, float a) /*-{ $wnd.gl.blendColor(r, g, b, a); }-*/; private static native void nglBlendEquation(int mode) /*-{ $wnd.gl.blendEquation(mode); }-*/; private static native void nglBlendEquationSeparate(int modeRGB, int modeAlpha) /*-{ $wnd.gl.blendEquationSeparate(modeRGB, modeAlpha); }-*/; private static native void nglBlendFunc(int srcFactor, int dstFactor) /*-{ $wnd.gl.blendFunc(srcFactor, dstFactor); }-*/; private static native void nglBlendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) /*-{ $wnd.gl.blendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha); }-*/; private static native void nglBufferData(int target, float[] data, int usage) /*-{ $wnd.gl.bufferData(target, new Float32Array(data), usage); }-*/; private static native void nglBufferData(int target, int[] data, int usage) /*-{ $wnd.gl.bufferData(target, new Int32Array(data), usage); }-*/; private static native void nglBufferData(int target, short[] data, int usage) /*-{ $wnd.gl.bufferData(target, new Int16Array(data), usage); }-*/; private static native void nglBufferData(int target, ArrayBufferView data, int usage) /*-{ $wnd.gl.bufferData(target, data, usage); }-*/; private static native void nglBufferSubData(int target, int offset, double size, float[] data) /*-{ $wnd.gl.bufferSubData(target, offset, size, new Float32Array(data)); }-*/; private static native void nglBufferSubData(int target, int offset, double size, int[] data) /*-{ $wnd.gl.bufferSubData(target, offset, size, new Int32Array(data)); }-*/; private static native void nglBufferSubData(int target, int offset, double size, short[] data) /*-{ $wnd.gl.bufferSubData(target, offset, size, new Int16Array(data)); }-*/; private static native void nglBufferSubData(int target, int offset, double size, ArrayBufferView data) /*-{ $wnd.gl.bufferSubData(target, offset, size, data); }-*/; private static native int nglCheckFramebufferStatus(int target) /*-{ return $wnd.gl.checkFramebufferStatus(target); }-*/; private static native void nglClear(int masks) /*-{ $wnd.gl.clear(masks); }-*/; private static native void nglClearColor(float r, float g, float b, float a) /*-{ $wnd.gl.clearColor(r, g, b, a); }-*/; private static native void nglClearDepth(float depth) /*-{ $wnd.gl.clearDepth(depth); }-*/; private static native void nglClearStencil(int stencil) /*-{ $wnd.gl.clearStencil(stencil); }-*/; private static native void nglColorMask(boolean red, boolean green, boolean blue, boolean alpha) /*-{ $wnd.gl.colorMask(red, green, blue, alpha); }-*/; private static native void nglCompileShader(JavaScriptObject shaderID) /*-{ $wnd.gl.compileShader(shaderID); }-*/; private static native void nglCompressedTexImage2D(int target, int level, int internalFormat, int border, double imageSize, JavaScriptObject JavaScriptObject) /*-{ $wnd.gl.compressedTexImage2D(target, level, internalFormat, border, imageSize, JavaScriptObject); }-*/; private static native void nglCompressedTexImage2D(int target, int level, int internalFormat, double width, double height, int border, double imageSize, ArrayBufferView pixels) /*-{ $wnd.gl.compressedTexImage2D(target, level, internalFormat, width, height, border, imageSize, pixels); }-*/; private static native void nglCompressedTexSubImage2D(int target, int level, int xOffset, int yOffset, int format, double imageSize, JavaScriptObject data) /*-{ $wnd.gl.compressedTexSubImage2D(target, level, xOffset, yOffset, format, imageSize, data); }-*/; private static native void nglCompressedTexSubImage2D(int target, int level, int xOffset, int yOffset, double width, double height, int format, double imageSize, ArrayBufferView data) /*-{ $wnd.gl.compressedTexSubImage2D(target, level, xOffset, yOffset, width, height, format, imageSize, data); }-*/; private static native void nglCopyTexImage2D(int target, int level, int internalFormat, int x, int y, double width, double height, int border) /*-{ $wnd.gl.copyTexImage2D(target, level, internalFormat, x, y, width, height, border); }-*/; private static native void nglCopyTexSubImage2D(int target, int level, int xOffset, int yOffset, int x, int y, double width, double height) /*-{ $wnd.gl.copyTexSubImage2D(target, level, xOffset, yOffset, x, y, width, height); }-*/; private static native JavaScriptObject nglCreateBuffer() /*-{ return $wnd.gl.createBuffer(); }-*/; private static native JavaScriptObject nglCreateFramebuffer() /*-{ return $wnd.gl.createFramebuffer(); }-*/; private static native JavaScriptObject nglCreateProgram() /*-{ return $wnd.gl.createProgram(); }-*/; private static native JavaScriptObject nglCreateRenderbuffer() /*-{ return $wnd.gl.createRenderbuffer(); }-*/; private static native JavaScriptObject nglCreateShader(int type) /*-{ return $wnd.gl.createShader(type); }-*/; private static native JavaScriptObject nglCreateTexture() /*-{ return $wnd.gl.createTexture(); }-*/; private static native void nglCullFace(int mode) /*-{ $wnd.gl.cullFace(mode); }-*/; private static native void nglDeleteBuffer(JavaScriptObject bufferID) /*-{ $wnd.gl.deleteBuffer(bufferID); }-*/; private static native void nglDeleteFramebuffer(JavaScriptObject frameBufferID) /*-{ $wnd.gl.deleteFramebuffer(frameBufferID); }-*/; private static native void nglDeleteProgram(JavaScriptObject programID) /*-{ $wnd.gl.deleteProgram(programID); }-*/; private static native void nglDeleteRenderbuffer(JavaScriptObject renderBufferID) /*-{ $wnd.gl.deleteRenderbuffer(renderBufferID); }-*/; private static native void nglDeleteShader(JavaScriptObject shaderID) /*-{ $wnd.gl.deleteShader(shaderID); }-*/; private static native void nglDeleteTexture(JavaScriptObject textureID) /*-{ $wnd.gl.deleteTexture(textureID); }-*/; private static native void nglDepthFunc(int func) /*-{ $wnd.gl.depthFunc(func); }-*/; private static native void nglDepthMask(boolean flag) /*-{ $wnd.gl.depthMask(flag); }-*/; private static native void nglDepthRange(double nearVal, double farVal) /*-{ $wnd.gl.depthRange(nearVal, farVal); }-*/; private static native void nglDetachShader(JavaScriptObject programID, JavaScriptObject shaderID) /*-{ $wnd.gl.detachShader(programID, shaderID); }-*/; private static native void nglDisable(int disableCap) /*-{ $wnd.gl.disable(disableCap); }-*/; private static native void nglDisableVertexAttribArray(int index) /*-{ $wnd.gl.disableVertexAttribArray(index); }-*/; private static native void nglDrawArrays(int mode, int first, int count) /*-{ $wnd.gl.drawArrays(mode, first, count); }-*/; private static native void nglDrawElements(int mode, int count, int type, int offset) /*-{ $wnd.gl.drawElements(mode, count, type, offset); }-*/; private static native void nglEnable(int enableCap) /*-{ $wnd.gl.enable(enableCap); }-*/; private static native void nglEnableVertexAttribArray(int index) /*-{ $wnd.gl.enableVertexAttribArray(index); }-*/; private static native void nglFinish() /*-{ $wnd.gl.finish(); }-*/; private static native void nglFlush() /*-{ $wnd.gl.flush(); }-*/; private static native void nglFramebufferRenderbuffer(int target, int attachment, int renderbufferTarget, JavaScriptObject renderBuffer) /*-{ $wnd.gl.framebufferRenderbuffer(target, attachment, renderbufferTarget, renderBuffer); }-*/; private static native void nglFramebufferTexture2D(int target, int attachment, int textureTarget, JavaScriptObject texture, int level) /*-{ $wnd.gl.framebufferTexture2D(target, attachment, textureTarget, texture, level); }-*/; private static native void nglFrontFace(int mode) /*-{ $wnd.gl.frontFace(mode); }-*/; private static native void nglGenerateMipmap(int target) /*-{ $wnd.gl.generateMipmap(target); }-*/; private static native ActiveInfo nglGetActiveAttrib(JavaScriptObject programID, int index) /*-{ return $wnd.gl.getActiveAttrib(programID, index); }-*/; private static native ActiveInfo nglGetActiveUniform(JavaScriptObject programID, int index) /*-{ return $wnd.gl.getActiveUniform(programID, index); }-*/; private static native JavaScriptObject[] nglGetAttachedShaders(JavaScriptObject programID) /*-{ return $wnd.gl.getAttachedShaders(programID); }-*/; private static native int nglGetAttribLocation(JavaScriptObject programID, String name) /*-{ return $wnd.gl.getAttribLocation(programID, name); }-*/; private static native int nglGetBufferParameter(int target, int pname) /*-{ return $wnd.gl.getBufferParameter(target, pname); }-*/; private static native Element nglGetCanvas() /*-{ return $wnd.gl.canvas; }-*/; private static native WebGLContext.Attributes nglGetContextAttributes() /*-{ return $wnd.gl.getContextAttributes(); }-*/; private static native int nglGetDrawingBufferHeight() /*-{ return $wnd.gl.drawingBufferHeight; }-*/; private static native int nglGetDrawingBufferWidth() /*-{ return $wnd.gl.drawingBufferWidth; }-*/; private static native int nglGetError() /*-{ return $wnd.gl.getError(); }-*/; private static native JavaScriptObject nglGetExtension(String name) /*-{ return $wnd.gl.getExtension(name); }-*/; private static native int nglGetFramebufferAttachmentParameter(int target, int attachment, int pname) /*-{ return $wnd.gl.getFramebufferAttachmentParameter(target, attachment, pname); }-*/; private static native <T extends JavaScriptObject> T nglGetParameter(int pname) /*-{ return $wnd.gl.getParameter(pname); }-*/; private static native int nglGetParameteri(int pname) /*-{ return $wnd.gl.getParameter(pname); }-*/; private static native boolean nglGetParameterb(int pname) /*-{ return $wnd.gl.getParameter(pname); }-*/; private static native int[] nglGetParameterii(int pname) /*-{ return $wnd.gl.getParameter(pname); }-*/; private static native float[] nglGetParameterff(int pname) /*-{ return $wnd.gl.getParameter(pname); }-*/; private static native boolean[] nglGetParameterbb(int pname) /*-{ return $wnd.gl.getParameter(pname); }-*/; private static native String nglGetParameters(int pname) /*-{ return $wnd.gl.getParameter(pname); }-*/; private static native String nglGetProgramInfoLog(JavaScriptObject programID) /*-{ return $wnd.gl.getProgramInfoLog(programID); }-*/; private static native int nglGetProgramParameteri(JavaScriptObject programID, int pname) /*-{ return $wnd.gl.getProgramParameter(programID, pname); }-*/; private static native boolean nglGetProgramParameterb(JavaScriptObject programID, int pname) /*-{ return $wnd.gl.getProgramParameter(programID, pname); }-*/; private static native int nglGetRenderbufferParameter(int target, int pname) /*-{ return $wnd.gl.getRenderbufferParameter(target, pname); }-*/; private static native String nglGetShaderInfoLog(JavaScriptObject shaderID) /*-{ return $wnd.gl.getShaderInfoLog(shaderID); }-*/; private static native int nglGetShaderParameteri(JavaScriptObject shaderID, int pname) /*-{ return $wnd.gl.getShaderParameter(shaderID, pname); }-*/; private static native boolean nglGetShaderParameterb(JavaScriptObject shaderID, int pname) /*-{ return $wnd.gl.getShaderParameter(shaderID, pname); }-*/; private static native ShaderPrecisionFormat nglGetShaderPrecisionFormat(int shaderType, int precisionType) /*-{ return $wnd.gl.getShaderPrecisionFormat(shaderType, precisionType); }-*/; private static native String nglGetShaderSource(JavaScriptObject shaderID) /*-{ return $wnd.gl.getShaderSource(shaderID); }-*/; private static native String[] nglGetSupportedExtensions() /*-{ return $wnd.gl.getSupportedExtensions(); }-*/; private static native int nglGetTexParameter(JavaScriptObject textureID, int pname) /*-{ return $wnd.gl.getTexParameter(textureID, pname); }-*/; private static native boolean[] nglGetUniformbv(JavaScriptObject programID, JavaScriptObject location) /*-{ return $wnd.gl.getUniform(programID, location); }-*/; private static native float[] nglGetUniformfv(JavaScriptObject programID, JavaScriptObject location) /*-{ return $wnd.gl.getUniform(programID, location); }-*/; private static native int[] nglGetUniformiv(JavaScriptObject programID, JavaScriptObject location) /*-{ return $wnd.gl.getUniform(programID, location); }-*/; private static native JavaScriptObject nglGetUniformLocation(JavaScriptObject programID, String name) /*-{ return $wnd.gl.getUniformLocation(programID, name); }-*/; private static native boolean nglGetVertexAttribb(int index, int pname) /*-{ return $wnd.gl.getVertexAttrib(index, pname); }-*/; private static native float[] nglGetVertexAttribfv(int index, int pname) /*-{ return $wnd.gl.getVertexAttrib(index, pname); }-*/; private static native int nglGetVertexAttribi(int index, int pname) /*-{ return $wnd.gl.getVertexAttrib(index, pname); }-*/; private static native int nglGetVertexAttribOffset(int index, int pname) /*-{ return $wnd.gl.getVertexAttribOffset(index, pname); }-*/; private static native void nglHint(int target, int mode) /*-{ return $wnd.gl.hint(target, mode); }-*/; private static native boolean nglIsBuffer(JavaScriptObject bufferID) /*-{ return $wnd.gl.isBuffer(bufferID); }-*/; private static native boolean nglIsContextLost() /*-{ return $wnd.gl.isContextLost(); }-*/; private static native boolean nglIsEnabled(int capability) /*-{ return $wnd.gl.isEnabled(capability); }-*/; private static native boolean nglIsFramebuffer(JavaScriptObject framebufferID) /*-{ return $wnd.gl.isFramebuffer(framebufferID); }-*/; private static native boolean nglIsProgram(JavaScriptObject programID) /*-{ return $wnd.gl.isProgram(programID); }-*/; private static native boolean nglIsRenderbuffer(JavaScriptObject renderbufferID) /*-{ return $wnd.gl.isRenderbuffer(renderbufferID); }-*/; private static native boolean nglIsShader(JavaScriptObject shaderID) /*-{ return $wnd.gl.isShader(shaderID); }-*/; private static native boolean nglIsTexture(JavaScriptObject textureID) /*-{ return $wnd.gl.isTexture(textureID); }-*/; private static native void nglLineWidth(int width) /*-{ $wnd.gl.lineWidth(width); }-*/; private static native void nglLinkProgram(JavaScriptObject programID) /*-{ $wnd.gl.linkProgram(programID); }-*/; private static native void nglPixelStorei(int pname, int param) /*-{ $wnd.gl.pixelStorei(pname, param); }-*/; private static native void nglPolygonOffset(double factor, double units) /*-{ $wnd.gl.polygonOffset(factor, units); }-*/; private static native void nglReadPixels(int x, int y, int w, int h, int format, int type, ArrayBufferView pixels) /*-{ $wnd.gl.readPixels(x, y, w, h, format, type, pixels); }-*/; private static native void nglRenderbufferStorage(int target, int internalFormat, int width, int height) /*-{ $wnd.gl.renderbufferStorage(target, internalFormat, width, height); }-*/; private static native void nglSampleCoverage(float value, boolean invert) /*-{ $wnd.gl.sampleCoverage(value, invert); }-*/; private static native void nglScissor(int x, int y, int w, int h) /*-{ $wnd.gl.scissor(x, y, w, h); }-*/; private static native void nglShaderSource(JavaScriptObject shaderID, String source) /*-{ return $wnd.gl.shaderSource(shaderID, source); }-*/; private static native void nglStencilFunc(int func, int ref, int mask) /*-{ $wnd.gl.stencilFunc(func, ref, mask); }-*/; private static native void nglStencilFuncSeparate(int face, int func, int ref, int mask) /*-{ $wnd.gl.stencilFuncSeparate(face, func, ref, mask); }-*/; private static native void nglStencilMask(int mask) /*-{ $wnd.gl.stencilMask(mask); }-*/; private static native void nglStencilMaskSeparate(int face, int mask) /*-{ $wnd.gl.stencilMaskSeparate(face, mask); }-*/; private static native void nglStencilOp(int sFail, int dpFail, int dpPass) /*-{ $wnd.gl.stencilOp(sFail, dpFail, dpPass); }-*/; private static native void nglStencilOpSeparate(int face, int fail, int zFail, int zPass) /*-{ $wnd.gl.stencilOpSeparate(face, fail, zFail, zPass); }-*/; private static native void nglTexImage2D(int target, int level, int internalFormat, int width, int height, int border, int format, int type, ArrayBufferView pixels) /*-{ $wnd.gl.texImage2D(target, level, internalFormat, width, height, border, format, type, pixels); }-*/; private static native void nglTexImage2D(int target, int level, int internalFormat, int format, int type, JavaScriptObject pixels) /*-{ $wnd.gl.texImage2D(target, level, internalFormat, format, type, pixels); }-*/; private static native void nglTexParameterf(int target, int pname, float value) /*-{ $wnd.gl.texParameterf(target, pname, value); }-*/; private static native void nglTexParameteri(int target, int pname, int value) /*-{ $wnd.gl.texParameteri(target, pname, value); }-*/; private static native void nglTexSubImage2D(int target, int level, int xOffset, int yOffset, int width, int height, int format, int type, ArrayBufferView pixels) /*-{ $wnd.gl.texSubImage2D(target, level, xOffset, yOffset, width, height, format, type, pixels); }-*/; private static native void nglTexSubImage2D(int target, int level, int xOffset, int yOffset, int width, int height, int format, int type, JavaScriptObject pixels) /*-{ $wnd.gl.texSubImage2D(target, level, xOffset, yOffset, width, height, format, type, pixels); }-*/; private static native void nglUniform1f(JavaScriptObject location, float x) /*-{ $wnd.gl.uniform1f(location, x); }-*/; private static native void nglUniform1fv(JavaScriptObject location, Float32Array x) /*-{ $wnd.gl.uniform1fv(location, x); }-*/; private static native void nglUniform1i(JavaScriptObject location, int x) /*-{ $wnd.gl.uniform1i(location, x); }-*/; private static native void nglUniform1iv(JavaScriptObject location, Int32Array x) /*-{ $wnd.gl.uniform1iv(location, x); }-*/; private static native void nglUniform2f(JavaScriptObject location, float x, float y) /*-{ $wnd.gl.uniform2f(location, x, y); }-*/; private static native void nglUniform2fv(JavaScriptObject location, Float32Array xy) /*-{ $wnd.gl.uniform2fv(location, xy); }-*/; private static native void nglUniform2i(JavaScriptObject location, int x, int y) /*-{ $wnd.gl.uniform2i(location, x, y); }-*/; private static native void nglUniform2iv(JavaScriptObject location, Int32Array xy) /*-{ $wnd.gl.uniform2iv(location, xy); }-*/; private static native void nglUniform3f(JavaScriptObject location, float x, float y, float z) /*-{ $wnd.gl.uniform3f(location, x, y, z); }-*/; private static native void nglUniform3fv(JavaScriptObject location, Float32Array xy) /*-{ $wnd.gl.uniform3fv(location, xy); }-*/; private static native void nglUniform3i(JavaScriptObject location, int x, int y, int z) /*-{ $wnd.gl.uniform3i(location, x, y, z); }-*/; private static native void nglUniform3iv(JavaScriptObject location, Int32Array xy) /*-{ $wnd.gl.uniform3iv(location, xy); }-*/; private static native void nglUniform4f(JavaScriptObject location, float x, float y, float z, float w) /*-{ $wnd.gl.uniform4f(location, x, y, z, w); }-*/; private static native void nglUniform4fv(JavaScriptObject location, Float32Array xy) /*-{ $wnd.gl.uniform4fv(location, xy); }-*/; private static native void nglUniform4i(JavaScriptObject location, int x, int y, int z, int w) /*-{ $wnd.gl.uniform4i(location, x, y, z, w); }-*/; private static native void nglUniform4iv(JavaScriptObject location, Int32Array xy) /*-{ $wnd.gl.uniform4iv(location, xy); }-*/; private static native void nglUniformMatrix2fv(JavaScriptObject location, boolean transpose, Float32Array value)/*-{ $wnd.gl.uniformMatrix2fv(location, transpose, value); }-*/; private static native void nglUniformMatrix3fv(JavaScriptObject location, boolean transpose, Float32Array value)/*-{ $wnd.gl.uniformMatrix3fv(location, transpose, value); }-*/; private static native void nglUniformMatrix4fv(JavaScriptObject location, boolean transpose, Float32Array value)/*-{ $wnd.gl.uniformMatrix4fv(location, transpose, value); }-*/; private static native void nglUseProgram(JavaScriptObject programID) /*-{ $wnd.gl.useProgram(programID); }-*/; private static native void nglValidateProgram(JavaScriptObject programID) /*-{ $wnd.gl.validateProgram(programID); }-*/; private static native void nglVertexAttribPointer(int index, int size, int type, boolean normalized, double stride, double offset) /*-{ $wnd.gl.vertexAttribPointer(index, size, type, normalized, stride, offset); }-*/; private static native void nglVertexAttrib1f(int index, float x) /*-{ $wnd.gl.vertexAttrib1f(x); }-*/; private static native void nglVertexAttrib1fv(int index, ArrayBufferView values) /*-{ $wnd.gl.vertexAttrib1fv(index, values); }-*/; private static native void nglVertexAttrib1fv(int index, JavaScriptObject values) /*-{ $wnd.gl.vertexAttrib1fv(index, values); }-*/; private static native void nglVertexAttrib2f(int index, float x, float y) /*-{ $wnd.gl.vertexAttrib2f(x, y); }-*/; private static native void nglVertexAttrib2fv(int index, ArrayBufferView values) /*-{ $wnd.gl.vertexAttrib2fv(index, values); }-*/; private static native void nglVertexAttrib2fv(int index, JavaScriptObject values) /*-{ $wnd.gl.vertexAttrib2fv(index, values); }-*/; private static native void nglVertexAttrib3f(int index, float x, float y, float z) /*-{ $wnd.gl.vertexAttrib3f(x, y, z); }-*/; private static native void nglVertexAttrib3fv(int index, ArrayBufferView values) /*-{ $wnd.gl.vertexAttrib3fv(index, values); }-*/; private static native void nglVertexAttrib3fv(int index, JavaScriptObject values) /*-{ $wnd.gl.vertexAttrib3fv(index, values); }-*/; private static native void nglVertexAttrib4f(int index, float x, float y, float z, float w) /*-{ $wnd.gl.vertexAttrib4f(x, y, z, w); }-*/; private static native void nglVertexAttrib4fv(int index, ArrayBufferView values) /*-{ $wnd.gl.vertexAttrib4fv(index, values); }-*/; private static native void nglVertexAttrib4fv(int index, JavaScriptObject values) /*-{ $wnd.gl.vertexAttrib4fv(index, values); }-*/; private static native void nglViewport(int x, int y, int w, int h) /*-{ $wnd.gl.viewport(x, y, w, h); }-*/; public static class ActiveInfo extends JavaScriptObject { protected ActiveInfo() { } public final native int getName() /*-{ return this.name; }-*/; public final native int getSize() /*-{ return this.size; }-*/; public final native int getType() /*-{ return this.type; }-*/; } public static class ShaderPrecisionFormat extends JavaScriptObject { protected ShaderPrecisionFormat() { } public final native int getPrecision() /*-{ return this.precision; }-*/; public final native int getRangeMax() /*-{ return this.rangeMax; }-*/; public final native int getRangeMin() /*-{ return this.rangeMin; }-*/; } }
// This file is part of OpenTSDB. // This program is free software: you can redistribute it and/or modify it // option) any later version. This program is distributed in the hope that it // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser package net.opentsdb.tools; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import net.opentsdb.core.Const; import net.opentsdb.core.TSDB; import net.opentsdb.meta.TSMeta; import net.opentsdb.meta.UIDMeta; import net.opentsdb.uid.NoSuchUniqueId; import net.opentsdb.uid.UniqueId; import net.opentsdb.uid.UniqueId.UniqueIdType; import org.hbase.async.Bytes; import org.hbase.async.HBaseException; import org.hbase.async.KeyValue; import org.hbase.async.Scanner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.stumbleupon.async.Callback; import com.stumbleupon.async.Deferred; import com.stumbleupon.async.DeferredGroupException; /** * Tool helper class used to generate or update meta data for UID names and * timeseries. This class should only be used by CLI tools as it can take a long * time to complete. * A scanner is opened on the data table and it scans the entire thing looking * for timeseries that are missing TSMeta objects or may have the wrong "created" * time. Each timeseries also causes a check on the UIDMeta objects to verify * they have values and have a proper "Created" time as well. * <b>Note:</b> This class will also update configured search plugins with * meta data generated or updated */ final class MetaSync extends Thread { private static final Logger LOG = LoggerFactory.getLogger(MetaSync.class); /** TSDB to use for storage access */ final TSDB tsdb; /** The ID to start the sync with for this thread */ final long start_id; /** The end of the ID block to work on */ final long end_id; /** A shared list of TSUIDs that have been processed by this or other * threads. It stores hashes instead of the bytes or strings to save * on space */ final Set<Integer> processed_tsuids; /** List of metric UIDs and their earliest detected timestamp */ final ConcurrentHashMap<String, Long> metric_uids; /** List of tagk UIDs and their earliest detected timestamp */ final ConcurrentHashMap<String, Long> tagk_uids; /** List of tagv UIDs and their earliest detected timestamp */ final ConcurrentHashMap<String, Long> tagv_uids; /** Diagnostic ID for this thread */ final int thread_id; /** * Constructor that sets local variables * @param tsdb The TSDB to process with * @param start_id The starting ID of the block we'll work on * @param quotient The total number of IDs in our block * @param thread_id The ID of this thread (starts at 0) */ public MetaSync(final TSDB tsdb, final long start_id, final double quotient, final Set<Integer> processed_tsuids, ConcurrentHashMap<String, Long> metric_uids, ConcurrentHashMap<String, Long> tagk_uids, ConcurrentHashMap<String, Long> tagv_uids, final int thread_id) { this.tsdb = tsdb; this.start_id = start_id; this.end_id = start_id + (long) quotient + 1; // teensy bit of overlap this.processed_tsuids = processed_tsuids; this.metric_uids = metric_uids; this.tagk_uids = tagk_uids; this.tagv_uids = tagv_uids; this.thread_id = thread_id; } /** * Loops through the entire TSDB data set and exits when complete. */ public void run() { // list of deferred calls used to act as a buffer final ArrayList<Deferred<Boolean>> storage_calls = new ArrayList<Deferred<Boolean>>(); final Deferred<Object> result = new Deferred<Object>(); /** * Called when we have encountered a previously un-processed UIDMeta object. * This callback will update the "created" timestamp of the UIDMeta and * store the update, replace corrupted metas and update search plugins. */ final class UidCB implements Callback<Deferred<Boolean>, UIDMeta> { private final UniqueIdType type; private final byte[] uid; private final long timestamp; /** * Constructor that initializes the local callback * @param type The type of UIDMeta we're dealing with * @param uid The UID of the meta object as a byte array * @param timestamp The timestamp of the timeseries when this meta * was first detected */ public UidCB(final UniqueIdType type, final byte[] uid, final long timestamp) { this.type = type; this.uid = uid; this.timestamp = timestamp; } /** * A nested class called after fetching a UID name to use when creating a * new UIDMeta object if the previous object was corrupted. Also pushes * the meta off to the search plugin. */ final class UidNameCB implements Callback<Deferred<Boolean>, String> { @Override public Deferred<Boolean> call(final String name) throws Exception { UIDMeta new_meta = new UIDMeta(type, uid, name); new_meta.setCreated(timestamp); tsdb.indexUIDMeta(new_meta); LOG.info("Replacing corrupt UID [" + UniqueId.uidToString(uid) + "] of type [" + type + "]"); return new_meta.syncToStorage(tsdb, true); } } @Override public Deferred<Boolean> call(final UIDMeta meta) throws Exception { // we only want to update the time if it was outside of an hour // otherwise it's probably an accurate timestamp if (meta.getCreated() > (timestamp + 3600) || meta.getCreated() == 0) { LOG.info("Updating UID [" + UniqueId.uidToString(uid) + "] of type [" + type + "]"); meta.setCreated(timestamp); // if the UIDMeta object was missing any of these fields, we'll // consider it corrupt and replace it with a new object if (meta.getUID() == null || meta.getUID().isEmpty() || meta.getType() == null) { return tsdb.getUidName(type, uid) .addCallbackDeferring(new UidNameCB()); } else { // the meta was good, just needed a timestamp update so sync to // search and storage tsdb.indexUIDMeta(meta); LOG.info("Syncing valid UID [" + UniqueId.uidToString(uid) + "] of type [" + type + "]"); return meta.syncToStorage(tsdb, false); } } else { LOG.debug("UID [" + UniqueId.uidToString(uid) + "] of type [" + type + "] is up to date in storage"); return Deferred.fromResult(true); } } } /** * Called to handle a previously unprocessed TSMeta object. This callback * will update the "created" timestamp, create a new TSMeta object if * missing, and update search plugins. */ final class TSMetaCB implements Callback<Deferred<Boolean>, TSMeta> { private final String tsuid_string; private final byte[] tsuid; private final long timestamp; /** * Default constructor * @param tsuid ID of the timeseries * @param timestamp The timestamp when the first data point was recorded */ public TSMetaCB(final byte[] tsuid, final long timestamp) { this.tsuid = tsuid; tsuid_string = UniqueId.uidToString(tsuid); this.timestamp = timestamp; } @Override public Deferred<Boolean> call(final TSMeta meta) throws Exception { /** Called to process the new meta through the search plugin and tree code */ final class IndexCB implements Callback<Deferred<Boolean>, TSMeta> { @Override public Deferred<Boolean> call(final TSMeta new_meta) throws Exception { tsdb.indexTSMeta(new_meta); // pass through the trees return tsdb.processTSMetaThroughTrees(new_meta); } } /** Called to load the newly created meta object for passage onto the * search plugin and tree builder if configured */ final class GetCB implements Callback<Deferred<Boolean>, Boolean> { @Override public final Deferred<Boolean> call(final Boolean exists) throws Exception { if (exists) { return TSMeta.getTSMeta(tsdb, tsuid_string) .addCallbackDeferring(new IndexCB()); } else { return Deferred.fromResult(false); } } } /** Errback on the store new call to catch issues */ class ErrBack implements Callback<Object, Exception> { public Object call(final Exception e) throws Exception { LOG.warn("Failed creating meta for: " + tsuid + " with exception: ", e); return null; } } // if we couldn't find a TSMeta in storage, then we need to generate a // new one if (meta == null) { /** * Called after successfully creating a TSMeta counter and object, * used to convert the deferred long to a boolean so it can be * combined with other calls for waiting. */ final class CreatedCB implements Callback<Deferred<Boolean>, Long> { @Override public Deferred<Boolean> call(Long value) throws Exception { LOG.info("Created counter and meta for timeseries [" + tsuid_string + "]"); return Deferred.fromResult(true); } } /** * Called after checking to see if the counter exists and is used * to determine if we should create a new counter AND meta or just a * new meta */ final class CounterCB implements Callback<Deferred<Boolean>, Boolean> { @Override public Deferred<Boolean> call(final Boolean exists) throws Exception { if (!exists) { // note that the increment call will create the meta object // and send it to the search plugin so we don't have to do that // here or in the local callback return TSMeta.incrementAndGetCounter(tsdb, tsuid) .addCallbackDeferring(new CreatedCB()); } else { TSMeta new_meta = new TSMeta(tsuid, timestamp); tsdb.indexTSMeta(new_meta); LOG.info("Counter exists but meta was null, creating meta data " + "for timeseries [" + tsuid_string + "]"); return new_meta.storeNew(tsdb) .addCallbackDeferring(new GetCB()) .addErrback(new ErrBack()); } } } // Take care of situations where the counter is created but the // meta data is not. May happen if the TSD crashes or is killed // improperly before the meta is flushed to storage. return TSMeta.counterExistsInStorage(tsdb, tsuid) .addCallbackDeferring(new CounterCB()); } // verify the tsuid is good, it's possible for this to become // corrupted if (meta.getTSUID() == null || meta.getTSUID().isEmpty()) { LOG.warn("Replacing corrupt meta data for timeseries [" + tsuid_string + "]"); TSMeta new_meta = new TSMeta(tsuid, timestamp); tsdb.indexTSMeta(new_meta); return new_meta.storeNew(tsdb) .addCallbackDeferring(new GetCB()) .addErrback(new ErrBack()); } else { // we only want to update the time if it was outside of an // hour otherwise it's probably an accurate timestamp if (meta.getCreated() > (timestamp + 3600) || meta.getCreated() == 0) { meta.setCreated(timestamp); tsdb.indexTSMeta(meta); LOG.info("Updated created timestamp for timeseries [" + tsuid_string + "]"); return meta.syncToStorage(tsdb, false); } LOG.debug("TSUID [" + tsuid_string + "] is up to date in storage"); return Deferred.fromResult(false); } } } /** * Scanner callback that recursively loops through all of the data point * rows. Note that we don't process the actual data points, just the row * keys. */ final class MetaScanner implements Callback<Object, ArrayList<ArrayList<KeyValue>>> { private final Scanner scanner; private byte[] last_tsuid = null; private String tsuid_string = ""; /** * Default constructor that initializes the data row scanner */ public MetaScanner() { scanner = getScanner(); } /** * Fetches the next set of rows from the scanner and adds this class as * a callback * @return A meaningless deferred to wait on until all data rows have * been processed. */ public Object scan() { return scanner.nextRows().addCallback(this); } @Override public Object call(ArrayList<ArrayList<KeyValue>> rows) throws Exception { if (rows == null) { result.callback(null); return null; } for (final ArrayList<KeyValue> row : rows) { final byte[] tsuid = UniqueId.getTSUIDFromKey(row.get(0).key(), TSDB.metrics_width(), Const.TIMESTAMP_BYTES); // if the current tsuid is the same as the last, just continue // so we save time if (last_tsuid != null && Arrays.equals(last_tsuid, tsuid)) { continue; } last_tsuid = tsuid; // see if we've already processed this tsuid and if so, continue if (processed_tsuids.contains(Arrays.hashCode(tsuid))) { continue; } tsuid_string = UniqueId.uidToString(tsuid); // add tsuid to the processed list processed_tsuids.add(Arrays.hashCode(tsuid)); // we may have a new TSUID or UIDs, so fetch the timestamp of the // row for use as the "created" time. Depending on speed we could // parse datapoints, but for now the hourly row time is enough final long timestamp = Bytes.getUnsignedInt(row.get(0).key(), TSDB.metrics_width()); LOG.debug("[" + thread_id + "] Processing TSUID: " + tsuid_string + " row timestamp: " + timestamp); // now process the UID metric meta data final byte[] metric_uid_bytes = Arrays.copyOfRange(tsuid, 0, TSDB.metrics_width()); final String metric_uid = UniqueId.uidToString(metric_uid_bytes); Long last_get = metric_uids.get(metric_uid); if (last_get == null || last_get == 0 || timestamp < last_get) { // fetch and update. Returns default object if the meta doesn't // exist, so we can just call sync on this to create a missing // entry final UidCB cb = new UidCB(UniqueIdType.METRIC, metric_uid_bytes, timestamp); final Deferred<Boolean> process_uid = UIDMeta.getUIDMeta(tsdb, UniqueIdType.METRIC, metric_uid_bytes).addCallbackDeferring(cb); storage_calls.add(process_uid); metric_uids.put(metric_uid, timestamp); } // loop through the tags and process their meta final List<byte[]> tags = UniqueId.getTagsFromTSUID(tsuid_string); int idx = 0; for (byte[] tag : tags) { final UniqueIdType type = (idx % 2 == 0) ? UniqueIdType.TAGK : UniqueIdType.TAGV; idx++; final String uid = UniqueId.uidToString(tag); // check the maps to see if we need to bother updating if (type == UniqueIdType.TAGK) { last_get = tagk_uids.get(uid); } else { last_get = tagv_uids.get(uid); } if (last_get != null && last_get != 0 && last_get <= timestamp) { continue; } // fetch and update. Returns default object if the meta doesn't // exist, so we can just call sync on this to create a missing // entry final UidCB cb = new UidCB(type, tag, timestamp); final Deferred<Boolean> process_uid = UIDMeta.getUIDMeta(tsdb, type, tag) .addCallbackDeferring(cb); storage_calls.add(process_uid); if (type == UniqueIdType.TAGK) { tagk_uids.put(uid, timestamp); } else { tagv_uids.put(uid, timestamp); } } /** * An error callback used to cache issues with a particular timeseries * or UIDMeta such as a missing UID name. We want to continue * processing when this happens so we'll just log the error and * the user can issue a command later to clean up orphaned meta * entries. */ final class ErrBack implements Callback<Deferred<Boolean>, Exception> { @Override public Deferred<Boolean> call(Exception e) throws Exception { Throwable ex = e; while (ex.getClass().equals(DeferredGroupException.class)) { if (ex.getCause() == null) { LOG.warn("Unable to get to the root cause of the DGE"); break; } ex = ex.getCause(); } if (ex.getClass().equals(IllegalStateException.class)) { LOG.error("Invalid data when processing TSUID [" + tsuid_string + "]", ex); } else if (ex.getClass().equals(IllegalArgumentException.class)) { LOG.error("Invalid data when processing TSUID [" + tsuid_string + "]", ex); } else if (ex.getClass().equals(NoSuchUniqueId.class)) { LOG.warn("Timeseries [" + tsuid_string + "] includes a non-existant UID: " + ex.getMessage()); } else { LOG.error("Unmatched Exception: " + ex.getClass()); throw e; } return Deferred.fromResult(false); } } // handle the timeseries meta last so we don't record it if one // or more of the UIDs had an issue final Deferred<Boolean> process_tsmeta = TSMeta.getTSMeta(tsdb, tsuid_string) .addCallbackDeferring(new TSMetaCB(tsuid, timestamp)); process_tsmeta.addErrback(new ErrBack()); storage_calls.add(process_tsmeta); } /** * A buffering callback used to avoid StackOverflowError exceptions * where the list of deferred calls can exceed the limit. Instead we'll * process the Scanner's limit in rows, wait for all of the storage * calls to complete, then continue on to the next set. */ final class ContinueCB implements Callback<Object, ArrayList<Boolean>> { @Override public Object call(ArrayList<Boolean> puts) throws Exception { storage_calls.clear(); return scan(); } } /** * Catch exceptions in one of the grouped calls and continue scanning. * Without this the user may not see the exception and the thread will * just die silently. */ final class ContinueEB implements Callback<Object, Exception> { @Override public Object call(Exception e) throws Exception { Throwable ex = e; while (ex.getClass().equals(DeferredGroupException.class)) { if (ex.getCause() == null) { LOG.warn("Unable to get to the root cause of the DGE"); break; } ex = ex.getCause(); } LOG.error("[" + thread_id + "] Upstream Exception: ", ex); return scan(); } } // call ourself again but wait for the current set of storage calls to // complete so we don't OOM Deferred.group(storage_calls).addCallback(new ContinueCB()) .addErrback(new ContinueEB()); return null; } } final MetaScanner scanner = new MetaScanner(); try { scanner.scan(); result.joinUninterruptibly(); LOG.info("[" + thread_id + "] Complete"); } catch (Exception e) { LOG.error("[" + thread_id + "] Scanner Exception", e); throw new RuntimeException("[" + thread_id + "] Scanner exception", e); } } /** * Returns a scanner set to scan the range configured for this thread * @return A scanner on the "t" CF configured for the specified range * @throws HBaseException if something goes boom */ private Scanner getScanner() throws HBaseException { final short metric_width = TSDB.metrics_width(); final byte[] start_row = Arrays.copyOfRange(Bytes.fromLong(start_id), 8 - metric_width, 8); final byte[] end_row = Arrays.copyOfRange(Bytes.fromLong(end_id), 8 - metric_width, 8); LOG.debug("[" + thread_id + "] Start row: " + UniqueId.uidToString(start_row)); LOG.debug("[" + thread_id + "] End row: " + UniqueId.uidToString(end_row)); final Scanner scanner = tsdb.getClient().newScanner(tsdb.dataTable()); scanner.setStartKey(start_row); scanner.setStopKey(end_row); scanner.setFamily("t".getBytes(Charset.forName("ISO-8859-1"))); return scanner; } }
package org.yamcs; import static org.yamcs.api.Protocol.DATA_TO_HEADER_NAME; import static org.yamcs.api.Protocol.REPLYTO_HEADER_NAME; import static org.yamcs.api.Protocol.REQUEST_TYPE_HEADER_NAME; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.hornetq.api.core.HornetQException; import org.hornetq.api.core.SimpleString; import org.hornetq.api.core.client.ClientMessage; import org.hornetq.api.core.client.MessageHandler; import org.hornetq.core.server.embedded.EmbeddedHornetQ; import org.omg.PortableServer.POAManagerPackage.AdapterInactive; import org.omg.PortableServer.POAPackage.ServantNotActive; import org.omg.PortableServer.POAPackage.WrongPolicy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yamcs.api.Protocol; import org.yamcs.api.YamcsApiException; import org.yamcs.api.YamcsClient; import org.yamcs.api.YamcsSession; import org.yamcs.archive.ReplayServer; import org.yamcs.management.ManagementService; import org.yamcs.protobuf.Yamcs.MissionDatabase; import org.yamcs.protobuf.Yamcs.MissionDatabaseRequest; import org.yamcs.protobuf.Yamcs.YamcsInstance; import org.yamcs.protobuf.Yamcs.YamcsInstances; import org.yamcs.security.HornetQAuthManager; import org.yamcs.security.HqClientMessageToken; import org.yamcs.security.Privilege; import org.yamcs.time.RealtimeTimeService; import org.yamcs.time.TimeService; import org.yamcs.utils.HornetQBufferOutputStream; import org.yamcs.utils.YObjectLoader; import org.yamcs.xtce.Header; import org.yamcs.xtce.XtceDb; import org.yamcs.xtceproc.XtceDbFactory; import org.yamcs.yarch.streamsql.ParseException; import org.yamcs.yarch.streamsql.StreamSqlException; import com.google.common.util.concurrent.Service; import com.google.common.util.concurrent.Service.State; /** * * Main yamcs server, starts a Yarch instance for each defined instance * Handles basic requests for retrieving the configured instances, database versions * and retrieve databases in serialized form * * @author nm * */ public class YamcsServer { static EmbeddedHornetQ hornetServer; static Map<String, YamcsServer> instances=new LinkedHashMap<String, YamcsServer>(); String instance; ReplayServer replay; List<Service> serviceList=new ArrayList<Service>(); Logger log; static Logger staticlog=LoggerFactory.getLogger(YamcsServer.class.getName()); /**in the shutdown, allow servies this number of seconds for stopping*/ public static int SERVICE_STOP_GRACE_TIME = 10; TimeService timeService; @SuppressWarnings("unchecked") YamcsServer(String instance) throws HornetQException, IOException, ConfigurationException, StreamSqlException, ParseException, YamcsApiException { this.instance=instance; //TODO - fix bootstrap issue instances.put(instance, this); log=LoggerFactory.getLogger(YamcsServer.class.getName()+"["+instance+"]"); YConfiguration conf=YConfiguration.getConfiguration("yamcs."+instance); loadTimeService(); ManagementService managementService=ManagementService.getInstance(); StreamInitializer.createStreams(instance); List<Object> services=conf.getList("services"); for(Object servobj:services) { String servclass; Object args = null; if(servobj instanceof String) { servclass = (String)servobj; } else if (servobj instanceof Map<?, ?>) { Map<String, Object> m = (Map<String, Object>) servobj; servclass = YConfiguration.getString(m, "class"); args = m.get("args"); } else { throw new ConfigurationException("Services can either be specified by classname, or by {class: classname, args: ....} map. Cannot load a service from "+servobj); } log.info("loading service from "+servclass); YObjectLoader<Service> objLoader = new YObjectLoader<Service>(); Service serv; if(args == null) { serv = objLoader.loadObject(servclass, instance); } else { serv = objLoader.loadObject(servclass, instance, args); } serviceList.add(serv); managementService.registerService(instance, servclass, serv); } for(Service serv:serviceList) { serv.startAsync(); try { serv.awaitRunning(); } catch (IllegalStateException e) { //this happens when it fails, the next check will throw an error in this case } State result = serv.state(); if(result==State.FAILED) { throw new ConfigurationException("Failed to start service "+serv, serv.failureCause()); } } } static YamcsSession yamcsSession; static YamcsClient ctrlAddressClient; public static EmbeddedHornetQ setupHornet() throws Exception { //divert hornetq logging System.setProperty("org.jboss.logging.provider", "slf4j"); // load optional configuration file name for hornetq, // otherwise default will be hornetq-configuration.xml String hornetqConfigFile = null; try{ YConfiguration c=YConfiguration.getConfiguration("yamcs"); hornetqConfigFile = c.getString("hornetqConfigFile"); } catch (Exception e){} hornetServer = new EmbeddedHornetQ(); hornetServer.setSecurityManager( new HornetQAuthManager() ); if(hornetqConfigFile != null) hornetServer.setConfigResourcePath(hornetqConfigFile); hornetServer.start(); //create already the queue here to reduce (but not eliminate :( ) the chance that somebody connects to it before yamcs is started fully yamcsSession=YamcsSession.newBuilder().build(); ctrlAddressClient=yamcsSession.newClientBuilder().setRpcAddress(Protocol.YAMCS_SERVER_CONTROL_ADDRESS).setDataProducer(true).build(); return hornetServer; } public static void stopHornet() throws Exception { yamcsSession.close(); Protocol.closeKiller(); hornetServer.stop(); } public static void shutDown() throws Exception { for(YamcsServer ys: instances.values()) { ys.stop(); } } public void stop() { for(int i = serviceList.size()-1; i>=0; i Service s = serviceList.get(i); s.stopAsync(); try { s.awaitTerminated(SERVICE_STOP_GRACE_TIME, TimeUnit.SECONDS); } catch (TimeoutException e) { log.error("Service "+s+" did not stop in "+SERVICE_STOP_GRACE_TIME + " seconds"); } } } public static boolean hasInstance(String instance) { return instances.containsKey(instance); } @SuppressWarnings("unchecked") public static void setupYamcsServer() throws Exception { YConfiguration c=YConfiguration.getConfiguration("yamcs"); final List<String>instArray=c.getList("instances"); for(String inst:instArray) { instances.put(inst, new YamcsServer(inst)); } Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable thrown) { staticlog.error("Uncaught exception '"+thrown+"' in thread "+t+": "+Arrays.toString(thrown.getStackTrace())); } }); ctrlAddressClient.rpcConsumer.setMessageHandler(new MessageHandler() { @Override public void onMessage(ClientMessage msg) { SimpleString replyto=msg.getSimpleStringProperty(REPLYTO_HEADER_NAME); if(replyto==null) { staticlog.warn("did not receive a replyto header. Ignoring the request"); return; } try { String req=msg.getStringProperty(REQUEST_TYPE_HEADER_NAME); staticlog.debug("received request "+req); if("getYamcsInstances".equalsIgnoreCase(req)) { ctrlAddressClient.sendReply(replyto, "OK", getYamcsInstances()); } else if("getMissionDatabase".equalsIgnoreCase(req)) { Privilege priv = Privilege.getInstance(); HqClientMessageToken authToken = new HqClientMessageToken(msg, null); if( ! priv.hasPrivilege(authToken, Privilege.Type.SYSTEM, "MayGetMissionDatabase" ) ) { staticlog.warn( "User '{}' does not have 'MayGetMissionDatabase' privilege." ); ctrlAddressClient.sendErrorReply(replyto, "Privilege required but missing: MayGetMissionDatabase"); return; } SimpleString dataAddress=msg.getSimpleStringProperty(DATA_TO_HEADER_NAME); if(dataAddress == null) { staticlog.warn("Received a getMissionDatabase without a "+DATA_TO_HEADER_NAME +" header"); ctrlAddressClient.sendErrorReply(replyto, "no data address specified"); return; } MissionDatabaseRequest mdr = (MissionDatabaseRequest)Protocol.decode(msg, MissionDatabaseRequest.newBuilder()); sendMissionDatabase(mdr, replyto, dataAddress); } else { staticlog.warn("Received invalid request: "+req); } } catch (Exception e) { staticlog.warn("exception received when sending the reply: ", e); } } }); System.out.println("yamcsstartup success"); } private static YamcsInstances getYamcsInstances() { YamcsInstances.Builder aisb=YamcsInstances.newBuilder(); for(String inst:instances.keySet()) { YamcsInstance.Builder aib=YamcsInstance.newBuilder(); aib.setName(inst); YConfiguration c; try { MissionDatabase.Builder mdb = MissionDatabase.newBuilder(); c = YConfiguration.getConfiguration("yamcs."+inst); String configName = c.getString("mdb"); XtceDb xtcedb=XtceDbFactory.getInstanceByConfig(configName); mdb.setConfigName(configName); mdb.setName(xtcedb.getRootSpaceSystem().getName()); Header h =xtcedb.getRootSpaceSystem().getHeader(); if((h!=null) && (h.getVersion()!=null)) { mdb.setVersion(h.getVersion()); } aib.setMissionDatabase(mdb.build()); } catch (ConfigurationException e) { staticlog.warn("Got error when finding the mission database for instance "+inst, e); } aisb.addInstance(aib.build()); } return aisb.build(); } private static void sendMissionDatabase(MissionDatabaseRequest mdr, SimpleString replyTo, SimpleString dataAddress) throws HornetQException { final XtceDb xtcedb; try { if(mdr.hasInstance()) { xtcedb=XtceDbFactory.getInstance(mdr.getInstance()); } else if(mdr.hasDbConfigName()){ xtcedb=XtceDbFactory.getInstanceByConfig(mdr.getDbConfigName()); } else { staticlog.warn("getMissionDatabase request received with none of the instance or dbConfigName specified"); ctrlAddressClient.sendErrorReply(replyTo, "Please specify either instance or dbConfigName"); return; } ClientMessage msg=yamcsSession.session.createMessage(false); ObjectOutputStream oos=new ObjectOutputStream(new HornetQBufferOutputStream(msg.getBodyBuffer())); oos.writeObject(xtcedb); oos.close(); ctrlAddressClient.sendReply(replyTo, "OK", null); ctrlAddressClient.dataProducer.send(dataAddress, msg); } catch (ConfigurationException e) { YamcsException ye=new YamcsException(e.toString()); ctrlAddressClient.sendErrorReply(replyTo, ye); } catch (IOException e) { //this should not happen since all the ObjectOutputStream happens in memory throw new RuntimeException(e); } } private void loadTimeService() throws ConfigurationException, IOException { YConfiguration conf=YConfiguration.getConfiguration("yamcs."+instance); if(conf.containsKey("timeService")) { Map<String, Object> m = conf.getMap("timeService"); String servclass = YConfiguration.getString(m, "class"); Object args = m.get("args"); YObjectLoader<TimeService> objLoader = new YObjectLoader<TimeService>(); if(args == null) { timeService = objLoader.loadObject(servclass, instance); } else { timeService = objLoader.loadObject(servclass, instance, args); } } else { timeService = new RealtimeTimeService(); } } public static YamcsServer getInstance(String yamcsInstance) { return instances.get(yamcsInstance); } public TimeService getTimeService() { return timeService; } public static void configureNonBlocking(SimpleString dataAddress) { //TODO //Object o=hornetServer.getHornetQServer().getManagementService().getResource(dataAddress.toString()); } /** * @param args * @throws ConfigurationException * @throws IOException * @throws YProcessorException * @throws InvalidName * @throws AdapterInactive * @throws WrongPolicy * @throws ServantNotActive * @throws java.text.ParseException */ public static void main(String[] args) { if(args.length>0) printOptionsAndExit(); try { YConfiguration.setup(); setupSecurity(); setupHornet(); org.yamcs.yarch.management.ManagementService.setup(true); ManagementService.setup(true,true); setupYamcsServer(); } catch (ConfigurationException e) { staticlog.error("Could not start Yamcs Server: ", e); System.err.println(e.toString()); System.exit(-1); } catch (Throwable e) { staticlog.error("Could not start Yamcs Server: ", e); e.printStackTrace(); System.exit(-1); } } private static void setupSecurity() { org.yamcs.security.Privilege.getInstance(); } private static void printOptionsAndExit() { System.err.println("Usage: yamcs-server.sh"); System.err.println("\t All options are taken from yamcs.yaml"); System.exit(-1); } }
package au.edu.unimelb.boldapp; import java.io.StringWriter; import android.util.Log; import android.content.Intent; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import au.edu.unimelb.boldapp.sync.Client; public class SyncActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sync); } public void onResume() { super.onResume(); // Load previously set router info. JSONParser parser = new JSONParser(); String jsonStr = FileIO.read("router.json"); try { Object obj = parser.parse(jsonStr); JSONObject jsonObj = (JSONObject) obj; String routerIPAddress = jsonObj.get("ipaddress").toString(); String routerUsername = jsonObj.get("username").toString(); String routerPassword = jsonObj.get("password").toString(); EditText editText = (EditText) findViewById(R.id.edit_ip); editText.setText(routerIPAddress); editText = (EditText) findViewById(R.id.edit_router_username); editText.setText(routerUsername); editText = (EditText) findViewById(R.id.edit_password); editText.setText(routerPassword); } catch (Exception e) { e.printStackTrace(); } } /** * When the back button is pressed. * * @param view the back button. */ public void goBack(View view) { this.finish(); } /** * When the sync button is pressed, sync with the splash screen. * * @param view the sync button. */ public void sync(View view) { // Get the information from the edit views and add to the intent EditText editText = (EditText) findViewById(R.id.edit_ip); String routerIPAddress = editText.getText().toString(); editText = (EditText) findViewById(R.id.edit_router_username); String routerUsername = editText.getText().toString(); editText = (EditText) findViewById(R.id.edit_password); String routerPassword = editText.getText().toString(); JSONObject obj = new JSONObject(); obj.put("ipaddress", routerIPAddress); obj.put("username", routerUsername); obj.put("password", routerPassword); StringWriter stringWriter = new StringWriter(); try { obj.writeJSONString(stringWriter); } catch (Exception e) { e.printStackTrace(); } String jsonText = stringWriter.toString(); Log.i("ftp", FileIO.getAppRootPath() + "router.json"); if (routerIPAddress.equals("")) { Toast.makeText(this, "Please enter a router IP address", Toast.LENGTH_LONG).show(); } else if (!FileIO.write("router.json", jsonText)) { Log.i("ftp", "not working"); } else { Intent intent = new Intent(this, SyncSplashActivity.class); startActivity(intent); } } }
// MetadataStore.java package loci.formats; /** * A proxy whose responsibility it is to marshal biological image data into a * particular storage medium. * * The <code>MetadataStore</code> interface encompasses the basic metadata that * any specific storage medium (file, relational database, etc.) should be * expected to store and be expected to return with relationships maintained. * * It is expected that the constructors of all implementations of * <code>MetadataStore</code> interface throw a * {@link MetadataStoreException} if they are unable to initialize * some of their dependencies. * * @author Chris Allan callan at blackcat.ca * * TODO: Further work needs to be done to ensure the validity of the arguments * to these methods with not-null constraints and NullPointerException * declarations (should be unchecked exceptions). */ public interface MetadataStore { /** * Creates a new <i>root</i> object to be used by the metadata store and * resets the internal state of the metadata store. */ void createRoot(); /** * Sets the <i>root</i> object of the metadata store. * @param root object that the store can use as its root. */ void setRoot(Object root); /** * Retrieves the <i>root</i> object of the metadata store. * @return object that the store is using as its root. */ Object getRoot(); /** * Creates an image in the metadata store with a particular index. * @param name the full name of the image. * @param creationDate the creation date of the image. * @param description the full description of the image. * @param i the index to use in the store. If <code>null</code> the default * index of 0 will be used. */ void setImage(String name, String creationDate, String description, Integer i); /** * Creates an experimenter in the metadata store with a particular index. * @param firstName the first name of the experimenter * @param lastName the last name of the experimenter * @param email the e-mail address of the experimenter * @param institution the institution for which the experimenter belongs * @param dataDirectory the fully qualified path to the experimenter's data * @param group the group to which the experimenter belongs * @param i the index to use in the store. If <code>null</code> the default * index of 0 will be used. */ void setExperimenter(String firstName, String lastName, String email, String institution, String dataDirectory, Object group, Integer i); /** * Creates a group in the metadata store with a particular index. * @param name the name of the group. * @param leader the leader of the group. * @param contact the contact for the group. * @param i the index to use in the store. If <code>null</code> the default * index of 0 will be used. */ void setGroup(String name, Object leader, Object contact, Integer i); /** * Creates an instrument in the metadata store with a particular index. * @param manufacturer the name of the manufacturer. * @param model the model number of the instrument. * @param serialNumber the serial number of the instrument. * @param type the type of the instrument. * @param i the index to use in the store. If <code>null</code> the default * index of 0 will be used. */ void setInstrument(String manufacturer, String model, String serialNumber, String type, Integer i); /** * Creates a set of pixel dimensions in the metadata store with a particular * index. Unless both values are non-null, the MetadataStore should assume * pixelSizeX equals pixelSizeY (i.e., should populate the null field with * the other field's value). * @param pixelSizeX size of an individual pixel's X axis in microns. * @param pixelSizeY size of an individual pixel's Y axis in microns. * @param pixelSizeZ size of an individual pixel's Z axis in microns. * @param pixelSizeC FIXME: Unknown * @param pixelSizeT FIXME: Unknown * @param i the index to use in the store. If <code>null</code> the default * index of 0 will be used. */ void setDimensions(Float pixelSizeX, Float pixelSizeY, Float pixelSizeZ, Float pixelSizeC, Float pixelSizeT, Integer i); /** * Creates a 5D bounding box region of interest and a set of display options * in the metadata store with a particular index. * @param x0 the starting X coordinate. * @param y0 the starting Y coordinate. * @param z0 the starting Z coordinate. * @param x1 the ending X coordinate. * @param y1 the ending Y coordinate. * @param z1 the ending Z coordinate. * @param t0 the starting timepoint. * @param t1 the ending timepoint. * @param displayOptions the display options to attach to this region of * interest. * @param i the index to use in the store. If <code>null</code> the default * index of 0 will be used. */ void setDisplayROI(Integer x0, Integer y0, Integer z0, Integer x1, Integer y1, Integer z1, Integer t0, Integer t1, Object displayOptions, Integer i); /** * Creates a pixels set in the metadata store with a particular * image and pixels index. * @param sizeX size of an individual plane or section's X axis (width) * @param sizeY size of an individual plane of section's Y axis (height) * @param sizeZ number of optical sections per channel, per timepoint * (per stack) * @param sizeC number of channels per timepoint. * @param sizeT number of timepoints. * @param pixelType the pixel type. One of the enumerated static values * present in {@link FormatReader}. * @param bigEndian if the pixels set is big endian or not. * @param dimensionOrder the dimension order of the pixels set. * @param imageNo the image index to use in the store. * If <code>null</code> the default index of 0 will be used. * @param pixelsNo the pixels index to use in the store. * If <code>null</code> the default index of 0 will be used. */ void setPixels(Integer sizeX, Integer sizeY, Integer sizeZ, Integer sizeC, Integer sizeT, Integer pixelType, Boolean bigEndian, String dimensionOrder, Integer imageNo, Integer pixelsNo); /** * Creates a stage label in the metadata store with a particular index. * @param name a name for the stage label. * @param x coordinate of the stage. * @param y coordinate of the stage. * @param z coordinate of the stage. * @param i the index to use in the store. If <code>null</code> the default * index of 0 will be used. */ void setStageLabel(String name, Float x, Float y, Float z, Integer i); /** * Creates a logical channel and physical channel in the metadata store for a * particular pixels. * @param channelIdx the index of the channel within the pixels set. * @param name the logical channel's name. * @param ndFilter the neutral-density filter value. * @param emWave the emission wavelength. * @param exWave the excitation wavelength. * @param photometricInterpretation the photometric interpretation type. * @param mode the acquisition mode. * @param i the index of the pixels set within the metadata store. */ void setLogicalChannel(int channelIdx, String name, Float ndFilter, Integer emWave, Integer exWave, String photometricInterpretation, String mode, Integer i); /** * Sets a channel's global min and global max in the metadata store for a * particular pixels set. * * NOTE: The implementation of this method is optional and can be purely a * no-op. It is here to ensure compatability with certain stores which require * this data to be specified explicitly. * * @param channel the index of the channel within the pixels set. * @param globalMin the global minimum pixel value for the channel. * @param globalMax the global maximum pixel value for the channel. * @param i the index of the pixels set within the metadata store. */ void setChannelGlobalMinMax(int channel, Double globalMin, Double globalMax, Integer i); void setPlaneInfo(int theZ, int theC, int theT, Float timestamp, Float exposureTime, Integer i); /** * Instructs the metadata store to set the default display settings for a * particular pixels set. * @param i the index of the pixels set within the metadata store. */ void setDefaultDisplaySettings(Integer i); /** Sets the imaging environment for a particular image. */ void setImagingEnvironment(Float temperature, Float airPressure, Float humidity, Float co2Percent, Integer i); /** Sets information about the specified channel for a particular image. */ void setDisplayChannel(Integer channelNumber, Double blackLevel, Double whiteLevel, Float gamma, Integer i); /** Sets various display options for a particular pixels set. */ void setDisplayOptions(Float zoom, Boolean redChannelOn, Boolean greenChannelOn, Boolean blueChannelOn, Boolean displayRGB, String colorMap, Integer zstart, Integer zstop, Integer tstart, Integer tstop, Integer imageNdx, Integer pixelsNdx, Integer redChannel, Integer greenChannel, Integer blueChannel, Integer grayChannel); /** Sets a light source for a particular instrument. */ void setLightSource(String manufacturer, String model, String serialNumber, Integer instrumentIndex, Integer lightIndex); /** Sets a laser for a particular instrument. */ void setLaser(String type, String medium, Integer wavelength, Boolean frequencyDoubled, Boolean tunable, String pulse, Float power, Integer instrumentNdx, Integer lightNdx, Integer pumpNdx, Integer laserNdx); /** Sets a filament for a particular instrument. */ void setFilament(String type, Float power, Integer lightNdx, Integer filamentNdx); /** Sets an arc for a particular instrument. */ void setArc(String type, Float power, Integer lightNdx, Integer arcNdx); /** Sets a detector for a particular instrument. */ void setDetector(String manufacturer, String model, String serialNumber, String type, Float gain, Float voltage, Float offset, Integer instrumentNdx, Integer detectorNdx); /** Sets an objective for a particular instrument. */ void setObjective(String manufacturer, String model, String serialNumber, Float lensNA, Float magnification, Integer instrumentNdx, Integer objectiveNdx); /** Sets an excitation filter for a particular instrument. */ void setExcitationFilter(String manufacturer, String model, String lotNumber, String type, Integer filterNdx); /** Sets a dichroic for a particular instrument. */ void setDichroic(String manufacturer, String model, String lotNumber, Integer dichroicNdx); /** Sets an emission filter for a particular instrument. */ void setEmissionFilter(String manufacturer, String model, String lotNumber, String type, Integer filterNdx); /** Sets a filter set for a particular instrument. */ void setFilterSet(String manufacturer, String model, String lotNumber, Integer filterSetNdx, Integer filterNdx); /** Sets an OTF for a particular instrument. */ void setOTF(Integer sizeX, Integer sizeY, String pixelType, String path, Boolean opticalAxisAverage, Integer instrumentNdx, Integer otfNdx, Integer filterNdx, Integer objectiveNdx); }
// SystemControls.java package loci.visbio; import com.jgoodies.forms.builder.PanelBuilder; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Enumeration; import java.util.Properties; import javax.swing.*; import loci.visbio.util.LAFUtil; import loci.visbio.util.VisUtil; import visad.VisADException; import visad.data.qt.QTForm; import visad.util.ReflectedUniverse; /** SystemControls is the control panel for reporting system information. */ public class SystemControls extends ControlPanel implements ActionListener { // -- GUI components -- /** Memory usage text field. */ private JTextField memField; // -- Fields -- /** Current memory usage. */ protected String memUsage; // -- Constructor -- /** Constructs a control panel for viewing system information. */ public SystemControls(LogicManager logic) { super(logic, "System", "Reports system information"); VisBioFrame bio = lm.getVisBio(); SystemManager sm = (SystemManager) lm; // dump properties button JButton dump = new JButton("Dump all"); if (!LAFUtil.isMacLookAndFeel()) dump.setMnemonic('d'); dump.setToolTipText("Dumps system property values to the output console"); dump.setActionCommand("dump"); dump.addActionListener(this); // operating system text field JTextField osField = new JTextField(System.getProperty("os.name") + " (" + System.getProperty("os.arch") + ")"); osField.setEditable(false); // java version text field JTextField javaField = new JTextField(System.getProperty("java.version") + " (" + System.getProperty("java.vendor") + ")"); javaField.setEditable(false); // memory usage text field memField = new JTextField("xxxx MB used (xxxx MB reserved)"); memField.setEditable(false); // garbage collection button JButton clean = new JButton("Clean"); if (!LAFUtil.isMacLookAndFeel()) clean.setMnemonic('c'); clean.setToolTipText( "Calls the Java garbage collector to free wasted memory"); clean.setActionCommand("clean"); clean.addActionListener(this); // memory maximum text field JTextField heapField = new JTextField( sm.getMaximumMemory() + " MB maximum"); heapField.setEditable(false); // memory maximum alteration button JButton heap = new JButton("Change..."); if (!LAFUtil.isMacLookAndFeel()) heap.setMnemonic('a'); if (sm.isJNLP()) heap.setEnabled(false); heap.setToolTipText( "Edits the maximum amount of memory available to VisBio"); heap.setActionCommand("heap"); heap.addActionListener(this); // Java3D library text field JTextField java3dField = new JTextField( getVersionString("javax.vecmath.Point3d")); java3dField.setEditable(false); // JPEG library text field JTextField jpegField = new JTextField( getVersionString("com.sun.image.codec.jpeg.JPEGCodec")); jpegField.setEditable(false); // QuickTime library text field String qtVersion = null; try { ReflectedUniverse r = new QTForm().getUniverse(); String qtMajor = r.exec("QTSession.getMajorVersion()").toString(); String qtMinor = r.exec("QTSession.getMinorVersion()").toString(); qtVersion = qtMajor + "." + qtMinor; } catch (VisADException exc) { qtVersion = "Missing"; } JTextField qtField = new JTextField(qtVersion); qtField.setEditable(false); // Python library text field JTextField pythonField = new JTextField( getVersionString("org.python.util.PythonInterpreter")); pythonField.setEditable(false); // JAI library text field JTextField jaiField = new JTextField( getVersionString("javax.media.jai.JAI")); jaiField.setEditable(false); // Look & Feel text field JTextField lafField = new JTextField(LAFUtil.getLookAndFeel()[0]); lafField.setEditable(false); // Look & Feel alteration button JButton laf = new JButton("Change..."); if (!LAFUtil.isMacLookAndFeel()) laf.setMnemonic('n'); if (sm.isJNLP()) laf.setEnabled(false); laf.setToolTipText("Edits VisBio's graphical Look & Feel"); laf.setActionCommand("laf"); laf.addActionListener(this); // Stereo configuration text field JTextField stereoField = new JTextField( VisUtil.getStereoConfiguration() == null ? "Not available" : "Enabled"); stereoField.setEditable(false); // lay out components FormLayout layout = new FormLayout( "right:pref, 3dlu, pref:grow, 3dlu, pref", "pref, 3dlu, pref, 3dlu, pref, 3dlu, pref, 3dlu, pref, 9dlu, " + "pref, 3dlu, pref, 3dlu, pref, 3dlu, pref, 3dlu, pref, 3dlu, " + "pref, 9dlu, pref, 3dlu, pref, 3dlu, pref"); PanelBuilder builder = new PanelBuilder(layout); builder.setDefaultDialogBorder(); CellConstraints cc = new CellConstraints(); builder.addSeparator("Properties", cc.xyw(1, 1, 3)); builder.add(dump, cc.xy(5, 1)); builder.addLabel("&Operating system", cc.xy(1, 3)).setLabelFor(osField); builder.add(osField, cc.xyw(3, 3, 3)); builder.addLabel("&Java version", cc.xy(1, 5)).setLabelFor(javaField); builder.add(javaField, cc.xyw(3, 5, 3)); builder.addLabel("&Memory usage", cc.xy(1, 7)).setLabelFor(memField); builder.add(memField, cc.xy(3, 7)); builder.add(clean, cc.xy(5, 7)); builder.addLabel("&Memory maximum", cc.xy(1, 9)).setLabelFor(heapField); builder.add(heapField, cc.xy(3, 9)); builder.add(heap, cc.xy(5, 9)); builder.addSeparator("Libraries", cc.xyw(1, 11, 5)); builder.addLabel("Java&3D", cc.xy(1, 13)).setLabelFor(java3dField); builder.add(java3dField, cc.xyw(3, 13, 3)); builder.addLabel("JPE&G", cc.xy(1, 15)).setLabelFor(jpegField); builder.add(jpegField, cc.xyw(3, 15, 3)); builder.addLabel("&QuickTime", cc.xy(1, 17)).setLabelFor(qtField); builder.add(qtField, cc.xyw(3, 17, 3)); builder.addLabel("&Python", cc.xy(1, 19)).setLabelFor(pythonField); builder.add(pythonField, cc.xyw(3, 19, 3)); builder.addLabel("JA&I", cc.xy(1, 21)).setLabelFor(jaiField); builder.add(jaiField, cc.xyw(3, 21, 3)); builder.addSeparator("Configuration", cc.xyw(1, 23, 5)); builder.addLabel("&Look && Feel", cc.xy(1, 25)).setLabelFor(lafField); builder.add(lafField, cc.xy(3, 25)); builder.add(laf, cc.xy(5, 25)); builder.addLabel("&Stereo", cc.xy(1, 27)).setLabelFor(stereoField); builder.add(stereoField, cc.xyw(3, 27, 3)); controls.add(builder.getPanel()); // update system information twice per second Timer t = new Timer(500, this); t.start(); } // -- ActionListener API methods -- /** Handles action events. */ public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); SystemManager sm = (SystemManager) lm; if ("dump".equals(cmd)) { Properties properties = System.getProperties(); // Properties.list() truncates the property values, so we iterate //properties.list(System.out); System.out.println("-- listing properties --"); Enumeration list = properties.propertyNames(); while (list.hasMoreElements()) { String key = (String) list.nextElement(); String value = properties.getProperty(key); System.out.println(key + "=" + value); } } else if ("clean".equals(cmd)) sm.cleanMemory(); else if ("heap".equals(cmd)) { String max = "" + sm.getMaximumMemory(); String heapSize = (String) JOptionPane.showInputDialog(this, "New maximum memory value:", "VisBio", JOptionPane.QUESTION_MESSAGE, null, null, "" + max); if (heapSize == null || heapSize.equals(max)) return; int maxHeap = -1; try { maxHeap = Integer.parseInt(heapSize); } catch (NumberFormatException exc) { } if (maxHeap < 16) { JOptionPane.showMessageDialog(this, "Maximum memory value must be at least 16 MB.", "VisBio", JOptionPane.ERROR_MESSAGE); return; } sm.writeScript(maxHeap, null); JOptionPane.showMessageDialog(controls, "The change will take effect next time you run VisBio.", "VisBio", JOptionPane.INFORMATION_MESSAGE); } else if ("laf".equals(cmd)) { String[] laf = LAFUtil.getLookAndFeel(); final String[][] lafs = LAFUtil.getAvailableLookAndFeels(); String lafName = (String) JOptionPane.showInputDialog(this, "New Look & Feel:", "VisBio", JOptionPane.QUESTION_MESSAGE, null, lafs[0], laf[0]); if (lafName == null) return; int ndx = -1; for (int i=0; i<lafs[0].length; i++) { if (lafs[0][i].equals(lafName)) { ndx = i; break; } } if (ndx < 0 || lafs[1][ndx].equals(laf[1])) return; sm.writeScript(-1, lafs[1][ndx]); JOptionPane.showMessageDialog(controls, "The change will take effect next time you run VisBio.", "VisBio", JOptionPane.INFORMATION_MESSAGE); } else { // update system information if (!lm.getVisBio().isVisible()) return; String mem = ((SystemManager) lm).getMemoryUsage(); if (!mem.equals(memUsage)) { memUsage = mem; memField.setText(mem); } } } // -- Helper methods -- /** Gets version information for the specified class. */ private String getVersionString(String clas) { Class c = null; try { c = Class.forName(clas); } catch (ClassNotFoundException exc) { c = null; } return getVersionString(c); } /** Gets version information for the specified class. */ private String getVersionString(Class c) { if (c == null) return "Missing"; Package p = c.getPackage(); if (p == null) return "No package"; String vendor = p.getImplementationVendor(); String version = p.getImplementationVersion(); if (vendor == null && version == null) return "Installed"; else if (vendor == null) return version; else if (version == null) return vendor; else return version + " (" + vendor + ")"; } }
// DataCache.java package loci.visbio.data; import java.util.Hashtable; import loci.formats.FormatTools; import visad.Data; public class DataCache { // -- Constants -- /** Debugging flag. */ protected static final boolean DEBUG = false; // -- Fields -- /** Hashtable backing this cache of full-resolution data. */ protected Hashtable hash; // -- Constructor -- /** Constructs a cache for managing full-resolution data in memory. */ public DataCache() { hash = new Hashtable(); } // -- DataCache API methods -- /** Gets the data object from the cache, computing it if the cache misses. */ public synchronized Data getData(DataTransform trans, int[] pos, String append, int dim) { String key = getKey(trans, pos, append); Data d = getCachedData(key); if (d == null) { // do not compute for non-null append if (append == null || append.equals("")) { // compute automatically for null append string d = trans.getData(null, pos, dim, null); putCachedData(key, d); } if (DEBUG) System.out.println("DataCache: cache miss for " + key); } else if (DEBUG) System.out.println("DataCache: cache hit for " + key); return d; } /** * Puts the given data object into the cache for the specified transform * at the given dimensional position. */ public synchronized void putData(DataTransform trans, int[] pos, String append, Data d) { putCachedData(getKey(trans, pos, append), d); } /** * Gets whether the cache has data for the given transform * at the specified dimensional position. */ public synchronized boolean hasData(DataTransform trans, int[] pos, String append) { return getCachedData(getKey(trans, pos, append)) != null; } /** * Removes the data object at the specified * dimensional position from the cache. */ public synchronized void dump(DataTransform trans, int[] pos, String append) { dump(getKey(trans, pos, append)); } /** * Removes from the cache data objects at all dimensional positions * for the given data object. */ public synchronized void dump(DataTransform trans, String append) { int[] lengths = trans.getLengths(); int len = FormatTools.getRasterLength(lengths); for (int i=0; i<len; i++) { int[] pos = FormatTools.rasterToPosition(lengths, i); dump(getKey(trans, pos, append)); } } /** Removes everything from the cache. */ public synchronized void dumpAll() { hash.clear(); } // -- Internal DataCache API methods -- /** Gets the data in the cache at the specified key. */ protected Data getCachedData(String key) { if (key == null) return null; Object o = hash.get(key); if (!(o instanceof Data)) return null; return (Data) o; } /** Sets the data in the cache at the specified key. */ protected void putCachedData(String key, Data d) { if (key != null && d != null) hash.put(key, d); } /** Removes the data object at the specified key from the cache. */ protected void dump(String key) { if (key != null) { hash.remove(key); if (DEBUG) System.out.println("DataCache: dumped " + key); } } // -- Helper methods -- /** * Gets a key string suitable for hashing for the given transform at the * specified position. Changing the append string allows storage of multiple * data objects at the same dimensional position for the same transform. */ protected String getKey(DataTransform trans, int[] pos, String append) { if (append == null) append = ""; String id = pos == null ? null : trans.getCacheId(pos, true); return id + append; } }
/* * $Log: IAdapter.java,v $ * Revision 1.6 2004-08-09 08:43:46 L190409 * added formatErrorMessage() * * Revision 1.5 2004/06/16 12:34:46 Johan Verrips <johan.verrips@ibissource.org> * Added AutoStart functionality on Adapter * * Revision 1.4 2004/03/26 10:42:50 Johan Verrips <johan.verrips@ibissource.org> * added @version tag in javadoc * * Revision 1.3 2004/03/23 17:36:58 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added methods for Transaction control * */ package nl.nn.adapterframework.core; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.util.MessageKeeper; import java.util.Iterator; import javax.transaction.UserTransaction; /** * The Adapter is the central manager in the framework. It has knowledge of both * <code>IReceiver</code>s as well as the <code>PipeLine</code> and statistics. * The Adapter is the class that is responsible for configuring, initializing and * accessing/activating IReceivers, Pipelines, statistics etc. * * @version Id **/ public interface IAdapter extends IManagable { public static final String version="$Id: IAdapter.java,v 1.6 2004-08-09 08:43:46 L190409 Exp $"; /** * Instruct the adapter to configure itself. The adapter will call the * pipeline to configure itself, the pipeline will call the individual * pipes to configure themselves. * @see nl.nn.adapterframework.pipes.AbstractPipe#configure() * @see PipeLine#configurePipes() */ public void configure() throws ConfigurationException; /** * The messagekeeper is used to keep the last x messages, relevant to * display in the web-functions. */ public MessageKeeper getMessageKeeper(); public IReceiver getReceiverByName(String receiverName); public Iterator getReceiverIterator(); public PipeLineResult processMessage(String correlationID, String message); public void registerPipeLine (PipeLine pipeline) throws ConfigurationException; public void setName(String name); public boolean isAutoStart(); public String toString(); /** * return the userTransaction object that can be used to demarcate (begin/commit/rollback) transactions */ public UserTransaction getUserTransaction() throws TransactionException; /** * return true when the current thread is running under a transaction. */ public boolean inTransaction() throws TransactionException; public String formatErrorMessage( String errorMessage, Throwable t, String originalMessage, String messageID, INamedObject objectInError, long receivedTime); }
package org.unitime.timetable.model; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.TreeSet; import org.hibernate.criterion.Restrictions; import org.unitime.timetable.model.base.BaseBuilding; import org.unitime.timetable.model.dao.BuildingDAO; import org.unitime.timetable.model.dao.RoomDAO; public class Building extends BaseBuilding implements Comparable { private static final long serialVersionUID = 3256440313428981557L; /*[CONSTRUCTOR MARKER BEGIN]*/ public Building () { super(); } /** * Constructor for primary key */ public Building (java.lang.Long uniqueId) { super(uniqueId); } /** * Constructor for required fields */ public Building ( java.lang.Long uniqueId, org.unitime.timetable.model.Session session, java.lang.String externalUniqueId, java.lang.String abbreviation, java.lang.String name, java.lang.Integer coordinateX, java.lang.Integer coordinateY) { super ( uniqueId, session, externalUniqueId, abbreviation, name, coordinateX, coordinateY); } /*[CONSTRUCTOR MARKER END]*/ /** Request attribute name for available buildings **/ public static String BLDG_LIST_ATTR_NAME = "bldgsList"; /** * @return Building Identifier of the form {Abbr} - {Name} */ public String getAbbrName() { return this.getAbbreviation() + " - " + this.getName(); } /** * Dummy setter - does nothing (Do not use) */ public void setAbbrName(String abbrName) { } /** * @return Building Identifier of the form {Abbr} - {Name} */ public String toString() { return getAbbrName(); } public int compareTo(Object o) { if (o==null || !(o instanceof Building)) return -1; Building b = (Building)o; int cmp = getAbbreviation().compareTo(b.getAbbreviation()); if (cmp!=0) return cmp; return getUniqueId().compareTo(b.getUniqueId()); } /** * * @param bldgAbbv * @param sessionId * @return * @throws Exception */ public static Building findByBldgAbbv(String bldgAbbv, Long sessionId) throws Exception { List bldgs = (new BuildingDAO()).getQuery( "SELECT distinct b FROM Building b "+ "WHERE b.session.uniqueId=:sessionId AND b.abbreviation=:bldgAbbv"). setLong("sessionId", sessionId.longValue()). setString("bldgAbbv", bldgAbbv). list(); if (!bldgs.isEmpty()) return (Building)bldgs.get(0); return null; } /* * Update building information using External Building * @param sessionId */ public static void updateBuildings(Long sessionId) { Session currentSession = Session.getSessionById(sessionId); TreeSet currentBuildings = new TreeSet(currentSession.getBuildings()); Hashtable updateBuildings = ExternalBuilding.getBuildings(sessionId); Iterator b = currentBuildings.iterator(); BuildingDAO bldgDAO = new BuildingDAO(); while(b.hasNext()) { Building bldg = (Building)b.next(); String externalUniqueId = bldg.getExternalUniqueId(); if(externalUniqueId != null) { ExternalBuilding extBldg = (ExternalBuilding)updateBuildings.get(externalUniqueId); if(extBldg != null) { if(updateBldgInfo(bldg, extBldg)) { bldgDAO.update(bldg); } updateBuildings.remove(extBldg.getExternalUniqueId()); } else { if(checkBuildingDelete(bldg)) { currentSession.getBuildings().remove(bldg); bldgDAO.delete(bldg); } } } } Iterator eb = (updateBuildings.values()).iterator(); while(eb.hasNext()) { ExternalBuilding extBldg = (ExternalBuilding)eb.next(); Building newBldg = new Building(); newBldg.setAbbreviation(extBldg.getAbbreviation()); newBldg.setCoordinateX(extBldg.getCoordinateX()); newBldg.setCoordinateY(extBldg.getCoordinateY()); newBldg.setName(extBldg.getDisplayName()); newBldg.setSession(currentSession); newBldg.setExternalUniqueId(extBldg.getExternalUniqueId()); bldgDAO.save(newBldg); } return; } /* * Update building information * @param bldg (Building) * @param extBldg (ExternalBuilding) * @return update (True if updates are made) */ private static boolean updateBldgInfo(Building bldg, ExternalBuilding extBldg) { boolean updated = false; if(!bldg.getAbbreviation().equals(extBldg.getAbbreviation())) { bldg.setAbbreviation(extBldg.getAbbreviation()); updated = true; } if(!bldg.getName().equals(extBldg.getDisplayName())) { bldg.setName(extBldg.getDisplayName()); updated = true; } if((bldg.getCoordinateX().compareTo(extBldg.getCoordinateX())) != 0) { bldg.setCoordinateX(extBldg.getCoordinateX()); updated = true; } if((bldg.getCoordinateY().compareTo(extBldg.getCoordinateY())) != 0) { bldg.setCoordinateY(extBldg.getCoordinateY()); updated = true; } return updated; } /* * Check if building can be deleted * @param bldg * @return boolean (True if building can be deleted) */ private static boolean checkBuildingDelete(Building bldg) { boolean result = false;; List rooms = (new RoomDAO()).getQuery( "from Room as rm " + "where rm.building.uniqueId = " + (bldg.getUniqueId()).longValue()). list(); if(rooms.isEmpty()) { result = true; } return result; } public Object clone() { Building b = new Building(); b.setAbbreviation(getAbbreviation()); b.setCoordinateX(getCoordinateX()); b.setCoordinateY(getCoordinateY()); b.setExternalUniqueId(getExternalUniqueId()); b.setName(getName()); b.setSession(getSession()); return b; } public Building findSameBuildingInSession(Session newSession) throws Exception{ if (newSession == null){ return(null); } Building newBuilding = Building.findByBldgAbbv(this.getAbbreviation(), newSession.getUniqueId()); if (newBuilding == null && this.getExternalUniqueId() != null){ newBuilding = Building.findByExternalIdAndSession(getExternalUniqueId(), newSession); } return(newBuilding); } public static Building findByExternalIdAndSession(String externalId, Session session){ BuildingDAO bDao = new BuildingDAO(); List bldgs = bDao.getSession().createCriteria(Building.class) .add(Restrictions.eq("externalUniqueId", externalId)) .add(Restrictions.eq("session.uniqueId", session.getUniqueId())) .setCacheable(true).list(); if (bldgs != null && bldgs.size() == 1){ return((Building) bldgs.get(0)); } return(null); } }
package ui; import java.io.IOException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.concurrent.Task; import javafx.geometry.Orientation; import javafx.scene.Node; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.ScrollBar; import javafx.scene.control.ScrollPane; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCodeCombination; import javafx.scene.input.KeyCombination; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import service.ServiceManager; import ui.issuecolumn.ColumnControl; import util.DialogMessage; import util.events.IssueCreatedEvent; import util.events.LabelCreatedEvent; import util.events.MilestoneCreatedEvent; public class MenuControl extends MenuBar { private static final Logger logger = LogManager.getLogger(MenuControl.class.getName()); private final ColumnControl columns; private final ScrollPane columnsScroll; private final UI ui; public MenuControl(UI ui, ColumnControl columns, ScrollPane columnsScroll) { this.columns = columns; this.columnsScroll = columnsScroll; this.ui = ui; createMenuItems(); } private void createMenuItems() { Menu newMenu = new Menu("New"); newMenu.getItems().addAll(createNewMenuItems()); Menu view = new Menu("View"); view.getItems().addAll(createRefreshMenuItem(), createForceRefreshMenuItem(), createColumnsMenuItem(), createDocumentationMenuItem()); getMenus().addAll(newMenu, view); } private MenuItem createColumnsMenuItem() { Menu cols = new Menu("Panels"); MenuItem createLeft = new MenuItem("Create Panel (Left)"); createLeft.setOnAction(e -> { logger.info("Menu: View > Panels > Create Panel (Left)"); columns.createNewPanelAtStart(); columnsScroll.setHvalue(columnsScroll.getHmin()); }); createLeft.setAccelerator(new KeyCodeCombination(KeyCode.N, KeyCombination.CONTROL_DOWN, KeyCombination.SHIFT_DOWN)); MenuItem createRight = new MenuItem("Create Panel"); createRight.setOnAction(e -> { logger.info("Menu: View > Panels > Create Panel"); columns.createNewPanelAtEnd(); // listener is used as columnsScroll's Hmax property doesn't update synchronously ChangeListener<Number> listener = new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> arg0, Number arg1, Number arg2) { for (Node child : columnsScroll.getChildrenUnmodifiable()) { if (child instanceof ScrollBar) { ScrollBar scrollBar = (ScrollBar) child; if (scrollBar.getOrientation() == Orientation.HORIZONTAL && scrollBar.visibleProperty().get()) { columnsScroll.setHvalue(columnsScroll.getHmax()); break; } } } columns.widthProperty().removeListener(this); } }; columns.widthProperty().addListener(listener); }); createRight.setAccelerator(new KeyCodeCombination(KeyCode.N, KeyCombination.CONTROL_DOWN)); MenuItem closeColumn = new MenuItem("Close Panel"); closeColumn.setOnAction(e -> { logger.info("Menu: View > Panels > Close Panel"); columns.closeCurrentColumn(); }); closeColumn.setAccelerator(new KeyCodeCombination(KeyCode.W, KeyCombination.CONTROL_DOWN)); cols.getItems().addAll(createRight, createLeft, closeColumn); return cols; } private MenuItem createDocumentationMenuItem() { MenuItem documentationMenuItem = new MenuItem("Documentation"); documentationMenuItem.setOnAction((e) -> { logger.info("Menu: View > Documentation"); ui.getBrowserComponent().showDocs(); }); documentationMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.F1)); return documentationMenuItem; } private MenuItem createRefreshMenuItem() { MenuItem refreshMenuItem = new MenuItem("Refresh"); refreshMenuItem.setOnAction((e) -> { logger.info("Menu: View > Refresh"); ServiceManager.getInstance().restartModelUpdate(); columns.refresh(); }); refreshMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.F5)); return refreshMenuItem; } private MenuItem createForceRefreshMenuItem() { MenuItem forceRefreshMenuItem = new MenuItem("Force Refresh"); forceRefreshMenuItem.setOnAction((e) -> { triggerForceRefreshProgressDialog(); }); forceRefreshMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.F5, KeyCombination.CONTROL_DOWN)); return forceRefreshMenuItem; } private void triggerForceRefreshProgressDialog() { Task<Boolean> task = new Task<Boolean>(){ @Override protected Boolean call() throws IOException { try { logger.info("Menu: View > Force Refresh"); ServiceManager.getInstance().stopModelUpdate(); ServiceManager.getInstance().getModel().forceReloadComponents(); ServiceManager.getInstance().restartModelUpdate(); } catch (SocketTimeoutException e) { handleSocketTimeoutException(e); return false; } catch (UnknownHostException e) { handleUnknownHostException(e); return false; } catch (Exception e) { logger.error(e.getMessage(), e); e.printStackTrace(); return false; } logger.info("Menu: View > Force Refresh completed"); return true; } private void handleSocketTimeoutException(Exception e) { Platform.runLater(() -> { logger.error(e.getMessage(), e); DialogMessage.showWarningDialog("Internet Connection is down", "Timeout while loading items from github. Please check your internet connection."); }); } private void handleUnknownHostException(Exception e) { Platform.runLater(() -> { logger.error(e.getMessage(), e); DialogMessage.showWarningDialog("No Internet Connection", "Please check your internet connection and try again"); }); } }; DialogMessage.showProgressDialog(task, "Reloading issues for current repo... This may take awhile, please wait."); Thread thread = new Thread(task); thread.setDaemon(true); thread.start(); } private MenuItem[] createNewMenuItems() { MenuItem newIssueMenuItem = new MenuItem("Issue"); newIssueMenuItem.setOnAction(e -> { logger.info("Menu: New > Issue"); ui.triggerEvent(new IssueCreatedEvent()); }); newIssueMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.I, KeyCombination.CONTROL_DOWN)); MenuItem newLabelMenuItem = new MenuItem("Label"); newLabelMenuItem.setOnAction(e -> { logger.info("Menu: New > Label"); ui.triggerEvent(new LabelCreatedEvent()); }); newLabelMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.L, KeyCombination.CONTROL_DOWN)); MenuItem newMilestoneMenuItem = new MenuItem("Milestone"); newMilestoneMenuItem.setOnAction(e -> { logger.info("Menu: New > Milestone"); ui.triggerEvent(new MilestoneCreatedEvent()); }); newMilestoneMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.M, KeyCombination.CONTROL_DOWN)); return new MenuItem[] {newIssueMenuItem, newLabelMenuItem, newMilestoneMenuItem}; } }
package org.minimalj.model; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import org.minimalj.util.StringUtils; public class Code { private final ResourceBundle resources; private final String prefix; private final String displayName; private final String nullText; private final String defolt; private final List<CodeItem<String>> codeItems = new ArrayList<>(); public Code(ResourceBundle resources, String prefix) { this.resources = resources; this.prefix = prefix; displayName = readDisplayName(); nullText = readNullText(); defolt = readDefault(); readValues(); } protected String getString(String key) { key = prefix + "." + key; if (resources.containsKey(key)) return resources.getString(key); else return null; } private String readDisplayName() { return getString("object"); } private String readNullText() { String unknownText = getString("null.text"); if (StringUtils.isBlank(unknownText)) { unknownText = ""; } return unknownText; } private String readDefault() { return getString("default"); } protected void readValues() { int index = 0; String key = null; while ((key = getString("key." + index)) != null) { String text = getString("text." + index); if (StringUtils.isBlank(text)) text = "Wert " + key; String description = getString("description." + index); codeItems.add(new CodeItem<String>(key, text, description)); index++; } if (index == 0) { throw new RuntimeException("Code without values: " + prefix); } } public String getDisplayName() { return displayName; } public String getNullText() { return nullText; } public String getDefault() { return defolt; } public List<CodeItem<String>> getCodeItems() { return codeItems; } public String getText(String key) { for (CodeItem<String> codeItem : codeItems) { if (StringUtils.equals(key, codeItem.getKey())) { return codeItem.getText(); } } return "Wert " + key; } public int count() { return codeItems.size(); } public int getSize() { int maxSize = 0; for (CodeItem<String> codeItem : codeItems) { maxSize = Math.max(maxSize, codeItem.getKey().length()); } return maxSize; } }
package com.bgmagar.config; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import com.bgmagar.dao.ProductDao; import com.bgmagar.dao.impl.ProductDaoImpl; import com.bgmagar.service.ProductService; import com.bgmagar.service.impl.ProductServiceImpl; @Configuration @ComponentScan("com.bgmagar") @EnableWebMvc public class AppConfig { @Bean(name = "dataSource") public DataSource getDataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://127.9.224.2:3306/api"); dataSource.setUsername("admintkFzf36"); dataSource.setPassword("UK5ehTSTmgmx"); return dataSource; } @Autowired @Bean(name = "jdbcTemplate") public JdbcTemplate getJdbcTemplate(DataSource dataSource) { return new JdbcTemplate(dataSource); } @Autowired @Bean(name = "productDao") public ProductDao getProductDao() { return new ProductDaoImpl(); } @Autowired @Bean(name = "productService") public ProductService getProductService() { return new ProductServiceImpl(); } }
package com.jcabi.ssl.maven.plugin; import java.io.File; import java.util.Properties; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; /** * Test case for {@link Cacerts}. * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ */ public final class CacertsTest { /** * Temporary folder. * @checkstyle VisibilityModifier (3 lines) */ @Rule public transient TemporaryFolder temp = new TemporaryFolder(); /** * Cacerts can generate a keystore. * @throws Exception If something is wrong */ @Test public void importsCertificatesFromKeystore() throws Exception { final File keystore = this.temp.newFile("keystore.jks"); keystore.delete(); final File truststore = this.temp.newFile("cacerts.jks"); truststore.delete(); final String pwd = "some-password"; new Keystore(pwd).activate(keystore); final Cacerts cacerts = new Cacerts(truststore); cacerts.imprt(); MatcherAssert.assertThat( new Keytool(truststore, "changeit").list(), Matchers.containsString("localhost") ); final Properties props = new Properties(); cacerts.populate(props); MatcherAssert.assertThat( truststore.getAbsolutePath(), Matchers.equalTo(props.getProperty(Cacerts.TRUST)) ); MatcherAssert.assertThat( Cacerts.STD_PWD, Matchers.equalTo(props.getProperty(Cacerts.TRUST_PWD)) ); } }
package com.jcabi.w3c; import com.jcabi.http.mock.MkAnswer; import com.jcabi.http.mock.MkContainer; import com.jcabi.http.mock.MkGrizzlyContainer; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.hamcrest.Matcher; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Ignore; import org.junit.Test; /** * Test case for {@link DefaultHtmlValidator}. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ */ public final class DefaultHtmlValidatorTest { /** * DefaultHtmlValidator can validate HTML document. * * @throws Exception If something goes wrong inside */ @Test public void validatesHtmlDocument() throws Exception { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple(this.validReturn()) ).start(); final Validator validator = new DefaultHtmlValidator(container.home()); final ValidationResponse response = validator.validate("<html/>"); container.stop(); MatcherAssert.assertThat(response.toString(), response.valid()); } /** * Test if {@link DefaultHtmlValidator} validades invalid html. * @throws Exception If something goes wrong inside */ @Test public void validateInvalidHtml() throws Exception { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple( this.invalidHtmlResponse() ) ).start(); final Validator validator = new DefaultHtmlValidator(container.home()); final ValidationResponse response = validator .validate("this is an invalid html"); container.stop(); MatcherAssert.assertThat( "Validity must be invalid!", !response.valid() ); MatcherAssert.assertThat( "Must has at least one error", response.errors(), this.withoutDefects() ); MatcherAssert.assertThat( "Must has at least one warning", response.warnings(), this.withoutDefects() ); } /** * DefaultHtmlValidator throw IOException when W3C server error occurred. * * @throws Exception If something goes wrong inside * @todo #10:30min DefaultHtmlValidator have to be updated to throw only * IOException when W3C validation server is unavailable. Any other * exception type can be confusing for users. Remove @Ignore * annotation after finishing implementation. */ @Ignore @Test @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public void throwsIOExceptionWhenValidationServerErrorOccurred() throws Exception { final Set<Integer> responses = new HashSet<Integer>( Arrays.asList( HttpURLConnection.HTTP_INTERNAL_ERROR, HttpURLConnection.HTTP_NOT_IMPLEMENTED, HttpURLConnection.HTTP_BAD_GATEWAY, HttpURLConnection.HTTP_UNAVAILABLE, HttpURLConnection.HTTP_GATEWAY_TIMEOUT, HttpURLConnection.HTTP_VERSION ) ); final Set<Integer> caught = new HashSet<Integer>(); for (final Integer status : responses) { MkContainer container = null; try { container = new MkGrizzlyContainer().next( new MkAnswer.Simple(status) ).start(); new DefaultHtmlValidator(container.home()) .validate("<html></html>"); } catch (final IOException ex) { caught.add(status); } finally { container.stop(); } } final Integer[] data = responses.toArray(new Integer[responses.size()]); MatcherAssert.assertThat(caught, Matchers.containsInAnyOrder(data)); } /** * Build a response with valid result from W3C. * @return Response from W3C. */ private String validReturn() { return StringUtils.join( "<env:Envelope", " xmlns:env='http: "<env:Body><m:markupvalidationresponse", " xmlns:m='http: "<m:validity>true</m:validity>", "<m:checkedby>W3C</m:checkedby>", "<m:doctype>text/html</m:doctype>", "<m:charset>UTF-8</m:charset>", "</m:markupvalidationresponse></env:Body></env:Envelope>" ); } /** * Use a file to build the request. * @return Request inside the file. * @throws IOException if something goes wrong. */ private String invalidHtmlResponse() throws IOException { final InputStream file = DefaultHtmlValidator.class .getResourceAsStream("invalid-html-response.xml"); final String xml = IOUtils.toString(file); IOUtils.closeQuietly(file); return xml; } /** * Matcher that checks if has no errors. * @return Matcher */ private Matcher<Collection<Defect>> withoutDefects() { return Matchers.not(Matchers.emptyCollectionOf(Defect.class)); } }
package com.newput.testCase; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.newput.domain.Employee; import com.newput.mapper.DateSheetMapper; import com.newput.mapper.EmployeeMapper; import com.newput.service.EmpService; import com.newput.service.LoginService; import com.newput.service.TSchedualService; import com.newput.utility.EMailSender; import com.newput.utility.ExcelTimeSheet; import com.newput.utility.JsonResService; import com.newput.utility.ReqParseService; import com.newput.utility.TTUtil; import static org.junit.Assert.*; import java.io.File; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "/applicationContext.xml") public class ControllerTestCase { @Autowired DateSheetMapper dateSheetMapper; @Autowired private Employee emp; @Autowired private EmpService empService; @Autowired private TSchedualService timeSchedual; @Autowired private ReqParseService reqParser; @Autowired private JsonResService jsonResService; @Autowired private LoginService loginService; @Autowired private TTUtil util; @Autowired private EMailSender emailSend; @Autowired private ExcelTimeSheet excelTimeSheet; @Autowired EmployeeMapper empMapper; public Long getCurrentTime() { return System.currentTimeMillis() / 1000; } String email = "rahul@newput.com"; String password = "abcd"; String empId = "1"; String firstName = "deepti"; String lastName = "gmail"; String dob = "28-05-1990"; String doj = "10-10-2015"; String address = "indore local"; String contact = "1234567890"; String gender = "f"; String month = "October"; String year = "2015"; @Test @Ignore public void testRegisterUser(){ try{ SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); emp.setFirstName(firstName); emp.setLastName(lastName); emp.setEmail(email); Date userDob = sdf.parse(dob); Date userDoj = sdf.parse(doj); emp.setDob(userDob); emp.setDoj(userDoj); emp.setAddress(address); emp.setContact(contact); emp.setGender(gender); String getPassword = util.md5(password); emp.setPassword(getPassword); emp.setStatus(false); emp.setPasswordVerification(false); emp.setRole("guest"); emp.setCreated(getCurrentTime()); emp.setTimeZone(new BigDecimal("5.5")); String token = util.generateRandomString(); emp.setvToken(token); }catch(Exception e){} empService.addUser(emp); assertEquals(true, jsonResService.isSuccess()); if (jsonResService.isSuccess()) { String sendMail = emailSend.sendMail("registration"); assertEquals(null, sendMail); } } @Test @Ignore public void testMailVerification(){ emp.setvToken("3686"); emp.setEmail(email); empService.mailVerify(emp); assertEquals(true, jsonResService.isSuccess()); } @Test @Ignore public void testLogin() { emp.setEmail(email); emp.setPassword(password); loginService.createSession(emp); assertEquals(true, jsonResService.isSuccess()); } @Test @Ignore public void testTimeEntry() throws ParseException { timeSchedual.timeSheetValue("12:00", "9:00", "19:30", "06-10-2015", "12:30", "21:00", "23:00", Integer.parseInt(empId)); reqParser.setDateSheetValue("this is my 6 date", "06-10-2015", Integer.parseInt(empId)); timeSchedual.dateSheetValue(); assertEquals(true, jsonResService.isSuccess()); } @Test @Ignore public void testForgotPwd(){ emp.setEmail(email); String ptoken = util.generateRandomString(); empService.resetPassword(email, ptoken, "password"); assertEquals(true, jsonResService.isSuccess()); if (jsonResService.isSuccess()) { String sendMail = emailSend.sendMail("password"); assertEquals(null, sendMail); } } @Test @Ignore public void testExcelExport(){ assertEquals(true, util.validCheck(month, year)); File file = excelTimeSheet.createExcelSheet(Integer.parseInt(empId), month, year); assertEquals(true, jsonResService.isSuccess()); file.delete(); } @Test @Ignore public void testPasswordVerification(){ emp.setId(Integer.parseInt(empId)); emp.setpToken("4669"); String newPassword = util.md5("rahul"); emp.setPassword(newPassword); emp.setUpdated(getCurrentTime()); empService.pwdVerify(emp); assertEquals(true, jsonResService.isSuccess()); } @Test @Ignore public void testMonthlyExcel(){ assertEquals(true, util.validCheck(month, year)); //excelTimeSheet.getTimeSheetData(month, Integer.parseInt(empId), year); assertEquals(true, jsonResService.isSuccess()); assertNotNull(jsonResService.getData()); } @Test public void testName(){ assertEquals("John Smith", "John Smith"); } }
package com.tatadada.api; import com.tatadada.api.frontend.ChannelController; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.MediaType; import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.hamcrest.Matchers.equalTo; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MockServletContext.class) @WebAppConfiguration public class ChannelControllerTest { private MockMvc mvc; @Before public void setUp() throws Exception { mvc = MockMvcBuilders.standaloneSetup(new ChannelController()).build(); } @Test public void getHello() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(equalTo("Greetings from Spring Boot!"))); } }
package ml.shifu.shifu.core; import org.testng.Assert; import org.testng.annotations.Test; public class ConvergeJudgerTest { @Test public void testIsConverged() { double train_err = 1.0; double test_err = 3.0; double threshold1 = 1.0; double threshold2 = 2.0; double threshold3 = 3.0; Assert.assertFalse(ConvergeJudger.isConverged(train_err, test_err, threshold1)); Assert.assertTrue(ConvergeJudger.isConverged(train_err, test_err, threshold2)); Assert.assertTrue(ConvergeJudger.isConverged(train_err, test_err, threshold3)); } }
package net.tascalate.concurrent; import static org.junit.Assert.assertTrue; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; public class PromisesTests { @Before public void setUp() { } @After public void tearDown() { } @Test public void testGenericArgsWithList() { Promise<List<Number>> p = combineWithList(BigDecimal.valueOf(10), Long.valueOf(11)); List<Number> v = p.join(); assertTrue("Fisrt is BigDecimal ", v.get(0) instanceof BigDecimal); assertTrue("Second is Long ", v.get(1) instanceof Long); } @Test public void testGenericArgsWithArray() { Promise<List<Number>> p = combineWithArray1(BigDecimal.valueOf(10), Long.valueOf(11)); List<Number> v = p.join(); assertTrue("Fisrt is BigDecimal ", v.get(0) instanceof BigDecimal); assertTrue("Second is Long ", v.get(1) instanceof Long); } <T, U extends T, V extends T> Promise<List<T>> combineWithList(U a, V b) { List<Promise<T>> promises = new ArrayList<>(); promises.add(Promises.success(a)); promises.add(Promises.success(b)); Promise<List<T>> all = Promises.all(promises); return all; } <T, U extends T, V extends T> Promise<List<T>> combineWithArray1(U a, V b) { @SuppressWarnings("unchecked") Promise<T>[] promises = new Promise[2]; promises[0] = Promises.success(a); promises[1] = Promises.success(b); Promise<List<T>> all = Promises.all(promises); return all; } <T, U extends T, V extends T> Promise<List<T>> combineWithArray2(U a, V b) { Promise<List<T>> all = Promises.all(Promises.success(a), Promises.success(b)); return all; } }
package org.goldenorb.queue; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.goldenorb.Message; import org.goldenorb.Messages; import org.goldenorb.OrbPartitionCommunicationProtocol; import org.goldenorb.Vertex; import org.goldenorb.Vertices; import org.goldenorb.io.input.RawSplit; public class QueueInfoCollector implements OrbPartitionCommunicationProtocol { List<Message> mList = Collections.synchronizedList(new ArrayList<Message>()); List<Vertex> vList = Collections.synchronizedList(new ArrayList<Vertex>()); @Override public void sendMessages(Messages messages) { // add all outgoing Messages to a synchronizedList to check if any Messages are lost mList.addAll(messages.getList()); } @Override public void sendVertices(Vertices vertices) { // add all outgoing Vertices to a synchronizedList to check if any messages are lost vList.addAll(vertices.getArrayList()); } @Override public long getProtocolVersion(String arg0, long arg1) throws IOException { return versionID; } @Override public void becomeActive() { // TODO Auto-generated method stub } @Override public void loadVerticesFromInputSplit(RawSplit rawsplit) { // TODO Auto-generated method stub } }
package org.mvel.tests.perftests; import ognl.Ognl; import org.mvel.MVEL; import org.mvel.tests.main.res.Base; import static java.lang.System.currentTimeMillis; import java.math.BigDecimal; import java.math.RoundingMode; /** * Performance Tests Comparing MVEL to OGNL with Same Expressions. */ public class ELComparisons { private Base baseClass = new Base(); private static int mvel = 1; private static int ognl = 1 << 1; private static int ALL = mvel + ognl; private static final int TESTNUM = 50000; private static final int TESTITER = 5; public ELComparisons() { } public static void main(String[] args) throws Exception { ELComparisons omc = new ELComparisons(); if (args.length > 0 && args[0].equals("-continuous")) { while (true) omc.runTests(); } omc.runTests(); } public void runTests() throws Exception { runTest("Simple String Pass-Through", "'Hello World'", TESTNUM, ALL); runTest("Shallow Property", "data", TESTNUM, ALL); runTest("Deep Property", "foo.bar.name", TESTNUM, ALL); runTest("Static Field Access (MVEL)", "Integer.MAX_VALUE", TESTNUM, mvel); runTest("Static Field Access (OGNL)", "@java.lang.Integer@MAX_VALUE", TESTNUM, ognl); runTest("Inline Array Creation (MVEL)", "{'foo', 'bar'}", TESTNUM, mvel); runTest("Inline Array Creation (OGNL)", "new String[] {'foo', 'bar'}", TESTNUM, ognl); runTest("Collection Access + Method Call", "funMap['foo'].happy()", TESTNUM, ALL); runTest("Boolean compare", "data == 'cat'", TESTNUM, ALL); runTest("Object instantiation", "new String('Hello')", TESTNUM, ALL); runTest("Method access", "readBack('this is a string')", TESTNUM, ALL); runTest("Arithmetic", "10 + 1 - 1", TESTNUM, ALL); } public void runTest(String name, String expression, int count, int totest) throws Exception { System.out.println("Test Name : " + name); System.out.println("Expression : " + expression); System.out.println("Iterations : " + count); System.out.println("Interpreted Results :"); long time; long mem; long total = 0; long[] res = new long[TESTITER]; if ((totest & ognl) != 0) { try { // unbenched warm-up for (int i = 0; i < count; i++) { Ognl.getValue(expression, baseClass); } System.gc(); time = currentTimeMillis(); mem = Runtime.getRuntime().freeMemory(); for (int reps = 0; reps < TESTITER; reps++) { for (int i = 0; i < count; i++) { Ognl.getValue(expression, baseClass); } if (reps == 0) res[0] = total += currentTimeMillis() - time; else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total); } System.out.println("(OGNL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP) + "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res)); } catch (Exception e) { System.out.println("(OGNL) : <<COULD NOT EXECUTE>>"); } } total = 0; if ((totest & mvel) != 0) { try { for (int i = 0; i < count; i++) { MVEL.eval(expression, baseClass); } System.gc(); time = currentTimeMillis(); mem = Runtime.getRuntime().freeMemory(); for (int reps = 0; reps < TESTITER; reps++) { for (int i = 0; i < count; i++) { MVEL.eval(expression, baseClass); } if (reps == 0) res[0] = total += currentTimeMillis() - time; else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total); } System.out.println("(MVEL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP) + "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res)); } catch (Exception e) { System.out.println("(MVEL) : <<COULD NOT EXECUTE>>"); } } // try { // for (int i = 0; i < count; i++) { // ReflectiveOptimizer.get(expression, baseClass); // System.gc(); // time = System.currentTimeMillis(); // mem = Runtime.getRuntime().freeMemory(); // for (int reps = 0; reps < 5; reps++) { // for (int i = 0; i < count; i++) { // ReflectiveOptimizer.get(expression, baseClass); // System.out.println("(MVELPropAcc) : " + new BigDecimal(((System.currentTimeMillis() - time))).divide(new BigDecimal(6), 2, RoundingMode.HALF_UP) // + "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb)"); // catch (Exception e) { // System.out.println("(MVELPropAcc) : <<COULD NOT EXECUTE>>"); // try { // for (int i = 0; i < count; i++) { // PropertyResolver.getValue(expression, baseClass); // System.gc(); // time = System.currentTimeMillis(); // mem = Runtime.getRuntime().freeMemory(); // for (int reps = 0; reps < 5; reps++) { // for (int i = 0; i < count; i++) { // PropertyResolver.getValue(expression, baseClass); // System.out.println("(WicketPropRes) : " + new BigDecimal(((System.currentTimeMillis() - time))) // .divide(new BigDecimal(6), 2, RoundingMode.HALF_UP) // + "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb)"); // catch (Exception e) { // System.out.println("(WicketPropRes) : <<COULD NOT EXECUTE>>"); runTestCompiled(name, expression, count, totest); System.out.println(" } public void runTestCompiled(String name, String expression, int count, int totest) throws Exception { Object compiled; long time; long mem; long total = 0; long[] res = new long[TESTITER]; System.out.println("Compiled Results :"); if ((totest & ognl) != 0) { try { compiled = Ognl.parseExpression(expression); for (int i = 0; i < count; i++) { Ognl.getValue(compiled, baseClass); } System.gc(); time = currentTimeMillis(); mem = Runtime.getRuntime().freeMemory(); for (int reps = 0; reps < TESTITER; reps++) { for (int i = 0; i < count; i++) { Ognl.getValue(compiled, baseClass); } if (reps == 0) res[0] = total += currentTimeMillis() - time; else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total); } System.out.println("(OGNL Compiled) : " + new BigDecimal(currentTimeMillis() - time).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP) + "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res)); } catch (Exception e) { System.out.println("(OGNL) : <<COULD NOT EXECUTE>>"); } } total = 0; if ((totest & mvel) != 0) { try { compiled = MVEL.compileExpression(expression); for (int i = 0; i < count; i++) { MVEL.executeExpression(compiled, baseClass); } System.gc(); time = currentTimeMillis(); mem = Runtime.getRuntime().freeMemory(); for (int reps = 0; reps < TESTITER; reps++) { for (int i = 0; i < count; i++) { MVEL.executeExpression(compiled, baseClass); } if (reps == 0) res[0] = total += currentTimeMillis() - time; else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total); } System.out.println("(MVEL Compiled) : " + new BigDecimal(currentTimeMillis() - time).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP) + "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res)); } catch (Exception e) { System.out.println("(MVEL) : <<COULD NOT EXECUTE>>"); } } } private static String resultsToString(long[] res) { StringBuffer sbuf = new StringBuffer("["); for (int i = 0; i < res.length; i++) { sbuf.append(res[i]); if ((i + 1) < res.length) sbuf.append(","); } sbuf.append("]"); return sbuf.toString(); } }
package org.oblodiff.util; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import static org.hamcrest.Matchers.either; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import org.junit.Test; import static org.junit.Assert.*; import org.junit.Rule; import org.junit.rules.ExpectedException; /** * Tests for {@link CharacterMatcher}. * * @author Sven Strittmatter &lt;weltraumschaf@googlemail.com&gt; */ public class CharacterMatcherTest { @Rule //CHECKSTYLE:OFF public final ExpectedException thrown = ExpectedException.none(); //CHECKSTYLE:ON @Test public void invokeConstructorByReflectionThrowsException() throws Exception { assertThat(CharacterMatcher.class.getDeclaredConstructors().length, is(1)); final Constructor<CharacterMatcher> ctor = CharacterMatcher.class.getDeclaredConstructor(); ctor.setAccessible(true); thrown.expect(either(instanceOf(UnsupportedOperationException.class)) .or(instanceOf(InvocationTargetException.class))); ctor.newInstance(); } @Test public void isLineFeed_null() { assertThat(CharacterMatcher.isLineFeed(null), is(false)); } @Test public void isLineFeed_space() { assertThat(CharacterMatcher.isLineFeed(' '), is(false)); } @Test public void isLineFeed_someChars() { assertThat(CharacterMatcher.isLineFeed('a'), is(false)); assertThat(CharacterMatcher.isLineFeed('F'), is(false)); assertThat(CharacterMatcher.isLineFeed('X'), is(false)); assertThat(CharacterMatcher.isLineFeed('?'), is(false)); assertThat(CharacterMatcher.isLineFeed(';'), is(false)); } @Test public void isLineFeed_cr() { assertThat(CharacterMatcher.isLineFeed('\r'), is(false)); } @Test public void isLineFeed_lf() { assertThat(CharacterMatcher.isLineFeed('\n'), is(true)); } @Test public void isCariageReturn_null() { assertThat(CharacterMatcher.isCariageReturn(null), is(false)); } @Test public void isCariageReturn_space() { assertThat(CharacterMatcher.isCariageReturn(' '), is(false)); } @Test public void isCariageReturn_someChars() { assertThat(CharacterMatcher.isCariageReturn('a'), is(false)); assertThat(CharacterMatcher.isCariageReturn('F'), is(false)); assertThat(CharacterMatcher.isCariageReturn('X'), is(false)); assertThat(CharacterMatcher.isCariageReturn('?'), is(false)); assertThat(CharacterMatcher.isCariageReturn(';'), is(false)); } @Test public void isCariageReturn_cr() { assertThat(CharacterMatcher.isCariageReturn('\r'), is(true)); } @Test public void isCariageReturn_lf() { assertThat(CharacterMatcher.isCariageReturn('\n'), is(false)); } @Test public void isWhiteSpace_null() { assertThat(CharacterMatcher.isWhiteSpace(null), is(false)); } @Test public void isWhiteSpace_spaces() { assertThat(CharacterMatcher.isWhiteSpace(' '), is(true)); assertThat(CharacterMatcher.isWhiteSpace('\t'), is(true)); } @Test public void isWhiteSpace_nonSpaces() { assertThat(CharacterMatcher.isWhiteSpace('.'), is(false)); assertThat(CharacterMatcher.isWhiteSpace('a'), is(false)); assertThat(CharacterMatcher.isWhiteSpace('Z'), is(false)); assertThat(CharacterMatcher.isWhiteSpace('9'), is(false)); } @Test public void isNonWhiteSpace_null() { assertThat(CharacterMatcher.isNonWhiteSpace(null), is(false)); } @Test public void isNonWhiteSpace_spaces() { assertThat(CharacterMatcher.isNonWhiteSpace(' '), is(false)); assertThat(CharacterMatcher.isNonWhiteSpace('\t'), is(false)); } @Test public void isNonWhiteSpace_nonSpaces() { assertThat(CharacterMatcher.isNonWhiteSpace('.'), is(true)); assertThat(CharacterMatcher.isNonWhiteSpace('a'), is(true)); assertThat(CharacterMatcher.isNonWhiteSpace('Z'), is(true)); assertThat(CharacterMatcher.isNonWhiteSpace('9'), is(true)); } }
package org.openremote.security; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.testng.Assert; import org.testng.annotations.Test; import javax.crypto.spec.SecretKeySpec; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.security.KeyStore; import java.security.Provider; import java.security.Security; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.UUID; /** * Unit tests for shared implementation in abstract {@link org.openremote.security.KeyManager} * class. * * @author <a href="mailto:juha@openremote.org">Juha Lindfors</a> */ public class KeyManagerTest { // TODO : test loading zero file behavior // TODO : test saving with non-ascii password /** * Very basic test runs on StorageType enum to ensure implementation consistency. */ @Test public void testStorageTypes() { Assert.assertTrue( KeyManager.StorageType.PKCS12.name().equals(KeyManager.StorageType.PKCS12.toString()) ); Assert.assertTrue( KeyManager.StorageType.PKCS12.name().equals(KeyManager.StorageType.PKCS12.getStorageTypeName()) ); Assert.assertTrue( KeyManager.StorageType.JCEKS.name().equals(KeyManager.StorageType.JCEKS.toString()) ); Assert.assertTrue( KeyManager.StorageType.JCEKS.name().equals(KeyManager.StorageType.JCEKS.getStorageTypeName()) ); Assert.assertTrue( KeyManager.StorageType.JKS.name().equals(KeyManager.StorageType.JKS.toString()) ); Assert.assertTrue( KeyManager.StorageType.JKS.name().equals(KeyManager.StorageType.JKS.getStorageTypeName()) ); Assert.assertTrue( KeyManager.StorageType.BKS.name().equals(KeyManager.StorageType.BKS.toString()) ); Assert.assertTrue( KeyManager.StorageType.BKS.name().equals(KeyManager.StorageType.BKS.getStorageTypeName()) ); } /** * Tests keystore save when file descriptor is null. * * @throws Exception if test fails */ @Test public void testSaveWithNullFile() throws Exception { TestKeyManager keyMgr = new TestKeyManager(); char[] storePW = new char[] { 'f', 'o', 'o'}; try { keyMgr.save(null, storePW); Assert.fail("should not get here..."); } catch (KeyManager.KeyManagerException e) { // expected... } } /** * Tests storing an empty in-memory keystore. * * @throws Exception if test fails for any reason */ @Test public void testEmptyInMemoryKeystore() throws Exception { TestKeyManager keyMgr = new TestKeyManager(); char[] password = new char[] { 'f', 'o', 'o' }; KeyStore keystore = keyMgr.save(password); Assert.assertTrue(keystore.size() == 0); // Ensure we've erased the password from memory after API call... for (char c : password) { Assert.assertTrue(c == 0); } } /** * Tests storing an empty in-memory keystore with empty keystore password. * * @throws Exception if test fails for any reason */ @Test public void testEmptyInMemoryKeystoreWithEmptyPassword() throws Exception { TestKeyManager keyMgr = new TestKeyManager(); try { keyMgr.save(new char[] { }); Assert.fail("should not get here..."); } catch (KeyManager.KeyManagerException e) { // expected... } } /** * Tests storing an empty in-memory keystore with null keystore password. * * @throws Exception if test fails for any reason */ @Test public void testEmptyInMemoryKeystoreWithNullPassword() throws Exception { TestKeyManager keyMgr = new TestKeyManager(); try { keyMgr.save(null); Assert.fail("should not get here..."); } catch (KeyManager.KeyManagerException e) { // expected... } } /** * Tests storing a keystore with null master password. * * @throws Exception if test fails */ @Test public void testFileKeyStoreNullPassword() throws Exception { TestKeyManager keyMgr = new TestKeyManager(); File dir = new File(System.getProperty("user.dir")); File f = new File(dir, "test.keystore." + UUID.randomUUID()); f.deleteOnExit(); try { keyMgr.save(f, null); Assert.fail("should not get here..."); } catch (KeyManager.KeyManagerException e) { // expected } } /** * Test behavior when loading keystore with wrong password. * * @throws Exception if test fails */ @Test public void testWrongPassword() throws Exception { JCEKSStorage ks = new JCEKSStorage(); File dir = new File(System.getProperty("user.dir")); File f = new File(dir, "test.keystore." + UUID.randomUUID()); f.deleteOnExit(); ks.add( "alias", new KeyStore.SecretKeyEntry( new SecretKeySpec(new byte[] { 'a' }, "test") ), new KeyStore.PasswordProtection(new char[] { 'b' }) ); char[] password = new char[] { 'f', 'o', 'o' }; ks.save(f, password); try { ks.save(f, new char[] { 0 }); Assert.fail("should not get here..."); } catch (KeyManager.KeyManagerException e) { // expected... } } /** * Test behavior when a secret key is added to storage that does not * support them. * * @throws Exception if test fails */ @Test public void testAddingSecretKeyToPKCS12() throws Exception { PKCS12Storage ks = new PKCS12Storage(); ks.add( "alias", new KeyStore.SecretKeyEntry( new SecretKeySpec(new byte[] { 'a' }, "test") ), new KeyStore.PasswordProtection(new char[] { 'b' }) ); char[] password = new char[] { 'f', 'o', 'o' }; try { ks.save(password); Assert.fail("should not get here..."); } catch (KeyManager.KeyManagerException e) { // expected... } } /** * Tests adding a secret key to JCEKS storage. * * @throws Exception if test fails */ @Test public void testAddingSecretKeyToJCEKS() throws Exception { JCEKSStorage ks = new JCEKSStorage(); ks.add( "alias", new KeyStore.SecretKeyEntry( new SecretKeySpec(new byte[] { 'a' }, "test") ), new KeyStore.PasswordProtection(new char[] { 'b' }) ); char[] password = new char[] { 'f', 'o', 'o' }; ks.save(password); } /** * Tests adding a secret key to BKS storage. * * @throws Exception if test fails */ @Test public void testAddingSecretKeyToBKS() throws Exception { // BKS implementation requires "BC" to be available as security provider... try { Security.addProvider(new BouncyCastleProvider()); BKSStorage ks = new BKSStorage(); ks.add( "alias", new KeyStore.SecretKeyEntry( new SecretKeySpec(new byte[] { 'a' }, "test") ), new KeyStore.PasswordProtection(new char[] { 'b' }) ); char[] password = new char[] { 'f', 'o', 'o' }; ks.save(password); } finally { Security.removeProvider("BC"); } } /** * Test implementation behavior when requested keystore algorithm is not available. * * @throws Exception if test fails */ @Test public void testAddingSecretKeyToUnavailableBKS() throws Exception { UnavailableBKS ks = new UnavailableBKS(); ks.add( "alias", new KeyStore.SecretKeyEntry( new SecretKeySpec(new byte[] { 'a' }, "test") ), new KeyStore.PasswordProtection(new char[] { 'b' }) ); char[] password = new char[] { 'f', 'o', 'o' }; try { ks.save(password); Assert.fail("Should not get here..."); } catch (KeyManager.ConfigurationException e) { // expected... } } /** * Tests behavior when an existing keystore has been corrupted. * * @throws Exception if test fails */ @Test public void testCorruptJCEKS() throws Exception { JCEKSStorage ks = new JCEKSStorage(); ks.add( "alias", new KeyStore.SecretKeyEntry( new SecretKeySpec(new byte[] { 'a' }, "test") ), new KeyStore.PasswordProtection(new char[] { 'b' }) ); char[] password = new char[] { 'f', 'o', 'o' }; File dir = new File(System.getProperty("user.dir")); File f = new File(dir, "test.keystore." + UUID.randomUUID()); f.deleteOnExit(); ks.add( "foobar", new KeyStore.SecretKeyEntry( new SecretKeySpec(new byte[] { 'a' }, "test") ), new KeyStore.PasswordProtection(new char[] { 'b' }) ); ks.save(f, password); FileOutputStream fout = new FileOutputStream(f); BufferedOutputStream bout = new BufferedOutputStream(fout); bout.write("Add some garbage".getBytes()); bout.close(); password = new char[] { 'f', 'o', 'o' }; try { ks.save(f, password); Assert.fail("should not get here..."); } catch (KeyManager.KeyManagerException e) { // expected... } } /** * Tests storing a keystore with empty master password. * * @throws Exception if test fails */ @Test public void testFileKeyStoreEmptyPassword() throws Exception { TestKeyManager keyMgr = new TestKeyManager(); File dir = new File(System.getProperty("user.dir")); File f = new File(dir, "test.keystore." + UUID.randomUUID()); f.deleteOnExit(); try { keyMgr.save(f, new char[] {}); Assert.fail("should not get here..."); } catch (KeyManager.KeyManagerException e) { // expected... } } /** * Test against a broken implementation (subclass) of a key manager. */ @Test public void testBrokenStorageManager() { try { new BrokenStorageManager(); Assert.fail("should not get here..."); } catch (IllegalArgumentException e) { // expected... } } /** * Test error behavior when file doesn't exist. */ @Test public void testSaveWithBrokenFile() { TestKeyManager mgr = new TestKeyManager(); File f = new File(" char[] pw = new char[] { 'p' }; try { mgr.save(f, pw); Assert.fail("should not get here..."); } catch (KeyManager.KeyManagerException e) { // expected... } for (Character c : pw) { Assert.assertTrue(c == 0); } } /** * Tests error handling behavior on add() with null alias. * * @see KeyManager#add(String, java.security.KeyStore.Entry, java.security.KeyStore.ProtectionParameter) */ @Test public void testAddNullAlias() { TestKeyManager mgr = new TestKeyManager(); try { mgr.add( null, new KeyStore.SecretKeyEntry(new SecretKeySpec(new byte[] { 'a' }, "foo")), new KeyStore.PasswordProtection(new char[] { 'b' }) ); Assert.fail("should not get here..."); } catch (IllegalArgumentException e) { // expected... } } /** * Tests error handling behavior on add() with empty alias. * * @see KeyManager#add(String, java.security.KeyStore.Entry, java.security.KeyStore.ProtectionParameter) */ @Test public void testAddEmptyAlias() { TestKeyManager mgr = new TestKeyManager(); try { mgr.add( "", new KeyStore.SecretKeyEntry(new SecretKeySpec(new byte[] { 'a' }, "foo")), new KeyStore.PasswordProtection(new char[] { 'b' }) ); Assert.fail("should not get here..."); } catch (IllegalArgumentException e) { // expected... } } /** * Tests error handling behavior on add() with empty alias. * * @see KeyManager#add(String, java.security.KeyStore.Entry, java.security.KeyStore.ProtectionParameter) */ @Test public void testAddNullEntry() { TestKeyManager mgr = new TestKeyManager(); try { mgr.add( "test", null, new KeyStore.PasswordProtection(new char[] { 'b' }) ); Assert.fail("should not get here..."); } catch (IllegalArgumentException e) { // expected... } } private static class TestKeyManager extends KeyManager { // no op, just to test abstract superclass implementation... } private static class JCEKSStorage extends KeyManager { private static Provider findJCEKSProvider() { Map<String, String> props = new HashMap<String, String>(); props.put("keystore.jceks", ""); Provider[] providers = Security.getProviders(props); if (providers.length == 0) { Assert.fail("Cannot find a security provider for Sun JCEKS"); return null; } else { return providers[0]; } } JCEKSStorage() { super(StorageType.JCEKS, findJCEKSProvider()); } } /** * BKS keystorage from BouncyCastle. */ private static class BKSStorage extends KeyManager { BKSStorage() { super(StorageType.BKS, new BouncyCastleProvider()); } } /** * Test KeyManager implementation that attempts to load/create a keystore of a type * that is not available in the security provider. */ private static class UnavailableBKS extends KeyManager { UnavailableBKS() { super(StorageType.BKS, new EmptyProvider()); } } /** * PKCS12 storage from a default security prover. */ private static class PKCS12Storage extends KeyManager { PKCS12Storage() { super(StorageType.PKCS12, null); } } private static class BrokenStorageManager extends KeyManager { BrokenStorageManager() { super(null, new BouncyCastleProvider()); } } /** * An empty test security provider used for some test cases. */ private static class EmptyProvider extends Provider { EmptyProvider() { super("Empty Test Provider", 0.0, "Testing"); } } }
package org.purl.wf4ever.robundle.fs; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.net.URI; import java.nio.file.DirectoryStream; import java.nio.file.FileAlreadyExistsException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.ZipOutputStream; import org.junit.Test; public class TestZipFS { private static Path zip; @Test public void directoryOrFile() throws Exception { try (FileSystem fs = tempZipFS()) { Path folder = fs.getPath("folder"); assertFalse(Files.exists(folder)); Files.createFile(folder); assertTrue(Files.exists(folder)); assertTrue(Files.isRegularFile(folder)); assertFalse(Files.isDirectory(folder)); try { Path folderCreated = Files.createDirectory(folder); assertEquals(folder, folderCreated); folder = folderCreated; System.out.println(folder + " " + folderCreated); // Disable for now, just to see where this leads // fail("Should have thrown FileAlreadyExistsException"); } catch (FileAlreadyExistsException ex) { } // For some reason the second createDirectory() fails correctly try { Files.createDirectory(folder); fail("Should have thrown FileAlreadyExistsException"); } catch (FileAlreadyExistsException ex) { } Path child = folder.resolve("child"); Files.createFile(child); // Look, it's both a file and folder! // Can this be asserted? assertTrue(Files.isRegularFile(folder)); // Yes, if you include the final / assertTrue(Files.isDirectory(fs.getPath("folder/"))); // But not the parent // assertTrue(Files.isDirectory(child.getParent())); // Or the original Path // assertTrue(Files.isDirectory(folder)); } // What if we open it again.. can we find both? try (FileSystem fs2 = FileSystems.newFileSystem(zip, null)) { assertTrue(Files.isRegularFile(fs2.getPath("folder"))); assertTrue(Files.isRegularFile(fs2.getPath("folder/child"))); assertTrue(Files.isDirectory(fs2.getPath("folder/"))); // We can even list the folder try (DirectoryStream<Path> s = Files.newDirectoryStream(fs2 .getPath("folder/"))) { boolean found = false; for (Path p : s) { found = p.endsWith("child"); } assertTrue("Did not find 'child'", found); } // But if we list the root, do we find "folder" or "folder/"? Path root = fs2.getRootDirectories().iterator().next(); try (DirectoryStream<Path> s = Files.newDirectoryStream(root)) { List<String> paths = new ArrayList<>(); for (Path p : s) { paths.add(p.toString()); } // We find both! assertEquals(2, paths.size()); assertTrue(paths.contains("/folder")); assertTrue(paths.contains("/folder/")); } // SO does that mean this is a feature, and not a bug? } } public static FileSystem tempZipFS() throws Exception { zip = Files.createTempFile("test", ".zip"); Files.delete(zip); System.out.println(zip); URI jar = new URI("jar", zip.toUri().toString(), null); Map<String, Object> env = new HashMap<>(); env.put("create", "true"); return FileSystems.newFileSystem(jar, env); } @Test public void jarWithSpaces() throws Exception { Path path = Files.createTempFile("with several spaces", ".zip"); Files.delete(path); // Will fail with FileSystemNotFoundException without env: //FileSystems.newFileSystem(path, null); // Neither does this work, as it does not double-escape: // URI jar = URI.create("jar:" + path.toUri().toASCIIString()); URI jar = new URI("jar", path.toUri().toString(), null); assertTrue(jar.toASCIIString().contains("with%2520several%2520spaces")); Map<String, Object> env = new HashMap<>(); env.put("create", "true"); try (FileSystem fs = FileSystems.newFileSystem(jar, env)) { URI root = fs.getPath("/").toUri(); assertTrue(root.toString().contains("with%2520several%2520spaces")); } // Reopen from now-existing Path to check that the URI is // escaped in the same way try (FileSystem fs = FileSystems.newFileSystem(path, null)) { URI root = fs.getPath("/").toUri(); //System.out.println(root.toASCIIString()); assertTrue(root.toString().contains("with%2520several%2520spaces")); } } @Test public void jarWithSpacesJava8() throws Exception { Path dir = Files.createTempDirectory("test"); dir.resolve("test"); Path path = dir.resolve("with several spaces.zip"); // Make empty zip file - the old way! try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream( path, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING))) { out.closeEntry(); } Map<String, Object> env = new HashMap<>(); URI root; // Open by path try (FileSystem fs = FileSystems.newFileSystem(path, null)) { // Works fine root = fs.getPath("/").toUri(); //System.out.println(root.toASCIIString()); // Double-escaped, as expected and compatible with Java 7 assertTrue(root.toString().contains("with%2520several%2520spaces.zip")) ; } // Open it again from the URI try (FileSystem fs = FileSystems.newFileSystem(root, env)) { root = fs.getPath("/").toUri(); //System.out.println(root.toASCIIString()); assertTrue(root.toString().contains("with%2520several%2520spaces.zip")); } // What if we construct the JAR URI as in Java 7? URI jar = new URI("jar", path.toUri().toString(), null); try (FileSystem fs = FileSystems.newFileSystem(jar, env)) { root = fs.getPath("/").toUri(); //System.out.println(root.toASCIIString()); assertTrue(root.toString().contains("with%2520several%2520spaces.zip")); } // OK, let's just create one and see what we get env.put("create", "true"); Files.delete(path); try (FileSystem fs = FileSystems.newFileSystem(jar, env)) { root = fs.getPath("/").toUri(); //System.out.println(root.toASCIIString()); assertTrue(root.toString().contains("with%2520several%2520spaces.zip")); } try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { for (Path file : stream) { assertEquals("with several spaces.zip", file.getFileName().toString()); // not with%20several%20spaces.zip } } } }
package programminglife.parser; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import programminglife.model.GenomeGraph; import programminglife.model.GenomeGraphTest; import programminglife.model.Segment; import programminglife.model.exception.UnknownTypeException; import java.io.File; import java.util.Collection; import java.util.Observable; import java.util.Observer; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; public class GraphParserTest implements Observer { private static String TEST_PATH, TEST_FAULTY_PATH; private String linkLine, nodeLine; private GraphParser graphParser, faultyGraphParser; @BeforeClass public static void setUpClass() throws Exception { TEST_PATH = new File(GenomeGraphTest.class.getResource("/test.gfa").toURI()).getAbsolutePath(); TEST_FAULTY_PATH = new File( GenomeGraphTest.class.getClass().getResource("/test-faulty.gfa").toURI() ).getAbsolutePath(); } @Before public void setUp() throws Exception { File testFile = new File(TEST_PATH); graphParser = new GraphParser(testFile, testFile.getName()); File faultyTestFile = new File(TEST_FAULTY_PATH); faultyGraphParser = new GraphParser(faultyTestFile, faultyTestFile.getName()); linkLine = "L\t34\t+\t35\t+\t0M"; nodeLine = "S\t6\tC\t*\tORI:Z:TKK_04_0031.fasta\tCRD:Z:TKK_04_0031.fasta\tCRDCTG:Z:7000000219691771\tCTG:Z:7000000219691771\tSTART:Z:3039"; } @Test(expected = UnknownTypeException.class) public void faultyParseTest() throws Exception { faultyGraphParser.parse(); } @Test public void parseTest() throws Exception { graphParser.parse(); GenomeGraph graph = graphParser.getGraph(); Collection<Segment> nodes = graph.getNodes(); assertEquals(8, nodes.size()); assertEquals(9, nodes.stream() .mapToInt(node -> node.getChildren().size()) .sum()); } @Test public void parseLinkTest() { graphParser.parseLink(linkLine); } @Test public void parseSegmentTest() { graphParser.parseSegment(nodeLine); Segment node = graphParser.getGraph().getNode(6); assertEquals(6, node.getIdentifier()); assertEquals("C", node.getSequence()); assertEquals(0, node.getParents().size()); assertEquals(0, node.getChildren().size()); } @Test public void runTestSuccess() { graphParser.addObserver(this); graphParser.run(); } @Test(expected = UnknownTypeException.class) public void runTestFailure() throws Throwable { try { faultyGraphParser.addObserver(this); faultyGraphParser.run(); fail(); } catch (RuntimeException re) { throw re.getCause(); } } @Override public void update(Observable o, Object arg) { if (o instanceof GraphParser) { if (arg instanceof GenomeGraph) { GenomeGraph graph = (GenomeGraph) arg; Segment node = graph.getNode(8); assertEquals(new File(TEST_PATH).getName(), graph.getId()); assertEquals("GTC", node.getSequence()); } else if (arg instanceof Exception) { throw new RuntimeException((Exception) arg); } } } }
package uk.org.okapibarcode.backend; import static java.lang.Integer.toHexString; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.awt.Color; import java.awt.Font; import java.awt.FontFormatException; import java.awt.Graphics2D; import java.awt.GraphicsEnvironment; import java.awt.image.BufferedImage; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CodingErrorAction; import java.nio.file.Files; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.imageio.ImageIO; import org.junit.ComparisonFailure; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.reflections.Reflections; import uk.org.okapibarcode.output.Java2DRenderer; import com.google.zxing.BinaryBitmap; import com.google.zxing.DecodeHintType; import com.google.zxing.LuminanceSource; import com.google.zxing.Reader; import com.google.zxing.ReaderException; import com.google.zxing.Result; import com.google.zxing.aztec.AztecReader; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.oned.CodaBarReader; import com.google.zxing.oned.Code128Reader; import com.google.zxing.oned.Code39Reader; import com.google.zxing.oned.Code93Reader; import com.google.zxing.oned.EAN13Reader; import com.google.zxing.oned.EAN8Reader; import com.google.zxing.oned.UPCAReader; import com.google.zxing.oned.UPCEReader; import com.google.zxing.pdf417.PDF417Reader; import com.google.zxing.qrcode.QRCodeReader; /** * <p> * Scans the test resources for file-based bar code tests. * * <p> * Tests that verify successful behavior will contain the following sets of files: * * <pre> * /src/test/resources/uk/org/okapibarcode/backend/[symbol-name]/[test-name].properties (bar code initialization attributes) * /src/test/resources/uk/org/okapibarcode/backend/[symbol-name]/[test-name].codewords (expected intermediate coding of the bar code) * /src/test/resources/uk/org/okapibarcode/backend/[symbol-name]/[test-name].png (expected final rendering of the bar code) * </pre> * * <p> * Tests that verify error conditions will contain the following sets of files: * * <pre> * /src/test/resources/uk/org/okapibarcode/backend/[symbol-name]/[test-name].properties (bar code initialization attributes) * /src/test/resources/uk/org/okapibarcode/backend/[symbol-name]/[test-name].error (expected error message) * </pre> * * <p> * If a properties file is found with no matching expectation files, we assume that it was recently added to the test suite and * that we need to generate suitable expectation files for it. * * <p> * A single properties file can contain multiple test configurations (separated by an empty line), as long as the expected output * is the same for all of those tests. */ @RunWith(Parameterized.class) public class SymbolTest { /** The directory to which barcode images (expected and actual) are saved when an image check fails. */ private static final File TEST_FAILURE_IMAGES_DIR = new File("build", "test-failure-images"); /** The font used to render human-readable text when drawing the symbologies; allows for consistent results across operating systems. */ private static final Font DEJA_VU_SANS; static { String path = "/uk/org/okapibarcode/fonts/OkapiDejaVuSans.ttf"; try { InputStream is = SymbolTest.class.getResourceAsStream(path); DEJA_VU_SANS = Font.createFont(Font.TRUETYPE_FONT, is); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); boolean registered = ge.registerFont(DEJA_VU_SANS); assertTrue("Unable to register test font!", registered); } catch (IOException | FontFormatException e) { throw new RuntimeException(e.getMessage(), e); } } /** The type of symbology being tested. */ private final Class< ? extends Symbol > symbolType; /** The test configuration properties. */ private final Map< String, String > properties; /** The file containing the expected intermediate coding of the bar code, if this test verifies successful behavior. */ private final File codewordsFile; /** The file containing the expected final rendering of the bar code, if this test verifies successful behavior. */ private final File pngFile; /** The file containing the expected error message, if this test verifies a failure. */ private final File errorFile; /** * Creates a new test. * * @param symbolType the type of symbol being tested * @param properties the test configuration properties * @param codewordsFile the file containing the expected intermediate coding of the bar code, if this test verifies successful behavior * @param pngFile the file containing the expected final rendering of the bar code, if this test verifies successful behavior * @param errorFile the file containing the expected error message, if this test verifies a failure * @param symbolName the name of the symbol type (used only for test naming) * @param fileBaseName the base name of the test file (used only for test naming) * @throws IOException if there is any I/O error */ public SymbolTest(Class< ? extends Symbol > symbolType, Map< String, String > properties, File codewordsFile, File pngFile, File errorFile, String symbolName, String fileBaseName) throws IOException { this.symbolType = symbolType; this.properties = properties; this.codewordsFile = codewordsFile; this.pngFile = pngFile; this.errorFile = errorFile; } /** * Runs the test. If there are no expectation files yet, we generate them instead of checking against them. * * @throws Exception if any error occurs during the test */ @Test public void test() throws Exception { Symbol symbol = symbolType.newInstance(); symbol.setFontName(DEJA_VU_SANS.getFontName()); try { setProperties(symbol, properties); } catch (InvocationTargetException e) { symbol.error_msg = e.getCause().getMessage(); // TODO: migrate completely to exceptions? } if (codewordsFile.exists() && pngFile.exists()) { verifySuccess(symbol); } else if (errorFile.exists()) { verifyError(symbol); } else { generateExpectationFiles(symbol); } } /** * Verifies that the specified symbol was encoded and rendered in a way that matches expectations. * * @param symbol the symbol to check * @throws IOException if there is any I/O error * @throws ReaderException if ZXing has an issue decoding the barcode image */ private void verifySuccess(Symbol symbol) throws IOException, ReaderException { assertEquals("error message", "", symbol.error_msg); List< String > expectedList = Files.readAllLines(codewordsFile.toPath(), UTF_8); try { // try to verify codewords int[] actualCodewords = symbol.getCodewords(); assertEquals(expectedList.size(), actualCodewords.length); for (int i = 0; i < actualCodewords.length; i++) { int expected = getInt(expectedList.get(i)); int actual = actualCodewords[i]; assertEquals("at codeword index " + i, expected, actual); } } catch (UnsupportedOperationException e) { // codewords aren't supported, try to verify patterns String[] actualPatterns = symbol.pattern; assertEquals(expectedList.size(), actualPatterns.length); for (int i = 0; i < actualPatterns.length; i++) { String expected = expectedList.get(i); String actual = actualPatterns[i]; assertEquals("at pattern index " + i, expected, actual); } } // make sure the barcode images match String parentName = pngFile.getParentFile().getName(); String pngName = pngFile.getName(); String dirName = parentName + "-" + pngName.substring(0, pngName.lastIndexOf('.')); File failureDirectory = new File(TEST_FAILURE_IMAGES_DIR, dirName); BufferedImage expected = ImageIO.read(pngFile); BufferedImage actual = draw(symbol); assertEqual(expected, actual, failureDirectory); // if possible, ensure an independent third party (ZXing) can read the generated barcode and agrees on what it represents Reader zxingReader = findReader(symbol); if (zxingReader != null) { LuminanceSource source = new BufferedImageLuminanceSource(expected); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Map< DecodeHintType, Boolean > hints = Collections.singletonMap(DecodeHintType.PURE_BARCODE, Boolean.TRUE); Result result = zxingReader.decode(bitmap, hints); String zxingData = massageZXingData(result.getText(), symbol); String okapiData = massageOkapiData(symbol.getContent(), symbol); assertEquals("checking against ZXing results", okapiData, zxingData); } } /** * Returns a ZXing reader that can read the specified symbol. * * @param symbol the symbol to be read * @return a ZXing reader that can read the specified symbol */ private static Reader findReader(Symbol symbol) { if (symbol instanceof Code128 || symbol instanceof UspsPackage) { return new Code128Reader(); } else if (symbol instanceof Code93) { return new Code93Reader(); } else if (symbol instanceof Code3Of9) { return new Code39Reader(); } else if (symbol instanceof Codabar) { return new CodaBarReader(); } else if (symbol instanceof AztecCode) { return new AztecReader(); } else if (symbol instanceof QrCode) { return new QRCodeReader(); } else if (symbol instanceof Ean) { Ean ean = (Ean) symbol; if (ean.getMode() == Ean.Mode.EAN8) { return new EAN8Reader(); } else { return new EAN13Reader(); } } else if (symbol instanceof Pdf417) { Pdf417 pdf417 = (Pdf417) symbol; if (pdf417.getMode() != Pdf417.Mode.MICRO) { return new PDF417Reader(); } } else if (symbol instanceof Upc) { Upc upc = (Upc) symbol; if (upc.getMode() == Upc.Mode.UPCA) { return new UPCAReader(); } else { return new UPCEReader(); } } // no corresponding ZXing reader exists, or it behaves badly so we don't use it for testing return null; } /** * Massages ZXing barcode reading results to make them easier to check against Okapi data. * * @param s the barcode content * @param symbol the symbol which encoded the content * @return the massaged barcode content */ private static String massageZXingData(String s, Symbol symbol) { if (symbol instanceof Ean || symbol instanceof Upc) { // remove the checksum from the barcode content return s.substring(0, s.length() - 1); } else { // no massaging return s; } } /** * Massages Okapi barcode content to make it easier to check against ZXing output. * * @param s the barcode content * @param symbol the symbol which encoded the content * @return the massaged barcode content */ private static String massageOkapiData(String s, Symbol symbol) { if (symbol instanceof Codabar) { // remove the start/stop characters from the specified barcode content return s.substring(1, s.length() - 1); } else if (symbol instanceof Code128) { // remove function characters, since ZXing mostly ignores them during read return s.replaceAll("[" + Code128.FNC1 + "]", "") .replaceAll("[" + Code128.FNC2 + "]", "") .replaceAll("[" + Code128.FNC3 + "]", "") .replaceAll("[" + Code128.FNC4 + "]", ""); } else if (symbol instanceof UspsPackage) { // remove AI brackets, since ZXing doesn't include them return s.replaceAll("[\\[\\]]", ""); } else { // no massaging return s; } } /** * Verifies that the specified symbol encountered the expected error during encoding. * * @param symbol the symbol to check * @throws IOException if there is any I/O error */ private void verifyError(Symbol symbol) throws IOException { String expectedError = Files.readAllLines(errorFile.toPath(), UTF_8).get(0); assertEquals(expectedError, symbol.error_msg); } /** * Generates the expectation files for the specified symbol. * * @param symbol the symbol to generate expectation files for * @throws IOException if there is any I/O error */ private void generateExpectationFiles(Symbol symbol) throws IOException { if (symbol.error_msg != null && !symbol.error_msg.isEmpty()) { generateErrorExpectationFile(symbol); } else { generateCodewordsExpectationFile(symbol); generatePngExpectationFile(symbol); } } /** * Generates the error expectation file for the specified symbol. * * @param symbol the symbol to generate the error expectation file for * @throws IOException if there is any I/O error */ private void generateErrorExpectationFile(Symbol symbol) throws IOException { if (!errorFile.exists()) { PrintWriter writer = new PrintWriter(errorFile); writer.println(symbol.error_msg); writer.close(); } } /** * Generates the codewords expectation file for the specified symbol. * * @param symbol the symbol to generate codewords for * @throws IOException if there is any I/O error */ private void generateCodewordsExpectationFile(Symbol symbol) throws IOException { if (!codewordsFile.exists()) { PrintWriter writer = new PrintWriter(codewordsFile); try { int[] codewords = symbol.getCodewords(); for (int codeword : codewords) { writer.println(codeword); } } catch (UnsupportedOperationException e) { for (String pattern : symbol.pattern) { writer.println(pattern); } } writer.close(); } } /** * Generates the image expectation file for the specified symbol. * * @param symbol the symbol to draw * @throws IOException if there is any I/O error */ private void generatePngExpectationFile(Symbol symbol) throws IOException { if (!pngFile.exists()) { BufferedImage img = draw(symbol); ImageIO.write(img, "png", pngFile); } } /** * Returns the integer contained in the specified string. If the string contains a tab character, it and everything after it * is ignored. * * @param s the string to extract the integer from * @return the integer contained in the specified string */ private static int getInt(String s) { int i = s.indexOf('\t'); if (i != -1) { s = s.substring(0, i); } return Integer.parseInt(s); } /** * Draws the specified symbol and returns the resultant image. * * @param symbol the symbol to draw * @return the resultant image */ private static BufferedImage draw(Symbol symbol) { int magnification = 10; int width = symbol.getWidth() * magnification; int height = symbol.getHeight() * magnification; BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); Graphics2D g2d = img.createGraphics(); g2d.setPaint(Color.WHITE); g2d.fillRect(0, 0, width, height); Java2DRenderer renderer = new Java2DRenderer(g2d, magnification, Color.WHITE, Color.BLACK); renderer.render(symbol); g2d.dispose(); return img; } /** * Initializes the specified symbol using the specified properties, where keys are attribute names and values are attribute * values. * * @param symbol the symbol to initialize * @param properties the attribute names and values to set * @throws ReflectiveOperationException if there is any reflection error */ private static void setProperties(Symbol symbol, Map< String, String > properties) throws ReflectiveOperationException { for (Map.Entry< String, String > entry : properties.entrySet()) { String name = entry.getKey(); String value = entry.getValue(); String setterName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1); Method setter = getMethod(symbol.getClass(), setterName); invoke(symbol, setter, value); } } /** * Returns the method with the specified name in the specified class, or throws an exception if the specified method cannot be * found. * * @param clazz the class to search in * @param name the name of the method to search for * @return the method with the specified name in the specified class */ private static Method getMethod(Class< ? > clazz, String name) { for (Method method : clazz.getMethods()) { if (method.getName().equals(name)) { return method; } } throw new RuntimeException("Unable to find method: " + name); } @SuppressWarnings("unchecked") private static < E extends Enum< E >> void invoke(Object object, Method setter, Object parameter) throws ReflectiveOperationException, IllegalArgumentException { Class< ? > paramType = setter.getParameterTypes()[0]; if (String.class.equals(paramType)) { setter.invoke(object, parameter.toString()); } else if (boolean.class.equals(paramType)) { setter.invoke(object, Boolean.valueOf(parameter.toString())); } else if (int.class.equals(paramType)) { setter.invoke(object, Integer.parseInt(parameter.toString())); } else if (double.class.equals(paramType)) { setter.invoke(object, Double.parseDouble(parameter.toString())); } else if (Character.class.equals(paramType)) { setter.invoke(object, parameter.toString().charAt(0)); } else if (paramType.isEnum()) { Class< E > e = (Class< E >) paramType; setter.invoke(object, Enum.valueOf(e, parameter.toString())); } else { throw new RuntimeException("Unknown setter type: " + paramType); } } /** * Returns all .properties files in the specified directory, or an empty array if none are found. * * @param dir the directory to search in * @return all .properties files in the specified directory, or an empty array if none are found */ private static File[] getPropertiesFiles(String dir) { File[] files = new File(dir).listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".properties"); } }); if (files != null) { return files; } else { return new File[0]; } } /** * Verifies that the specified images match. * * @param expected the expected image to check against * @param actual the actual image * @param failureDirectory the directory to save images to if the assertion fails * @throws IOException if there is any I/O error */ private static void assertEqual(BufferedImage expected, BufferedImage actual, File failureDirectory) throws IOException { int w = expected.getWidth(); int h = expected.getHeight(); if (w != actual.getWidth()) { writeImageFilesToFailureDirectory(expected, actual, failureDirectory); throw new ComparisonFailure("image width", String.valueOf(w), String.valueOf(actual.getWidth())); } if (h != actual.getHeight()) { writeImageFilesToFailureDirectory(expected, actual, failureDirectory); throw new ComparisonFailure("image height", String.valueOf(h), String.valueOf(actual.getHeight())); } int[] expectedPixels = new int[w * h]; expected.getRGB(0, 0, w, h, expectedPixels, 0, w); int[] actualPixels = new int[w * h]; actual.getRGB(0, 0, w, h, actualPixels, 0, w); for (int i = 0; i < expectedPixels.length; i++) { int expectedPixel = expectedPixels[i]; int actualPixel = actualPixels[i]; if (expectedPixel != actualPixel) { writeImageFilesToFailureDirectory(expected, actual, failureDirectory); int x = i % w; int y = i / w; throw new ComparisonFailure("pixel at " + x + ", " + y, toHexString(expectedPixel), toHexString(actualPixel)); } } } private static void writeImageFilesToFailureDirectory(BufferedImage expected, BufferedImage actual, File failureDirectory) throws IOException { mkdirs(failureDirectory); ImageIO.write(actual, "png", new File(failureDirectory, "actual.png")); ImageIO.write(expected, "png", new File(failureDirectory, "expected.png")); } /** * Extracts test configuration properties from the specified properties file. A single properties file can contain * configuration properties for multiple tests. * * @param propertiesFile the properties file to read * @return the test configuration properties in the specified file * @throws IOException if there is an error reading the properties file */ private static List< Map< String, String > > readProperties(File propertiesFile) throws IOException { String content; try { byte[] bytes = Files.readAllBytes(propertiesFile.toPath()); content = decode(bytes, UTF_8); } catch (CharacterCodingException e) { throw new IOException("Invalid UTF-8 content in file " + propertiesFile.getAbsolutePath(), e); } String eol = System.lineSeparator(); String[] lines = content.split(eol); List< Map< String, String > > allProperties = new ArrayList<>(); Map< String, String > properties = new LinkedHashMap<>(); for (String line : lines) { if (line.isEmpty()) { // an empty line signals the start of a new test configuration within this single file if (!properties.isEmpty()) { allProperties.add(properties); properties = new LinkedHashMap<>(); } } else if (!line.startsWith(" int index = line.indexOf('='); if (index != -1) { String name = line.substring(0, index); String value = replacePlaceholders(line.substring(index + 1)); properties.put(name, value); } else { String path = propertiesFile.getAbsolutePath(); throw new IOException(path + ": found line '" + line + "' without '=' character; unintentional newline?"); } } } if (!properties.isEmpty()) { allProperties.add(properties); } return allProperties; } /** * Equivalent to {@link String#String(byte[], Charset)}, except that encoding errors result in runtime errors instead of * silent character replacement. * * @param bytes the bytes to decode * @param charset the character set use to decode the bytes * @return the specified bytes, as a string * @throws CharacterCodingException if there is an error decoding the specified bytes */ private static String decode(byte[] bytes, Charset charset) throws CharacterCodingException { CharsetDecoder decoder = charset.newDecoder(); decoder.onMalformedInput(CodingErrorAction.REPORT); decoder.onUnmappableCharacter(CodingErrorAction.REPORT); CharBuffer chars = decoder.decode(ByteBuffer.wrap(bytes)); return chars.toString(); } /** * Replaces any special placeholders supported in test properties files with their raw values. * * @param s the string to check for placeholders * @return the specified string, with placeholders replaced */ private static String replacePlaceholders(String s) { return s.replaceAll("\\\\r", "\r") // "\r" -> CR .replaceAll("\\\\n", "\n"); // "\n" -> LF } /** * Finds all test resources and returns the information that JUnit needs to dynamically create the corresponding test cases. * * @return the test data needed to dynamically create the test cases * @throws IOException if there is an error reading a file */ @Parameters(name = "test {index}: {5}: {6}") public static List< Object[] > data() throws IOException { clear(TEST_FAILURE_IMAGES_DIR); mkdirs(TEST_FAILURE_IMAGES_DIR); String filter = System.getProperty("okapi.symbol.test"); String backend = "uk.org.okapibarcode.backend"; Reflections reflections = new Reflections(backend); Set< Class< ? extends Symbol >> symbols = reflections.getSubTypesOf(Symbol.class); List< Object[] > data = new ArrayList<>(); for (Class< ? extends Symbol > symbol : symbols) { String symbolName = symbol.getSimpleName().toLowerCase(); if (filter == null || filter.equals(symbolName)) { String dir = "src/test/resources/" + backend.replace('.', '/') + "/" + symbolName; for (File file : getPropertiesFiles(dir)) { String fileBaseName = file.getName().replaceAll(".properties", ""); File codewordsFile = new File(file.getParentFile(), fileBaseName + ".codewords"); File pngFile = new File(file.getParentFile(), fileBaseName + ".png"); File errorFile = new File(file.getParentFile(), fileBaseName + ".error"); for (Map< String, String > properties : readProperties(file)) { data.add(new Object[] { symbol, properties, codewordsFile, pngFile, errorFile, symbolName, fileBaseName }); } } } } return data; } private static void clear(File dir) { if (dir.exists()) { for (File file : dir.listFiles()) { if (file.isDirectory()) { clear(file); } if (!file.delete()) { throw new OkapiException("Unable to delete file: " + file); } } } } private static void mkdirs(File dir) { if (!dir.exists() && !dir.mkdirs()) { throw new OkapiException("Unable to create directory: " + dir); } } }
package jelloeater.StockTicker; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.junit.Test; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.junit.Assert.assertTrue; //import java.io.File; //import java.util.Scanner; public class GoogleTickerDataTest extends App{ @Test public void testTickerOnline() throws Throwable { // Tests if ticker parser still works *NOTE: Needs to be online* TickerInfo test = TickerInfo.makeTickerObject("GOOG"); String p = test.getPrice(); // TODO Fix Parser for test //float price = Float.parseFloat(p); System.err.println(p); System.err.println("break"); //assertTrue(price > .01); } /* @Test public void testGoogleJsonParser() throws Throwable { // Is the parser broken? //Assumes client is online // TODO rewrite test to work with private vars? UtilsGUI.setLookAndFeel(); debugMode= true; String dirtyQuertyString= Utils.readFile("src/test/jelloeater/StockTicker/rawJsonDataForTesting.txt"); // Reads raw file to string // It's a mess to try storing it in software, JSON has lots of escape characters that makes java throw up //String rawQuertyString = TickerInfo.GoogleTickerData.cleanGoogleJSONdata(dirtyQuertyString); TickerInfo.GoogleTickerData dataStore = new TickerInfo.GoogleTickerData(); // Creates dataStore Objects dataStore=GoogleTickerData.mapJsonDataToObject(rawQuertyString); // Sends raw data to JSON parser to be converted to object String correctValue = dataStore.getPrice(); // Gets value from process in tickerInfo String regexOutputPrice = GoogleTickerDataTest.oldOfflineGoogleWebRegexParser(rawQuertyString); assertTrue(null, regexOutputPrice.equals(correctValue)); } */ }
package view; import controller.Manager; import controller.ModelManager; import model.Managers.EntityManager; public class UIManager { private ModelManager modelManager; private EntityManager entityManager; private HackerGame game; public UIManager (ModelManager model) { modelManager = model; entityManager = modelManager.getEntityManager(); game = new HackerGame(this, modelManager); initialize(); } public void initialize() { game.setScreen(new MainMenuScreen(this.game)); } public EntityManager getEntityManager() { return entityManager; } public HackerGame getGame() { return this.game; } public void setState (Manager.STATE state) { modelManager.getManager().stateManager(state); } }
package stroom.db.util; import stroom.util.logging.LogUtil; import stroom.util.shared.BaseCriteria; import stroom.util.shared.CriteriaFieldSort; import stroom.util.shared.PageRequest; import stroom.util.shared.Range; import stroom.util.shared.Selection; import stroom.util.shared.StringCriteria; import org.jooq.Condition; import org.jooq.DSLContext; import org.jooq.Field; import org.jooq.OrderField; import org.jooq.Record; import org.jooq.SQLDialect; import org.jooq.Table; import org.jooq.conf.Settings; import org.jooq.impl.DSL; import org.jooq.impl.SQLDataType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.sql.Date; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.sql.DataSource; public final class JooqUtil { private static final Logger LOGGER = LoggerFactory.getLogger(JooqUtil.class); private static final String DEFAULT_ID_FIELD_NAME = "id"; private static final Boolean RENDER_SCHEMA = false; private JooqUtil() { // Utility class. } public static void disableJooqLogoInLogs() { System.getProperties().setProperty("org.jooq.no-logo", "true"); } public static DSLContext createContext(final Connection connection) { Settings settings = new Settings(); // Turn off fully qualified schemata. settings = settings.withRenderSchema(RENDER_SCHEMA); return DSL.using(connection, SQLDialect.MYSQL, settings); } public static DSLContext createContextWithOptimisticLocking(final Connection connection) { Settings settings = new Settings(); // Turn off fully qualified schemata. settings = settings.withRenderSchema(RENDER_SCHEMA); settings = settings.withExecuteWithOptimisticLocking(true); return DSL.using(connection, SQLDialect.MYSQL, settings); } public static void context(final DataSource dataSource, final Consumer<DSLContext> consumer) { try (final Connection connection = dataSource.getConnection()) { final DSLContext context = createContext(connection); consumer.accept(context); } catch (final Exception e) { throw convertException(e); } } public static <R extends Record> void truncateTable(final DataSource dataSource, final Table<R> table) { try (final Connection connection = dataSource.getConnection()) { final DSLContext context = createContext(connection); context .batch( "SET FOREIGN_KEY_CHECKS=0", "truncate table " + table.getName(), "SET FOREIGN_KEY_CHECKS=1") .execute(); } catch (final Exception e) { throw convertException(e); } } public static <R extends Record> int getTableCount(final DataSource dataSource, final Table<R> table) { try (final Connection connection = dataSource.getConnection()) { final DSLContext context = createContext(connection); return context .selectCount() .from(table) .fetchOne() .value1(); } catch (final Exception e) { throw convertException(e); } } public static <R> R contextResult(final DataSource dataSource, final Function<DSLContext, R> function) { R result; try (final Connection connection = dataSource.getConnection()) { final DSLContext context = createContext(connection); result = function.apply(context); } catch (final Exception e) { throw convertException(e); } return result; } // public static void contextResultWithOptimisticLocking( // final DataSource dataSource, final Consumer<DSLContext> consumer) { // try (final Connection connection = dataSource.getConnection()) { // final DSLContext context = createContextWithOptimisticLocking(connection); // consumer.accept(context); // } catch (final Exception e) { // LOGGER.error(e.getMessage(), e); // throw new RuntimeException(e.getMessage(), e); public static <R> R contextResultWithOptimisticLocking(final DataSource dataSource, final Function<DSLContext, R> function) { R result; try (final Connection connection = dataSource.getConnection()) { final DSLContext context = createContextWithOptimisticLocking(connection); result = function.apply(context); } catch (final Exception e) { throw convertException(e); } return result; } public static void transaction(final DataSource dataSource, final Consumer<DSLContext> consumer) { context(dataSource, context -> context.transaction(nested -> consumer.accept(DSL.using(nested)))); } public static <R> R transactionResult(final DataSource dataSource, final Function<DSLContext, R> function) { return contextResult(dataSource, context -> context.transactionResult(nested -> function.apply(DSL.using(nested)))); } /** * Delete all rows matching the passed id value * * @param field The field to match id against * @param id The id value to match on * @return The number of deleted records */ public static <R extends Record> int deleteById(final DataSource dataSource, final Table<R> table, final Field<Integer> field, final int id) { return JooqUtil.contextResult(dataSource, context -> context .deleteFrom(table) .where(field.eq(id)) .execute()); } /** * Delete all rows matching the passed id value * * @param id The id value to match on * @return The number of deleted records */ public static <R extends Record> int deleteById(final DataSource dataSource, final Table<R> table, final int id) { final Field<Integer> idField = getIdField(table); return JooqUtil.contextResult(dataSource, context -> context .deleteFrom(table) .where(idField.eq(id)) .execute()); } /** * Fetch a single row using the passed id value. If the id matches zero rows or more than one row then * an exception will be thrown. Assumes the table's id field is named 'id'. * * @param type The type of record to return * @param id The id to match on * @return An optional containing the record if it was found. */ public static <R extends Record, T> Optional<T> fetchById(final DataSource dataSource, final Table<R> table, final Class<T> type, final int id) { final Field<Integer> idField = getIdField(table); return JooqUtil.contextResult(dataSource, context -> context .fetchOptional(table, idField.eq(id)) .map(record -> record.into(type))); } private static Field<Integer> getIdField(Table<?> table) { final Field<Integer> idField = table.field(DEFAULT_ID_FIELD_NAME, Integer.class); if (idField == null) { throw new RuntimeException(LogUtil.message("Field [id] not found on table [{}]", table.getName())); } return idField; } public static int getLimit(final PageRequest pageRequest, final boolean oneLarger) { return getLimit(pageRequest, oneLarger, Integer.MAX_VALUE); } public static int getLimit(final PageRequest pageRequest, final boolean oneLarger, final int defaultValue) { if (pageRequest != null) { if (pageRequest.getLength() != null) { if (oneLarger) { return pageRequest.getLength() + 1; } else { return pageRequest.getLength(); } } } return defaultValue; } public static int getOffset(final PageRequest pageRequest) { if (pageRequest != null) { if (pageRequest.getOffset() != null) { return pageRequest.getOffset(); } } return 0; } public static int getOffset(final PageRequest pageRequest, final int limit, final int count) { if (pageRequest != null) { if (pageRequest.getOffset() != null) { if (pageRequest.getOffset() == -1 || count < pageRequest.getOffset()) { return Math.max(0, count - limit); } return pageRequest.getOffset(); } } return 0; } @SafeVarargs @SuppressWarnings("varargs") // Creating a stream from an array is safe public static Collection<Condition> conditions(final Optional<Condition>... conditions) { return Stream.of(conditions) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()); } /** * Used to build JOOQ conditions from our Criteria Range * * @param field The jOOQ field being range queried * @param criteria The criteria to apply * @param <T> The type of the range * @return A condition that applies the given range. */ public static <T extends Number> Optional<Condition> getRangeCondition( final Field<T> field, final Range<T> criteria) { if (criteria == null || !criteria.isConstrained()) { return Optional.empty(); } Boolean matchNull = null; if (criteria.isMatchNull()) { matchNull = Boolean.TRUE; } final Optional<Condition> fromCondition; if (criteria.getFrom() == null) { fromCondition = Optional.empty(); } else { fromCondition = Optional.of(field.greaterOrEqual(criteria.getFrom())); } final Optional<Condition> toCondition; if (criteria.getTo() == null) { toCondition = Optional.empty(); } else { toCondition = Optional.of(field.lessThan(criteria.getTo())); } // Combine conditions. final Optional<Condition> condition = fromCondition.map(c1 -> toCondition.map(c1::and).orElse(c1)) .or(() -> toCondition); return convertMatchNull(field, matchNull, condition); } /** * Used to build jOOQ conditions from criteria sets * * @param field The jOOQ field being set queried * @param criteria The criteria to apply * @param <T> The type of the range * @return A condition that applies the given set. */ public static <T> Optional<Condition> getSetCondition( final Field<T> field, final Selection<T> criteria) { if (criteria == null || criteria.isMatchAll()) { return Optional.empty(); } return Optional.of(field.in(criteria.getSet())); } /** * Used to build jOOQ conditions from string criteria * * @param field The jOOQ field being queried * @param criteria The criteria to apply * @return A condition that applies the given criteria */ public static Optional<Condition> getStringCondition( final Field<String> field, final StringCriteria criteria) { if (criteria == null || !criteria.isConstrained()) { return Optional.empty(); } final Optional<Condition> valueCondition; if (criteria.getMatchString() != null) { if (criteria.getMatchStyle() == null) { if (criteria.isCaseInsensitive()) { valueCondition = Optional.of(field.upper().eq(criteria.getMatchString())); } else { valueCondition = Optional.of(field.eq(criteria.getMatchString())); } } else { if (criteria.isCaseInsensitive()) { valueCondition = Optional.of(field.upper().like(criteria.getMatchString())); } else { valueCondition = Optional.of(field.like(criteria.getMatchString())); } } } else { valueCondition = Optional.empty(); } return convertMatchNull(field, criteria.getMatchNull(), valueCondition); } public static Optional<Condition> getBooleanCondition(final Field<Boolean> field, final Boolean value) { if (value == null) { return Optional.empty(); } else { return Optional.of(field.eq(value)); } } private static Optional<Condition> convertMatchNull(final Field<?> field, final Boolean matchNull, final Optional<Condition> condition) { if (matchNull == null) { return condition; } if (matchNull) { return condition.map(c -> c.or(field.isNull())).or(() -> Optional.of(field.isNull())); } return condition.or(() -> Optional.of(field.isNotNull())); } public static Collection<OrderField<?>> getOrderFields(final Map<String, Field<?>> fieldMap, final BaseCriteria criteria, final OrderField<?>... defaultSortFields) { if (criteria.getSortList() == null || criteria.getSortList().isEmpty()) { if (defaultSortFields != null && defaultSortFields.length > 0) { return new ArrayList<>(Arrays.asList(defaultSortFields)); } else { return Collections.emptyList(); } } else { return criteria.getSortList() .stream() .map(s -> getOrderField(fieldMap, s)) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()); } } private static Optional<OrderField<?>> getOrderField(final Map<String, Field<?>> fieldMap, final CriteriaFieldSort sort) { final Field<?> field = fieldMap.get(sort.getId()); if (field != null) { if (sort.isDesc()) { return Optional.of(field.desc()); } else { return Optional.of(field.asc()); } } return Optional.empty(); } /** * Converts a time in millis since epoch to a {@link java.sql.Timestamp} */ public static Field<Timestamp> epochMsToTimestamp(Field<? extends Number> field) { return DSL.field("from_unixtime({0} / 1000)", SQLDataType.TIMESTAMP, field); } /** * Converts a time in millis since epoch to a {@link java.sql.Date} */ public static Field<Date> epochMsToDate(Field<? extends Number> field) { return DSL.field("from_unixtime({0} / 1000)", SQLDataType.DATE, field); } public static Field<Integer> periodDiff(final Field<? extends Date> date1, final Field<? extends Date> date2) { return DSL.field("period_diff(extract(year_month from {0}), extract(year_month from {1}))", SQLDataType.INTEGER, date1, date2); } public static Field<Integer> periodDiff(final Field<? extends Date> date1, final Date date2) { return DSL.field("period_diff(extract(year_month from {0}), extract(year_month from {1}))", SQLDataType.INTEGER, date1, date2); } private static RuntimeException convertException(final Exception e) { LOGGER.error(e.getMessage(), e); if (e instanceof RuntimeException) { return (RuntimeException) e; } else { return new RuntimeException(e.getMessage(), e); } } }
package com.example.odroiddvfs; import android.app.Application; import android.content.Intent; public class MyApplication extends Application { public void onCreate(){ Intent keepAppIntent= new Intent(this, KeepAppAlive.class); startService(keepAppIntent); } }
package com.bbn.kbp; import com.bbn.bue.common.StringUtils; import com.bbn.bue.common.TextGroupImmutable; import com.bbn.bue.common.symbols.Symbol; import com.google.common.base.Optional; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.Sets; import org.immutables.value.Value; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import static com.google.common.base.Preconditions.checkArgument; /** * A class to hold the entire knowledge-base of assertions as objects. Confidence is stored as a map * from an Assertion object to a double value despite being an (optional) part of an assertion. * Confidences range from 0.0 (exclusive) to 1.0 (inclusive). The knowledge-base must not have any * duplicate assertions, which are defined as assertions that have identical "subject predicate object" * triples and identical provenance(s). (Note: If two assertions only differ in confidence, they * are still considered duplicates. Confidence is not part of the assertion identity.) */ @TextGroupImmutable @Value.Immutable public abstract class KnowledgeBase { public abstract Symbol runId(); public abstract ImmutableSet<Node> nodes(); /** * Maps nodes to identifiers. This is for convenience in order to maintain node names * from input to output through KB transformations. It is not necessary to assign a name to * all (or even any) nodes. Because of deletion, it is acceptable for nodes which * are not in the database to appear in this bimap, so don't iterate over it. This is * why it is not public and we have {@link #nameForNode(Node)} */ abstract ImmutableBiMap<Node, String> nodesToNames(); public abstract ImmutableSet<Assertion> assertions(); public abstract ImmutableMap<Assertion, Double> confidence(); /** * Gets the stable name assigned to a node, if any. * This is for convenience in order to maintain node names * from input to output through KB transformations. */ public final Optional<String> nameForNode(Node node) { return Optional.fromNullable(nodesToNames().get(node)); } /** * Get the entity canonical mentions found in a given document. This is useful for * aligning external system output to this knowledge base. */ @Value.Lazy public ImmutableMultimap<Symbol, EntityCanonicalMentionAssertion> documentToEntityCanonicalMentions() { return FluentIterable.from(assertions()) .filter(EntityCanonicalMentionAssertion.class) .index(EntityCanonicalMentionAssertionFunctions.docId()); } @Value.Check protected void check() { // check every assertion that has a confidence is also in the set of assertions checkArgument(assertions().containsAll(confidence().keySet())); // check that all nodes used in assertions are also in nodes for (final Assertion assertion : assertions()) { checkArgument(nodes().containsAll(assertion.allNodes()), "Assertion %s contains unknown nodes %s.", assertion, prettyNodes(Sets.difference(assertion.allNodes(), nodes()))); } // check that confidence scores are valid (between 0.0 and 1.0) for (final Map.Entry<Assertion, Double> e : confidence().entrySet()) { checkArgument(e.getValue() > 0.0 && e.getValue() <= 1.0, "%s is an invalid value as a confidence score for %s. " + "A confidence score must be between 0.0 (exclusive) and 1.0 (inclusive).", e.getValue(), e.getKey()); } checkTypeAssertions(); checkMentionAssertions(); for (final String name : nodesToNames().values()) { checkArgument(!name.isEmpty(), "You do not have to specify names for nodes, but if you do they can't be empty"); } } private void checkTypeAssertions() { final ImmutableSetMultimap.Builder<Node, Assertion> typeAssertionsByNodeB = ImmutableSetMultimap.builder(); for (final Assertion assertion : assertions()) { if (assertion instanceof TypeAssertion) { typeAssertionsByNodeB.put(assertion.subject(), assertion); } } final ImmutableSetMultimap<Node, Assertion> typeAssertionsByNode = typeAssertionsByNodeB.build(); // check each node has no more than one type assertion for (final Map.Entry<Node, Collection<Assertion>> e : typeAssertionsByNode.asMap().entrySet()) { checkArgument(e.getValue().size() == 1, "Got multiple type assertions for node %s: %s.", prettyNode(e.getKey()), e.getValue()); } // check every node has a type assertion checkArgument(nodes().equals(typeAssertionsByNode.keySet()), "Nodes lack a corresponding type assertion: %s.", prettyNodes(Sets.difference(nodes(), typeAssertionsByNode.keySet()))); } private void checkMentionAssertions() { final ImmutableSet.Builder<Node> mentionedNodesB = ImmutableSet.builder(); for (final Assertion assertion : assertions()) { if (assertion instanceof MentionAssertion) { mentionedNodesB.add(assertion.subject()); } } final ImmutableSet<Node> mentionedNodes = mentionedNodesB.build(); // check every node has at least one mention checkArgument(nodes().equals(mentionedNodes), "The following nodes lack a mention assertions: %s.", prettyNodes(Sets.difference(nodes(), mentionedNodes))); // TODO: check each canonical mention has a corresponding non-canonical mention. Issue #537 // TODO: check each normalized mention has a corresponding non-normalized mention. Issue #537 } /** * Provides a name for a node, if possible. For use in error messages. */ private String prettyNode(Node node) { final Optional<String> name = nameForNode(node); if (name.isPresent()) { return name.get(); } else { return "unnamed node"; } } /** * Provides a human-readable representation of a set of nodes, using names if possible. * For use in error messages. */ private String prettyNodes(Collection<Node> nodes) { final List<String> parts = new ArrayList<>(); int numUnnamed = 0; for (final Node node : nodes) { final Optional<String> name = nameForNode(node); if (name.isPresent()) { parts.add(name.get()); } else { ++numUnnamed; } } if (numUnnamed > 0) { parts.add(((parts.size() > 0) ? " and " : "") + numUnnamed + " unnamed nodes"); } return "[" + StringUtils.commaJoiner().join(parts) + "]"; } public static Builder builder() { return new Builder(); } public static class Builder extends ImmutableKnowledgeBase.Builder { public Builder nameNode(Node node, String name) { putNodesToNames(node, name); return this; } /** * Convenience method to add an assertion to the KB and record its confidence at the * same time. */ public Builder registerAssertion(Assertion assertion, double confidence) { this.addAssertions(assertion); this.putConfidence(assertion, confidence); return this; } public Builder registerAllAssertions(Map<? extends Assertion, Double> assertionsToConfidences) { for (final Map.Entry<? extends Assertion, Double> e : assertionsToConfidences.entrySet()) { registerAssertion(e.getKey(), e.getValue()); } return this; } // .of() only deprecated to warn external users @SuppressWarnings("deprecation") public StringNode newStringNode() { final StringNode ret = StringNode.of(); addNodes(ret); return ret; } // .of() only deprecated to warn external users @SuppressWarnings("deprecation") public EntityNode newEntityNode() { final EntityNode ret = EntityNode.of(); addNodes(ret); return ret; } // .of() only deprecated to warn external users @SuppressWarnings("deprecation") public EventNode newEventNode() { final EventNode ret = EventNode.of(); addNodes(ret); return ret; } } }
package com.pironet.tda.utils; import java.util.Comparator; import javax.swing.tree.DefaultMutableTreeNode; /** * compares monitor nodes based on the amount of threads refering to the monitors. * It return 0 for two monitors having the same amount of threads refering to them. * Using this in a TreeSet is not feasible as only one thread of on thread amount * refering to it would survive, the others would be lost. * * @author irockel */ public class MonitorComparator implements Comparator { /** * compares two monitor nodes based on the amount of threads refering to the monitors. * @param arg0 first monitor node * @param arg1 second monitor node * @return difference between amount of refering threads. */ public int compare(Object arg0, Object arg1) { if(arg0 instanceof DefaultMutableTreeNode && arg1 instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode firstNode = (DefaultMutableTreeNode) arg0; DefaultMutableTreeNode secondNode = (DefaultMutableTreeNode) arg1; return(secondNode.getChildCount() - firstNode.getChildCount()); } return(0); } }
package urlshortener.aeternum; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.ReadContext; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import urlshortener.aeternum.web.QrGenerator; import java.net.URI; import java.nio.charset.Charset; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.springframework.boot.Banner.Mode.LOG; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment= RANDOM_PORT) @DirtiesContext public class SystemTests { private static final Logger LOG = LoggerFactory .getLogger(SystemTests.class); @Value("${local.server.port}") private int port = 0; @Test public void testHome() throws Exception { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port, String.class); assertThat(entity.getStatusCode(), is(HttpStatus.OK)); assertTrue(entity.getHeaders().getContentType().isCompatibleWith(new MediaType("text", "html"))); assertThat(entity.getBody(), containsString("<title>URL")); } @Test public void testCss() throws Exception { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/webjars/bootstrap/3.3.5/css/bootstrap.min.css", String.class); assertThat(entity.getStatusCode(), is(HttpStatus.OK)); assertThat(entity.getHeaders().getContentType(), is(MediaType.valueOf("text/css"))); assertThat(entity.getBody(), containsString("body")); } @Test public void testCreateLink() throws Exception { ResponseEntity<String> entity = postLink("http://example.com/"); assertThat(entity.getStatusCode(), is(HttpStatus.CREATED)); assertThat(entity.getHeaders().getLocation(), is(new URI("http://localhost:"+ this.port+"/f684a3c4"))); assertThat(entity.getHeaders().getContentType(), is(new MediaType("application", "json", Charset.forName("UTF-8")))); ReadContext rc = JsonPath.parse(entity.getBody()); assertThat(rc.read("$.hash"), is("f684a3c4")); assertThat(rc.read("$.uri"), is("http://localhost:"+ this.port+"/f684a3c4")); assertThat(rc.read("$.target"), is("http://example.com/")); assertThat(rc.read("$.sponsor"), is(nullValue())); } @Test public void testRedirection() throws Exception { postLink("http://example.com/"); ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/f684a3c4", String.class); assertThat(entity.getStatusCode(), is("307")); LOG.info("STATUS: " + entity.getStatusCode().toString()); assertThat(entity.getHeaders().getLocation(), is("http://example.com/")); LOG.info("Direction: " + entity.getHeaders().getLocation()); } private ResponseEntity<String> postLink(String url) { MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>(); parts.add("url", url); return new TestRestTemplate().postForEntity( "http://localhost:" + this.port+"/link", parts, String.class); } }
package java7.autoclose; import com.sun.tools.doclets.formats.html.SourceToHTMLConverter; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class AutocloseDemo { String readFirstLine_priorToJava7(String path) throws IOException { BufferedReader br = new BufferedReader(new FileReader(path)); try { return br.readLine(); } finally { if (br != null) br.close(); } } String readFirstLine_java7(String path) throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); } } public void writeToFileZipFileContents(String src, String out) throws java.io.IOException { Charset charset = java.nio.charset.StandardCharsets.US_ASCII; Path outputFilePath = java.nio.file.Paths.get(out); try ( ZipFile zf = new ZipFile(src); BufferedWriter writer = Files.newBufferedWriter(outputFilePath, charset) ) { for (Enumeration entries = zf.entries(); entries.hasMoreElements(); ) { String newLine = System.getProperty("line.separator"); String zipEntryName = ((ZipEntry) entries.nextElement()).getName() + newLine; writer.write(zipEntryName, 0, zipEntryName.length()); } } } public void custom1() { // try(String str = "abc") {} try (MyResource res1 = new MyResource()) { System.out.println(res1); } } public void custom() { System.out.println("001"); try (MyResource res = new MyResource()) { System.out.println(res); } catch (Exception e) { System.out.println("002"); e.printStackTrace(); } finally { System.out.println("003"); } System.out.println("004"); } /* 001 java7.autoclose.MyResource@66d3c617 MyResource close() 003 004 */ public static void main(String[] args) { AutocloseDemo obj = new AutocloseDemo(); obj.custom(); } } class MyResource implements AutoCloseable { String member = "xxx"; @Override public void close() { member = null; System.out.println("MyResource close()"); } // public void close() throws Exception { }
package org.voovan.tools.json; import org.voovan.tools.TDateTime; import org.voovan.tools.TString; import org.voovan.tools.reflect.TReflect; import java.lang.reflect.Array; import java.math.BigDecimal; import java.util.Collection; import java.util.Date; import java.util.Map; public class JSONEncode { /** * JSON * * @param object * @return JSON * @throws ReflectiveOperationException */ private static String complexObject(Object object) throws ReflectiveOperationException { return mapObject(TReflect.getMapfromObject(object)); } /** * MapJSON * * @param mapObject map * @return JSON * @throws ReflectiveOperationException */ private static String mapObject(Map<?, ?> mapObject) throws ReflectiveOperationException { String mapString = "{"; StringBuilder contentStringBuilder = new StringBuilder(); String ContentString = null; Object[] keys = mapObject.keySet().toArray(); for (Object mapkey : keys) { Object key = fromObject(mapkey); String Value = fromObject(mapObject.get(mapkey)); contentStringBuilder.append(key); contentStringBuilder.append(":"); contentStringBuilder.append(Value); contentStringBuilder.append(","); } ContentString = contentStringBuilder.toString(); if (!ContentString.trim().isEmpty()){ ContentString = ContentString.substring(0, ContentString.length() - 1); } mapString = mapString + ContentString + "}"; return mapString; } /** * CollectionJSON * * @param listObject List * @return JSON * @throws ReflectiveOperationException */ private static String CollectionObject(Collection<Object> listObject) throws ReflectiveOperationException { return arrayObject(listObject.toArray()); } /** * ArrayJSON * * @param arrayObject Array * @throws ReflectiveOperationException * @return JSON */ private static String arrayObject(Object[] arrayObject) throws ReflectiveOperationException { String arrayString = "["; String ContentString = ""; StringBuilder ContentStringBuilder = new StringBuilder(); for (Object object : arrayObject) { String Value = fromObject(object); ContentStringBuilder.append(Value); ContentStringBuilder.append(","); } ContentString = ContentStringBuilder.toString(); if (!ContentString.trim().isEmpty()) { ContentString = ContentString.substring(0, ContentString.length() - 1); } arrayString = arrayString + ContentString + "]"; return arrayString; } /** * JSON * * @param object * @return :String JSON * @throws ReflectiveOperationException */ @SuppressWarnings("unchecked") public static String fromObject(Object object) throws ReflectiveOperationException { String value = null; if (object == null) { value = "null"; } else if (object instanceof BigDecimal) { if(BigDecimal.ZERO.compareTo((BigDecimal)object)==0){ object = BigDecimal.ZERO; } value = ((BigDecimal) object).toPlainString(); } else if (object instanceof Date) { value = "\"" + TDateTime.format(((Date)object), TDateTime.STANDER_DATETIME_TEMPLATE)+ "\"";; } else if (object instanceof Map) { Map<Object, Object> mapObject = (Map<Object, Object>) object; value = mapObject(mapObject); } else if (object instanceof Collection) { Collection<Object> collectionObject = (Collection<Object>)object; value = CollectionObject(collectionObject); } else if (object.getClass().isArray()) { Object[] arrayObject = (Object[])object; // java , if(object.getClass().getComponentType().isPrimitive()) { int length = Array.getLength(object); arrayObject = new Object[length]; for(int i=0;i<length;i++){ arrayObject[i] = Array.get(object, i); } } else { arrayObject = (Object[])object; } value = arrayObject(arrayObject); } else if (object instanceof Integer || object instanceof Float || object instanceof Double || object instanceof Boolean || object instanceof Long || object instanceof Short) { value = object.toString(); } else if (TReflect.isBasicType(object.getClass())) { // js eval js String strValue = object.toString(); if(JSON.isConvertEscapeChar()) { strValue = TString.convertEscapeChar(object.toString()); } value = "\"" + strValue + "\""; } else { value = complexObject(object); } return value; } }
package io.xchris6041x.devin.commands; /** * Used to return the result of a command, this gives DEVIN more information than just true or false. * @author Christopher Bishop */ public class CommandResult { public enum Status { SUCCESS, FAILED, USAGE } private Status status; private String message = null; private boolean usePrefix = false; public CommandResult(Status status, String message, boolean usePrefix) { this.status = status; this.message = message; this.usePrefix = usePrefix; } public Status getStatus() { return status; } public String getMessage() { return message; } public boolean usePrefix() { return usePrefix; } }
package example; //-*- mode:java; encoding:utf8n; coding:utf-8 -*- // vim:set fileencoding=utf-8: //@homepage@ import java.awt.*; import java.awt.event.*; import java.io.File; import java.util.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.filechooser.FileSystemView; import javax.swing.tree.*; public class MainPanel extends JPanel { public MainPanel() { super(new BorderLayout()); final FileSystemView fileSystemView = FileSystemView.getFileSystemView(); DefaultMutableTreeNode root = new DefaultMutableTreeNode(); final DefaultTreeModel treeModel = new DefaultTreeModel(root); for(File fileSystemRoot: fileSystemView.getRoots()) { DefaultMutableTreeNode node = new DefaultMutableTreeNode(new CheckBoxNode(fileSystemRoot, Status.DESELECTED)); root.add(node); for(File file: fileSystemView.getFiles(fileSystemRoot, true)) { if(file.isDirectory()) { node.add(new DefaultMutableTreeNode(new CheckBoxNode(file, Status.DESELECTED))); } } } treeModel.addTreeModelListener(new CheckBoxStatusUpdateListener()); final JTree tree = new JTree(treeModel) { @Override public void updateUI() { setCellRenderer(null); setCellEditor(null); super.updateUI(); //???#1: JDK 1.6.0 bug??? Nimbus LnF setCellRenderer(new FileTreeCellRenderer(fileSystemView)); setCellEditor(new CheckBoxNodeEditor(fileSystemView)); } }; tree.setBorder(BorderFactory.createEmptyBorder(4,4,4,4)); tree.setRootVisible(false); tree.addTreeSelectionListener(new FolderSelectionListener(fileSystemView)); //tree.setCellRenderer(new FileTreeCellRenderer(fileSystemView)); //tree.setCellEditor(new CheckBoxNodeEditor(fileSystemView)); tree.setEditable(true); tree.expandRow(0); //tree.setToggleClickCount(1); setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); add(new JScrollPane(tree)); add(new JButton(new AbstractAction("test") { @Override public void actionPerformed(ActionEvent ae) { System.out.println(" searchTreeForCheckedNode(tree, tree.getPathForRow(0)); // DefaultMutableTreeNode root = (DefaultMutableTreeNode)treeModel.getRoot(); // java.util.Enumeration e = root.breadthFirstEnumeration(); // while(e.hasMoreElements()) { // DefaultMutableTreeNode node = (DefaultMutableTreeNode)e.nextElement(); // CheckBoxNode check = (CheckBoxNode)node.getUserObject(); // if(check!=null && check.status==Status.SELECTED) { // System.out.println(check.file.toString()); } }), BorderLayout.SOUTH); setPreferredSize(new Dimension(320, 240)); } private static void searchTreeForCheckedNode(JTree tree, TreePath path) { Object o = path.getLastPathComponent(); if(o==null || !(o instanceof DefaultMutableTreeNode)) return; DefaultMutableTreeNode node = (DefaultMutableTreeNode)o; o = node.getUserObject(); if(o==null || !(o instanceof CheckBoxNode)) return; CheckBoxNode check = (CheckBoxNode)o; if(check.status==Status.SELECTED) { System.out.println(check.file.toString()); }else if(check.status==Status.INDETERMINATE && !node.isLeaf() && node.getChildCount()>=0) { Enumeration e = node.children(); while(e.hasMoreElements()) { searchTreeForCheckedNode(tree, path.pathByAddingChild(e.nextElement())); } } } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } public static void createAndShowGUI() { try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }catch(Exception e) { e.printStackTrace(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class TriStateCheckBox extends JCheckBox{ private Icon currentIcon; @Override public void updateUI() { currentIcon = getIcon(); setIcon(null); super.updateUI(); EventQueue.invokeLater(new Runnable() { @Override public void run() { if(currentIcon!=null) { setIcon(new IndeterminateIcon()); } setOpaque(false); } }); } } class IndeterminateIcon implements Icon { private final Color FOREGROUND = new Color(50,20,255,200); //TEST: UIManager.getColor("CheckBox.foreground"); private final Icon icon = UIManager.getIcon("CheckBox.icon"); @Override public void paintIcon(Component c, Graphics g, int x, int y) { icon.paintIcon(c, g, x, y); int w = getIconWidth(), h = getIconHeight(); int a = 4, b = 2; Graphics2D g2 = (Graphics2D)g; g2.setPaint(FOREGROUND); g2.translate(x, y); g2.fillRect(a, (h-b)/2, w-a-a, b); g2.translate(-x, -y); } @Override public int getIconWidth() { return icon.getIconWidth(); } @Override public int getIconHeight() { return icon.getIconHeight(); } } enum Status { SELECTED, DESELECTED, INDETERMINATE } class CheckBoxNode{ public final File file; public final Status status; public CheckBoxNode(File file) { this.file = file; status = Status.INDETERMINATE; } public CheckBoxNode(File file, Status status) { this.file = file; this.status = status; } @Override public String toString() { return file.getName(); } } class FolderSelectionListener implements TreeSelectionListener{ private final FileSystemView fileSystemView; public FolderSelectionListener(FileSystemView fileSystemView) { this.fileSystemView = fileSystemView; } @Override public void valueChanged(TreeSelectionEvent e) { final JTree tree = (JTree)e.getSource(); final DefaultMutableTreeNode node = (DefaultMutableTreeNode)e.getPath().getLastPathComponent(); final DefaultTreeModel model = (DefaultTreeModel)tree.getModel(); if(!node.isLeaf()) return; CheckBoxNode check = (CheckBoxNode)node.getUserObject(); if(check==null) return; final File parent = check.file; if(!parent.isDirectory()) return; final Status parent_status = check.status==Status.SELECTED?Status.SELECTED:Status.DESELECTED; SwingWorker<String, File> worker = new SwingWorker<String, File>() { @Override public String doInBackground() { File[] children = fileSystemView.getFiles(parent, true); for(File child: children) { if(child.isDirectory()) { publish(child); } } return "done"; } @Override protected void process(java.util.List<File> chunks) { for(File file: chunks) { node.add(new DefaultMutableTreeNode(new CheckBoxNode(file, parent_status))); } model.nodeStructureChanged(node); } }; worker.execute(); } } class FileTreeCellRenderer extends TriStateCheckBox implements TreeCellRenderer { private final FileSystemView fileSystemView; private final JPanel panel = new JPanel(new BorderLayout()); private JTree tree = null; private DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer(); public FileTreeCellRenderer(FileSystemView fileSystemView) { super(); String uiName = getUI().getClass().getName(); if(uiName.contains("Synth") && System.getProperty("java.version").startsWith("1.7.0")) { System.out.println("XXX: FocusBorder bug?, JDK 1.7.0, Nimbus start LnF"); renderer.setBackgroundSelectionColor(new Color(0,0,0,0)); } this.fileSystemView = fileSystemView; panel.setFocusable(false); panel.setRequestFocusEnabled(false); panel.setOpaque(false); panel.add(this, BorderLayout.WEST); this.setOpaque(false); } @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { this.tree = tree; JLabel l = (JLabel)renderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); l.setFont(tree.getFont()); if(value != null && value instanceof DefaultMutableTreeNode) { this.setEnabled(tree.isEnabled()); this.setFont(tree.getFont()); Object userObject = ((DefaultMutableTreeNode)value).getUserObject(); if(userObject!=null && userObject instanceof CheckBoxNode) { CheckBoxNode node = (CheckBoxNode)userObject; if(node.status==Status.INDETERMINATE) { setIcon(new IndeterminateIcon()); }else{ setIcon(null); } setText(""); File file = (File)node.file; l.setIcon(fileSystemView.getSystemIcon(file)); l.setText(fileSystemView.getSystemDisplayName(file)); l.setToolTipText(file.getPath()); setSelected(node.status==Status.SELECTED); } //panel.add(this, BorderLayout.WEST); panel.add(l); return panel; } return l; } @Override public void updateUI() { super.updateUI(); if(panel!=null) { //panel.removeAll(); //??? Change to Nimbus LnF, JDK 1.6.0 panel.updateUI(); //panel.add(this, BorderLayout.WEST); } setName("Tree.cellRenderer"); //???#1: JDK 1.6.0 bug??? @see 1.7.0 DefaultTreeCellRenderer#updateUI() //if(System.getProperty("java.version").startsWith("1.6.0")) { // renderer = new DefaultTreeCellRenderer(); } } class CheckBoxNodeEditor extends TriStateCheckBox implements TreeCellEditor { private final FileSystemView fileSystemView; private final JPanel panel = new JPanel(new BorderLayout()); private DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer(); private File file; public CheckBoxNodeEditor(FileSystemView fileSystemView) { super(); this.fileSystemView = fileSystemView; this.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { stopCellEditing(); } }); panel.setFocusable(false); panel.setRequestFocusEnabled(false); panel.setOpaque(false); panel.add(this, BorderLayout.WEST); this.setOpaque(false); } @Override public Component getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) { //JLabel l = (JLabel)renderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); JLabel l = (JLabel)renderer.getTreeCellRendererComponent(tree, value, true, expanded, leaf, row, true); l.setFont(tree.getFont()); setOpaque(false); if(value != null && value instanceof DefaultMutableTreeNode) { this.setEnabled(tree.isEnabled()); this.setFont(tree.getFont()); Object userObject = ((DefaultMutableTreeNode)value).getUserObject(); if(userObject!=null && userObject instanceof CheckBoxNode) { CheckBoxNode node = (CheckBoxNode)userObject; if(node.status==Status.INDETERMINATE) { setIcon(new IndeterminateIcon()); }else{ setIcon(null); } file = node.file; l.setIcon(fileSystemView.getSystemIcon(file)); l.setText(fileSystemView.getSystemDisplayName(file)); setSelected(node.status==Status.SELECTED); } //panel.add(this, BorderLayout.WEST); panel.add(l); return panel; } return l; } @Override public Object getCellEditorValue() { return new CheckBoxNode(file, isSelected()?Status.SELECTED:Status.DESELECTED); } @Override public boolean isCellEditable(EventObject e) { if(e != null && e instanceof MouseEvent && e.getSource() instanceof JTree) { MouseEvent me = (MouseEvent)e; JTree tree = (JTree)e.getSource(); TreePath path = tree.getPathForLocation(me.getX(), me.getY()); Rectangle r = tree.getPathBounds(path); if(r==null) return false; Dimension d = getPreferredSize(); r.setSize(new Dimension(d.width, r.height)); if(r.contains(me.getX(), me.getY())) { if(file==null && System.getProperty("java.version").startsWith("1.7.0")) { System.out.println("XXX: Java 7, only on first run\n"+getBounds()); setBounds(new Rectangle(0,0,d.width,r.height)); } //System.out.println(getBounds()); return true; } } return false; } @Override public void updateUI() { super.updateUI(); setName("Tree.cellEditor"); if(panel!=null) { //panel.removeAll(); //??? Change to Nimbus LnF, JDK 1.6.0 panel.updateUI(); //panel.add(this, BorderLayout.WEST); } //???#1: JDK 1.6.0 bug??? @see 1.7.0 DefaultTreeCellRenderer#updateUI() //if(System.getProperty("java.version").startsWith("1.6.0")) { // renderer = new DefaultTreeCellRenderer(); } //Copid from AbstractCellEditor // protected EventListenerList listenerList = new EventListenerList(); // transient protected ChangeEvent changeEvent = null; @Override public boolean shouldSelectCell(java.util.EventObject anEvent) { return true; } @Override public boolean stopCellEditing() { fireEditingStopped(); return true; } @Override public void cancelCellEditing() { fireEditingCanceled(); } @Override public void addCellEditorListener(CellEditorListener l) { listenerList.add(CellEditorListener.class, l); } @Override public void removeCellEditorListener(CellEditorListener l) { listenerList.remove(CellEditorListener.class, l); } public CellEditorListener[] getCellEditorListeners() { return listenerList.getListeners(CellEditorListener.class); } protected void fireEditingStopped() { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); // Process the listeners last to first, notifying // those that are interested in this event for(int i = listeners.length-2; i>=0; i-=2) { if(listeners[i]==CellEditorListener.class) { // Lazily create the event: if(changeEvent == null) changeEvent = new ChangeEvent(this); ((CellEditorListener)listeners[i+1]).editingStopped(changeEvent); } } } protected void fireEditingCanceled() { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); // Process the listeners last to first, notifying // those that are interested in this event for(int i = listeners.length-2; i>=0; i-=2) { if(listeners[i]==CellEditorListener.class) { // Lazily create the event: if(changeEvent == null) changeEvent = new ChangeEvent(this); ((CellEditorListener)listeners[i+1]).editingCanceled(changeEvent); } } } } class CheckBoxStatusUpdateListener implements TreeModelListener{ private boolean adjusting = false; @Override public void treeNodesChanged(TreeModelEvent e) { if(adjusting) return; adjusting = true; TreePath parent = e.getTreePath(); Object[] children = e.getChildren(); DefaultTreeModel model = (DefaultTreeModel)e.getSource(); DefaultMutableTreeNode node; CheckBoxNode c; // = (CheckBoxNode)node.getUserObject(); if(children!=null && children.length==1) { node = (DefaultMutableTreeNode)children[0]; c = (CheckBoxNode)node.getUserObject(); DefaultMutableTreeNode n = (DefaultMutableTreeNode)parent.getLastPathComponent(); while(n!=null) { updateParentUserObject(n); DefaultMutableTreeNode tmp = (DefaultMutableTreeNode)n.getParent(); if(tmp==null) { break; }else{ n = tmp; } } model.nodeChanged(n); }else{ node = (DefaultMutableTreeNode)model.getRoot(); c = (CheckBoxNode)node.getUserObject(); } updateAllChildrenUserObject(node, c.status); model.nodeChanged(node); adjusting = false; } private void updateParentUserObject(DefaultMutableTreeNode parent) { Object userObject = parent.getUserObject(); if(userObject==null || !(userObject instanceof CheckBoxNode)) { //System.out.println("parent.getUserObject()==null"); return; } File file = ((CheckBoxNode)userObject).file; int selectedCount = 0; int indeterminateCount = 0; java.util.Enumeration children = parent.children(); while(children.hasMoreElements()) { DefaultMutableTreeNode node = (DefaultMutableTreeNode)children.nextElement(); CheckBoxNode check = (CheckBoxNode)node.getUserObject(); if(check.status==Status.INDETERMINATE) { indeterminateCount++; break; } if(check.status==Status.SELECTED) selectedCount++; } if(indeterminateCount>0) { parent.setUserObject(new CheckBoxNode(file)); }else if(selectedCount==0) { parent.setUserObject(new CheckBoxNode(file, Status.DESELECTED)); }else if(selectedCount==parent.getChildCount()) { parent.setUserObject(new CheckBoxNode(file, Status.SELECTED)); }else{ parent.setUserObject(new CheckBoxNode(file)); } } private void updateAllChildrenUserObject(DefaultMutableTreeNode root, Status status) { java.util.Enumeration breadth = root.breadthFirstEnumeration(); while(breadth.hasMoreElements()) { DefaultMutableTreeNode node = (DefaultMutableTreeNode)breadth.nextElement(); if(root==node) { continue; } CheckBoxNode check = (CheckBoxNode)node.getUserObject(); node.setUserObject(new CheckBoxNode(check.file, status)); } } @Override public void treeNodesInserted(TreeModelEvent e) {} @Override public void treeNodesRemoved(TreeModelEvent e) {} @Override public void treeStructureChanged(TreeModelEvent e) {} }
package com.ehpefi.iforgotthat; import java.io.IOException; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.location.Address; import android.location.Geocoder; import android.net.ConnectivityManager; import android.util.Log; import com.google.android.gms.location.Geofence; /** * Performs CRUD operations on geofences in the 'I Forgot This' app. * * @author Even Holthe * @since 1.0.0 */ public class GeofenceHelper extends SQLiteOpenHelper { // Context private final Context context; // Important constants for handling the database private static final int VERSION = 1; private static final String DATABASE_NAME = "ift.db"; private static final String TABLE_NAME = "geofence"; // Column names in the database public static final String COL_ID = "_id"; public static final String COL_LAT = "lat"; public static final String COL_LON = "lon"; public static final String COL_DISTANCE = "distance"; public static final String COL_ADDRESS = "address"; public static final String COL_TITLE = "title"; // Specify which class that logs messages private static final String TAG = "GeofenceHelper"; /** * Constructs a new instance of the GeofenceHelper class * * @param context The context in which the new instance should be created, usually 'this'. * @since 1.0.0 */ public GeofenceHelper(Context context) { // Call the super class' constructor super(context, DATABASE_NAME, null, VERSION); this.context = context; } @Override public void onCreate(SQLiteDatabase db) { Log.d(TAG, "onCreate() was called. Creating the table '" + TABLE_NAME + "'..."); // SQL to create the 'geofence' table String createGeofenceSQL = String.format( "CREATE TABLE %s (%s INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, %s REAL NOT NULL, %s REAL NOT NULL, %s INTEGER NOT NULL, %s TEXT NOT NULL, %s TEXT NOT NULL)", TABLE_NAME, COL_ID, COL_LAT, COL_LON, COL_DISTANCE, COL_ADDRESS, COL_TITLE); // Create the table try { db.execSQL(createGeofenceSQL); Log.i(TAG, "The table '" + TABLE_NAME + "' was successfully created"); } catch (SQLException sqle) { Log.e(TAG, "Invalid SQL detected", sqle); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.d(TAG, "onUpgrade() was called, but nothing to upgrade..."); } @Override public void onOpen(SQLiteDatabase db) { // Maybe somewhat hacky, but SQLiteOpenHelper doesn't call onCreate() for a new // table, just a new database completely // Ask the database if the table 'items' exist Cursor cursor = db.rawQuery(String.format("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='%s'", TABLE_NAME), null); cursor.moveToFirst(); // If not, create it if (cursor.getInt(0) == 0) { onCreate(db); } cursor.close(); } @Override public void onConfigure(SQLiteDatabase db) { // Enable foreign keys db.setForeignKeyConstraintsEnabled(true); } /** * Inserts a new geofence to the database * * @param latitude The geofence's latitude coordinate * @param longitude The geofence's longitude coordinate * @param distance Distance in meters where the geofence should trigger * @param address Address of the coordinates * @param title The user's title * @return The id of the geofence in the database on success, 0 otherwise * @since 1.0.0 */ public int createNewGeofence(double latitude, double longitude, int distance, String address, String title) { // Create a pointer to the database SQLiteDatabase db = getWritableDatabase(); // Create the data to insert ContentValues values = new ContentValues(); values.put(COL_LAT, latitude); values.put(COL_LON, longitude); values.put(COL_DISTANCE, distance); values.put(COL_ADDRESS, address); values.put(COL_TITLE, title); // Try to save the list element try { // Runs the query and stores the id long returnId = db.insertOrThrow(TABLE_NAME, null, values); // Check for success if (returnId != -1) { // Success Log.i(TAG, "The geofence with address '" + address + "' was successfully saved"); // Close the database connection db.close(); return (int) returnId; } // Failure Log.e(TAG, "Could not save the geofence with address '" + address + "'. That's all I know..."); // Close the database connection db.close(); return 0; } catch (SQLException sqle) { // Something wrong with the SQL Log.e(TAG, "Error in inserting the geofence with address '" + address + "'", sqle); // Close the database connection db.close(); return 0; } } /** * Deletes an existing geofence from the database * * @param id The id of the geofence * @return True on success, false otherwise * @since 1.0.0 */ public boolean deleteGeofence(int id) { // Create a pointer to the database SQLiteDatabase db = getWritableDatabase(); // Log that we are deleting a list element Log.i(TAG, "Deletion of geofence with id " + id + " requested"); // For reminders that has this geofence, set it's geofence to 0 ListElementHelper leh = new ListElementHelper(context); ArrayList<ListElementObject> reminders = leh.getItemsWithGeofence(id); if (reminders.size() > 0) { for (ListElementObject reminder : leh.getItemsWithGeofence(id)) { Log.d(TAG, "Resetting geofenceId to 0 for reminder with id " + reminder.getId()); reminder.setGeofenceId(0); leh.updateListElement(reminder); } } // Try to delete the list element if (db.delete(TABLE_NAME, COL_ID + "=?", new String[] { Integer.toString(id) }) == 1) { Log.i(TAG, "Geofence with id " + id + " was successfully deleted"); // Close the database connection db.close(); return true; } // Couldn't delete list element Log.e(TAG, "Could not delete geofence with id " + id); // Close the database connection db.close(); return false; } /** * Updates the address for a given geofence * * @param id The id of the geofence in the database * @param newAddress The new address for the geofence * @return True on success, false otherwise * @since 1.0.0 */ public boolean setAddressForGeofence(int id, String newAddress) { // Create a pointer to the database SQLiteDatabase db = getWritableDatabase(); // Provide updated data ContentValues values = new ContentValues(); values.put(COL_ID, id); values.put(COL_ADDRESS, newAddress); // Try to update the list element if (db.update(TABLE_NAME, values, COL_ID + "=?", new String[] { Integer.toString(id) }) == 1) { Log.i(TAG, "The address for geofence with id " + id + " was successfully set to " + newAddress + "!"); // Close the database connection db.close(); return true; } Log.e(TAG, "Couldn't update the address for geofence with id " + id); db.close(); return false; } /** * Gets the saved address of a geofence in the database * * @param id The geofence id * @return The address of the geofence on success, "No address available" otherwise */ public String getAddressForGeofence(int id) { String address = context.getString(R.string.no_address_available); // Check for internet connection ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (cm.getActiveNetworkInfo() == null) { return address; } // Create a pointer to the database SQLiteDatabase db = getReadableDatabase(); // The SQL for selecting one geofence from the database String sql = String.format("SELECT %s, %s, %s, %s, %s, %s FROM %s WHERE %s = %d", COL_ID, COL_LAT, COL_LON, COL_DISTANCE, COL_ADDRESS, COL_TITLE, TABLE_NAME, COL_ID, id); // Cursor who points at the result Cursor cursor = db.rawQuery(sql, null); // As long as we have exactly one result if (cursor.getCount() == 1) { // Move to the only record cursor.moveToFirst(); Geocoder gc = new Geocoder(context); try { List<Address> addresses = gc.getFromLocation(cursor.getDouble(1), cursor.getDouble(2), 1); address = addresses.get(0).getAddressLine(0) + ", " + addresses.get(0).getAddressLine(1); } catch (IOException e) { } // Close the database connection cursor.close(); db.close(); // Return the geofence address return address; } Log.e(TAG, "The cursor in getAddressForGeofence() contains an unexpected value: " + cursor.getCount() + ". Returning a null object!"); // Close the database connection cursor.close(); db.close(); // Fail return null; } /** * A simple class for holding geofence data * * @author Even Holthe * @since 1.0.0 */ public class GeofenceData { public int id; public double lat; public double lon; public float distance; public String address; public String title; } /** * Gets all the geofences in the database. For populating a ListView so the user can pick a single geofence * * @return An array of simple GeofenceData objects on success, empty array on failure * @since 1.0.0 */ public ArrayList<GeofenceHelper.GeofenceData> getAllGeofences() { // Create a pointer to the database SQLiteDatabase db = getReadableDatabase(); // The SQL for selecting all geofences from the database String sql = String.format("SELECT %s, %s, %s, %s, %s, %s FROM %s ORDER BY %s %s", COL_ID, COL_LAT, COL_LON, COL_DISTANCE, COL_ADDRESS, COL_TITLE, TABLE_NAME, COL_ID, "DESC"); // Cursor who points at the result Cursor cursor = db.rawQuery(sql, null); // Array to hold our data ArrayList<GeofenceHelper.GeofenceData> returnData = new ArrayList<GeofenceHelper.GeofenceData>(); // As long as we have exactly one result if (cursor != null && cursor.getCount() >= 1) { // Move to the only record cursor.moveToFirst(); for (int i = 0; i < cursor.getCount(); i++) { GeofenceData data = new GeofenceData(); data.id = cursor.getInt(0); data.lat = cursor.getDouble(1); data.lon = cursor.getDouble(2); data.distance = Float.valueOf(cursor.getInt(3)); data.address = cursor.getString(4); data.title = cursor.getString(5); returnData.add(data); cursor.moveToNext(); } // Close the database connection cursor.close(); db.close(); // Return the geofence return returnData; } Log.i(TAG, "No geofences in the database!"); // Close the database connection cursor.close(); db.close(); // Fail return null; } /** * Gets a specific geofence, meant to be used for listing out data * * @return An simple GeofenceData object on success, null on failure * @param id The id of the geofence in the database * @since 1.0.0 */ public GeofenceData getGeofence(int id) { // Create a pointer to the database SQLiteDatabase db = getReadableDatabase(); // The SQL for selecting all geofences from the database String sql = String.format("SELECT %s, %s, %s, %s, %s, %s FROM %s WHERE %s = %d", COL_ID, COL_LAT, COL_LON, COL_DISTANCE, COL_ADDRESS, COL_TITLE, TABLE_NAME, COL_ID, id); // Cursor who points at the result Cursor cursor = db.rawQuery(sql, null); // As long as we have exactly one result if (cursor != null && cursor.getCount() >= 1) { // Move to the only record cursor.moveToFirst(); GeofenceData data = new GeofenceData(); data.id = cursor.getInt(0); data.lat = cursor.getDouble(1); data.lon = cursor.getDouble(2); data.distance = Float.valueOf(cursor.getInt(3)); data.address = cursor.getString(4); data.title = cursor.getString(5); // Close the database connection cursor.close(); db.close(); // Return the geofence return data; } Log.e(TAG, "The cursor in getGeofence() (GeofenceData) contains an unexpected value: " + cursor.getCount() + ". Returning a null object!"); // Close the database connection cursor.close(); db.close(); // Fail return null; } /** * Gets a specific geofence * * @param id The id of the geofence from the database * @param reminderId The id of the ListElementObject * @return An Android Geofence object * @since 1.0.0 */ public Geofence getGeofence(int id, int reminderId) { // Create a pointer to the database SQLiteDatabase db = getReadableDatabase(); // The SQL for selecting one geofence from the database String sql = String.format("SELECT %s, %s, %s, %s, %s, %s FROM %s WHERE %s = %d", COL_ID, COL_LAT, COL_LON, COL_DISTANCE, COL_ADDRESS, COL_TITLE, TABLE_NAME, COL_ID, id); // Cursor who points at the result Cursor cursor = db.rawQuery(sql, null); // As long as we have exactly one result if (cursor.getCount() == 1) { // Move to the only record cursor.moveToFirst(); Geofence fence = new Geofence.Builder().setRequestId("GEO" + reminderId).setCircularRegion(cursor.getDouble(1), cursor.getDouble(2), Float.valueOf(cursor.getInt(3))) .setExpirationDuration(Geofence.NEVER_EXPIRE).setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER).build(); // Close the database connection cursor.close(); db.close(); // Return the geofence return fence; } Log.e(TAG, "The cursor in getGeofence() (Geofence) contains an unexpected value: " + cursor.getCount() + ". Returning a null object!"); // Close the database connection cursor.close(); db.close(); // Fail return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:20-01-27"); this.setApiVersion("15.15.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:21-10-22"); this.setApiVersion("17.12.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:21-07-11"); this.setApiVersion("17.5.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:21-07-27"); this.setApiVersion("17.5.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.awt.geom.AffineTransform; import java.net.URL; import javax.swing.*; public final class MainPanel extends JPanel { private MainPanel() { super(new GridLayout(2, 2)); ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL url = cl.getResource("example/duke.running.gif"); assert url != null; ImageIcon imageIcon = new ImageIcon(url); JLabel label0 = new JLabel(imageIcon); label0.setBorder(BorderFactory.createTitledBorder("Default ImageIcon")); JLabel label1 = new JLabel(new ClockwiseRotateIcon(imageIcon)); label1.setBorder(BorderFactory.createTitledBorder("Wrapping with another Icon")); Image img = imageIcon.getImage(); JPanel label2 = new JPanel() { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g.create(); int x = getWidth() / 2; int y = getHeight() / 2; g2.setTransform(AffineTransform.getQuadrantRotateInstance(1, x, y)); int x2 = x - img.getWidth(this) / 2; int y2 = y - img.getHeight(this) / 2; // imageIcon.paintIcon(this, g2, x2, y2); g2.drawImage(img, x2, y2, this); g2.dispose(); } }; label2.setBorder(BorderFactory.createTitledBorder("Override JPanel#paintComponent(...)")); Icon icon3 = new ImageIcon(url) { @SuppressWarnings("PMD.AvoidSynchronizedAtMethodLevel") @Override public synchronized void paintIcon(Component c, Graphics g, int x, int y) { Graphics2D g2 = (Graphics2D) g.create(); g2.translate(x + getIconHeight(), y); g2.transform(AffineTransform.getQuadrantRotateInstance(1)); super.paintIcon(c, g2, 0, 0); g2.dispose(); } @Override public int getIconWidth() { return super.getIconHeight(); } @Override public int getIconHeight() { return super.getIconWidth(); } }; JLabel label3 = new JLabel(icon3); label3.setBorder(BorderFactory.createTitledBorder("Override ImageIcon#paintIcon(...)")); add(label0); add(label1); add(label2); add(label3); setPreferredSize(new Dimension(320, 240)); } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class ClockwiseRotateIcon implements Icon { private final Icon icon; protected ClockwiseRotateIcon(Icon icon) { this.icon = icon; } @Override public void paintIcon(Component c, Graphics g, int x, int y) { Graphics2D g2 = (Graphics2D) g.create(); g2.translate(x + icon.getIconHeight(), y); g2.transform(AffineTransform.getQuadrantRotateInstance(1)); icon.paintIcon(c, g2, 0, 0); g2.dispose(); } @Override public int getIconWidth() { return icon.getIconHeight(); } @Override public int getIconHeight() { return icon.getIconWidth(); } }
package it.swim.servlet.profilo; import it.swim.util.UtenteCollegatoUtil; import java.io.IOException; import java.text.DecimalFormat; import java.util.List; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import sessionBeans.localInterfaces.GestioneCollaborazioniLocal; import sessionBeans.localInterfaces.GestioneRicercheLocal; import lombok.extern.slf4j.Slf4j; import entityBeans.Abilita; import entityBeans.Utente; import exceptions.LoginException; import exceptions.RicercheException; /** * Servlet implementation class ProfiloServlet */ @Slf4j public class ProfiloServlet extends HttpServlet { private static final long serialVersionUID = 1L; @EJB private GestioneCollaborazioniLocal gestCollaborazioni; @EJB private GestioneRicercheLocal ricerche; /** * @see HttpServlet#HttpServlet() */ public ProfiloServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // ottengo l'email dell'utente collegato dalla sessione, appoggiandomi // ad una classe di utilita' String emailUtenteCollegato = (String) UtenteCollegatoUtil.getEmailUtenteCollegato(request); // se e' null e' perche' l'utente non e' collegato e allora devo fare il // redirect alla home if (emailUtenteCollegato == null) { response.sendRedirect("../home"); return; } // ottengo utente collegato con riferimento al vero oggetto Utente Utente utenteCollegato; try { utenteCollegato = gestCollaborazioni.getUtenteByEmail(emailUtenteCollegato); // mando sulla request i dati dell'utente tramite il setAttribute, e li // contraddistinguo dai 2 parametri passati come string request.setAttribute("cognomeUtenteCollegato", utenteCollegato.getCognome()); request.setAttribute("nomeUtenteCollegato", utenteCollegato.getNome()); // ottengo punteggio di feedback dell'utente Double punteggio = gestCollaborazioni.getPunteggioFeedback(emailUtenteCollegato); String feedback; if(punteggio==null) { feedback = new String("Non disponibile"); } else { DecimalFormat df = new DecimalFormat(" feedback = df.format(punteggio); request.setAttribute("feedback", punteggio.intValue() + ""); } request.setAttribute("punteggioUtenteCollegato", feedback); log.debug("punteggioUtenteCollegato:" + feedback); } catch (LoginException e) { log.error(e.getMessage(), e); } List<Abilita> abilitaInsiemePersonale; try { abilitaInsiemePersonale = ricerche.insiemeAbilitaPersonaliUtente(emailUtenteCollegato); request.setAttribute("abilita", abilitaInsiemePersonale); } catch (RicercheException e) { log.error(e.getMessage(), e); } getServletConfig().getServletContext().getRequestDispatcher("/jsp/utenti/profilo/profilo.jsp").forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
package data; import android.content.SharedPreferences; import java.util.ArrayList; public class PreferencesLayer { private static PreferencesLayer instance; private SharedPreferences sharedPreferences; private PreferencesLayer(SharedPreferences sharedPreferences) { this.sharedPreferences = sharedPreferences; } public static void initialize(SharedPreferences sharedPreferences) { instance = new PreferencesLayer(sharedPreferences); } public static PreferencesLayer getInstance() { if (instance == null) { throw new IllegalStateException("PreferencesLayer not initialized!"); } else { return instance; } } public void setDonationAmountPref(double amount) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putLong("donationAmount", Double.doubleToLongBits(amount)); editor.apply(); } public void setCallPref(boolean flag) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean("call", flag); editor.apply(); } public void setPostPref(boolean flag) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean("post", flag); editor.apply(); } public void setDonatePref(boolean flag) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean("donate", flag); editor.apply(); } public void setMailPref(boolean flag) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean("mail", flag); editor.apply(); } public void setKey(String id) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("id", id); editor.apply(); } public void setPhoneNumbers(ArrayList<String> phoneNumbers) { int size = phoneNumbers.size(); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt("phoneNumbersCount", size); for (int i = 0; i < size; i++) { editor.putString("phoneNumber" + i, phoneNumbers.get(i)); } editor.apply(); } public void setEmails(ArrayList<String> emails) { int size = emails.size(); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt("emailsCount", size); for (int i = 0; i < size; i++) { editor.putString("email" + i, emails.get(i)); } editor.apply(); } public double getDonationAmountPref() { return Double.longBitsToDouble(sharedPreferences.getLong("donationAmount", Double.doubleToLongBits(1))); } public boolean getCallPref() { return sharedPreferences.getBoolean("call", true); } public boolean getPostPref() { return sharedPreferences.getBoolean("post", true); } public boolean getDonatePref() { return sharedPreferences.getBoolean("donate", false); } public boolean getMailPref() { return sharedPreferences.getBoolean("mail", false); } public String getKey() { return sharedPreferences.getString("id", ""); } public ArrayList<String> getPhoneNumbers() { ArrayList<String> phoneNumbers = new ArrayList<>(); int size = sharedPreferences.getInt("phoneNumbersCount", 0); for (int i = 0; i < size; i++) { phoneNumbers.add(sharedPreferences.getString("email" + i, "")); } return phoneNumbers; } public ArrayList<String> getEmails() { ArrayList<String> emails = new ArrayList<>(); int size = sharedPreferences.getInt("emailsCount", 0); for (int i = 0; i < size; i++) { emails.add(sharedPreferences.getString("phoneNumber" + i, "")); } return emails; } }
package com.eegeo.searchmenu; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.eegeo.animation.ReversibleValueAnimator; import com.eegeo.animation.updatelisteners.ViewHeightAnimatorUpdateListener; import com.eegeo.entrypointinfrastructure.MainActivity; import com.eegeo.menu.MenuExpandableListAdapter; import com.eegeo.menu.MenuExpandableListOnClickListener; import com.eegeo.menu.MenuExpandableListView; import com.eegeo.menu.MenuListAnimationHandler; import com.eegeo.menu.MenuView; import com.eegeo.mobileexampleapp.R; import com.eegeo.searchmenu.SearchResultsScrollButtonTouchDownListener; import com.eegeo.searchmenu.SearchResultsScrollListener; import com.eegeo.searchmenu.SearchMenuResultsListAnimationConstants; import android.graphics.drawable.Drawable; import android.os.Handler; import android.text.Editable; import android.text.TextWatcher; import android.text.TextUtils.TruncateAt; import android.view.KeyEvent; import android.view.View; import android.view.View.OnFocusChangeListener; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.DecelerateInterpolator; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ExpandableListView; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; public class SearchMenuView extends MenuView implements TextView.OnEditorActionListener, OnFocusChangeListener, TextWatcher { protected View m_closeButtonView = null; protected View m_progressSpinner = null; protected View m_anchorArrow = null; protected View m_searchMenuResultsSeparator = null; protected int m_totalHeightPx; protected int m_dragStartPosYPx; protected int m_controlStartPosYPx; private ListView m_searchList = null; private SearchMenuAdapter m_searchListAdapter = null; private MenuExpandableListAdapter m_expandableListAdapter = null; private OnItemClickListener m_searchMenuItemSelectedListener = null; private EditText m_editText; private int m_disabledTextColor; private int m_enabledTextColor; private TextView m_searchCountText; private Integer m_searchCount; private boolean m_isTag; private boolean m_isFindMenuChildItemClicked; private ArrayList<String> m_pendingResults = null; private int m_resultsCount = 0; private SearchMenuAnimationHandler m_searchMenuAnimationHandler = null; private MenuListAnimationHandler m_menuListAnimationHandler = null; private ImageView m_searchResultsFade; private Button m_searchResultsScrollButton; private boolean m_searchResultsScrollable; private SearchResultsScrollButtonTouchDownListener m_searchResultsScrollButtonTouchDownListener; private SearchResultsScrollListener m_searchResultsScrollListener; private int m_menuScrollIndex = 0; private boolean m_editingText = false; private ImageButton m_dragButton; private Drawable m_dragButtonSearchStates; private Drawable m_dragButtonCloseStates; public SearchMenuView(MainActivity activity, long nativeCallerPointer) { super(activity, nativeCallerPointer); createView(); } protected void createView() { final RelativeLayout uiRoot = (RelativeLayout)m_activity.findViewById(R.id.ui_container); m_view = m_activity.getLayoutInflater().inflate(R.layout.search_menu_layout, uiRoot, false); m_list = (MenuExpandableListView)m_view.findViewById(R.id.search_menu_options_list_view); m_searchList = (ListView)m_view.findViewById(R.id.search_menu_item_list); m_dragButton = (ImageButton) m_view.findViewById(R.id.search_menu_drag_button_view); m_dragButton.setOnClickListener(this); m_dragButtonSearchStates = m_activity.getResources().getDrawable(R.drawable.button_search_menu_states); m_dragButtonCloseStates = m_activity.getResources().getDrawable(R.drawable.button_search_menu_close_states); m_closeButtonView = m_view.findViewById(R.id.search_menu_clear_button); m_closeButtonView.setOnClickListener(new SearchMenuCloseButtonClickedHandler(m_nativeCallerPointer, this)); m_closeButtonView.setVisibility(View.INVISIBLE); m_progressSpinner = m_view.findViewById(R.id.search_menu_spinner); m_progressSpinner.setVisibility(View.GONE); m_editText = (EditText)m_view.findViewById(R.id.search_menu_view_edit_text_view); m_editText.setImeActionLabel("Search", KeyEvent.KEYCODE_ENTER); m_editText.setOnEditorActionListener(this); m_editText.addTextChangedListener(this); m_editText.setOnFocusChangeListener(this); m_editText.clearFocus(); m_disabledTextColor = m_activity.getResources().getColor(R.color.text_field_disabled); m_enabledTextColor = m_activity.getResources().getColor(R.color.text_field_enabled); m_editText.setTextColor(m_enabledTextColor); m_editText.setEllipsize(TruncateAt.END); m_searchCountText = (TextView)m_view.findViewById(R.id.search_menu_result_count); m_searchCountText.setText(""); m_searchCount = new Integer(0); m_anchorArrow = m_view.findViewById(R.id.search_results_anchor_arrow); m_anchorArrow.setVisibility(View.GONE); m_searchMenuResultsSeparator = m_view.findViewById(R.id.search_menu_results_separator); m_searchMenuResultsSeparator.setVisibility(View.GONE); m_searchResultsFade = (ImageView)m_view.findViewById(R.id.search_results_fade); m_searchResultsScrollButton = (Button)m_view.findViewById(R.id.search_results_scroll_button); m_searchResultsScrollable = false; final MenuView scopedMenuView = this; m_view.addOnLayoutChangeListener(new View.OnLayoutChangeListener() { @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { m_menuAnimationHandler = m_searchMenuAnimationHandler = new SearchMenuAnimationHandler(m_activity, m_view, scopedMenuView); m_menuAnimationHandler.setToIntermediateOnScreenState(0.0f); m_view.removeOnLayoutChangeListener(this); } }); uiRoot.addView(m_view); View listContainerView = m_view.findViewById(R.id.search_menu_list_container); m_menuListAnimationHandler = new MenuListAnimationHandler(m_activity, listContainerView); m_expandableListAdapter = new MenuExpandableListAdapter(m_activity, m_list, m_menuListAnimationHandler, R.layout.menu_list_item, R.layout.menu_list_subitem, R.layout.menu_list_subitem_with_details); m_list.setAdapter(m_expandableListAdapter); m_expandableListOnClickListener = new MenuExpandableListOnClickListener(m_activity, m_nativeCallerPointer, this); m_list.setOnChildClickListener(m_expandableListOnClickListener); m_list.setOnGroupClickListener(m_expandableListOnClickListener); m_searchListAdapter = new SearchMenuAdapter(m_activity, R.layout.search_menu_list_item); m_searchList.setAdapter(m_searchListAdapter); m_searchMenuItemSelectedListener = new SearchMenuItemSelectedListener(m_nativeCallerPointer, this); m_searchList.setOnItemClickListener(m_searchMenuItemSelectedListener); ViewGroup vg = (ViewGroup)m_view; m_activity.recursiveDisableSplitMotionEvents(vg); m_isTag = false; m_searchResultsScrollListener = new SearchResultsScrollListener(m_searchResultsScrollButton, m_searchResultsFade, m_searchResultsScrollable, m_searchList); m_searchList.setOnScrollListener(m_searchResultsScrollListener); m_searchResultsScrollButtonTouchDownListener = new SearchResultsScrollButtonTouchDownListener(m_searchList, m_activity); m_searchResultsScrollButton.setOnTouchListener(m_searchResultsScrollButtonTouchDownListener); } @Override public boolean onEditorAction(TextView view, int actionId, KeyEvent event) { setClearButtonVisible(true); if (actionId == EditorInfo.IME_ACTION_DONE || actionId == KeyEvent.KEYCODE_ENTER) { final String queryText = m_editText.getText().toString(); m_activity.dismissKeyboard(m_editText.getWindowToken()); m_editText.clearFocus(); if(queryText.length() > 0) { SearchMenuViewJniMethods.PerformSearchQuery(m_nativeCallerPointer, queryText); } return true; } return false; } @Override public void afterTextChanged(Editable s) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(s.length() > 0) { setClearButtonVisible(true); m_editingText = true; showCloseButtonView(false); } else { setClearButtonVisible(false); showCloseButtonView(true); } } public void removeSearchKeyboard() { m_activity.dismissKeyboard(m_editText.getWindowToken()); } public void setSearchInProgress() { m_closeButtonView.setVisibility(View.INVISIBLE); m_progressSpinner.setVisibility(View.VISIBLE); m_editingText = false; } public void setSearchEnded() { m_closeButtonView.setVisibility(View.VISIBLE); m_progressSpinner.setVisibility(View.GONE); } public void setEditText(String searchText, boolean isTag) { setEditTextInternal(searchText, isTag); m_editText.clearFocus(); } private void setEditTextInternal(String searchText, boolean isTag) { m_editText.setText(searchText); m_isTag = isTag; if(!searchText.isEmpty()) { setClearButtonVisible(true); } else { setClearButtonVisible(false); } } public String getEditText() { return m_editText.getText().toString(); } private void setClearButtonVisible(boolean visible) { if(visible) { m_closeButtonView.setVisibility(View.VISIBLE); } else { m_closeButtonView.setVisibility(View.INVISIBLE); } } public void setSearchResultCount(final int searchResultCount) { m_searchCount = searchResultCount; m_searchCountText.setText(m_searchCount.toString()); m_searchMenuAnimationHandler.showSearchResultsView(); m_closeButtonView.setVisibility(View.VISIBLE); m_anchorArrow.setVisibility(View.VISIBLE); m_searchMenuResultsSeparator.setVisibility(View.VISIBLE); } public void fadeInButtonAnimation() { Animation fadeIn = new AlphaAnimation(0, 1); fadeIn.setInterpolator(new DecelerateInterpolator()); fadeIn.setDuration(SearchMenuResultsListAnimationConstants.SearchMenuResultsListScrollButtonAnimationSpeedMilliseconds); AnimationSet animation = new AnimationSet(false); animation.addAnimation(fadeIn); m_searchResultsScrollButton.setAnimation(animation); } @Override public void animateOffScreen() { super.animateOffScreen(); showCloseButtonView(false); } @Override public void animateToClosedOnScreen() { super.animateToClosedOnScreen(); showCloseButtonView(false); } @Override public void animateToOpenOnScreen() { super.animateToOpenOnScreen(); showCloseButtonView(m_editText.getText().length() == 0); } @Override protected void handleDragFinish(int xPx, int yPx) { } @Override protected void handleDragUpdate(int xPx, int yPx) { } @Override protected void refreshListData(List<String> groups, HashMap<String, List<String>> groupToChildrenMap) { m_expandableListAdapter.setData(groups, groupToChildrenMap); } public void removeSearchQueryResults() { hideSearchResultCount(); if(!m_editingText) { m_editText.setText(""); showCloseButtonView(false); } } public void hideSearchResultCount() { m_searchCount = 0; m_searchCountText.setText(""); if(m_searchMenuAnimationHandler != null) { m_searchMenuAnimationHandler.hideSearchResultsView(); } m_anchorArrow.setVisibility(View.GONE); m_searchMenuResultsSeparator.setVisibility(View.GONE); } public void setSearchSection(final int resultCount, final String[] searchResults) { ArrayList<String> searchResultList = new ArrayList<String>(); for(int i = 0; i < resultCount; i++) { searchResultList.add(searchResults[i]); } if(m_menuAnimationHandler.isOffScreen()) { m_pendingResults = searchResultList; } else { updateResults(searchResultList); } } private void updateResults(ArrayList<String> searchResults) { m_resultsCount = searchResults.size(); if (m_resultsCount > 0) { m_list.collapseAllGroups(); } updateSearchMenuHeight(m_resultsCount); m_searchListAdapter.setData(searchResults); m_pendingResults = null; } private void updateSearchMenuHeight(int resultCount) { final RelativeLayout mainSearchSubview = (RelativeLayout)m_view.findViewById(R.id.search_menu_view); final View topBar = (View)m_view.findViewById(R.id.search_menu_title_bar); final float viewHeight = mainSearchSubview.getHeight(); final int groupCount = m_expandableListAdapter.getGroupCount(); final int groupHeaderSize = (int)m_activity.getResources().getDimension(R.dimen.menu_item_header_height); final int menuItemDividerHeightSize = (int)m_activity.getResources().getDimension(R.dimen.menu_item_divider_height); final int menuListContainerCollapsedSize = groupCount * groupHeaderSize + ((groupCount - 1) * menuItemDividerHeightSize); final int totalMenuSeparatorSize = 2 * (int)m_activity.getResources().getDimension(R.dimen.menu_section_divider_height); final float occupiedHeight = topBar.getHeight() + menuListContainerCollapsedSize + totalMenuSeparatorSize; final float availableHeight = viewHeight - occupiedHeight; final float cellDividerHeight = m_activity.getResources().getDimension(R.dimen.search_menu_result_cell_divider_height); final float cellHeight = m_activity.getResources().getDimension(R.dimen.search_menu_result_cell_height); final float fullHeight = ((cellHeight + cellDividerHeight) * resultCount) - cellDividerHeight; final int height = (int)Math.max(Math.min(fullHeight, availableHeight), 0); ViewGroup.LayoutParams params = m_searchList.getLayoutParams(); int oldHeight = params.height; ReversibleValueAnimator menuHeightAnimator = ReversibleValueAnimator.ofInt(oldHeight, height); menuHeightAnimator.addUpdateListener(new ViewHeightAnimatorUpdateListener<LinearLayout.LayoutParams>(m_searchList)); menuHeightAnimator.setDuration(SearchMenuResultsListAnimationConstants.SearchMenuListTotalAnimationSpeedMilliseconds); menuHeightAnimator.start(); m_searchList.setSelection(0); if(fullHeight > availableHeight + cellHeight) { m_searchResultsFade.setVisibility(View.VISIBLE); m_searchResultsScrollButton.setVisibility(View.VISIBLE); m_searchResultsScrollable = true; if(resultCount > 0 && oldHeight == 0) { fadeInButtonAnimation(); } } else { m_searchResultsFade.setVisibility(View.INVISIBLE); m_searchResultsScrollButton.setVisibility(View.INVISIBLE); m_searchResultsScrollable = false; } m_searchResultsScrollListener.UpdateScrollable(m_searchResultsScrollable); if (m_searchResultsScrollButton.getX() == 0) { m_searchResultsScrollButton.setX(m_searchResultsFade.getPaddingLeft() - m_searchResultsScrollButton.getWidth()/2 + (m_searchResultsFade.getWidth() - (m_searchResultsFade.getPaddingLeft() + m_searchResultsFade.getPaddingRight()))/2); } } @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus && m_isTag) { setEditTextInternal("", false); } } private boolean hasPendingResults() { return m_pendingResults != null; } @Override public void onOpenOnScreenAnimationStart() { super.onOpenOnScreenAnimationStart(); m_list.setVisibility(View.VISIBLE); m_searchList.setVisibility(View.VISIBLE); if(hasPendingResults()) { updateResults(m_pendingResults); } updateSearchMenuHeight(m_resultsCount); m_searchList.setSelection(m_menuScrollIndex); } @Override public void onClosedOnScreenAnimationComplete() { super.onClosedOnScreenAnimationComplete(); m_menuScrollIndex = m_searchList.getFirstVisiblePosition(); m_list.setVisibility(View.GONE); m_searchList.setVisibility(View.GONE); if(m_isFindMenuChildItemClicked) { m_list.collapseAllGroups(); } m_isFindMenuChildItemClicked = false; } @Override protected void onMenuChildItemClick(ExpandableListView parent, View view, int groupPosition, int childPosition, long id) { m_isFindMenuChildItemClicked = groupPosition == 0 ? true : false; } private void showCloseButtonView(boolean shouldShowCloseView) { if(shouldShowCloseView) { m_dragButton.setImageDrawable(m_dragButtonCloseStates); } else { m_dragButton.setImageDrawable(m_dragButtonSearchStates); } } }
package com.demo.activity; import android.os.Bundle; import android.widget.Toast; import com.facebook.react.ReactActivity; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactNativeHost; import com.facebook.react.devsupport.interfaces.DevOptionHandler; import com.facebook.react.devsupport.interfaces.DevSupportManager; public class MainActivity extends ReactActivity { /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */ @Override protected String getMainComponentName() { return "ActivityDemoComponent"; } /** * Demonstrates how to add a custom option to the dev menu. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MainApplication application = (MainApplication) getApplication(); ReactNativeHost reactNativeHost = application.getReactNativeHost(); ReactInstanceManager reactInstanceManager = reactNativeHost.getReactInstanceManager(); DevSupportManager devSupportManager = reactInstanceManager.getDevSupportManager(); devSupportManager.addCustomDevOption("Custom dev option", new DevOptionHandler() { @Override public void onOptionSelected() { Toast.makeText(MainActivity.this, "Hello from custom dev option", Toast.LENGTH_SHORT).show(); } }); } }
package com.mapswithme.maps.location; import java.util.HashSet; import java.util.Iterator; import java.util.List; import android.content.Context; import android.hardware.GeomagneticField; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; public class LocationService implements LocationListener, SensorEventListener { private static final String TAG = "LocationService"; /// These constants should correspond to values defined in platform/location.hpp public static final int STOPPED = 0; public static final int STARTED = 1; public static final int FIRST_EVENT = 2; public static final int NOT_SUPPORTED = 3; public static final int DISABLED_BY_USER = 4; public interface Listener { public void onLocationUpdated(long time, double lat, double lon, float accuracy); public void onCompassUpdated(long time, double magneticNorth, double trueNorth, float accuracy); public void onLocationStatusChanged(int status); }; private HashSet<Listener> m_observers = new HashSet<Listener>(2); private Location m_lastLocation = null; private LocationManager m_locationManager; private SensorManager m_sensorManager; private Sensor m_compassSensor; // To calculate true north for compass private GeomagneticField m_magneticField = null; private boolean m_isActive = false; // @TODO Refactor to deliver separate first update notification to each provider, // or do not use it at all in the location service logic private boolean m_reportFirstUpdate = true; public LocationService(Context c) { // Acquire a reference to the system Location Manager m_locationManager = (LocationManager) c.getSystemService(Context.LOCATION_SERVICE); m_sensorManager = (SensorManager) c.getSystemService(Context.SENSOR_SERVICE); if (m_sensorManager != null) m_compassSensor = m_sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); } private void notifyStatusChanged(int newStatus) { Iterator<Listener> it = m_observers.iterator(); while (it.hasNext()) it.next().onLocationStatusChanged(newStatus); } private void notifyLocationUpdated(long time, double lat, double lon, float accuracy) { Iterator<Listener> it = m_observers.iterator(); while (it.hasNext()) it.next().onLocationUpdated(time, lat, lon, accuracy); } private void notifyCompassUpdated(long time, double magneticNorth, double trueNorth, float accuracy) { Iterator<Listener> it = m_observers.iterator(); while (it.hasNext()) it.next().onCompassUpdated(time, magneticNorth, trueNorth, accuracy); } public boolean isSubscribed(Listener observer) { return m_observers.contains(observer); } public void startUpdate(Listener observer) { m_observers.add(observer); if (!m_isActive) { // @TODO Add WiFi provider final List<String> enabledProviders = m_locationManager.getProviders(true); if (enabledProviders.size() == 0) { observer.onLocationStatusChanged(DISABLED_BY_USER); } else { m_isActive = true; observer.onLocationStatusChanged(STARTED); for (String provider : enabledProviders) { // @TODO change frequency and accuracy to save battery if (m_locationManager.isProviderEnabled(provider)) { m_locationManager.requestLocationUpdates(provider, 0, 0, this); // Send last known location for faster startup. // It should pass filter in the handler below. onLocationChanged(m_locationManager.getLastKnownLocation(provider)); } } if (m_sensorManager != null) m_sensorManager.registerListener(this, m_compassSensor, SensorManager.SENSOR_DELAY_NORMAL); } } else observer.onLocationStatusChanged(STARTED); } public void stopUpdate(Listener observer) { m_observers.remove(observer); // Stop only if no more observers are subscribed if (m_observers.size() == 0) { m_locationManager.removeUpdates(this); if (m_sensorManager != null) m_sensorManager.unregisterListener(this); m_isActive = false; m_reportFirstUpdate = true; m_magneticField = null; } observer.onLocationStatusChanged(STOPPED); } private static final int TWO_MINUTES = 1000 * 60 * 2; // Determines whether one Location reading is better than the current Location // @param location The new Location that you want to evaluate // @param currentBestLocation The current Location fix, to which you want to compare the new one protected boolean isBetterLocation(Location newLocation, Location currentBestLocation) { // A new location is better than no location only if it's not too old if (currentBestLocation == null) { if (java.lang.System.currentTimeMillis() - newLocation.getTime() > TWO_MINUTES) return false; return true; } // Check whether the new location fix is newer or older final long timeDelta = newLocation.getTime() - currentBestLocation.getTime(); final boolean isSignificantlyNewer = timeDelta > TWO_MINUTES; final boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES; final boolean isNewer = timeDelta >= 0; // If it's been more than two minutes since the current location, use the // new location because the user has likely moved if (isSignificantlyNewer) return true; else if (isSignificantlyOlder) { // If the new location is more than two minutes older, it must be worse return false; } // Check whether the new location fix is more or less accurate final int accuracyDelta = (int) (newLocation.getAccuracy() - currentBestLocation.getAccuracy()); final boolean isLessAccurate = accuracyDelta > 0; final boolean isMoreAccurate = accuracyDelta < 0; final boolean isSignificantlyLessAccurate = accuracyDelta > 200; // Check if the old and new location are from the same provider final boolean isFromSameProvider = isSameProvider(newLocation.getProvider(), currentBestLocation.getProvider()); // Determine location quality using a combination of timeliness and accuracy if (isMoreAccurate) return true; else if (isNewer && !isLessAccurate) return true; else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) return true; return false; } // Checks whether two providers are the same private static boolean isSameProvider(String provider1, String provider2) { if (provider1 == null) return provider2 == null; return provider1.equals(provider2); } //@Override public void onLocationChanged(Location l) { if (isBetterLocation(l, m_lastLocation)) { m_lastLocation = l; if (m_reportFirstUpdate) { m_reportFirstUpdate = false; notifyStatusChanged(FIRST_EVENT); } // Used for more precise compass updates if (m_sensorManager != null) { // Recreate magneticField if location has changed significantly if (m_lastLocation != null && (m_lastLocation == null || l.getTime() - m_lastLocation.getTime() > TWO_MINUTES)) m_magneticField = new GeomagneticField((float)l.getLatitude(), (float)l.getLongitude(), (float)l.getAltitude(), l.getTime()); } notifyLocationUpdated(l.getTime(), l.getLatitude(), l.getLongitude(), l.getAccuracy()); } } //@Override public void onSensorChanged(SensorEvent event) { if (m_magneticField == null) notifyCompassUpdated(event.timestamp, event.values[0], 0.0, 1.0f); else notifyCompassUpdated(event.timestamp, event.values[0], event.values[0] + m_magneticField.getDeclination(), m_magneticField.getDeclination()); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { Log.d(TAG, "Compass accuracy changed to " + String.valueOf(accuracy)); } @Override public void onProviderDisabled(String provider) { Log.d(TAG, "Disabled location provider: " + provider); } @Override public void onProviderEnabled(String provider) { Log.d(TAG, "Enabled location provider: " + provider); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { Log.d(TAG, String.format("Status changed for location provider: %s to %d", provider, status)); } }
package com.blogspot.ludumdaresforfun; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; import com.badlogic.gdx.maps.tiled.TiledMap; import com.badlogic.gdx.maps.tiled.TiledMapTileLayer; import com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell; import com.badlogic.gdx.maps.tiled.TmxMapLoader; import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Pool; public class MainScreen extends BaseScreen { public boolean pause = false; public boolean toggle = false; ConfigControllers configControllers; Rectangle playerRect; private OrthogonalTiledMapRenderer renderer; private OrthographicCamera camera; private Player player; private ShapeRenderer shapeRenderer; private TiledMap map; private boolean normalGravity = true; private boolean bossActive = false; private Array<Enemy> enemies = new Array<Enemy>(); private Array<Rectangle> tiles = new Array<Rectangle>(); private Array<Rectangle> spikes = new Array<Rectangle>(); private Array<Shot> shotArray = new Array<Shot>(); private Array<Vector2> spawns = new Array<Vector2>(); private Array<Vector2> lifes = new Array<Vector2>(); private Boss boss; private Vector2 door; private Pool<Rectangle> rectPool = new Pool<Rectangle>() { @Override protected Rectangle newObject () { return new Rectangle(); } }; HUD hud; private final float GRAVITY = -10f; final int SCREEN_HEIGHT = 240; final int SCREEN_WIDTH = 400; final int MAP_HEIGHT; final int MAP_WIDTH; final int POS_UPPER_WORLD; final int POS_LOWER_WORLD; final int DISTANCESPAWN = 410; final int TILED_SIZE; final float activateBossXPosition = 420; private float xRightBossWall = 420 + 200; private float xLeftBossWall = 420; public boolean bossCheckPoint = false; float UpOffset = 0; public MainScreen(boolean checkPoint) { this.shapeRenderer = new ShapeRenderer(); this.map = new TmxMapLoader().load("newtiles.tmx"); this.MAP_HEIGHT = (Integer) this.map.getProperties().get("height"); this.MAP_WIDTH = (Integer) this.map.getProperties().get("width"); this.TILED_SIZE = (Integer) this.map.getProperties().get("tileheight"); this.POS_LOWER_WORLD = ((this.MAP_HEIGHT / 2) * this.TILED_SIZE) - this.TILED_SIZE; this.POS_UPPER_WORLD = this.MAP_HEIGHT * this.TILED_SIZE ; this.renderer = new OrthogonalTiledMapRenderer(this.map, 1); //Assets.dispose(); //TODO: for debugging this.camera = new OrthographicCamera(); this.camera.setToOrtho(false, this.SCREEN_WIDTH, this.SCREEN_HEIGHT); this.camera.position.y = this.POS_UPPER_WORLD - this.MAP_HEIGHT; this.camera.update(); this.player = new Player(Assets.playerStand); this.boss = new Boss(Assets.bossStanding); this.configControllers = new ConfigControllers(); this.configControllers.init(); TiledMapTileLayer layerSpawn = (TiledMapTileLayer)(this.map.getLayers().get("Spawns")); this.rectPool.freeAll(this.tiles); this.tiles.clear(); for (int x = 0; x <= layerSpawn.getWidth(); x++) { for (int y = 0; y <= layerSpawn.getHeight(); y++) { Cell cell = layerSpawn.getCell(x, y); if (cell != null) { String type = (String) cell.getTile().getProperties().get("type"); if (type != null) { if (type.equals("enemy")) { this.spawns.add(new Vector2(x * this.TILED_SIZE, y * this.TILED_SIZE)); } else if (type.equals("pollo")) { this.lifes.add(new Vector2(x * this.TILED_SIZE, y * this.TILED_SIZE)); } else if (type.equals("player")) { this.player.setPosition(x * this.TILED_SIZE, y * this.TILED_SIZE); } else if (type.equals("boss")) { this.boss.setPosition(x * this.TILED_SIZE, y * this.TILED_SIZE); } else if (type.equals("door")) { this.door = new Vector2(x, y); } } } } } this.hud = new HUD(Assets.hudBase); if (checkPoint) this.player.setPosition(765*16, 62*16); } @Override public void render(float delta) { Gdx.gl.glClearColor(.9f, .9f, .9f, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); this.updatePlayer(delta); this.player.act(delta); this.activateBoss(); if (!this.bossActive){ //update x if ((this.player.getX() - (this.SCREEN_WIDTH / 2)) < this.TILED_SIZE) this.camera.position.x = (this.SCREEN_WIDTH / 2) + this.TILED_SIZE; else if ((this.player.getX() + (this.SCREEN_WIDTH / 2)) > (this.MAP_WIDTH * this.TILED_SIZE)) this.camera.position.x = (this.MAP_WIDTH * 16) - (this.SCREEN_WIDTH / 2); else this.camera.position.x = this.player.getX(); //update y if ((this.player.getY() - (this.SCREEN_HEIGHT / 2)) >= this.POS_LOWER_WORLD) this.camera.position.y = this.player.getY(); else if (this.player.getY() > this.POS_LOWER_WORLD) this.camera.position.y = this.POS_LOWER_WORLD + (this.SCREEN_HEIGHT / 2); else if ((this.player.getY() + (this.SCREEN_HEIGHT / 2)) >= this.POS_LOWER_WORLD) this.camera.position.y = this.POS_LOWER_WORLD - (this.SCREEN_HEIGHT / 2); else this.camera.position.y = this.player.getY(); this.camera.update(); } if (this.spawns.size > 0) { Vector2 auxNextSpawn = this.spawns.first(); if ((this.camera.position.x + this.DISTANCESPAWN) >= auxNextSpawn.x) { Enemy auxShadow = new Enemy(Assets.enemyWalk); if (auxNextSpawn.y < 240) { auxNextSpawn.y -= 5; // Offset fixed collision } auxShadow.setPosition(auxNextSpawn.x, auxNextSpawn.y); auxShadow.state = Enemy.State.BeingInvoked; auxShadow.stateTime = 0; auxShadow.beingInvoked = true; this.enemies.add(auxShadow); this.spawns.removeIndex(0); } } this.collisionLifes(delta); this.updateEnemies(delta); this.renderer.setView(this.camera); this.renderer.render(new int[]{0, 1, 3}); this.renderEnemies(delta); this.renderPlayer(delta); for (Shot shot : this.shotArray){ if (shot != null) this.renderShot(shot, delta); } if (this.bossActive && (this.boss != null)) { this.updateBoss(delta); if (this.boss != null) this.renderBoss(delta); } this.renderHUD(delta); } private void updateBoss(float delta) { if (this.boss.state.equals(Boss.State.Jumping) || this.boss.state.equals(Boss.State.Falling)){ if (this.player.getRect().overlaps(new Rectangle (this.boss.getX(), this.boss.getY(), this.boss.getWidth(), this.boss.getHeight()))) { this.player.beingHit(); } } else{ if (this.player.getRect().overlaps(this.boss.getRect())) { this.player.beingHit(); } } this.boss.desiredPosition.y = this.boss.getY(); this.boss.stateTime += delta; if (this.normalGravity) this.boss.velocity.add(0, this.GRAVITY); else this.boss.velocity.add(0, -this.GRAVITY); this.boss.velocity.scl(delta); this.collisionForBoss(this.boss); // unscale the velocity by the inverse delta time and set the latest position this.boss.desiredPosition.add(this.boss.velocity); this.boss.velocity.scl(1 / delta); this.flowBoss(delta); this.boss.setPosition(this.boss.desiredPosition.x, this.boss.desiredPosition.y); if (this.boss.setToDie && Assets.bossDie.isAnimationFinished(this.boss.stateTime)) this.boss = null; } private void flowBoss(float delta) { this.changeOfStatesInCaseOfAnimationFinish(); if (this.boss.flowState == Boss.FlowState.WalkingLeft){ this.boss.velocity.x = -100; this.boss.flowState = Boss.FlowState.Transition; this.boss.state = Boss.State.Walking; } else if (this.boss.flowState == Boss.FlowState.WalkingRight){ this.boss.velocity.x = 100; this.boss.flowState = Boss.FlowState.Transition; this.boss.state = Boss.State.Walking; } else if (this.boss.flowState == Boss.FlowState.Jumping){ if ((this.boss.getX() - this.player.getX()) > 0) this.boss.velocity.x = -200; else this.boss.velocity.x = 200; this.boss.velocity.y = 400; this.boss.flowState = Boss.FlowState.Transition; this.boss.state = Boss.State.Jumping; if (this.boss.getX() > this.xRightBossWall) //if going to hit wall turns back this.boss.velocity.x = -100; else if (this.boss.getX() < this.xLeftBossWall) //same for other wall this.boss.velocity.x = 100; } else if (this.boss.flowState == Boss.FlowState.Attack){ if ((this.boss.getX() - this.player.getX()) > 0) this.boss.facesRight = false; else this.boss.facesRight = true; this.boss.velocity.x = 0; //attack to character(detect position and collision) this.boss.flowState = Boss.FlowState.Transition; this.boss.state = Boss.State.Attack; this.boss.stateTime = 0; } else if (this.boss.flowState == Boss.FlowState.Summon){ this.boss.velocity.x = 0; this.Summon(); this.boss.flowState = Boss.FlowState.Transition; this.boss.state = Boss.State.Summon; this.boss.stateTime = 0; } else if (this.boss.flowState == Boss.FlowState.Standing){ this.boss.velocity.x = 0; this.boss.flowState = Boss.FlowState.Transition; this.boss.counter.gainLife(3); this.boss.state = Boss.State.Standing; } else if (this.boss.flowState == Boss.FlowState.Die){ this.boss.velocity.x = 0; this.boss.velocity.y = 0; } else if (this.boss.flowState == Boss.FlowState.Transition){ //door.x is the left side of the tiles if (!this.boss.state.equals(Boss.State.Die)){ if (this.boss.getX() > this.xRightBossWall) //if going to hit wall turns back this.boss.flowState = Boss.FlowState.WalkingLeft; else if (this.boss.getX() < this.xLeftBossWall) //same for other wall this.boss.flowState = Boss.FlowState.WalkingRight; else if (this.boss.flowTime > 2){ //takes pseudo-random action int nextState = (int)Math.round(Math.random() * 7); if ((Math.abs(this.boss.getX() - this.player.getX()) < 48) && ((nextState % 2) == 0)) //3 tiles far: attacks 50% time this.boss.flowState = Boss.FlowState.Attack; else if ((nextState == 0) || (nextState == 1)) //one possibility is jump this.boss.flowState = Boss.FlowState.Jumping; else if ((nextState == 2) || (nextState == 3)) this.boss.flowState = Boss.FlowState.Summon; //another summon else if ((nextState == 4) || (nextState == 5)){ //or move in your direction if ((this.boss.getX() - this.player.getX()) > 0) this.boss.flowState = Boss.FlowState.WalkingLeft; else this.boss.flowState = Boss.FlowState.WalkingRight; } else this.boss.flowState = Boss.FlowState.Standing; this.boss.flowTime = 0; } } } this.boss.flowTime += delta; } private void Summon() { this.spawns.add(new Vector2(this.boss.getX(), this.boss.getY() + 60)); if ((this.boss.getX() + 30) < this.xRightBossWall) this.spawns.add(new Vector2(this.boss.getX() + 10 + this.boss.getWidth(), this.boss.getY() + 5)); if ((this.boss.getX() - 30) > this.xLeftBossWall) this.spawns.add(new Vector2(this.boss.getX() - 30, this.boss.getY() + 5)); } private void changeOfStatesInCaseOfAnimationFinish() { if ((this.boss.state == Boss.State.Jumping) && (this.boss.velocity.y < 0)) this.boss.state = Boss.State.Falling; if (this.boss.setToDie) this.boss.flowState = Boss.FlowState.Die; } private void renderBoss(float delta) { this.boss.actualFrame = null; if (this.boss.velocity.x > 0) this.boss.facesRight = true; else if (this.boss.velocity.x < 0) this.boss.facesRight = false; if (this.boss.state == Boss.State.Standing) this.boss.actualFrame = (AtlasRegion)Assets.bossStanding.getKeyFrame(this.boss.stateTime); else if (this.boss.state == Boss.State.Walking) this.boss.actualFrame = (AtlasRegion)Assets.bossWalking.getKeyFrame(this.boss.stateTime); else if (this.boss.state == Boss.State.Attack) this.boss.actualFrame = (AtlasRegion)Assets.bossAttack.getKeyFrame(this.boss.stateTime); else if (this.boss.state == Boss.State.Jumping) this.boss.actualFrame = (AtlasRegion)Assets.bossJumping.getKeyFrame(this.boss.stateTime); else if (this.boss.state == Boss.State.Falling) this.boss.actualFrame = (AtlasRegion)Assets.bossFalling.getKeyFrame(this.boss.stateTime); else if (this.boss.state == Boss.State.Hurting) this.boss.actualFrame = (AtlasRegion)Assets.bossGethit.getKeyFrame(this.boss.stateTime); else if (this.boss.state == Boss.State.Die) this.boss.actualFrame = (AtlasRegion)Assets.bossDie.getKeyFrame(this.boss.stateTime); else if (this.boss.state == Boss.State.Summon) this.boss.actualFrame = (AtlasRegion)Assets.bossSummon.getKeyFrame(this.boss.stateTime); if (this.boss.invincible && this.boss.toggle) { this.boss.actualFrame = (AtlasRegion)Assets.bossGethit.getKeyFrame(this.player.stateTime); this.boss.toggle = !this.boss.toggle; } else if (this.boss.invincible && !this.boss.toggle) { this.boss.toggle = !this.boss.toggle; } else if (!this.boss.invincible) { this.boss.toggle = false; } Batch batch = this.renderer.getSpriteBatch(); batch.begin(); if (this.boss.facesRight) { if (this.boss.actualFrame.isFlipX()) this.boss.actualFrame.flip(true, false); batch.draw(this.boss.actualFrame, (this.boss.getX() + this.boss.actualFrame.offsetX) - this.boss.offSetX, (this.boss.getY() + this.boss.actualFrame.offsetY) - this.boss.offSetY); } else { if (!this.boss.actualFrame.isFlipX()) this.boss.actualFrame.flip(true, false); batch.draw(this.boss.actualFrame, (this.boss.getX() + this.boss.actualFrame.offsetX) - this.boss.offSetX, (this.boss.getY() + this.boss.actualFrame.offsetY) - this.boss.offSetY); } batch.end(); } private void renderShot(Shot shot, float deltaTime){ AtlasRegion frame = null; if (shot.state == Shot.State.Normal) frame = (AtlasRegion) Assets.playerShot.getKeyFrame(shot.stateTime); else if (shot.state == Shot.State.Exploding) frame = (AtlasRegion) Assets.playerShotHit.getKeyFrame(shot.stateTime); if (!this.normalGravity) { if (!frame.isFlipY()) frame.flip(false, true); } else { if (frame.isFlipY()) frame.flip(false, true); } Batch batch = this.renderer.getSpriteBatch(); batch.begin(); if (shot.shotGoesRight) { if (frame.isFlipX()) frame.flip(true, false); batch.draw(frame, shot.getX(), shot.getY()); } else { if (!frame.isFlipX()) frame.flip(true, false); batch.draw(frame, shot.getX(), shot.getY()); } batch.end(); } public boolean updateShot(Shot shot, float deltaTime){ boolean killMe = false; shot.desiredPosition.y = shot.getY(); shot.stateTime += deltaTime; if (this.normalGravity && !shot.state.equals(Shot.State.Exploding)) shot.velocity.add(0, this.GRAVITY); else shot.velocity.add(0, -this.GRAVITY); shot.velocity.scl(deltaTime); //collision (destroy if necessary) boolean collided = this.collisionShotEnemy(shot); if (!collided) collided = this.collisionShot(shot); // unscale the velocity by the inverse delta time and set // the latest position if (shot != null){ shot.desiredPosition.add(shot.velocity); shot.velocity.scl(1 / deltaTime); shot.setPosition(shot.desiredPosition.x, shot.desiredPosition.y); if (shot.normalGravity && (shot.getY() < this.POS_LOWER_WORLD)) collided = true; //dont traspass to the other world else if (!shot.normalGravity && (shot.getY() >= this.POS_LOWER_WORLD)) collided = true; else if ((shot.getY() > (this.MAP_HEIGHT * this.TILED_SIZE)) || (shot.getY() < 0)) collided = true; } if (collided && !shot.state.equals(Shot.State.Exploding)){ Assets.playSound("holyWaterBroken"); shot.state = Shot.State.Exploding; shot.stateTime = 0; shot.velocity.x = 0f; shot.velocity.y = 0f; } if (Assets.playerShotHit.isAnimationFinished(shot.stateTime) && shot.state.equals(Shot.State.Exploding)) killMe = true; return killMe; } private boolean collisionShotEnemy(Shot shot) { boolean collided = false; this.playerRect = this.rectPool.obtain(); shot.desiredPosition.y = Math.round(shot.getY()); shot.desiredPosition.x = Math.round(shot.getX()); this.playerRect = shot.getRect(); for (Enemy enemy : this.enemies){ if (this.playerRect.overlaps(enemy.getRect())) { if (!enemy.dying){ enemy.die(); collided = true; break; } } } if ((this.boss != null) && this.playerRect.overlaps(this.boss.getRect())) { if (!this.boss.invincible) this.boss.beingHit(); if (!this.boss.setToDie){ this.boss.invincible = true; //activates also the flickering } else if (this.boss.state != Boss.State.Die){ this.boss.state = Boss.State.Die; } collided = true; } return collided; } private boolean collisionShot(Shot shot) { this.playerRect = this.rectPool.obtain(); shot.desiredPosition.y = Math.round(shot.getY()); shot.desiredPosition.x = Math.round(shot.getX()); this.playerRect = shot.getRect(); int startX, startY, endX, endY; if (shot.velocity.x > 0) { //this.raya.velocity.x > 0 startX = endX = (int)((shot.desiredPosition.x + shot.velocity.x + shot.actualFrame.packedWidth) / 16); } else { startX = endX = (int)((shot.desiredPosition.x + shot.velocity.x) / 16); } startY = (int)((shot.desiredPosition.y) / 16); endY = (int)((shot.desiredPosition.y + shot.actualFrame.packedHeight) / 16); this.getTiles(startX, startY, endX, endY, this.tiles); this.playerRect.x += shot.velocity.x; for (Rectangle tile : this.tiles){ if (this.playerRect.overlaps(tile)) { shot = null; return true; } } this.playerRect.x = shot.desiredPosition.x; if (this.normalGravity){ if (shot.velocity.y > 0) { startY = endY = (int)((shot.desiredPosition.y + shot.velocity.y + shot.actualFrame.packedHeight) / 16f); } else { startY = endY = (int)((shot.desiredPosition.y + shot.velocity.y) / 16f); } } else{ if (shot.velocity.y < 0) { startY = endY = (int)((shot.desiredPosition.y + shot.velocity.y) / 16f); } else { startY = endY = (int)((shot.desiredPosition.y + shot.velocity.y + shot.actualFrame.packedHeight ) / 16f); } } startX = (int)((shot.desiredPosition.x + shot.offSetX) / 16); //16 tile size endX = (int)((shot.desiredPosition.x + shot.actualFrame.packedWidth) / 16); // System.out.println(startX + " " + startY + " " + endX + " " + endY); this.getTiles(startX, startY, endX, endY, this.tiles); shot.desiredPosition.y += (int)(shot.velocity.y); for (Rectangle tile : this.tiles) { if (this.playerRect.overlaps(tile)) { shot = null; return true; } } return false; } private void renderPlayer (float deltaTime) { AtlasRegion frame = null; switch (this.player.state) { case Standing: frame = (AtlasRegion)Assets.playerStand.getKeyFrame(this.player.stateTime); break; case Walking: frame = (AtlasRegion)Assets.playerWalk.getKeyFrame(this.player.stateTime); break; case Jumping: frame = (AtlasRegion)Assets.playerJump.getKeyFrame(this.player.stateTime); break; case Intro: frame = (AtlasRegion)Assets.playerIntro.getKeyFrame(this.player.stateTime); break; case Attacking: frame = (AtlasRegion)Assets.playerAttack.getKeyFrame(this.player.stateTime); break; case Die: frame = (AtlasRegion)Assets.playerDie.getKeyFrame(this.player.stateTime); break; case BeingHit: frame = (AtlasRegion)Assets.playerBeingHit.getKeyFrame(this.player.stateTime); break; } if (this.player.invincible && this.toggle) { frame = (AtlasRegion)Assets.playerEmpty.getKeyFrame(this.player.stateTime); this.toggle = !this.toggle; } else if (this.player.invincible && !this.toggle) { this.toggle = !this.toggle; } else if (!this.player.invincible) { this.toggle = false; } // draw the koala, depending on the current velocity // on the x-axis, draw the koala facing either right // or left Batch batch = this.renderer.getSpriteBatch(); batch.begin(); if (this.player.facesRight && frame.isFlipX()) { frame.flip(true, false); this.player.rightOffset = 1f; //fix differences } else if (!this.player.facesRight && !frame.isFlipX()) { frame.flip(true, false); this.player.rightOffset = -4f; //fix differences } if (this.normalGravity && frame.isFlipY()) { frame.flip(false, true); this.UpOffset = 0; } else if (!this.normalGravity && !frame.isFlipY()){ frame.flip(false, true); this.UpOffset = -2; } //batch.draw(frame, this.player.getX() + frame.offsetX, this.player.getY() + frame.offsetY + this.UpOffset); batch.draw(frame, (this.player.getX() + this.player.actualFrame.offsetX) - this.player.offSetX, (this.player.getY() + this.player.actualFrame.offsetY) - this.player.offSetY); batch.end(); this.shapeRenderer.begin(ShapeType.Filled); this.shapeRenderer.setColor(Color.BLACK); this.getTiles(0, 0, 25, 15, this.tiles); //for (Rectangle tile : this.tiles) { // shapeRenderer.rect(tile.x * 1.6f, tile.y * 2, tile.width * 2, tile.height * 2); this.shapeRenderer.setColor(Color.RED); //shapeRenderer.rect(playerRect.x * 1.6f, playerRect.y * 2, playerRect.width * 2, playerRect.height * 2); this.shapeRenderer.end(); } private void renderEnemies(float deltaTime) { for (Enemy enemy : this.enemies) { enemy.actualFrame = null; switch (enemy.state) { case Walking: enemy.actualFrame = (AtlasRegion)Assets.enemyWalk.getKeyFrame(enemy.stateTime); break; case Running: enemy.actualFrame = (AtlasRegion)Assets.enemyRun.getKeyFrame(enemy.stateTime); break; case Hurting: enemy.actualFrame = (AtlasRegion)Assets.enemyHurt.getKeyFrame(enemy.stateTime); break; case BeingInvoked: enemy.actualFrame = (AtlasRegion)Assets.enemyAppearing.getKeyFrame(enemy.stateTime); break; } Batch batch = this.renderer.getSpriteBatch(); batch.begin(); if (enemy.dir == Enemy.Direction.Right) { if (enemy.actualFrame.isFlipX()) enemy.actualFrame.flip(true, false); batch.draw(enemy.actualFrame, enemy.getX(), enemy.getY()); } else { if (!enemy.actualFrame.isFlipX()) enemy.actualFrame.flip(true, false); batch.draw(enemy.actualFrame, enemy.getX(), enemy.getY()); } batch.end(); this.shapeRenderer.begin(ShapeType.Filled); this.shapeRenderer.setColor(Color.BLACK); this.getTiles(0, 0, 25, 15, this.tiles); this.shapeRenderer.setColor(Color.RED); this.shapeRenderer.end(); } } private void renderHUD(float deltaTime) { AtlasRegion frame = null; AtlasRegion playerLife = null; AtlasRegion bossLife = null; AtlasRegion bossHead = null; frame = (AtlasRegion)Assets.hudBase.getKeyFrame(this.hud.stateTime); playerLife = (AtlasRegion)Assets.hudLifePlayer.getKeyFrame(this.hud.stateTime); bossLife = (AtlasRegion)Assets.hudLifeBoss.getKeyFrame(this.hud.stateTime); bossHead = (AtlasRegion)Assets.hudBossHead.getKeyFrame(this.hud.stateTime); Batch batch = this.renderer.getSpriteBatch(); batch.begin(); if (this.normalGravity) { batch.draw(frame, (this.camera.position.x - (this.SCREEN_WIDTH / 2)), (this.camera.position.y + (this.SCREEN_HEIGHT / 2)) - this.TILED_SIZE); for (int pl=0; pl < this.player.getLifes(); pl++) { batch.draw(playerLife, ((this.camera.position.x - (this.SCREEN_WIDTH / 2)) + Assets.offsetLifePlayer.x + (pl * (playerLife.getRegionWidth() + this.hud.OFFSET_LIFES_PLAYER))), (((this.camera.position.y + (this.SCREEN_HEIGHT / 2)) - this.TILED_SIZE - Assets.offsetLifePlayer.y) + playerLife.getRegionHeight())); } if (this.bossActive && (this.boss != null)) { batch.draw(bossHead, ((this.camera.position.x - (this.SCREEN_WIDTH / 2)) + Assets.offsetBoosHead), (this.camera.position.y + (this.SCREEN_HEIGHT / 2)) - this.TILED_SIZE); for (int bl=0; bl < this.boss.getLifes(); bl++) { batch.draw(bossLife, ((this.camera.position.x - (this.SCREEN_WIDTH / 2)) + Assets.offsetLifeBoss.x + (bl * (bossLife.getRegionWidth() + this.hud.OFFSET_LIFES_BOSS))), (((this.camera.position.y + (this.SCREEN_HEIGHT / 2)) - this.TILED_SIZE - Assets.offsetLifeBoss.y) + bossLife.getRegionHeight())); } } } else { batch.draw(frame, this.camera.position.x - (this.SCREEN_WIDTH / 2), this.camera.position.y - (this.SCREEN_HEIGHT / 2)); for (int pl=0; pl < this.player.getLifes(); pl++) { batch.draw(playerLife, ((this.camera.position.x - (this.SCREEN_WIDTH / 2)) + Assets.offsetLifePlayer.x + (pl * (playerLife.getRegionWidth() + this.hud.OFFSET_LIFES_PLAYER))), (((this.camera.position.y - (this.SCREEN_HEIGHT / 2)) + Assets.offsetLifePlayer.y))); } } batch.end(); this.shapeRenderer.begin(ShapeType.Filled); this.shapeRenderer.setColor(Color.BLACK); this.getTiles(0, 0, 25, 15, this.tiles); this.shapeRenderer.setColor(Color.RED); this.shapeRenderer.end(); } private void collisionLifes(float deltaTime) { Array<Vector2> obtainLifes = new Array<Vector2>(); for (Vector2 life : this.lifes) { if (this.normalGravity) { if ((life.dst(this.player.getX(), this.player.getCenterY()) < this.player.getWidth()) && (this.player.getLifes() < this.player.MAX_LIFES)) { this.player.counter.gainLife(1); obtainLifes.add(life); // Remove life in map TiledMapTileLayer layerPlantfs = (TiledMapTileLayer)(this.map.getLayers().get("Platfs")); layerPlantfs.setCell((int)life.x / this.TILED_SIZE, (int)life.y / this.TILED_SIZE, null); } } else { if ((life.dst(this.player.getX(), this.player.getY()) < this.player.getWidth()) && (this.player.getLifes() < this.player.MAX_LIFES)) { this.player.counter.gainLife(1); obtainLifes.add(life); // Remove life in map TiledMapTileLayer layerPlantfs = (TiledMapTileLayer)(this.map.getLayers().get("Platfs")); layerPlantfs.setCell((int)life.x / this.TILED_SIZE, (int)life.y / this.TILED_SIZE, null); } } } this.lifes.removeAll(obtainLifes, false); } private void updateEnemies(float deltaTime) { for (Enemy enemy : this.enemies) { this.isEnemyInScreen(enemy); this.isEnemyFinishedInvoking(enemy); // Collision between player vs enemy if (!enemy.dying){ if (this.player.getX() > enemy.getX()){ if (this.player.getRect().overlaps(enemy.getRect())) { this.player.beingHit(); } } else{ if (this.player.getRect().overlaps(enemy.getRect())) { this.player.beingHit(); } } } enemy.stateTime += deltaTime; // Check if player is invincible and check distance to player for attack him. if (!enemy.running && !enemy.dying && !enemy.beingInvoked){ // Attack if (!this.player.invincible && (Math.abs(((enemy.getCenterY() - this.player.getCenterY()))) <= this.player.getHeight())) { if (enemy.getX() < this.player.getX()) { if ((enemy.getX() + enemy.ATTACK_DISTANCE) >= (this.player.getRight())) { enemy.dir = Enemy.Direction.Right; enemy.run(); enemy.attackHereX = this.player.getX(); enemy.attackRight = true; } } else { if ((enemy.getX() - enemy.ATTACK_DISTANCE) <= this.player.getX()) { enemy.dir = Enemy.Direction.Left; enemy.run(); enemy.attackHereX = this.player.getX(); enemy.attackRight = false; } } } else if (enemy.dir == Enemy.Direction.Left) { if (-enemy.RANGE >= enemy.diffInitialPos) { enemy.dir = Enemy.Direction.Right; } enemy.walk(); } else if (enemy.dir == Enemy.Direction.Right) { if (enemy.diffInitialPos >= enemy.RANGE) { enemy.dir = Enemy.Direction.Left; } enemy.walk(); } } else if ((enemy.getX() > enemy.attackHereX) && enemy.attackRight) enemy.running = false; else if ((enemy.getX() < enemy.attackHereX) && !enemy.attackRight) enemy.running = false; enemy.velocity.scl(deltaTime); // Enviroment collision enemy.desiredPosition.y = Math.round(enemy.getY()); enemy.desiredPosition.x = Math.round(enemy.getX()); int startX, startY, endX, endY; if (enemy.velocity.x > 0) { startX = endX = (int)((enemy.desiredPosition.x + enemy.velocity.x + enemy.getWidth()) / this.TILED_SIZE); } else { startX = endX = (int)((enemy.desiredPosition.x + enemy.velocity.x) / this.TILED_SIZE); } startY = (int) enemy.getY() / this.TILED_SIZE; endY = (int) (enemy.getY() + enemy.getHeight()) / this.TILED_SIZE; this.getTiles(startX, startY, endX, endY, this.tiles); enemy.getRect(); enemy.rect.x += enemy.velocity.x; for (Rectangle tile : this.tiles) { if (enemy.rect.overlaps(tile)) { enemy.velocity.x = 0; enemy.running = false; break; } } enemy.rect.x = enemy.desiredPosition.x; enemy.desiredPosition.add(enemy.velocity); enemy.velocity.scl(1 / deltaTime); enemy.setPosition(enemy.desiredPosition.x, enemy.desiredPosition.y); if (Assets.playerDie.isAnimationFinished(enemy.stateTime) && enemy.dying){ enemy.setToDie = true; } } int i = 0; boolean[] toBeDeleted = new boolean[this.enemies.size]; for (Enemy enemy : this.enemies){ if (enemy != null){ if(enemy.setToDie == true) //&& animation finished toBeDeleted[i] = true; } i++; } for(int j = 0; j < toBeDeleted.length; j++){ if (toBeDeleted[j] && (this.enemies.size >= (j + 1))) this.enemies.removeIndex(j); } } private void isEnemyFinishedInvoking(Enemy enemy) { if (Assets.enemyAppearing.isAnimationFinished(enemy.stateTime) && enemy.state.equals(Enemy.State.BeingInvoked)){ enemy.beingInvoked = false; enemy.walk(); } } private void isEnemyInScreen(Enemy enemy) { if (enemy.inScreen) return; Rectangle cameraRect = new Rectangle(0, 0, this.SCREEN_WIDTH, this.SCREEN_HEIGHT); cameraRect.setCenter(this.camera.position.x, this.camera.position.y); if (enemy.rect.overlaps(cameraRect)) { if ((this.player.getX() - enemy.getX()) < 0) enemy.dir = Enemy.Direction.Left; else enemy.dir = Enemy.Direction.Right; enemy.inScreen = true; } } private void updatePlayer(float deltaTime) { if (deltaTime == 0) return; this.player.stateTime += deltaTime; this.player.desiredPosition.x = this.player.getX(); this.player.desiredPosition.y = this.player.getY(); this.movingShootingJumping(deltaTime); this.gravityAndClamping(); this.player.velocity.scl(deltaTime); //retreat if noControl //velocity y is changed in beingHit if (this.player.noControl){ if (this.player.facesRight) this.player.velocity.x = -120f * deltaTime; else this.player.velocity.x = 120 * deltaTime; } boolean collisionSpike = this.collisionWallsAndSpike(); // unscale the velocity by the inverse delta time and set the latest position this.player.desiredPosition.add(this.player.velocity); this.player.velocity.scl(1 / deltaTime); if (Assets.playerBeingHit.isAnimationFinished(this.player.stateTime) && !this.player.dead) this.player.noControl = false; if (this.player.noControl == false) this.player.velocity.x *= 0; //0 is totally stopped if not pressed this.player.setPosition(this.player.desiredPosition.x, this.player.desiredPosition.y); if (Assets.playerDie.isAnimationFinished(this.player.stateTime) && this.player.dead){ this.gameOver(); } if (collisionSpike) { this.player.beingHit(); } } private void gameOver() { LD.getInstance().GAMEOVER_SCREEN = new GameOverScreen(this.bossCheckPoint); LD.getInstance().setScreen(LD.getInstance().GAMEOVER_SCREEN); } private void activateBoss() { if (this.boss == null) return; if ((this.player.getX() >= (this.boss.getX() - this.boss.ACTIVATE_DISTANCE)) && !this.bossActive) { this.bossActive = true; this.bossCheckPoint = true; this.camera.position.x = (this.MAP_WIDTH * this.TILED_SIZE) - (this.SCREEN_WIDTH / 2); this.camera.update(); this.xRightBossWall = (((this.door.x * this.TILED_SIZE) + this.SCREEN_WIDTH) - (this.TILED_SIZE * 4) - 16); this.xLeftBossWall = ((this.door.x * this.TILED_SIZE) + (this.TILED_SIZE * 2)) + 8; Assets.musicStage.stop(); Assets.musicBoss.setLooping(true); Assets.musicBoss.play(); //close door TiledMapTileLayer layerSpawn = null; Cell cell = null; //door = new Vector2(789 - 25, 61); layerSpawn = (TiledMapTileLayer)(this.map.getLayers().get("Platfs")); cell = layerSpawn.getCell((int)this.door.x, (int)this.door.y); //has to be solid block layerSpawn.setCell((int)this.door.x, (int)this.door.y + 1, cell); layerSpawn.setCell((int)this.door.x, (int)this.door.y + 2, cell); layerSpawn.setCell((int)this.door.x + 1, (int)this.door.y + 1, cell); layerSpawn.setCell((int)this.door.x + 1, (int)this.door.y + 2, cell); layerSpawn = (TiledMapTileLayer)(this.map.getLayers().get("Collisions")); cell = layerSpawn.getCell((int)this.door.x, (int)this.door.y); layerSpawn.setCell((int)this.door.x, (int)this.door.y + 1, cell); layerSpawn.setCell((int)this.door.x, (int)this.door.y + 2, cell); layerSpawn.setCell((int)this.door.x + 1, (int)this.door.y + 1, cell); layerSpawn.setCell((int)this.door.x + 1, (int)this.door.y + 2, cell); } } private void gravityAndClamping() { if (this.normalGravity) this.player.velocity.add(0, this.GRAVITY); else this.player.velocity.add(0, -this.GRAVITY); if (this.player.getY() < this.POS_LOWER_WORLD){ //this.camera.position.y = this.POS_LOWER_WORLD; if (this.normalGravity == true){ this.normalGravity = false; this.player.velocity.y = -this.player.JUMP_VELOCITY * 1.01f; //3 tiles in both } } else { //this.camera.position.y = 0;//this.yPosUpperWorld; if (this.normalGravity == false){ this.normalGravity = true; this.player.velocity.y = this.player.JUMP_VELOCITY / 1.3f; //3 tiles in both } } // clamp the velocity to the maximum, x-axis only if (Math.abs(this.player.velocity.x) > this.player.MAX_VELOCITY) { this.player.velocity.x = Math.signum(this.player.velocity.x) * this.player.MAX_VELOCITY; } // clamp the velocity to 0 if it's < 1, and set the state to standign if (Math.abs(this.player.velocity.x) < 1) { this.player.velocity.x = 0; if (this.player.grounded && Assets.playerAttack.isAnimationFinished(this.player.stateTime) && Assets.playerBeingHit.isAnimationFinished(this.player.stateTime) && !this.player.invincible) this.player.state = Player.State.Standing; } } private void movingShootingJumping(float deltaTime) { if (this.player.noControl == false){ if ((Gdx.input.isKeyJustPressed(Keys.S) || this.configControllers.jumpPressed) && this.player.grounded){ Assets.playSound("playerJump"); if (this.normalGravity) this.player.velocity.y = this.player.JUMP_VELOCITY; else this.player.velocity.y = -this.player.JUMP_VELOCITY; this.player.grounded = false; this.player.state = Player.State.Jumping; //this.player.stateTime = 0; } if (Gdx.input.isKeyPressed(Keys.LEFT) || this.configControllers.leftPressed){ this.player.velocity.x = -this.player.MAX_VELOCITY; if (this.player.grounded && Assets.playerAttack.isAnimationFinished(this.player.stateTime) && Assets.playerBeingHit.isAnimationFinished(this.player.stateTime)){ this.player.state = Player.State.Walking; //this.player.stateTime = 0; } this.player.facesRight = false; } if (Gdx.input.isKeyPressed(Keys.RIGHT) || this.configControllers.rightPressed){ this.player.velocity.x = this.player.MAX_VELOCITY; if (this.player.grounded && Assets.playerAttack.isAnimationFinished(this.player.stateTime) && Assets.playerBeingHit.isAnimationFinished(this.player.stateTime)){ this.player.state = Player.State.Walking; //this.player.stateTime = 0; } this.player.facesRight = true; } if ((Gdx.input.isKeyJustPressed(Keys.D) || this.configControllers.shootPressed) && (this.shotArray.size < 3)){ Assets.playSound("playerAttack"); Shot shot = new Shot(Assets.playerShot); if (this.player.facesRight){ //-1 necessary to be exactly the same as the other facing shot.Initialize((this.player.getCenterX()), ((this.player.getY() + (this.player.getHeight() / 2)) - 10), this.player.facesRight, this.normalGravity); } else { shot.Initialize((this.player.getCenterX()), ((this.player.getY() + (this.player.getHeight() / 2)) - 10), this.player.facesRight, this.normalGravity); } this.shotArray.add(shot); this.player.state = Player.State.Attacking; this.player.stateTime = 0; this.player.shooting = true; } } if (Assets.playerAttack.isAnimationFinished(this.player.stateTime)) this.player.shooting = false; int i = 0; boolean[] toBeDeleted = new boolean[3]; for (Shot shot : this.shotArray){ if (shot != null){ if(this.updateShot(shot, deltaTime) == true) toBeDeleted[i] = true; //pool of shots? } i++; } for(int j = 0; j < toBeDeleted.length; j++){ if (toBeDeleted[j] && (this.shotArray.size >= (j + 1))) this.shotArray.removeIndex(j); } } private boolean collisionForBoss(Boss boss) { //collision detection // perform collision detection & response, on each axis, separately // if the raya is moving right, check the tiles to the right of it's // right bounding box edge, otherwise check the ones to the left this.playerRect = this.rectPool.obtain(); boss.desiredPosition.y = Math.round(boss.getY()); boss.desiredPosition.x = Math.round(boss.getX()); this.playerRect = this.boss.getRect(); int startX, startY, endX, endY; if (this.player.velocity.x > 0) { startX = endX = (int)((boss.desiredPosition.x + boss.velocity.x + this.boss.actualFrame.getRegionWidth()) / this.TILED_SIZE); } else { startX = endX = (int)((boss.desiredPosition.x + boss.velocity.x) / this.TILED_SIZE); } if (boss.grounded && this.normalGravity){ startY = (int)((boss.desiredPosition.y) / this.TILED_SIZE); endY = (int)((boss.desiredPosition.y + this.boss.actualFrame.getRegionHeight()) / this.TILED_SIZE); } else if (boss.grounded && !this.normalGravity){ startY = (int)((boss.desiredPosition.y) / this.TILED_SIZE); endY = (int)((boss.desiredPosition.y + this.boss.actualFrame.getRegionHeight()) / this.TILED_SIZE); } else{ startY = (int)((boss.desiredPosition.y) / this.TILED_SIZE); endY = (int)((boss.desiredPosition.y + this.boss.actualFrame.getRegionHeight()) / this.TILED_SIZE); } this.getTiles(startX, startY, endX, endY, this.tiles); this.playerRect.x += boss.velocity.x; for (Rectangle tile : this.tiles) { if (this.playerRect.overlaps(tile)) { this.player.velocity.x = 0; break; } } this.playerRect.x = boss.desiredPosition.x; // if the koala is moving upwards, check the tiles to the top of it's // top bounding box edge, otherwise check the ones to the bottom if (this.normalGravity){ if (boss.velocity.y > 0) { startY = endY = (int)((boss.desiredPosition.y + boss.velocity.y + this.boss.actualFrame.getRegionHeight()) / this.TILED_SIZE); } else { startY = endY = (int)((boss.desiredPosition.y + boss.velocity.y) / this.TILED_SIZE); } } else{ if (this.player.velocity.y < 0) { startY = endY = (int)((boss.desiredPosition.y + boss.velocity.y) / this.TILED_SIZE); } else { startY = endY = (int)((boss.desiredPosition.y + boss.velocity.y + this.boss.actualFrame.getRegionHeight() ) / this.TILED_SIZE); } } startX = (int)(boss.desiredPosition.x / this.TILED_SIZE); //16 tile size endX = (int)((boss.desiredPosition.x + this.boss.actualFrame.getRegionWidth()) / this.TILED_SIZE); // System.out.println(startX + " " + startY + " " + endX + " " + endY); this.getTiles(startX, startY, endX, endY, this.tiles); this.playerRect.y += (int)(boss.velocity.y); boolean grounded = boss.grounded; for (Rectangle tile : this.tiles) { // System.out.println(playerRect.x + " " + playerRect.y + " " + tile.x + " " + tile.y); if (this.playerRect.overlaps(tile)) { // we actually reset the koala y-position here // so it is just below/above the tile we collided with // this removes bouncing :) if (this.normalGravity){ if (boss.velocity.y > 0) { boss.desiredPosition.y = tile.y - this.boss.actualFrame.getRegionHeight() - 1; // we hit a block jumping upwards, let's destroy it! } else { boss.desiredPosition.y = (tile.y + tile.height) - 1; //in this way he is in the ground // if we hit the ground, mark us as grounded so we can jump grounded = true; } } else{ if (boss.velocity.y > 0) { //this.player.desiredPosition.y = tile.y - tile.height- 1; // if we hit the ground, mark us as grounded so we can jump grounded = true; } else { boss.desiredPosition.y = (tile.y + tile.height) - 1; // we hit a block jumping upwards, let's destroy it! } } boss.velocity.y = 0; break; } } if (this.tiles.size == 0) grounded = false; //goes together with get this.rectPool.free(this.playerRect); return grounded; } private boolean collisionWallsAndSpike() { //collision detection // perform collision detection & response, on each axis, separately // if the raya is moving right, check the tiles to the right of it's // right bounding box edge, otherwise check the ones to the left this.playerRect = this.rectPool.obtain(); this.player.desiredPosition.y = Math.round(this.player.getY()); this.player.desiredPosition.x = Math.round(this.player.getX()); this.playerRect.set(this.player.getRect()); int startX, startY, endX, endY; if (this.player.velocity.x > 0) { startX = endX = (int)((this.player.desiredPosition.x + this.player.velocity.x + this.player.actualFrame.getRegionWidth()) / this.TILED_SIZE); } else { startX = endX = (int)(((this.player.desiredPosition.x + this.player.velocity.x) - 1) / this.TILED_SIZE); } if (this.player.grounded && this.normalGravity){ startY = (int)((this.player.desiredPosition.y) / this.TILED_SIZE) + 1; endY = (int)((this.player.desiredPosition.y + this.player.actualFrame.getRegionHeight()) / this.TILED_SIZE) + 1; } else if (this.player.grounded && !this.normalGravity){ startY = (int)((this.player.desiredPosition.y) / this.TILED_SIZE) - 1; endY = (int)((this.player.desiredPosition.y + this.player.actualFrame.getRegionHeight()) / this.TILED_SIZE) - 1; } else{ startY = (int)((this.player.desiredPosition.y) / this.TILED_SIZE); endY = (int)((this.player.desiredPosition.y + this.player.actualFrame.getRegionHeight()) / this.TILED_SIZE); } this.getTiles(startX, startY, endX, endY, this.tiles, this.spikes); this.playerRect.x += this.player.velocity.x; for (Rectangle tile : this.tiles) { if (this.playerRect.overlaps(tile)) { this.player.velocity.x = 0; break; } } for (Rectangle spike : this.spikes) { if (this.playerRect.overlaps(spike)) { this.player.velocity.x = 0; break; } } this.playerRect.x = this.player.desiredPosition.x; // if the koala is moving upwards, check the tiles to the top of it's // top bounding box edge, otherwise check the ones to the bottom if (this.normalGravity){ if (this.player.velocity.y > 0) { startY = endY = (int)((this.player.desiredPosition.y + this.player.velocity.y + this.player.actualFrame.getRegionHeight()) / this.TILED_SIZE); } else { startY = endY = (int)((this.player.desiredPosition.y + this.player.velocity.y) / this.TILED_SIZE); } } else{ if (this.player.velocity.y < 0) { startY = endY = (int)((this.player.desiredPosition.y + this.player.velocity.y) / this.TILED_SIZE); } else { startY = endY = (int)((this.player.desiredPosition.y + this.player.velocity.y + this.player.actualFrame.getRegionHeight() ) / this.TILED_SIZE); } } if (!this.player.facesRight) startX = (int)((this.player.desiredPosition.x + 2)/ this.TILED_SIZE); //16 tile size else startX = (int)((this.player.desiredPosition.x)/ this.TILED_SIZE); //16 tile size endX = (int)((this.player.desiredPosition.x + this.player.actualFrame.getRegionWidth()) / this.TILED_SIZE); // System.out.println(startX + " " + startY + " " + endX + " " + endY); this.getTiles(startX, startY, endX, endY, this.tiles, this.spikes); this.playerRect.y += (int)(this.player.velocity.y); boolean collisionSpike = false; for (Rectangle spike : this.spikes) { if (this.playerRect.overlaps(spike)) { if (this.normalGravity){ if (this.player.velocity.y > 0) // we hit a block jumping upwards this.player.desiredPosition.y = spike.y - this.player.actualFrame.getRegionHeight(); else { // if we hit the ground, mark us as grounded so we can jump this.player.desiredPosition.y = (spike.y + spike.height); this.player.grounded = true; } } else{ //upside down if (this.player.velocity.y > 0) { this.player.desiredPosition.y = (spike.y - this.player.actualFrame.getRegionHeight()); this.player.grounded = true; } else this.player.desiredPosition.y = (spike.y + spike.height); } collisionSpike = true; break; } } for (Rectangle tile : this.tiles) { if (this.playerRect.overlaps(tile)) { if (this.normalGravity){ if (this.player.velocity.y > 0) // we hit a block jumping upwards this.player.desiredPosition.y = tile.y - this.player.actualFrame.getRegionHeight() ; else { // if we hit the ground, mark us as grounded so we can jump this.player.desiredPosition.y = (tile.y + tile.height) - 1; this.player.grounded = true; } } else{ //upside down if (this.player.velocity.y > 0) { this.player.desiredPosition.y = (tile.y - this.player.actualFrame.getRegionHeight()) + 3; this.player.grounded = true; } else this.player.desiredPosition.y = (tile.y + tile.height); } this.player.velocity.y = 0; break; } } if (this.tiles.size == 0) this.player.grounded = false; //goes together with get this.rectPool.free(this.playerRect); return collisionSpike; } private void getTiles(int startX, int startY, int endX, int endY, Array<Rectangle> tiles) { this.getTiles(startX, startY, endX, endY, tiles, null); } private void getTiles(int startX, int startY, int endX, int endY, Array<Rectangle> tiles, Array<Rectangle> spikes) { TiledMapTileLayer layer = (TiledMapTileLayer)(this.map.getLayers().get("Collisions")); TiledMapTileLayer layer2 = (TiledMapTileLayer)(this.map.getLayers().get("Spikes")); this.rectPool.freeAll(tiles); tiles.clear(); if (spikes != null) { this.rectPool.freeAll(spikes); spikes.clear(); } for (int y = startY; y <= endY; y++) { for (int x = startX; x <= endX; x++) { Cell cell = layer.getCell(x, y); if (cell != null) { Rectangle rect = this.rectPool.obtain(); rect.set(x * this.TILED_SIZE, y * this.TILED_SIZE, this.TILED_SIZE, this.TILED_SIZE); tiles.add(rect); } if (spikes != null) { Cell cell2 = layer2.getCell(x, y); if (cell2 != null) { Rectangle rect = this.rectPool.obtain(); rect.set(x * this.TILED_SIZE, y * this.TILED_SIZE, this.TILED_SIZE, this.TILED_SIZE); spikes.add(rect); tiles.add(rect); } } } } } @Override public void backButtonPressed() { LD.getInstance().MENU_SCREEN = new MenuScreen(); LD.getInstance().setScreen(LD.getInstance().MENU_SCREEN); } @Override public void enterButtonPressed() { if (!this.pause) { this.pause(); } else { this.resume(); } } @Override public void pause() { this.pause = true; } @Override public void resume() { this.pause = false; } }
package com.openxc.enabler; import com.openxc.VehicleManager; import com.openxc.enabler.preferences.PreferenceManagerService; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class BootupReceiver extends BroadcastReceiver { private final static String TAG = BootupReceiver.class.getSimpleName(); // TODO what about when the device is already started? need an app to hit? // or do we rely on it being started by the bind call? might get duplicate @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "Loading configured vehicle services on bootup"); context.startService(new Intent(context, PreferenceManagerService.class)); } }
package com.mygdx.game.managers; import java.util.Stack; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.mygdx.game.Game; import com.mygdx.game.states.GameState; public class GameStateManager { // Application Reference private final Game game; private Stack<GameState> states; private enum State{ SPLASH, MAINMENU } public GameStateManager(Game game){ this.game = game; this.states = new Stack<GameState>(); this.setState(State.SPLASH); } public Game game(){ return game; } public void update(float delta){ states.peek().update(delta); } public void render(){ states.peek().render(); } public void dispose(){ for(GameState gs : states){ gs.dispose(); } } public void resize(int w , int h){ states.peek().resize(w,h); } public void setState(State state){ states.pop().dispose(); states.push(getState(state)); } private GameState getState(State state){ return null; } }
package com.zero.star.tabnyan; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class TabNyanRootFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_tabnyan_root, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initFragment(); } /** * Pop fragment backstack. * @return return true if exists backstack */ public boolean popBackStack() { return getChildFragmentManager().popBackStackImmediate(); } /** * Initialize Fragment. */ private void initFragment() { Bundle args = getArguments(); String rootClass = args.getString(TabNyanActivity.ROOT_FRAGMENT_ARGS); FragmentManager fragmentManager = getChildFragmentManager(); if (fragmentManager.findFragmentById(R.id.fragment) != null) { return; } FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); Fragment fragment = Fragment.instantiate(getActivity(), rootClass, args); fragmentTransaction.replace(R.id.fragment, fragment); fragmentTransaction.commit(); } /** * Return Fragment in displayed * @return Fragment */ Fragment getCurrentFragment() { FragmentManager fragmentManager = getChildFragmentManager(); return fragmentManager.findFragmentById(R.id.fragment); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Call child fragment method getCurrentFragment().onActivityResult(requestCode, resultCode, data); } }
package com.bigkoo.pickerviewdemo; import android.graphics.Color; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.bigkoo.pickerview.OptionsPickerView; import com.bigkoo.pickerview.TimePickerView; import com.bigkoo.pickerview.lib.WheelView; import com.bigkoo.pickerview.listener.CustomListener; import com.bigkoo.pickerview.model.IPickerViewData; import com.bigkoo.pickerviewdemo.bean.CardBean; import com.bigkoo.pickerviewdemo.bean.PickerViewData; import com.bigkoo.pickerviewdemo.bean.ProvinceBean; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private ArrayList<ProvinceBean> options1Items = new ArrayList<>(); private ArrayList<ArrayList<String>> options2Items = new ArrayList<>(); private ArrayList<ArrayList<ArrayList<IPickerViewData>>> options3Items = new ArrayList<>(); private Button btn_Time, btn_Options,btn_CustomOptions,btn_CustomTime; private TimePickerView pvTime,pvCustomTime; private OptionsPickerView pvOptions,pvCustomOptions; private ArrayList<CardBean> cardItem = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //APP initTimePicker(); initCustomTimePicker(); initOptionData(); initOptionPicker(); initCustomOptionPicker(); btn_Time = (Button) findViewById(R.id.btn_Time); btn_Options = (Button) findViewById(R.id.btn_Options); btn_CustomOptions = (Button) findViewById(R.id.btn_CustomOptions); btn_CustomTime = (Button) findViewById(R.id.btn_CustomTime); btn_Time.setOnClickListener(this); btn_Options.setOnClickListener(this); btn_CustomOptions.setOnClickListener(this); btn_CustomTime.setOnClickListener(this); } @Override public void onClick(View v) { if (v.getId() == R.id.btn_Time && pvTime != null) { pvTime.setDate(Calendar.getInstance()); pvTime.show(); } else if (v.getId() == R.id.btn_Options && pvOptions != null) { pvOptions.show(); } else if (v.getId() == R.id.btn_CustomOptions && pvCustomOptions != null) { pvCustomOptions.show(); }else if (v.getId() == R.id.btn_CustomTime && pvCustomTime != null) { pvCustomTime.show(); } } private void initTimePicker() { //(1900-2100) Calendar selectedDate = Calendar.getInstance(); selectedDate.set(2013,2,29); Calendar startDate = Calendar.getInstance(); startDate.set(2013,1,23); Calendar endDate = Calendar.getInstance(); endDate.set(2019,2,28); pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() { @Override public void onTimeSelect(Date date, View v) { btn_Time.setText(getTime(date)); } }) /*.setType(TimePickerView.Type.ALL)//default is all .setCancelText("Cancel") .setSubmitText("Sure") .setContentSize(18) .setTitleSize(20) .setTitleText("Title") .setOutSideCancelable(false)// default is true .isCyclic(true)// default is false .setTitleColor(Color.BLACK) .setDate(new Date())// default system*/ /*.setDividerColor(Color.WHITE)// .setTextColorCenter(Color.LTGRAY)// .setLineSpacingMultiplier(1.6f)// .setTitleBgColor(Color.DKGRAY)// Night mode .setBgColor(Color.BLACK)// Night mode .setSubmitColor(Color.WHITE) .setCancelColor(Color.WHITE)*/ /* .gravity(Gravity.RIGHT)// default is center*/ .setDividerColor(Color.BLACK) .setContentSize(20) .setLabel("", "", "", "", "", "") // hide label .setDate(selectedDate) .setRangDate(startDate,endDate) .build(); } private void initCustomTimePicker() { // id optionspicker timepicker // demo //(1900-2100) Calendar selectedDate = Calendar.getInstance(); Calendar startDate = Calendar.getInstance(); startDate.set(2013,1,23); Calendar endDate = Calendar.getInstance(); endDate.set(2019,2,28); pvCustomTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() { @Override public void onTimeSelect(Date date, View v) { btn_CustomTime.setText(getTime(date)); } }) .setType(TimePickerView.Type.YEAR_MONTH_DAY) .setDate(selectedDate) .setRangDate(startDate,endDate) .setLayoutRes(R.layout.pickerview_custom_time, new CustomListener() { @Override public void customLayout(View v) { final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish); ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel); tvSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pvCustomTime.returnData(tvSubmit); } }); ivCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pvCustomTime.dismiss(); } }); } }) .setDividerColor(Color.BLACK) .build(); } private String getTime(Date date) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return format.format(date); } private void initOptionData() { getData(); options1Items.add(new ProvinceBean(0,"","","")); options1Items.add(new ProvinceBean(1,"","","")); options1Items.add(new ProvinceBean(2,"","","")); ArrayList<String> options2Items_01 = new ArrayList<>(); options2Items_01.add(""); options2Items_01.add(""); options2Items_01.add(""); options2Items_01.add(""); options2Items_01.add(""); ArrayList<String> options2Items_02 = new ArrayList<>(); options2Items_02.add(""); options2Items_02.add(""); options2Items_02.add(""); options2Items_02.add(""); ArrayList<String> options2Items_03 = new ArrayList<>(); options2Items_03.add(""); options2Items_03.add(""); options2Items.add(options2Items_01); options2Items.add(options2Items_02); options2Items.add(options2Items_03); ArrayList<ArrayList<IPickerViewData>> options3Items_01 = new ArrayList<>(); ArrayList<ArrayList<IPickerViewData>> options3Items_02 = new ArrayList<>(); ArrayList<ArrayList<IPickerViewData>> options3Items_03 = new ArrayList<>(); ArrayList<IPickerViewData> options3Items_01_01 = new ArrayList<>(); options3Items_01_01.add(new PickerViewData("")); options3Items_01_01.add(new PickerViewData("")); options3Items_01_01.add(new PickerViewData("")); options3Items_01_01.add(new PickerViewData("")); options3Items_01_01.add(new PickerViewData("")); options3Items_01_01.add(new PickerViewData("")); options3Items_01_01.add(new PickerViewData("")); options3Items_01.add(options3Items_01_01); ArrayList<IPickerViewData> options3Items_01_02 = new ArrayList<>(); options3Items_01_02.add(new PickerViewData("")); options3Items_01_02.add(new PickerViewData("")); options3Items_01_02.add(new PickerViewData("")); options3Items_01_02.add(new PickerViewData("")); options3Items_01.add(options3Items_01_02); ArrayList<IPickerViewData> options3Items_01_03 = new ArrayList<>(); options3Items_01_03.add(new PickerViewData("")); options3Items_01_03.add(new PickerViewData("")); options3Items_01_03.add(new PickerViewData("")); options3Items_01.add(options3Items_01_03); ArrayList<IPickerViewData> options3Items_01_04 = new ArrayList<>(); options3Items_01_04.add(new PickerViewData("")); options3Items_01_04.add(new PickerViewData("")); options3Items_01_04.add(new PickerViewData("")); options3Items_01.add(options3Items_01_04); ArrayList<IPickerViewData> options3Items_01_05 = new ArrayList<>(); options3Items_01_05.add(new PickerViewData("1")); options3Items_01_05.add(new PickerViewData("2")); options3Items_01.add(options3Items_01_05); ArrayList<IPickerViewData> options3Items_02_01 = new ArrayList<>(); options3Items_02_01.add(new PickerViewData("1")); options3Items_02_01.add(new PickerViewData("2")); options3Items_02_01.add(new PickerViewData("3")); options3Items_02.add(options3Items_02_01); ArrayList<IPickerViewData> options3Items_02_02 = new ArrayList<>(); options3Items_02_02.add(new PickerViewData("1")); options3Items_02_02.add(new PickerViewData("2")); options3Items_02_02.add(new PickerViewData("3")); options3Items_02.add(options3Items_02_02); ArrayList<IPickerViewData> options3Items_02_03 = new ArrayList<>(); options3Items_02_03.add(new PickerViewData("1")); options3Items_02_03.add(new PickerViewData("2")); options3Items_02_03.add(new PickerViewData("3")); options3Items_02.add(options3Items_02_03); ArrayList<IPickerViewData> options3Items_02_04 = new ArrayList<>(); options3Items_02_04.add(new PickerViewData("1")); options3Items_02_04.add(new PickerViewData("2")); options3Items_02_04.add(new PickerViewData("3")); options3Items_02.add(options3Items_02_04); ArrayList<IPickerViewData> options3Items_03_01 = new ArrayList<>(); options3Items_03_01.add(new PickerViewData("")); options3Items_03.add(options3Items_03_01); ArrayList<IPickerViewData> options3Items_03_02 = new ArrayList<>(); options3Items_03_02.add(new PickerViewData("")); options3Items_03.add(options3Items_03_02); options3Items.add(options3Items_01); options3Items.add(options3Items_02); options3Items.add(options3Items_03); } private void initOptionPicker() { pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() { @Override public void onOptionsSelect(int options1, int options2, int options3, View v) { String tx = options1Items.get(options1).getPickerViewText()+ options2Items.get(options1).get(options2)+ options3Items.get(options1).get(options2).get(options3).getPickerViewText(); btn_Options.setText(tx); } }) .setOutSideCancelable(false)//*/ pvOptions.setPicker(options1Items, options2Items);//*/
public class RomanNumbers { private static int oneSymbolValues[] = new int[] { 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000 }; private static String getRomanValue(int number) { switch (number) { case 1: return "I"; case 4: return "IV"; case 5: return "V"; case 9: return "IX"; case 10: return "X"; case 40: return "XL"; case 50: return "L"; case 90: return "XC"; case 100: return "C"; case 400: return "CD"; case 500: return "D"; case 900: return "CM"; case 1000: return "M"; default: return ""; } } public static String intToRoman(int number) throws RomanNumbersException { if(number<=0 || number>=4000) throw new RomanNumbersException("out of range"); String str = ""; if (getRomanValue(number).equals("")) { for (int i = oneSymbolValues.length - 1; i >= 0; i while (number >= oneSymbolValues[i] && number != 0) { str += getRomanValue(oneSymbolValues[i]); number -= oneSymbolValues[i]; } if (!getRomanValue(number).equals("")) return str + getRomanValue(number); } return str; } else return getRomanValue(number); } private static int getIntValue(String roman) { switch (roman) { case "I": return 1; case "IV": return 4; case "V": return 5; case "IX": return 9; case "X": return 10; case "XL": return 40; case "L": return 50; case "XC": return 90; case "C": return 100; case "CD": return 400; case "D": return 500; case "CM": return 900; case "M": return 1000; default: return 0; } } public static int romanToInt(String roman) { int returnValue = 0; for( int i =0 ; i <roman.length() ; i++){ int twoSymboledNumber =0; if(i+2<=roman.length()){ twoSymboledNumber = getIntValue(roman.substring(i,i+2)); } if(twoSymboledNumber==0) returnValue += getIntValue(roman.substring(i,i+1)); else{ returnValue+=twoSymboledNumber; i++; } } return returnValue; } }
package org.nusco.narjillos; import java.util.Random; import org.nusco.narjillos.creature.genetics.Creature; import org.nusco.narjillos.creature.genetics.DNA; import org.nusco.narjillos.pond.Cosmos; import org.nusco.narjillos.pond.Pond; import org.nusco.narjillos.shared.physics.Vector; import org.nusco.narjillos.shared.utilities.Chronometer; import org.nusco.narjillos.shared.utilities.NumberFormat; import org.nusco.narjillos.shared.utilities.RanGen; public class Experiment { private static final int CYCLES = 100_000_000; private static final int PARSE_INTERVAL = 10000; private static final Chronometer ticksChronometer = new Chronometer(); private static long startTime = System.currentTimeMillis(); public static void main(String... args) { String gitCommit = (args.length > 0) ? args[0] : "UNKNOWN_COMMIT"; int seed = getSeed(args); System.out.println("Experiment ID: " + gitCommit + ":" + seed); RanGen.seed(seed); runExperiment(); } private static int getSeed(String... args) { if (args.length < 2) return Math.abs(new Random().nextInt()); return Integer.parseInt(args[1]); } private static long getTimeElapsed() { long currentTime = System.currentTimeMillis(); long timeInSeconds = (currentTime - startTime) / 1000; return timeInSeconds; } private static void runExperiment() { System.out.println(getHeadersString()); Pond pond = new Cosmos(); for (long tick = 0; tick < CYCLES; tick++) { pond.tick(); checkForMassExtinction(pond, tick); ticksChronometer.tick(); if (tick > 0 && (tick % PARSE_INTERVAL == 0)) System.out.println(getStatusString(pond, tick)); } System.out.println("*** The experiment is over at tick " + formatTick(CYCLES) + " (" + getTimeElapsed() + "s) ***"); } private static void checkForMassExtinction(Pond pond, long tick) { if (pond.getNumberOfNarjillos() > 0) return; System.out.println("*** Extinction happens. (tick " + tick + ") ***"); System.exit(0); } private static String getHeadersString() { return "\ntime_elapsed, " + "ticks_elapsed, " + "ticks_per_second, " + "number_of_narjillos, " + "number_of_food_pieces, " + "most_typical_specimen"; } private static String getStatusString(Pond pond, long tick) { Creature mostTypicalSpecimen = pond.getPopulation().getMostTypicalSpecimen(); if (mostTypicalSpecimen == null) mostTypicalSpecimen = getNullCreature(); return getStatusString(pond, tick, mostTypicalSpecimen); } private static String getStatusString(Pond pond, long tick, Creature mostTypicalSpecimen) { return getTimeElapsed() + ", " + tick + ", " + ticksChronometer.getTicksInLastSecond() + ", " + pond.getNumberOfNarjillos() + ", " + pond.getNumberOfFoodPieces() + ", " + mostTypicalSpecimen.getDNA(); } private static String formatTick(long tick) { return NumberFormat.format(tick); } private static Creature getNullCreature() { return new Creature() { @Override public void tick() { } @Override public DNA getDNA() { return new DNA("{0_0_0_0}"); } @Override public Vector getPosition() { return Vector.ZERO; } @Override public String getLabel() { return "nobody"; }}; } }
package com.dgmltn.morphclock.app; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.annotation.TargetApi; import android.app.Activity; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import com.dgmltn.morphclock.app.util.SystemUiHider; /** * An example full-screen activity that shows and hides the system UI (i.e. * status bar and navigation/system bar) with user interaction. * * @see SystemUiHider */ public class MainActivity extends Activity { /** * Whether or not the system UI should be auto-hidden after * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds. */ private static final boolean AUTO_HIDE = true; /** * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after * user interaction before hiding the system UI. */ private static final int AUTO_HIDE_DELAY_MILLIS = 3000; /** * If set, will toggle the system UI visibility upon interaction. Otherwise, * will show the system UI visibility upon interaction. */ private static final boolean TOGGLE_ON_CLICK = true; /** * The flags to pass to {@link SystemUiHider#getInstance}. */ private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION; /** * The instance of the {@link SystemUiHider} for this activity. */ private SystemUiHider mSystemUiHider; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final View content = LayoutInflater.from(this).inflate(R.layout.main_activity, null); setContentView(content); final View contentView = findViewById(R.id.fullscreen_content); // Set up an instance of SystemUiHider to control the system UI for // this activity. mSystemUiHider = SystemUiHider.getInstance(this, contentView, HIDER_FLAGS); mSystemUiHider.setup(); mSystemUiHider.setOnVisibilityChangeListener( new SystemUiHider.OnVisibilityChangeListener() { @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public void onVisibilityChange(boolean visible) { if (visible && AUTO_HIDE) { // Schedule a hide(). delayedHide(AUTO_HIDE_DELAY_MILLIS); } if (visible) { getActionBar().show(); } else { getActionBar().hide(); } } }); // Set up the user interaction to manually show or hide the system UI. contentView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (isInfoViewShowing()) { hideInfoView(); } else if (TOGGLE_ON_CLICK) { mSystemUiHider.toggle(); } else { mSystemUiHider.show(); } } }); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Trigger the initial hide() shortly after the activity has been // created, to briefly hint to the user that UI controls // are available. if (!isInfoViewShowing()) { delayedHide(100); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu items for use in the action bar MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { // Handle presses on the action bar items switch (item.getItemId()) { case R.id.action_info: if (isInfoViewShowing()) { hideInfoView(); } else { showInfoView(); } return true; default: return super.onOptionsItemSelected(item); } } @Override public void onBackPressed() { if (isInfoViewShowing()) { hideInfoView(); return; } super.onBackPressed(); } private void showInfoView() { View view = Ui.findView(this, R.id.app_info_view); view.setVisibility(View.VISIBLE); ObjectAnimator showInfo = ObjectAnimator.ofFloat(view, "alpha", 0f, 1f); ObjectAnimator scrollUp = ObjectAnimator.ofFloat(view, "translationY", 500, 0); View clock = Ui.findView(this, R.id.clock_container); ObjectAnimator hideClock = ObjectAnimator.ofFloat(clock, "alpha", 0f); AnimatorSet set = new AnimatorSet(); set.playTogether(showInfo, scrollUp, hideClock); set.start(); mHideHandler.removeCallbacks(mHideRunnable); } private boolean isInfoViewShowing() { View view = Ui.findView(this, R.id.app_info_view); return view.getVisibility() == View.VISIBLE; } private void hideInfoView() { final View view = Ui.findView(this, R.id.app_info_view); ObjectAnimator hideInfo = ObjectAnimator.ofFloat(view, "alpha", 0f); ObjectAnimator scrollDown = ObjectAnimator.ofFloat(view, "translationY", 0, 500); View clock = Ui.findView(this, R.id.clock_container); ObjectAnimator showClock = ObjectAnimator.ofFloat(clock, "alpha", 1f); AnimatorSet set = new AnimatorSet(); set.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { view.setVisibility(View.GONE); } }); set.playTogether(hideInfo, scrollDown, showClock); set.start(); delayedHide(AUTO_HIDE_DELAY_MILLIS); } Handler mHideHandler = new Handler(); Runnable mHideRunnable = new Runnable() { @Override public void run() { mSystemUiHider.hide(); } }; /** * Schedules a call to hide() in [delay] milliseconds, canceling any * previously scheduled calls. */ private void delayedHide(int delayMillis) { mHideHandler.removeCallbacks(mHideRunnable); mHideHandler.postDelayed(mHideRunnable, delayMillis); } }
package com.team980.thunderscout; import android.content.Context; import android.content.Intent; import android.net.Uri; import com.danielstone.materialaboutlibrary.MaterialAboutActivity; import com.danielstone.materialaboutlibrary.items.MaterialAboutActionItem; import com.danielstone.materialaboutlibrary.items.MaterialAboutTitleItem; import com.danielstone.materialaboutlibrary.model.MaterialAboutCard; import com.danielstone.materialaboutlibrary.model.MaterialAboutList; public class AboutActivity extends MaterialAboutActivity { @Override protected MaterialAboutList getMaterialAboutList(Context context) { MaterialAboutCard.Builder titleCard = new MaterialAboutCard.Builder(); titleCard.addItem(new MaterialAboutTitleItem.Builder() .text("ThunderScout") .icon(R.mipmap.ic_launcher) .build()); titleCard.addItem(new MaterialAboutActionItem.Builder() .text("Version") .subText(BuildConfig.VERSION_NAME) .icon(R.drawable.ic_info_outline_white) .build()); titleCard.addItem(new MaterialAboutActionItem.Builder() .text("View on Google Play") .icon(R.drawable.ic_google_play_white) .setOnClickListener(new MaterialAboutActionItem.OnClickListener() { @Override public void onClick() { try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + getPackageName()))); } catch (android.content.ActivityNotFoundException anfe) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + getPackageName()))); } } }) .build()); titleCard.addItem(new MaterialAboutActionItem.Builder() .text("Fork on GitHub") .subText("Team980/ThunderScout-Android") .icon(R.drawable.ic_github_white) .setOnClickListener(new MaterialAboutActionItem.OnClickListener() { @Override public void onClick() { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("https://github.com/Team980/ThunderScout-Android")); startActivity(i); } }) .build()); MaterialAboutCard.Builder authorCard = new MaterialAboutCard.Builder(); authorCard.title("Author"); authorCard.addItem(new MaterialAboutActionItem.Builder() .text("Luke Myers") .subText("Lead Developer") .icon(R.drawable.ic_person_white_24dp) .build()); authorCard.addItem(new MaterialAboutActionItem.Builder() .text("Chief Delphi") .subText("@19lmyers") .icon(R.drawable.ic_forum_white) .setOnClickListener(new MaterialAboutActionItem.OnClickListener() { @Override public void onClick() { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("https: startActivity(i); } }) .build()); MaterialAboutCard.Builder teamCard = new MaterialAboutCard.Builder(); teamCard.addItem(new MaterialAboutTitleItem.Builder() .text("FRC Team 980 ThunderBots") .icon(R.mipmap.team980_logo) .build()); teamCard.addItem(new MaterialAboutActionItem.Builder() .text("Like us on Facebook") .subText("@Team980Thunderbots") .icon(R.drawable.ic_facebook_white) .setOnClickListener(new MaterialAboutActionItem.OnClickListener() { @Override public void onClick() { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("https: startActivity(i); } }) .build()); teamCard.addItem(new MaterialAboutActionItem.Builder() .text("Follow us on Twitter") .subText("@frc980") .icon(R.drawable.ic_twitter_white) .setOnClickListener(new MaterialAboutActionItem.OnClickListener() { @Override public void onClick() { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("https://twitter.com/frc980")); startActivity(i); } }) .build()); teamCard.addItem(new MaterialAboutActionItem.Builder() .text("Follow us on Instagram") .subText("@frcteam980") .icon(R.drawable.ic_instagram_white) .setOnClickListener(new MaterialAboutActionItem.OnClickListener() { @Override public void onClick() { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("https: startActivity(i); } }) .build()); teamCard.addItem(new MaterialAboutActionItem.Builder() .text("Follow us on Snapchat") .subText("@frcteam980") .icon(R.drawable.ic_snapchat_white) .setOnClickListener(new MaterialAboutActionItem.OnClickListener() { @Override public void onClick() { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("https: startActivity(i); } }) .build()); teamCard.addItem(new MaterialAboutActionItem.Builder() .text("Subscribe to us on YouTube") .subText("FRC Team 980 Official") .icon(R.drawable.ic_youtube_white) .setOnClickListener(new MaterialAboutActionItem.OnClickListener() { @Override public void onClick() { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("https: startActivity(i); } }) .build()); teamCard.addItem(new MaterialAboutActionItem.Builder() .text("Visit our website") .subText("team980.com") .icon(R.drawable.ic_web_white) .setOnClickListener(new MaterialAboutActionItem.OnClickListener() { @Override public void onClick() { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("http://team980.com/")); startActivity(i); } }) .build()); return new MaterialAboutList.Builder() .addCard(titleCard.build()) .addCard(authorCard.build()) .addCard(teamCard.build()) .build(); } @Override protected CharSequence getActivityTitle() { return getString(R.string.mal_title_about); } }
package com.veniosg.dir.view; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.HorizontalScrollView; import android.widget.LinearLayout; import java.io.File; import static com.veniosg.dir.util.Utils.lastCommonDirectoryIndex; import static com.veniosg.dir.util.Utils.measureExactly; import static com.veniosg.dir.view.PathButtonFactory.newButton; import static java.lang.Math.max; public class PathContainerView extends HorizontalScrollView { /** * Additional padding to the end of mPathContainer * so that the last item is left aligned to the grid. */ private int mPathContainerRightPadding; private LinearLayout mPathContainer; private RightEdgeRangeListener mRightEdgeRangeListener = noOpRangeListener(); private int mRightEdgeRange; public PathContainerView(Context context) { super(context); } public PathContainerView(Context context, AttributeSet attrs) { super(context, attrs); } public PathContainerView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public PathContainerView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } @Override protected void onFinishInflate() { try { mPathContainer = (LinearLayout) getChildAt(0); // TODO remove once animations are in place mPathContainer.addOnLayoutChangeListener(new OnLayoutChangeListener() { @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { smoothScrollTo(mPathContainer.getWidth(), 0); } }); } catch (ClassCastException ex) { throw new RuntimeException("First and only child of PathContainerView must be a LinearLayout"); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); View lastChild = mPathContainer.getChildAt(mPathContainer.getChildCount() - 1); int marginStart = ((LinearLayout.LayoutParams) lastChild.getLayoutParams()).getMarginStart(); mPathContainerRightPadding = getMeasuredWidth() - lastChild.getMeasuredWidth() - marginStart; // On really long names that take up the whole screen width if (lastChild.getMeasuredWidth() >= getMeasuredWidth() - marginStart - mRightEdgeRange) { mPathContainerRightPadding -= getMeasuredHeight(); setPaddingRelative(0, 0, getMeasuredHeight(), 0); } else { setPaddingRelative(0, 0, 0, 0); } mPathContainer.measure(measureExactly(mPathContainerRightPadding + mPathContainer.getMeasuredWidth()), measureExactly(getMeasuredHeight())); } @Override protected void onScrollChanged(int l, int t, int oldl, int oldt) { super.onScrollChanged(l, t, oldl, oldt); invokeRightEdgeRangeListener(l); } public void setEdgeListener(RightEdgeRangeListener listener) { if (listener != null) { mRightEdgeRangeListener = listener; } else { mRightEdgeRangeListener = noOpRangeListener(); } mRightEdgeRange = mRightEdgeRangeListener.getRange(); } /** * @param previousDir Pass null to refresh the whole view. * @param newDir The new current directory. */ public void updateWithPaths(File previousDir, File newDir, final PathController controller) { // Remove only the non-matching buttons. int count = mPathContainer.getChildCount(); int lastCommonDirectory; if(previousDir != null && count > 0) { lastCommonDirectory = lastCommonDirectoryIndex(previousDir, newDir); mPathContainer.removeViews(lastCommonDirectory + 1, count - lastCommonDirectory - 1); } else { // First layout, init by hand. lastCommonDirectory = -1; mPathContainer.removeAllViews(); } // Reload buttons. fillPathContainer(lastCommonDirectory + 1, newDir, controller); } /** * Adds new buttons according to the fPath parameter. * @param firstDirToAdd The index of the first directory of fPath to add. */ private void fillPathContainer(int firstDirToAdd, File fPath, final PathController pathController) { StringBuilder cPath = new StringBuilder(); char cChar; int cDir = 0; String path = fPath.getAbsolutePath(); for (int i = 0; i < path.length(); i++) { cChar = path.charAt(i); cPath.append(cChar); if ((cChar == '/' || i == path.length() - 1)) { // if folder name ended, or path string ended but not if we 're on root if (cDir++ >= firstDirToAdd) { // Add a button mPathContainer.addView(newButton(cPath.toString(), pathController)); // TODO uncomment // if(firstDirToAdd != 0) // if not on first draw // mPathContainer.getChildAt(mPathContainer.getChildCount() - 1).setAlpha(0); // So that it doesn't flash due to the animation's delay } } } } private void invokeRightEdgeRangeListener(int l) { // Scroll pixels for the last item's right edge to reach the parent's right edge int scrollToEnd = mPathContainer.getWidth() - getWidth() - max(mPathContainerRightPadding, 0); int pixelsScrolledWithinRange = scrollToEnd - l + mRightEdgeRange; mRightEdgeRangeListener.rangeOffsetChanged(pixelsScrolledWithinRange); } private RightEdgeRangeListener noOpRangeListener() { return new RightEdgeRangeListener() { @Override public int getRange() { return 0; } @Override public void rangeOffsetChanged(int offsetInRange) {} }; } /** * Listener for when the last child is within the supplied mRangeRight of the right edge of this view. */ public interface RightEdgeRangeListener { /** * @return The range in which to get the callback. */ public int getRange(); /** * Called when the distance of the last child in regards to the right edge of this view * has changed. * @param offsetInRange The current number of pixels within the range. If <0 means that the * child is not yet within the specified range. */ public void rangeOffsetChanged(int offsetInRange); } }
package de.sopa.drawing; import org.andengine.entity.IEntityFactory; import org.andengine.entity.modifier.AlphaModifier; import org.andengine.entity.modifier.RotationModifier; import org.andengine.entity.particle.ParticleSystem; import org.andengine.entity.particle.initializer.GravityParticleInitializer; import org.andengine.entity.particle.initializer.VelocityParticleInitializer; import org.andengine.entity.primitive.Rectangle; import org.andengine.opengl.vbo.VertexBufferObjectManager; import org.andengine.util.color.Color; /** * @author Raphael Schilling - raphaelschiling@gmail.com * @author David Schilling - davejs92@gmail.com */ public class ConfettiParticleSystem extends ParticleSystem<Rectangle> { private static final Color[] COLOR_MAP = { new Color(1f, 0f, 0f), new Color(0.07f, 0.84f, 0.12f), new Color(0.24f, 0f, 0.87f), new Color(1f, 1f, 0f) }; public ConfettiParticleSystem(final VertexBufferObjectManager vbom, float cameraWidth) { super(createEntityFactory(vbom), new HorizontalLineParticleEmitter(0, 0, cameraWidth), 50f, 100f, 200); addParticleInitializer(new VelocityParticleInitializer<Rectangle>(-20, 20, 250, 300)); addParticleInitializer(new GravityParticleInitializer<Rectangle>()); } private static IEntityFactory<Rectangle> createEntityFactory(final VertexBufferObjectManager vbom) { return new IEntityFactory<Rectangle>() { @Override public Rectangle create(final float pX, final float pY) { Rectangle rectangle = new Rectangle(pX, pY, 30, 15, vbom); rectangle.setColor(COLOR_MAP[getRandomBetweenZeroAndThree()]); rectangle.registerEntityModifier(new RotationModifier(7f, (float) Math.random() * 360, (7 - (float) Math.random() * 15) * 360)); rectangle.registerEntityModifier(new AlphaModifier(4f, 0.7f, 0f)); return rectangle; }}; } private static int getRandomBetweenZeroAndThree() { return (int) (Math.random() * 4); } }
package eu.redray.trevie; import android.content.Context; import android.database.Cursor; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; /** * Creates custom CursorAdapter to display records from favourites database */ class FavouritesGridAdapter extends CursorAdapter { public FavouritesGridAdapter(Context context, Cursor c, int flags) { super(context, c, flags); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = LayoutInflater.from(context).inflate(R.layout.item_movie_grid, parent, false); ViewHolder viewHolder = new ViewHolder(view); view.setTag(viewHolder); return view; } @Override public void bindView(View view, Context context, Cursor cursor) { ViewHolder viewHolder = (ViewHolder) view.getTag(); // Read title from cursor String title = cursor.getString(MovieGridFragment.COL_MOVIE_TITLE); viewHolder.titleView.setText(title); viewHolder.titleView.setSelected(true); // Read release year from cursor String year = cursor.getString(MovieGridFragment.COL_MOVIE_RELEASE_DATE); viewHolder.yearView.setText(year.substring(0, 4)); // Read poster path Picasso.with(context).load(cursor.getString(MovieGridFragment.COL_MOVIE_POSTER_PATH)). placeholder(R.drawable.temp).error(R.drawable.error).fit().into(viewHolder.posterView); } /** Holds all the views used to display data in movie grid item. */ private static class ViewHolder { final ImageView posterView; final ImageView favouriteIconView; final TextView titleView; final TextView yearView; public ViewHolder(View view) { posterView = (ImageView) view.findViewById(R.id.grid_movie_poster); favouriteIconView = (ImageView) view.findViewById(R.id.grid_movie_favourite); titleView = (TextView) view.findViewById(R.id.grid_movie_title); yearView = (TextView) view.findViewById(R.id.grid_movie_genre); } } }
package net.alcuria.umbracraft.engine; import net.alcuria.umbracraft.Config; import net.alcuria.umbracraft.Game; import net.alcuria.umbracraft.engine.components.DirectedInputComponent; import net.alcuria.umbracraft.engine.entities.Entity; import net.alcuria.umbracraft.engine.map.Map; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.utils.Array; /** Handles pathfinding through a {@link DirectedInputComponent} * @author Andrew Keturi */ public class Pathfinder { public static class PathNode implements Comparable<PathNode> { public PathNode parent; /* g = dist from start, h=dist from end, f= g+h */ public int x, y, f, g, h; public PathNode(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(PathNode other) { return f - other.f; } public void draw(Color color, int altitude, SpriteBatch batch) { batch.setColor(color); final int w = Config.tileWidth; // Game.debug(color + " " + x + " " + y); batch.draw(Game.assets().get("debug.png", Texture.class), x * w, y * w + altitude * w, w, w); batch.setColor(Color.WHITE); } /** @param other another {@link PathNode} * @return <code>true</code> if the two nodes are pointing to the same * location */ public boolean hasSameLocationAs(final PathNode other) { return other.x == x && other.y == y; } @Override public String toString() { return String.format("(%d, %d)", x, y); } } private final Array<PathNode> closed = new Array<PathNode>(); private final DirectedInputComponent component; private PathNode destination, source; private final Array<PathNode> open = new Array<PathNode>(); private final Array<PathNode> solution = new Array<PathNode>(); private final boolean threaded = false; public Pathfinder(DirectedInputComponent component) { this.component = component; } public Array<PathNode> getSolution() { return solution; } private boolean isTraversible(Map map, PathNode cur, int destX, int destY) { if (map.isStairs(cur.x, cur.y) && map.isStairs(destX, destY)) { return true; } return (map.getAltitudeAt(destX, destY) - 1) <= map.getAltitudeAt(cur.x, cur.y); } /** Searches a list for a pathNode that matches the given x,y coordinates * @param list a list of {@link PathNode} objects * @param x the tile x coords * @param y the tile y coords * @return */ private boolean listContains(Array<PathNode> list, int x, int y) { if (list == null) { throw new NullPointerException("List cannot be null"); } for (int i = 0; i < list.size; i++) { if (list.get(i).x == x && list.get(i).y == y) { return true; } } return false; } public void renderPaths() { for (PathNode n : open) { n.draw(Color.GREEN, Game.map().getAltitudeAt(n.x, n.y), Game.batch()); } for (PathNode n : closed) { n.draw(Color.RED, Game.map().getAltitudeAt(n.x, n.y), Game.batch()); } if (source != null) { source.draw(Color.YELLOW, Game.map().getAltitudeAt(source.x, source.y), Game.batch()); } if (destination != null) { destination.draw(Color.MAGENTA, Game.map().getAltitudeAt(destination.x, destination.y), Game.batch()); } if (solution != null) { for (PathNode n : solution) { n.draw(Color.CYAN, Game.map().getAltitudeAt(n.x, n.y), Game.batch()); } } } /** Sets a destination to attempt to find a path to * @param source the starting {@link PathNode} * @param destination the ending {@link PathNode} */ public void setTarget(PathNode source, PathNode destination) { if (source == null) { throw new NullPointerException("source cannot be null"); } if (destination == null) { throw new NullPointerException("destination cannot be null"); } if (source.hasSameLocationAs(destination)) { Game.log("Target is already at destination"); return; } // clear out the lists open.clear(); closed.clear(); // set source and dest this.source = source; this.destination = destination; this.source.f = Heuristic.calculateFCost(source, destination, source); if (threaded) { new Thread("Pathfinder") { @Override public void run() { solve(); }; }.start(); } else { solve(); } } private void solve() { final Map map = Game.map(); final int[] dX = { 0, 1, 1, 1, 0, -1, -1, -1 }; // clockwise, from 12 oclock final int[] dY = { 1, 1, 0, -1, -1, -1, 0, 1 }; open.add(source); while (true) { // ensure we still have open nodes if (open.size <= 0) { Game.debug("No path found"); break; } // get a pointer to the node in the open list with the lowest f cost open.sort(); PathNode cur = open.removeIndex(0); closed.add(cur); if (cur.hasSameLocationAs(destination)) { Game.debug("Path found!"); solution.clear(); while (cur != null) { solution.add(cur); cur = cur.parent; } break; } // foreach current node neighbor for (int i = 0; i < dX.length; i++) { // if neighbor is not traversible or neighbor is in closed, skip it if (!map.isInBounds(cur.x + dX[i], cur.y + dY[i]) || !isTraversible(map, cur, cur.x + dX[i], cur.y + dY[i]) || listContains(closed, cur.x + dX[i], cur.y + dY[i])) { continue; } PathNode neighbor = new PathNode(cur.x + dX[i], cur.y + dY[i]); // if new path to neighbor is shorter or not in open if (neighbor.f < cur.f || !listContains(open, neighbor.x, neighbor.y)) { // set f cost of nbr neighbor.f = Heuristic.calculateFCost(source, destination, neighbor); // set parent of neighbor to current neighbor.parent = cur; if (!listContains(open, neighbor.x, neighbor.y)) { open.add(neighbor); } } } } } public void stop() { open.clear(); solution.clear(); closed.clear(); } public void update(Entity entity) { // if (Gdx.input.isKeyJustPressed(Keys.ENTER)) { // Entity hero = Game.entities().find(Entity.PLAYER); // setTarget(new PathNode((int) (entity.position.x / Config.tileWidth), (int) (entity.position.y / Config.tileWidth)), new PathNode((int) (hero.position.x / Config.tileWidth), (int) (hero.position.y / Config.tileWidth))); } }
package lt.markmerkk.utils.hourglass; import java.util.Timer; import java.util.TimerTask; import javafx.application.Platform; import javax.annotation.PreDestroy; import lt.markmerkk.utils.Utils; import lt.markmerkk.utils.hourglass.exceptions.TimeCalcError; import org.joda.time.DateTime; import org.joda.time.DateTimeUtils; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HourGlass { public static final Logger logger = LoggerFactory.getLogger(HourGlass.class); public static final String DATE_SHORT_FORMAT = "HH:mm"; public static final String DATE_LONG_FORMAT = "yyyy-MM-dd HH:mm"; public final static DateTimeFormatter shortFormat = DateTimeFormat.forPattern(DATE_SHORT_FORMAT); public final static DateTimeFormatter longFormat = DateTimeFormat.forPattern(DATE_LONG_FORMAT); public static final int DEFAULT_TICK = 1000; Timer timer = null; State state = State.STOPPED; long startMillis = 0; long endMillis = 0; long lastTick = 0; Listener listener; public HourGlass() { } //region Public /** * Starts timer * * @return reports if timer was started successfully */ public boolean start() { if (state == State.STOPPED) { state = State.RUNNING; lastTick = current(); endMillis = current(); startMillis = current(); TimerTask updateRunnable = new TimerTask() { @Override public void run() { Platform.runLater(() -> { update(); }); } }; timer = new Timer(); timer.scheduleAtFixedRate(updateRunnable, 1, DEFAULT_TICK); long delay = endMillis - startMillis; if (listener != null) listener.onStart(startMillis, endMillis, delay); return true; } return false; } /** * Stops timer * * @return reports if timer was stopped successfully */ public boolean stop() { if (state == State.RUNNING) { state = State.STOPPED; timer.cancel(); timer.purge(); long delay = endMillis - startMillis; if (listener != null) listener.onStop(startMillis, endMillis, delay); startMillis = 0; endMillis = 0; lastTick = -1; return true; } return false; } /** * Restarts timer */ public boolean restart() { long lastEnd = endMillis; stop(); start(); startMillis = lastEnd; endMillis = current(); logger.debug("Restarting timer. Start: {} / End: {}", startMillis, endMillis); update(); return true; } /** * Checks if all variables are valid * @return */ public boolean isValid() { try { checkAndThrowForError(); return true; } catch (TimeCalcError timeCalcError) { } return false; } @PreDestroy public void destroy() { if (state == State.RUNNING) stop(); } //endregion //region Core /** * A function to calculate duration and report a change */ void update() { if (state == State.STOPPED) return; try { checkAndThrowForError(); endMillis += calcTimeIncrease(); long delay = endMillis - startMillis; if (listener != null) listener.onTick(startMillis, endMillis, delay); logger.debug("Tick tock: start {} / end {}", startMillis, endMillis); } catch (TimeCalcError e) { logger.debug("Timer update error: start {} / end {}", startMillis, endMillis); lastTick = current(); if (listener != null) listener.onError(e.getError()); } } /** * Checks if all variables are correct for counting * @throws TimeCalcError */ void checkAndThrowForError() throws TimeCalcError { if (startMillis < 0) throw new TimeCalcError(Error.START); if (endMillis < 0) throw new TimeCalcError(Error.END); if (startMillis > endMillis) throw new TimeCalcError(Error.DURATION); } /** * Calculates time increase for the tick * * @return time increase */ long calcTimeIncrease() { if (lastTick < 0) return DEFAULT_TICK; if (current() < 0) return DEFAULT_TICK; if (current() < lastTick) return DEFAULT_TICK; long increase = current() - lastTick; lastTick = current(); return increase; } long current() { return DateTimeUtils.currentTimeMillis(); } //endregion //region Getters / Setters /** * Sets current day for the hourglass * @param currentDay provided current day */ public void setCurrentDay(DateTime currentDay) { if (currentDay == null) throw new IllegalArgumentException("Cannot set current day without provided date!"); try { startMillis = new DateTime(startMillis).withDate( currentDay.year().get(), currentDay.monthOfYear().get(), currentDay.dayOfMonth().get() ).getMillis(); endMillis = new DateTime(endMillis).withDate( currentDay.year().get(), currentDay.monthOfYear().get(), currentDay.dayOfMonth().get() ).getMillis(); update(); } catch (IllegalArgumentException e) { e.printStackTrace(); } } /** * Reports start time in {@link DateTime} * @return start time */ public DateTime reportStart() { if (isValid()) return new DateTime(startMillis); return new DateTime(current()); } /** * Reports end time in {@link DateTime} * @return end time */ public DateTime reportEnd() { if (isValid()) return new DateTime(endMillis); return new DateTime(current()); } /** * Updates timers with input start, end times and todays date. * @param today provided todays date * @param startTime provided start time in string * @param endTime provided end time in string */ public void updateTimers(DateTime today, String startTime, String endTime) { if (today == null) throw new IllegalArgumentException("Incorrect updateTimers use!"); if (startTime == null) throw new IllegalArgumentException("Incorrect updateTimers use!"); if (endTime == null) throw new IllegalArgumentException("Incorrect updateTimers use!"); // Parsing start time try { DateTime start = shortFormat.parseDateTime(startTime).withDate( today.year().get(), today.monthOfYear().get(), today.dayOfMonth().get() ); startMillis = start.getMillis(); } catch (IllegalArgumentException e) { startMillis = -1; } // Parsing end time try { DateTime end = shortFormat.parseDateTime(endTime).withDate( today.year().get(), today.monthOfYear().get(), today.dayOfMonth().get() ); endMillis = end.getMillis(); // Correct time with current millis long currentSeconds = (current() - DateTime.now().withSecondOfMinute(0).getMillis()); endMillis += currentSeconds; } catch (IllegalArgumentException e) { endMillis = -1; } update(); } /** * Updates timers with input start, end times. * @param startTime provided start time in string * @param endTime provided end time in string */ public void updateTimers(String startTime, String endTime) { if (startTime == null) throw new IllegalArgumentException("Incorrect updateTimers use!"); if (endTime == null) throw new IllegalArgumentException("Incorrect updateTimers use!"); // Parsing start time try { DateTime start = longFormat.parseDateTime(startTime); startMillis = start.getMillis(); } catch (IllegalArgumentException e) { startMillis = -1; } // Parsing end time try { DateTime end = longFormat.parseDateTime(endTime); endMillis = end.getMillis(); // Correct time with current millis long currentSeconds = (current() - DateTime.now().withSecondOfMinute(0).getMillis()); endMillis += currentSeconds; } catch (IllegalArgumentException e) { endMillis = -1; } update(); } public void setListener(Listener listener) { this.listener = listener; } public State getState() { return state; } public long getStartMillis() { return startMillis; } public long getEndMillis() { return endMillis; } //endregion //region Convenience /** * Appends a minute to a start time */ public void appendMinute() { if ((startMillis + 1000 * 60) < current()) { startMillis += 1000 * 60; // Adding 60 seconds } update(); } /** * Subtracts a minute from the time */ public void subractMinute() { startMillis -= 1000 * 60; // Adding 60 seconds update(); } /** * Parses time output and converts it into millis * @param time input formatted time * @return */ public static long parseMillisFromText(String time) { if (Utils.isEmpty(time)) return -1; try { return longFormat.parseDateTime(time).getMillis(); } catch (IllegalArgumentException e) { return -1; } } //endregion //region Classes /** * Represents the state that timer is in */ public enum State { STOPPED(0), RUNNING(1); private int value; private State(int value) { this.value = value; } public int getValue() { return value; } public static State parseState(int status) { switch (status) { case 0: return STOPPED; case 1: return RUNNING; default: return STOPPED; } } } /** * Represents an error when calculating a time change. */ public enum Error { START("Error in start time!"), END("Error in end time!"), DURATION( "Error calculating duration!"); String message; Error(String message) { this.message = message; } public String getMessage() { return message; } } //endregion //region Classes /** * Public listener that reports the changes */ public static interface Listener { /** * Called when timer has been started * * @param start provided start time * @param end provided end time * @param duration provided duration */ void onStart(long start, long end, long duration); /** * Called when timer has been stopped * * @param start provided start time * @param end provided end time * @param duration provided duration */ void onStop(long start, long end, long duration); /** * Called on every second tick when timer is running * * @param start provided start time * @param end provided end time * @param duration provided duration */ void onTick(long start, long end, long duration); /** * Reports an error when there is something wrong with calculation. */ void onError(Error error); } //endregion }
package net.formula97.fakegpbase; public class NfcTextRecord { private String mText; private String mLanguageCode; private Boolean mEncodeUtf8; public NfcTextRecord() { } public NfcTextRecord(String text, String languageCode, Boolean encodeUtf8) { this.mText = text; this.mLanguageCode = languageCode; this.mEncodeUtf8 = encodeUtf8; } public String getText() { return this.mText; } public String getLanguageCode() { return this.mLanguageCode; } public Boolean isEncodeUtf8() { return this.mEncodeUtf8; } public void setText(String text) { this.mText = text; } public void setLanguageCode(String languageCode) { this.mLanguageCode = languageCode; } public void setEncodeUtf8(Boolean encodeUtf8) { this.mEncodeUtf8 = encodeUtf8; } }
package net.ossrs.yasea.rtmp.io; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketException; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.concurrent.atomic.AtomicInteger; import android.util.Log; import net.ossrs.yasea.rtmp.RtmpPublisher; import net.ossrs.yasea.rtmp.amf.AmfMap; import net.ossrs.yasea.rtmp.amf.AmfNull; import net.ossrs.yasea.rtmp.amf.AmfNumber; import net.ossrs.yasea.rtmp.amf.AmfObject; import net.ossrs.yasea.rtmp.amf.AmfString; import net.ossrs.yasea.rtmp.packets.Abort; import net.ossrs.yasea.rtmp.packets.Data; import net.ossrs.yasea.rtmp.packets.Handshake; import net.ossrs.yasea.rtmp.packets.Command; import net.ossrs.yasea.rtmp.packets.Audio; import net.ossrs.yasea.rtmp.packets.SetPeerBandwidth; import net.ossrs.yasea.rtmp.packets.Video; import net.ossrs.yasea.rtmp.packets.UserControl; import net.ossrs.yasea.rtmp.packets.RtmpPacket; import net.ossrs.yasea.rtmp.packets.WindowAckSize; /** * Main RTMP connection implementation class * * @author francois, leoma */ public class RtmpConnection implements RtmpPublisher { private static final String TAG = "RtmpConnection"; private static final Pattern rtmpUrlPattern = Pattern.compile("^rtmp: private RtmpPublisher.EventHandler mHandler; private String appName; private String streamName; private String publishType; private String swfUrl; private String tcUrl; private String pageUrl; private Socket socket; private String srsServerInfo = ""; private String socketExceptionCause = ""; private RtmpSessionInfo rtmpSessionInfo; private RtmpDecoder rtmpDecoder; private BufferedInputStream inputStream; private BufferedOutputStream outputStream; private Thread rxPacketHandler; private volatile boolean connected = false; private volatile boolean publishPermitted = false; private final Object connectingLock = new Object(); private final Object publishLock = new Object(); private AtomicInteger videoFrameCacheNumber = new AtomicInteger(0); private int currentStreamId = 0; private int transactionIdCounter = 0; private AmfString serverIpAddr; private AmfNumber serverPid; private AmfNumber serverId; private int videoWidth; private int videoHeight; private int videoFrameCount; private int videoDataLength; private int audioFrameCount; private int audioDataLength; private long videoLastTimeMillis; private long audioLastTimeMillis; public RtmpConnection(RtmpPublisher.EventHandler handler) { mHandler = handler; } private void handshake(InputStream in, OutputStream out) throws IOException { Handshake handshake = new Handshake(); handshake.writeC0(out); handshake.writeC1(out); // Write C1 without waiting for S0 out.flush(); handshake.readS0(in); handshake.readS1(in); handshake.writeC2(out); handshake.readS2(in); } @Override public boolean connect(String url) throws IOException { int port; String host; Matcher matcher = rtmpUrlPattern.matcher(url); if (matcher.matches()) { tcUrl = url.substring(0, url.lastIndexOf('/')); swfUrl = ""; pageUrl = ""; host = matcher.group(1); String portStr = matcher.group(3); port = portStr != null ? Integer.parseInt(portStr) : 1935; appName = matcher.group(4); streamName = matcher.group(6); } else { throw new IllegalArgumentException("Invalid RTMP URL. Must be in format: rtmp://host[:port]/application[/streamName]"); } // socket connection Log.d(TAG, "connect() called. Host: " + host + ", port: " + port + ", appName: " + appName + ", publishPath: " + streamName); rtmpSessionInfo = new RtmpSessionInfo(); rtmpDecoder = new RtmpDecoder(rtmpSessionInfo); socket = new Socket(); SocketAddress socketAddress = new InetSocketAddress(host, port); socket.connect(socketAddress, 3000); inputStream = new BufferedInputStream(socket.getInputStream()); outputStream = new BufferedOutputStream(socket.getOutputStream()); Log.d(TAG, "connect(): socket connection established, doing handhake..."); handshake(inputStream, outputStream); Log.d(TAG, "connect(): handshake done"); // Start the "main" handling thread rxPacketHandler = new Thread(new Runnable() { @Override public void run() { try { Log.d(TAG, "starting main rx handler loop"); handleRxPacketLoop(); } catch (IOException ex) { Logger.getLogger(RtmpConnection.class.getName()).log(Level.SEVERE, null, ex); } } }); rxPacketHandler.start(); return rtmpConnect(); } private boolean rtmpConnect() throws IllegalStateException { if (connected) { throw new IllegalStateException("Already connected to RTMP server"); } // Mark session timestamp of all chunk stream information on connection. ChunkStreamInfo.markSessionTimestampTx(); Log.d(TAG, "rtmpConnect(): Building 'connect' invoke packet"); ChunkStreamInfo chunkStreamInfo = rtmpSessionInfo.getChunkStreamInfo(ChunkStreamInfo.RTMP_CID_OVER_CONNECTION); Command invoke = new Command("connect", ++transactionIdCounter, chunkStreamInfo); invoke.getHeader().setMessageStreamId(0); AmfObject args = new AmfObject(); args.setProperty("app", appName); args.setProperty("flashVer", "LNX 11,2,202,233"); args.setProperty("swfUrl", swfUrl); args.setProperty("tcUrl", tcUrl); args.setProperty("fpad", false); args.setProperty("capabilities", 239); args.setProperty("audioCodecs", 3575); args.setProperty("videoCodecs", 252); args.setProperty("videoFunction", 1); args.setProperty("pageUrl", pageUrl); args.setProperty("objectEncoding", 0); invoke.addData(args); sendRtmpPacket(invoke); mHandler.onRtmpConnecting("connecting"); synchronized (connectingLock) { try { connectingLock.wait(5000); } catch (InterruptedException ex) { // do nothing } } if (!connected) { shutdown(); } return connected; } @Override public boolean publish(String type) throws IllegalStateException, IOException { publishType = type; return createStream(); } private boolean createStream() { if (!connected) { throw new IllegalStateException("Not connected to RTMP server"); } if (currentStreamId != 0) { throw new IllegalStateException("Current stream object has existed"); } Log.d(TAG, "createStream(): Sending releaseStream command..."); // transactionId == 2 Command releaseStream = new Command("releaseStream", ++transactionIdCounter); releaseStream.getHeader().setChunkStreamId(ChunkStreamInfo.RTMP_CID_OVER_STREAM); releaseStream.addData(new AmfNull()); // command object: null for "createStream" releaseStream.addData(streamName); // command object: null for "releaseStream" sendRtmpPacket(releaseStream); Log.d(TAG, "createStream(): Sending FCPublish command..."); // transactionId == 3 Command FCPublish = new Command("FCPublish", ++transactionIdCounter); FCPublish.getHeader().setChunkStreamId(ChunkStreamInfo.RTMP_CID_OVER_STREAM); FCPublish.addData(new AmfNull()); // command object: null for "FCPublish" FCPublish.addData(streamName); sendRtmpPacket(FCPublish); Log.d(TAG, "createStream(): Sending createStream command..."); ChunkStreamInfo chunkStreamInfo = rtmpSessionInfo.getChunkStreamInfo(ChunkStreamInfo.RTMP_CID_OVER_CONNECTION); // transactionId == 4 Command createStream = new Command("createStream", ++transactionIdCounter, chunkStreamInfo); createStream.addData(new AmfNull()); // command object: null for "createStream" sendRtmpPacket(createStream); // Waiting for "NetStream.Publish.Start" response. synchronized (publishLock) { try { publishLock.wait(5000); } catch (InterruptedException ex) { // do nothing } } if (publishPermitted) { mHandler.onRtmpConnected("connected" + srsServerInfo); } else { shutdown(); } return publishPermitted; } private void fmlePublish() throws IllegalStateException { if (!connected) { throw new IllegalStateException("Not connected to RTMP server"); } if (currentStreamId == 0) { throw new IllegalStateException("No current stream object exists"); } Log.d(TAG, "fmlePublish(): Sending publish command..."); // transactionId == 0 Command publish = new Command("publish", 0); publish.getHeader().setChunkStreamId(ChunkStreamInfo.RTMP_CID_OVER_STREAM); publish.getHeader().setMessageStreamId(currentStreamId); publish.addData(new AmfNull()); // command object: null for "publish" publish.addData(streamName); publish.addData(publishType); sendRtmpPacket(publish); } private void onMetaData() throws IllegalStateException { if (!connected) { throw new IllegalStateException("Not connected to RTMP server"); } if (currentStreamId == 0) { throw new IllegalStateException("No current stream object exists"); } Log.d(TAG, "onMetaData(): Sending empty onMetaData..."); Data metadata = new Data("@setDataFrame"); metadata.getHeader().setMessageStreamId(currentStreamId); metadata.addData("onMetaData"); AmfMap ecmaArray = new AmfMap(); ecmaArray.setProperty("duration", 0); ecmaArray.setProperty("width", videoWidth); ecmaArray.setProperty("height", videoHeight); ecmaArray.setProperty("videodatarate", 0); ecmaArray.setProperty("framerate", 0); ecmaArray.setProperty("audiodatarate", 0); ecmaArray.setProperty("audiosamplerate", 44100); ecmaArray.setProperty("audiosamplesize", 16); ecmaArray.setProperty("stereo", true); ecmaArray.setProperty("filesize", 0); metadata.addData(ecmaArray); sendRtmpPacket(metadata); } @Override public void closeStream() throws IllegalStateException { if (!connected) { throw new IllegalStateException("Not connected to RTMP server"); } if (currentStreamId == 0) { throw new IllegalStateException("No current stream object exists"); } if (!publishPermitted) { throw new IllegalStateException("Not get _result(Netstream.Publish.Start)"); } Log.d(TAG, "closeStream(): setting current stream ID to 0"); Command closeStream = new Command("closeStream", 0); closeStream.getHeader().setChunkStreamId(ChunkStreamInfo.RTMP_CID_OVER_STREAM); closeStream.getHeader().setMessageStreamId(currentStreamId); closeStream.addData(new AmfNull()); sendRtmpPacket(closeStream); mHandler.onRtmpStopped("stopped"); } @Override public void shutdown() { if (socket != null) { try { // It will raise EOFException in handleRxPacketThread socket.shutdownInput(); // It will raise SocketException in sendRtmpPacket socket.shutdownOutput(); } catch (IOException ioe) { ioe.printStackTrace(); } // shutdown rxPacketHandler if (rxPacketHandler != null) { rxPacketHandler.interrupt(); try { rxPacketHandler.join(); } catch (InterruptedException ie) { rxPacketHandler.interrupt(); } rxPacketHandler = null; } // shutdown socket as well as its input and output stream try { socket.close(); Log.d(TAG, "socket closed"); } catch (IOException ex) { Log.e(TAG, "shutdown(): failed to close socket", ex); } mHandler.onRtmpDisconnected("disconnected"); } reset(); } private void reset() { connected = false; publishPermitted = false; tcUrl = null; swfUrl = null; pageUrl = null; appName = null; streamName = null; publishType = null; currentStreamId = 0; transactionIdCounter = 0; videoFrameCacheNumber.set(0); socketExceptionCause = ""; serverIpAddr = null; serverPid = null; serverId = null; rtmpSessionInfo = null; rtmpDecoder = null; } @Override public void publishAudioData(byte[] data, int dts) throws IllegalStateException { if (!connected) { throw new IllegalStateException("Not connected to RTMP server"); } if (currentStreamId == 0) { throw new IllegalStateException("No current stream object exists"); } if (!publishPermitted) { throw new IllegalStateException("Not get _result(Netstream.Publish.Start)"); } Audio audio = new Audio(); audio.setData(data); audio.getHeader().setAbsoluteTimestamp(dts); audio.getHeader().setMessageStreamId(currentStreamId); sendRtmpPacket(audio); calcAudioBitrate(audio.getHeader().getPacketLength()); mHandler.onRtmpAudioStreaming("audio streaming"); } @Override public void publishVideoData(byte[] data, int dts) throws IllegalStateException { if (!connected) { throw new IllegalStateException("Not connected to RTMP server"); } if (currentStreamId == 0) { throw new IllegalStateException("No current stream object exists"); } if (!publishPermitted) { throw new IllegalStateException("Not get _result(Netstream.Publish.Start)"); } Video video = new Video(); video.setData(data); video.getHeader().setAbsoluteTimestamp(dts); video.getHeader().setMessageStreamId(currentStreamId); sendRtmpPacket(video); videoFrameCacheNumber.decrementAndGet(); calcVideoFpsAndBitrate(video.getHeader().getPacketLength()); mHandler.onRtmpVideoStreaming("video streaming"); } private void calcVideoFpsAndBitrate(int length) { videoDataLength += length; if (videoFrameCount == 0) { videoLastTimeMillis = System.nanoTime() / 1000000; videoFrameCount++; } else { if (++videoFrameCount >= 48) { long diffTimeMillis = System.nanoTime() / 1000000 - videoLastTimeMillis; mHandler.onRtmpOutputFps((double) videoFrameCount * 1000 / diffTimeMillis); mHandler.onRtmpVideoBitrate((double) videoDataLength * 8 * 1000 / diffTimeMillis); videoFrameCount = 0; videoDataLength = 0; } } } private void calcAudioBitrate(int length) { audioDataLength += length; if (audioFrameCount == 0) { audioLastTimeMillis = System.nanoTime() / 1000000; audioFrameCount++; } else { if (++audioFrameCount >= 48) { long diffTimeMillis = System.nanoTime() / 1000000 - audioLastTimeMillis; mHandler.onRtmpAudioBitrate((double) audioDataLength * 8 * 1000 / diffTimeMillis); audioFrameCount = 0; audioDataLength = 0; } } } private void sendRtmpPacket(RtmpPacket rtmpPacket) { try { ChunkStreamInfo chunkStreamInfo = rtmpSessionInfo.getChunkStreamInfo(rtmpPacket.getHeader().getChunkStreamId()); chunkStreamInfo.setPrevHeaderTx(rtmpPacket.getHeader()); if (!(rtmpPacket instanceof Video || rtmpPacket instanceof Audio)) { rtmpPacket.getHeader().setAbsoluteTimestamp((int) chunkStreamInfo.markAbsoluteTimestampTx()); } rtmpPacket.writeTo(outputStream, rtmpSessionInfo.getTxChunkSize(), chunkStreamInfo); Log.d(TAG, "wrote packet: " + rtmpPacket + ", size: " + rtmpPacket.getHeader().getPacketLength()); if (rtmpPacket instanceof Command) { rtmpSessionInfo.addInvokedCommand(((Command) rtmpPacket).getTransactionId(), ((Command) rtmpPacket).getCommandName()); } outputStream.flush(); } catch (SocketException se) { if (!socketExceptionCause.contentEquals(se.getMessage())) { socketExceptionCause = se.getMessage(); Log.e(TAG, "Caught SocketException during write loop, shutting down: " + se.getMessage()); Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), se); } } catch (IOException ioe) { Log.e(TAG, "Caught IOException during write loop, shutting down: " + ioe.getMessage()); Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), ioe); } } private void handleRxPacketLoop() throws IOException { // Handle all queued received RTMP packets while (!Thread.interrupted()) { try { // It will be blocked when no data in input stream buffer RtmpPacket rtmpPacket = rtmpDecoder.readPacket(inputStream); if (rtmpPacket != null) { //Log.d(TAG, "handleRxPacketLoop(): RTMP rx packet message type: " + rtmpPacket.getHeader().getMessageType()); switch (rtmpPacket.getHeader().getMessageType()) { case ABORT: rtmpSessionInfo.getChunkStreamInfo(((Abort) rtmpPacket).getChunkStreamId()).clearStoredChunks(); break; case USER_CONTROL_MESSAGE: UserControl user = (UserControl) rtmpPacket; switch (user.getType()) { case STREAM_BEGIN: if (currentStreamId != user.getFirstEventData()) { throw new IllegalStateException("Current stream ID error!"); } break; case PING_REQUEST: ChunkStreamInfo channelInfo = rtmpSessionInfo.getChunkStreamInfo(ChunkStreamInfo.RTMP_CID_PROTOCOL_CONTROL); Log.d(TAG, "handleRxPacketLoop(): Sending PONG reply.."); UserControl pong = new UserControl(user, channelInfo); sendRtmpPacket(pong); break; case STREAM_EOF: Log.i(TAG, "handleRxPacketLoop(): Stream EOF reached, closing RTMP writer..."); break; default: // Ignore... break; } break; case WINDOW_ACKNOWLEDGEMENT_SIZE: WindowAckSize windowAckSize = (WindowAckSize) rtmpPacket; int size = windowAckSize.getAcknowledgementWindowSize(); Log.d(TAG, "handleRxPacketLoop(): Setting acknowledgement window size: " + size); rtmpSessionInfo.setAcknowledgmentWindowSize(size); break; case SET_PEER_BANDWIDTH: SetPeerBandwidth bw = (SetPeerBandwidth) rtmpPacket; rtmpSessionInfo.setAcknowledgmentWindowSize(bw.getAcknowledgementWindowSize()); int acknowledgementWindowsize = rtmpSessionInfo.getAcknowledgementWindowSize(); ChunkStreamInfo chunkStreamInfo = rtmpSessionInfo.getChunkStreamInfo(ChunkStreamInfo.RTMP_CID_PROTOCOL_CONTROL); Log.d(TAG, "handleRxPacketLoop(): Send acknowledgement window size: " + acknowledgementWindowsize); sendRtmpPacket(new WindowAckSize(acknowledgementWindowsize, chunkStreamInfo)); // Set socket option socket.setSendBufferSize(acknowledgementWindowsize); break; case COMMAND_AMF0: handleRxInvoke((Command) rtmpPacket); break; default: Log.w(TAG, "handleRxPacketLoop(): Not handling unimplemented/unknown packet of type: " + rtmpPacket.getHeader().getMessageType()); break; } } } catch (EOFException eof) { Thread.currentThread().interrupt(); } catch (SocketException se) { Log.e(TAG, "Caught SocketException while reading/decoding packet, shutting down: " + se.getMessage()); Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), se); } catch (IOException ioe) { Log.e(TAG, "Caught exception while reading/decoding packet, shutting down: " + ioe.getMessage()); Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), ioe); } } } private void handleRxInvoke(Command invoke) throws IOException { String commandName = invoke.getCommandName(); if (commandName.equals("_result")) { // This is the result of one of the methods invoked by us String method = rtmpSessionInfo.takeInvokedCommand(invoke.getTransactionId()); Log.d(TAG, "handleRxInvoke: Got result for invoked method: " + method); if ("connect".equals(method)) { // Capture server ip/pid/id information if any srsServerInfo = onSrsServerInfo(invoke); // We can now send createStream commands connected = true; synchronized (connectingLock) { connectingLock.notifyAll(); } } else if ("createStream".contains(method)) { // Get stream id currentStreamId = (int) ((AmfNumber) invoke.getData().get(1)).getValue(); Log.d(TAG, "handleRxInvoke(): Stream ID to publish: " + currentStreamId); if (streamName != null && publishType != null) { fmlePublish(); } } else if ("releaseStream".contains(method)) { Log.d(TAG, "handleRxInvoke(): 'releaseStream'"); } else if ("FCPublish".contains(method)) { Log.d(TAG, "handleRxInvoke(): 'FCPublish'"); } else { Log.w(TAG, "handleRxInvoke(): '_result' message received for unknown method: " + method); } } else if (commandName.equals("onBWDone")) { Log.d(TAG, "handleRxInvoke(): 'onBWDone'"); } else if (commandName.equals("onFCPublish")) { Log.d(TAG, "handleRxInvoke(): 'onFCPublish'"); } else if (commandName.equals("onStatus")) { String code = ((AmfString) ((AmfObject) invoke.getData().get(1)).getProperty("code")).getValue(); Log.d(TAG, "handleRxInvoke(): onStatus " + code); if (code.equals("NetStream.Publish.Start")) { onMetaData(); // We can now publish AV data publishPermitted = true; synchronized (publishLock) { publishLock.notifyAll(); } } } else { Log.e(TAG, "handleRxInvoke(): Unknown/unhandled server invoke: " + invoke); } } private String onSrsServerInfo(Command invoke) { // SRS server special information AmfObject objData = (AmfObject) invoke.getData().get(1); if ((objData).getProperty("data") instanceof AmfObject) { objData = ((AmfObject) objData.getProperty("data")); serverIpAddr = (AmfString) objData.getProperty("srs_server_ip"); serverPid = (AmfNumber) objData.getProperty("srs_pid"); serverId = (AmfNumber) objData.getProperty("srs_id"); } String info = ""; info += serverIpAddr == null ? "" : " ip: " + serverIpAddr.getValue(); info += serverPid == null ? "" : " pid: " + (int) serverPid.getValue(); info += serverId == null ? "" : " id: " + (int) serverId.getValue(); return info; } @Override public AtomicInteger getVideoFrameCacheNumber() { return videoFrameCacheNumber; } @Override public EventHandler getEventHandler() { return mHandler; } @Override public final String getServerIpAddr() { return serverIpAddr == null ? null : serverIpAddr.getValue(); } @Override public final int getServerPid() { return serverPid == null ? 0 : (int) serverPid.getValue(); } @Override public final int getServerId() { return serverId == null ? 0 : (int) serverId.getValue(); } @Override public void setVideoResolution(int width, int height) { videoWidth = width; videoHeight = height; } }
package ru.adios.budgeter.util; import android.content.Context; import android.graphics.Canvas; import android.os.AsyncTask; import android.support.annotation.ColorInt; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.annotation.concurrent.NotThreadSafe; import java8.util.Optional; import java8.util.function.Consumer; import ru.adios.budgeter.R; import ru.adios.budgeter.api.OptLimit; import ru.adios.budgeter.api.Order; import ru.adios.budgeter.api.OrderBy; import ru.adios.budgeter.api.OrderedField; import ru.adios.budgeter.api.RepoOption; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; @NotThreadSafe public class DataTableLayout extends TableLayout { @ColorInt private static final int BORDERS_COLOR = 0xFF4CAC45; private static final int MAX_ROW_CAPACITY = 8; private static final int DEFAULT_PAGE_SIZE = 10; private static final int MIN_PAGE_SIZE = 5; private static final int MAX_PAGE_SIZE = 100; private DataStore dataStore; private int rowsPerSet; private int count; private Optional<Consumer<DataTableLayout>> listener = Optional.empty(); private Optional<String> tableName = Optional.empty(); private Optional<OrderResolver> orderResolver = Optional.empty(); private int pageSize = DEFAULT_PAGE_SIZE; private int currentPage; private OptLimit pageLimit; private Optional<OrderBy> orderBy = Optional.empty(); private boolean tablePopulated = false; private Optional<TableRow[]> columnsRow; private Optional<LinearLayout> titleView = Optional.empty(); private LinearLayout footer; private Button pressedButton; private int itemsPerInnerRow; private int itemsInFirstRow; private int headerOffset; private int knownWidth; private TextView selectedColumn; private boolean insidePageSize = false; private Optional<List<Integer>> spinnerContents = Optional.empty(); private Spinner pageSizeSpinner; private final OnClickListener buttonListener = new OnClickListener() { @Override public void onClick(View v) { pressedButton.setPressed(false); pressedButton.setClickable(true); pressedButton.invalidate(); final Button thisBtn = (Button) v; thisBtn.setClickable(false); thisBtn.setPressed(true); pressedButton = thisBtn; turnToPage(Integer.valueOf(thisBtn.getText().toString())); thisBtn.invalidate(); } }; private final OnClickListener rowOrderListener = new OnClickListener() { @Override public void onClick(View v) { if (orderResolver.isPresent()) { final TextView tv = (TextView) v; if (tv.isSelected()) { orderBy = Optional.of(orderBy.get().flipOrder()); } else { final Optional<OrderBy> possibleOrder = orderResolver.get().byColumnName(tv.getText().toString(), Order.DESC); if (!possibleOrder.isPresent()) { return; } orderBy = Optional.of(possibleOrder.get()); selectOrderByColumn(tv); } clearContents(); loadTableProcedures(); } } }; private int dp1; private int dp2; private int dp3; private int dp4; private int dp5; public DataTableLayout(Context context, AttributeSet attrs) { super(context, attrs); init(); } public DataTableLayout(Context context, int rowsPerSet, DataStore dataStore) { super(context); checkArgument(rowsPerSet >= 1, "rowsPerSet must be positive"); checkArgument(dataStore != null, "dataStore is null"); this.rowsPerSet = rowsPerSet; this.dataStore = dataStore; setId(ElementsIdProvider.getNextId()); init(); } public DataTableLayout(Context context, DataStore dataStore) { this(context, 1, dataStore); } public void start() { if (!tablePopulated) { if (getChildCount() == 0) { populateFraming(dataStore.getDataHeaders()); } loadDataAndPopulateTable(); } } public void repopulate() { if (tablePopulated) { clearContents(); } else { removeAllViews(); populateFraming(dataStore.getDataHeaders()); } loadDataAndPopulateTable(); } public void setTableName(String tableName) { this.tableName = Optional.of(tableName); } public void enableUserOrdering(OrderResolver orderResolver) { checkArgument(orderResolver != null, "orderResolver is null"); this.orderResolver = Optional.of(orderResolver); if (getChildCount() > 0) { final TableRow columnsRow = (TableRow) getChildAt(2); for (int i = 0; i < columnsRow.getChildCount(); i++) { final TextView col = (TextView) columnsRow.getChildAt(i); final String text = col.getText().toString(); if (!orderBy.isPresent()) { final Optional<OrderBy> possibleOrder = orderResolver.byColumnName(text, Order.DESC); if (!possibleOrder.isPresent()) { continue; } orderBy = Optional.of(possibleOrder.get()); selectOrderByColumn(col); if (tablePopulated) { clearContents(); loadTableProcedures(); } return; } if (text.equals(orderResolver.byField(orderBy.get().field).orElse(null))) { if (!col.isSelected()) { selectOrderByColumn(col); col.invalidate(); } break; } } } } public void disableUserOrdering() { orderResolver = Optional.empty(); if (getChildCount() > 0) { final TableRow columnsRow = (TableRow) getChildAt(2); for (int i = 0; i < columnsRow.getChildCount(); i++) { final View childAt = columnsRow.getChildAt(i); if (childAt.isSelected()) { childAt.setSelected(false); childAt.invalidate(); break; } } } } public void setOnDataLoadedListener(Consumer<DataTableLayout> listener) { this.listener = Optional.ofNullable(listener); } public void setPageSize(int pageSize) { if (insidePageSize) { return; } checkArgument(pageSize > 0, "Page size must be positive"); insidePageSize = true; try { if (pageSize == this.pageSize) { return; } this.pageSize = pageSize; if (spinnerContents.isPresent()) { final List<Integer> contents = spinnerContents.get(); if (!contents.contains(pageSize)) { contents.add(pageSize); Collections.sort(contents); pageSizeSpinner.setSelection(contents.indexOf(pageSize)); } } int page = 1; if (pageLimit != null && pageLimit.offset > 0) { page = pageLimit.offset / pageSize + 1; } turnToPage(page); if (footer != null) { footer.removeAllViews(); populateFooter(); } } finally { insidePageSize = false; } } public void setOrderBy(OrderBy orderBy) { checkState(!orderResolver.isPresent() || orderBy != null, "User ordering enabled, cannot set no ordering at all"); if ((this.orderBy.isPresent() && !this.orderBy.get().equals(orderBy)) || (!this.orderBy.isPresent() && orderBy != null)) { if (orderResolver.isPresent() && columnsRow.isPresent()) { final TableRow[] colsRow = columnsRow.get(); outer: for (final TableRow r : colsRow) { for (int j = 0; j < r.getChildCount(); j++) { final TextView col = (TextView) r.getChildAt(j); if (col.getText().toString().equals(orderResolver.get().byField(orderBy.field).orElse(null))) { if (!col.isSelected()) { selectOrderByColumn(col); } break outer; } } } } this.orderBy = Optional.ofNullable(orderBy); if (tablePopulated) { clearContents(); loadTableProcedures(); } } } private void init() { setWillNotDraw(false); if (!isInEditMode()) { final int setSize = dataStore.getDataHeaders().size(); checkArgument(setSize >= rowsPerSet, "Data store returned set size less than rowsPerSet provided in constructor"); itemsPerInnerRow = setSize / rowsPerSet; checkArgument(itemsPerInnerRow < MAX_ROW_CAPACITY, "Row appears to be too large: %s", itemsPerInnerRow); itemsInFirstRow = setSize % rowsPerSet + itemsPerInnerRow; checkArgument(itemsInFirstRow < MAX_ROW_CAPACITY, "First row appears to be too large: %s, while others are %s", itemsInFirstRow, itemsPerInnerRow); } } private void loadDataAndPopulateTable() { new AsyncTask<DataStore, Void, Integer>() { @Override protected Integer doInBackground(DataStore... params) { return params[0].count(); } @Override protected void onPostExecute(Integer c) { count = c; if (c == 0) { insertNoDataRow(); tablePopulated = true; if (listener.isPresent()) { listener.get().accept(DataTableLayout.this); } invalidate(); return; } turnToPage(1); if (c > pageSize) { final Context context = getContext(); if (tableName.isPresent()) { pageSizeSpinner = new Spinner(context, Spinner.MODE_DROPDOWN); pageSizeSpinner.setMinimumWidth(UiUtils.dpAsPixels(context, 70)); pageSizeSpinner.setId(ElementsIdProvider.getNextId()); final List<Integer> contents = getPageSpinnerContents(); spinnerContents = Optional.of(contents); pageSizeSpinner.setAdapter(new ArrayAdapter<>( context, android.R.layout.simple_spinner_item, android.R.id.text1, contents )); pageSizeSpinner.setSelection(contents.indexOf(pageSize)); pageSizeSpinner.setLayoutParams(new LinearLayout.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 2f)); pageSizeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { setPageSize((Integer) parent.getAdapter().getItem(position)); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); pageSizeSpinner.setVisibility(VISIBLE); if (!titleView.isPresent()) { addTitleRowWithSeparator(context, 10f, 8f); } else { titleView.get().setWeightSum(10f); titleView.get() .getChildAt(0) .setLayoutParams( new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 8f) ); } titleView.get().addView(pageSizeSpinner, 0); } final TableRow.LayoutParams fp = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 1f); fp.span = itemsPerInnerRow; footer.setLayoutParams(fp); footer.setVisibility(VISIBLE); populateFooter(); } loadTableProcedures(); } }.execute(dataStore); } private List<Integer> getPageSpinnerContents() { final ArrayList<Integer> list = new ArrayList<>(11); int curValue = 0, circle = 0, additive = MIN_PAGE_SIZE, min = Math.min(MAX_PAGE_SIZE, count); boolean foundCurPSize = false; while (curValue < min) { if (circle++ == 3) { additive *= 2; circle = 0; } final int c = curValue += additive; if (c == pageSize) { foundCurPSize = true; } list.add(c); } if (!foundCurPSize) { list.add(pageSize); Collections.sort(list); } return list; } private void turnToPage(int numPage) { checkArgument(numPage > 0, "page number must be positive"); currentPage = numPage; pageLimit = numPage == 1 ? OptLimit.createLimit(pageSize) : OptLimit.create(pageSize, pageSize * (numPage - 1)); if (tablePopulated) { clearContents(); loadTableProcedures(); } } private void clearContents() { for (int i = getChildCount() - 4; i >= headerOffset; i removeViewAt(i); } tablePopulated = false; } private void loadTableProcedures() { new AsyncTask<DataStore, Void, List<Iterable<String>>>() { @Override protected List<Iterable<String>> doInBackground(DataStore... params) { return orderBy.isPresent() ? params[0].loadData(pageLimit, orderBy.get()) : params[0].loadData(pageLimit); } @Override protected void onPostExecute(List<Iterable<String>> iterables) { int rowId = headerOffset; for (final Iterable<String> dataSet : iterables) { rowId = addDataRow(dataSet, rowId, Optional.<Consumer<TextView>>empty()); } tablePopulated = true; if (listener.isPresent()) { listener.get().accept(DataTableLayout.this); } invalidate(); } }.execute(dataStore); } private void populateFraming(List<String> headers) { final Context context = getContext(); addView(constructRowSeparator(1)); headerOffset++; if (tableName.isPresent()) { addTitleRowWithSeparator(context, 1f, 1f); } if (orderResolver.isPresent() && !orderBy.isPresent()) { for (final String h : headers) { final Optional<OrderBy> possibleOrder = orderResolver.get().byColumnName(h, Order.DESC); if (possibleOrder.isPresent()) { orderBy = Optional.of(possibleOrder.get()); break; } } } final int curHdrOff = headerOffset; headerOffset = addDataRow(headers, headerOffset, Optional.<Consumer<TextView>>of(new Consumer<TextView>() { @Override public void accept(TextView textView) { if (orderResolver.isPresent() && textView.getText().toString().equals(orderResolver.get().byField(orderBy.get().field).orElse(null))) { selectOrderByColumn(textView); } textView.setOnClickListener(rowOrderListener); } })); final int colArrLength = headerOffset - curHdrOff; final TableRow[] rArr = new TableRow[colArrLength]; for (int i = 0; i < colArrLength; i++) { rArr[i] = (TableRow) getChildAt(curHdrOff + i); } columnsRow = Optional.of(rArr); addView(constructRowSeparator(1)); final TableRow footerRow = constructRow(context, 1f); footer = new LinearLayout(context); final TableRow.LayoutParams fp = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, 0, 1f); fp.span = itemsPerInnerRow; footer.setLayoutParams(fp); footer.setBackgroundResource(R.drawable.cell_shape); footer.setOrientation(HORIZONTAL); footer.setVisibility(GONE); footerRow.addView(footer); addView(footerRow); addView(constructRowSeparator(1)); } private void addTitleRowWithSeparator(Context context, float layoutWeightSum, float titleViewWeight) { final TableRow tableNameRow = new TableRow(context); tableNameRow.setId(ElementsIdProvider.getNextId()); tableNameRow.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); tableNameRow.setWeightSum(1f); titleView = Optional.of(getCenteredRowText(context, tableName.get(), layoutWeightSum, true, titleViewWeight)); tableNameRow.addView(titleView.get()); addView(tableNameRow, 1); addView(constructRowSeparator(1), 2); headerOffset += 2; } private void selectOrderByColumn(TextView col) { if (selectedColumn != null) { selectedColumn.setSelected(false); selectedColumn.invalidate(); } col.setSelected(true); selectedColumn = col; } private LinearLayout getCenteredRowText(Context context, String text, float layoutWeightSum, boolean largeText, float textViewWeight) { final LinearLayout inner = new LinearLayout(context); final TableRow.LayoutParams innerParams = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 1f); innerParams.span = itemsPerInnerRow; inner.setLayoutParams(innerParams); inner.setWeightSum(layoutWeightSum); inner.setBackgroundResource(R.drawable.cell_shape); final TextView nameTextView = new TextView(context); nameTextView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, textViewWeight)); nameTextView.setTextAppearance(context, largeText ? android.R.style.TextAppearance_Large : android.R.style.TextAppearance_Medium); nameTextView.setText(text); nameTextView.setGravity(Gravity.CENTER); inner.addView(nameTextView); return inner; } private void insertNoDataRow() { final Context context = getContext(); final TableRow noDataRow = constructRow(context, 1f); noDataRow.addView(getCenteredRowText(context, getResources().getString(R.string.data_table_no_rows), 1f, false, 1f)); addView(noDataRow, headerOffset); } private int addDataRow(Iterable<String> dataSet, int rowId, Optional<Consumer<TextView>> optional) { final Context context = getContext(); if (rowsPerSet > 1) { addView(constructRowSeparator(rowsPerSet), rowId++); } int i = 0; boolean firstInner = true, fistRow = true; TableRow currentRow = constructRow(context, itemsInFirstRow * 2f); for (final String str : dataSet) { if (i > 0 && (fistRow ? i % itemsInFirstRow == 0 : i % itemsPerInnerRow == 0)) { i = 0; fistRow = false; addView(currentRow, rowId++); currentRow = constructRow(context, itemsPerInnerRow * 2f); firstInner = true; } final TextView textView; if (firstInner) { textView = createSpyingColumnForTableRow(str, rowId, 2f, context); firstInner = false; } else { textView = createColumnForTableRow(str, 2f, context); } final Optional<Integer> maxWidth = dataStore.getMaxWidthForData(i); if (maxWidth.isPresent()) { textView.setMaxWidth(UiUtils.dpAsPixels(context, maxWidth.get())); } if (optional.isPresent()) { optional.get().accept(textView); } currentRow.addView(textView); i++; } addView(currentRow, rowId++); return rowId; } private TextView createColumnForTableRow(String text, float weight, Context context) { final TextView view = new TextView(context); populateColumn(view, context, weight); view.setText(text); return view; } private TextView createSpyingColumnForTableRow(String text, final int rowId, final float weight, Context context) { final SpyingTextView view = new SpyingTextView(context); populateColumn(view, context, weight); view.heightCatch = true; view.setHeightRunnable(new Runnable() { @Override public void run() { final TableRow row = (TableRow) getChildAt(rowId); final int childCount = row.getChildCount(); int maxHeight = 0; for (int i = 0; i < childCount; i++) { final TextView childAt = (TextView) row.getChildAt(i); maxHeight = Math.max(maxHeight, childAt.getHeight()); } for (int i = 0; i < childCount; i++) { final TextView childAt = (TextView) row.getChildAt(i); childAt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, maxHeight, weight)); } invalidate(); } }); view.setText(text); return view; } private void populateColumn(TextView view, Context context, float weight) { view.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, weight)); view.setId(ElementsIdProvider.getNextId()); view.setBackground(ContextCompat.getDrawable(context, R.drawable.cell_shape)); final int fiveDp = getDpAsPixels(5, context); view.setPadding(fiveDp, fiveDp, fiveDp, fiveDp); view.setTextAppearance(context, android.R.style.TextAppearance_Small); } private TableRow constructRow(Context context, float weightSum) { final TableRow row = new TableRow(context); row.setId(ElementsIdProvider.getNextId()); row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); row.setWeightSum(weightSum); return row; } private View constructRowSeparator(int heightDp) { final Context context = getContext(); final View view = new View(context); view.setBackgroundColor(BORDERS_COLOR); view.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, getDpAsPixels(heightDp, context))); return view; } private void populateFooter() { if (knownWidth > 0 && footer != null && footer.getVisibility() == VISIBLE && footer.getChildCount() == 0) { final int maxButtons = knownWidth / UiUtils.dpAsPixels(getContext(), 20); final int numPages = count / pageSize + 1; final int numButtons = Math.min(maxButtons, numPages); if (numButtons > 1) { for (int i = -numButtons; i <= numButtons; i++) { int page = currentPage + i; if (page < 1 || page > numPages) { continue; } footer.addView(createButtonForFooter(page, page == currentPage)); } } else { footer.addView(createButtonForFooter(1, true)); } footer.invalidate(); } } private Button createButtonForFooter(int pageNum, boolean pressed) { final Button button = new Button(getContext()); button.setText(String.valueOf(pageNum)); if (pressed) { button.setClickable(false); button.setPressed(true); pressedButton = button; } button.setOnClickListener(buttonListener); return button; } private int getDpAsPixels(int dps, Context context) { switch (dps) { case 1: if (dp1 == 0) { dp1 = UiUtils.dpAsPixels(context, dps); } return dp1; case 2: if (dp2 == 0) { dp2 = UiUtils.dpAsPixels(context, dps); } return dp2; case 3: if (dp3 == 0) { dp3 = UiUtils.dpAsPixels(context, dps); } return dp3; case 4: if (dp4 == 0) { dp4 = UiUtils.dpAsPixels(context, dps); } return dp4; case 5: if (dp5 == 0) { dp5 = UiUtils.dpAsPixels(context, dps); } return dp5; default: return UiUtils.dpAsPixels(context, dps); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); dp1 = 0; dp2 = 0; dp3 = 0; dp4 = 0; dp5 = 0; } @Override protected void onDraw(Canvas canvas) { knownWidth = getWidth(); populateFooter(); super.onDraw(canvas); } public interface DataStore { /** * For execution in a separate thread. * @param options optional pagination for table to request. * @return data in string form. */ List<Iterable<String>> loadData(RepoOption... options); /** * For execution in a separate thread. * @return count of total data records. */ int count(); List<String> getDataHeaders(); Optional<Integer> getMaxWidthForData(int index); } public interface OrderResolver { Optional<OrderBy> byColumnName(String columnName, Order order); Optional<String> byField(OrderedField field); } }
package edu.umd.cs.findbugs; /** * Version number and release date information. */ public class Version { /** Major version number. */ public static final int MAJOR = 0; /** Minor version number. */ public static final int MINOR = 6; /** Patch level. */ public static final int PATCHLEVEL = 5; /** Release version string. */ public static final String RELEASE = MAJOR + "." + MINOR + "." + PATCHLEVEL; /** Release date. */ public static final String DATE = "August 22, 2003"; public static void main(String[] argv) { if (argv.length != 1) usage(); String arg = argv[0]; if (arg.equals("-release")) System.out.println(RELEASE); else if (arg.equals("-date")) System.out.println(DATE); else if (arg.equals("-props")) { System.out.println("release.number="+RELEASE); System.out.println("release.date="+DATE); } else usage(); } private static void usage() { System.err.println("Usage: " + Version.class.getName() + " (-release|-date|-props)"); System.exit(1); } } // vim:ts=4
package edu.umd.cs.findbugs; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; /** * Version number and release date information. */ public class Version { /** * Major version number. */ public static final int MAJOR = 1; /** * Minor version number. */ public static final int MINOR = 3; /** * Patch level. */ public static final int PATCHLEVEL = 5; /** * Development version or release candidate? */ public static final boolean IS_DEVELOPMENT = true; /** * Release candidate number. * "0" indicates that the version is not a release candidate. */ public static final int RELEASE_CANDIDATE = 0; /** * Release date. */ public static final String COMPUTED_DATE; public static final String DATE; public static final String COMPUTED_ECLIPSE_DATE; public static final String ECLIPSE_DATE; static { SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss z, dd MMMM, yyyy"); SimpleDateFormat eclipseDateFormat = new SimpleDateFormat("yyyyMMdd"); COMPUTED_DATE = dateFormat.format(new Date()); COMPUTED_ECLIPSE_DATE = eclipseDateFormat.format(new Date()) ; } /** * Preview release number. * "0" indicates that the version is not a preview release. */ public static final int PREVIEW = 0; private static final String RELEASE_SUFFIX_WORD = (RELEASE_CANDIDATE > 0 ? "rc" + RELEASE_CANDIDATE : (PREVIEW > 0 ? "preview" + PREVIEW : "dev-" + COMPUTED_ECLIPSE_DATE)); public static final String RELEASE_BASE = MAJOR + "." + MINOR + "." + PATCHLEVEL ; /** * Release version string. */ public static final String COMPUTED_RELEASE = RELEASE_BASE + (IS_DEVELOPMENT ? "-" + RELEASE_SUFFIX_WORD : ""); /** * Release version string. */ public static final String RELEASE; /** * Version of Eclipse plugin. */ public static final String COMPUTED_ECLIPSE_UI_VERSION = MAJOR + "." + MINOR + "." + PATCHLEVEL + "." + COMPUTED_ECLIPSE_DATE; public static final String ECLIPSE_UI_VERSION; static { InputStream in = null; String release, eclipse_ui_version, date, eclipseDate; try { Properties versionProperties = new Properties(); in = Version.class.getResourceAsStream("version.properties"); versionProperties.load(in); release = (String) versionProperties.get("release.number"); eclipse_ui_version = (String) versionProperties.get("eclipse.ui.version"); date = (String) versionProperties.get("release.date"); eclipseDate = (String) versionProperties.get("eclipse.date"); if (release == null) release = COMPUTED_RELEASE; if (eclipse_ui_version == null) eclipse_ui_version = COMPUTED_ECLIPSE_UI_VERSION; if (date == null) date = COMPUTED_DATE; if (eclipseDate == null) eclipseDate = COMPUTED_ECLIPSE_DATE; } catch (RuntimeException e) { release = COMPUTED_RELEASE; eclipse_ui_version = COMPUTED_ECLIPSE_UI_VERSION; date = COMPUTED_DATE; eclipseDate = COMPUTED_ECLIPSE_DATE; } catch (IOException e) { release = COMPUTED_RELEASE; eclipse_ui_version = COMPUTED_ECLIPSE_UI_VERSION; date = COMPUTED_DATE; eclipseDate = COMPUTED_ECLIPSE_DATE; } finally { try { if (in != null) in.close(); } catch (IOException e) { assert true; // nothing to do here } } RELEASE = release; ECLIPSE_UI_VERSION = eclipse_ui_version; DATE = date; ECLIPSE_DATE = eclipseDate; } /** * FindBugs website. */ public static final String WEBSITE = "http://findbugs.sourceforge.net"; /** * Downloads website. */ public static final String DOWNLOADS_WEBSITE = "http://prdownloads.sourceforge.net/findbugs"; /** * Support email. */ public static final String SUPPORT_EMAIL = "http://findbugs.sourceforge.net/reportingBugs.html"; public static void main(String[] argv) { if (argv.length != 1) usage(); String arg = argv[0]; if (!IS_DEVELOPMENT && RELEASE_CANDIDATE != 0) { throw new IllegalStateException("Non developmental version, but is release candidate " + RELEASE_CANDIDATE); } if (arg.equals("-release")) System.out.println(RELEASE); else if (arg.equals("-date")) System.out.println(DATE); else if (arg.equals("-props")) { System.out.println("release.number=" + COMPUTED_RELEASE); System.out.println("release.date=" + COMPUTED_DATE); System.out.println("eclipse.date=" + COMPUTED_ECLIPSE_DATE); System.out.println("eclipse.ui.version=" + COMPUTED_ECLIPSE_UI_VERSION); System.out.println("findbugs.website=" + WEBSITE); System.out.println("findbugs.downloads.website=" + DOWNLOADS_WEBSITE); } else { usage(); System.exit(1); } } private static void usage() { System.err.println("Usage: " + Version.class.getName() + " (-release|-date|-props)"); } } // vim:ts=4
package org.commcare.dalvik.dialogs; /** * @author amstone326 * * Any progress dialog associated with a CommCareTask should use * this class to implement the dialog. Any class that launches such a task * should implement the generateProgressDialog() method of the DialogController * interface, and create the dialog in that method. The rest of the dialog's * lifecycle is handled by methods of the DialogController interface that are * fully implemented in CommCareActivity */ import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.ProgressBar; import android.widget.TextView; import org.commcare.android.framework.CommCareActivity; import org.commcare.dalvik.R; public class CustomProgressDialog extends DialogFragment { //keys for onSaveInstanceState private final static String KEY_TITLE = "title"; private final static String KEY_MESSAGE = "message"; private final static String KEY_USING_CB = "using_checkbox"; private final static String KEY_IS_CHECKED = "is_checked"; private final static String KEY_CB_TEXT = "checkbox_text"; private final static String KEY_USING_BUTTON = "using_cancel_buton"; private final static String KEY_TASK_ID = "task_id"; private final static String KEY_CANCELABLE = "is_cancelable"; private final static String KEY_USING_PROGRESS_BAR = "using_progress_bar"; private final static String KEY_PROGRESS_BAR_PROGRESS = "progress_bar_progress"; private final static String KEY_PROGRESS_BAR_MAX = "progress_bar_max"; //id of the task that spawned this dialog, -1 if not associated with a CommCareTask private int taskId; //for all dialogs private String title; private String message; private boolean isCancelable; //default is false, only set to true if setCancelable() is explicitly called //for checkboxes private boolean usingCheckbox; private boolean isChecked; private String checkboxText; //for cancel button private boolean usingCancelButton; //for progress bar private boolean usingHorizontalProgressBar; private int progressBarProgress; private int progressBarMax; public static CustomProgressDialog newInstance(String title, String message, int taskId) { CustomProgressDialog frag = new CustomProgressDialog(); frag.setTitle(title); frag.setMessage(message); frag.setTaskId(taskId); return frag; } public void addCheckbox(String text, boolean isChecked) { this.usingCheckbox = true; this.checkboxText = text; this.isChecked = isChecked; } public void addCancelButton() { usingCancelButton = true; } public void setCancelable() { this.isCancelable = true; } public void addProgressBar() { this.usingHorizontalProgressBar = true; this.progressBarProgress = 0; this.progressBarMax = 0; } private void setTaskId(int id) { this.taskId = id; } public int getTaskId() { return taskId; } private void setTitle(String s) { this.title = s; } private void setMessage(String s) { this.message = s; } public boolean isChecked() { return isChecked; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); restoreFields(savedInstanceState); } private void restoreFields(Bundle savedInstanceState) { if (savedInstanceState != null) { this.title = savedInstanceState.getString(KEY_TITLE); this.message = savedInstanceState.getString(KEY_MESSAGE); this.usingCheckbox = savedInstanceState.getBoolean(KEY_USING_CB); this.isChecked = savedInstanceState.getBoolean(KEY_IS_CHECKED); this.checkboxText = savedInstanceState.getString(KEY_CB_TEXT); this.usingCancelButton = savedInstanceState.getBoolean(KEY_USING_BUTTON); this.taskId = savedInstanceState.getInt(KEY_TASK_ID); this.isCancelable = savedInstanceState.getBoolean(KEY_CANCELABLE); this.usingHorizontalProgressBar = savedInstanceState.getBoolean(KEY_USING_PROGRESS_BAR); this.progressBarProgress = savedInstanceState.getInt(KEY_PROGRESS_BAR_PROGRESS); this.progressBarMax = savedInstanceState.getInt(KEY_PROGRESS_BAR_MAX); } } @Override public void onDestroyView() { if (getDialog() != null && getRetainInstance()) { getDialog().setDismissMessage(null); } super.onDestroyView(); } /* Creates the dialog that will reside within the fragment */ @Override public Dialog onCreateDialog(Bundle savedInstanceState) { restoreFields(savedInstanceState); Context context = getActivity(); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setCancelable(isCancelable); View view; if (usingHorizontalProgressBar) { view = LayoutInflater.from(context).inflate(R.layout.progress_dialog_determinate, null); setupDeterminateView(view); } else { view = LayoutInflater.from(context).inflate(R.layout.progress_dialog_indeterminate, null); } TextView titleView = (TextView) view.findViewById(R.id.progress_dialog_title); titleView.setText(title); TextView messageView = (TextView) view.findViewById(R.id.progress_dialog_message); messageView.setText(message); if (usingCancelButton) { setupCancelButton(view); } builder.setView(view); Dialog d = builder.create(); d.setCanceledOnTouchOutside(isCancelable); return d; } private void setupDeterminateView(View view) { ProgressBar bar = (ProgressBar) view.findViewById(R.id.progress_bar_horizontal); bar.setProgress(progressBarProgress); bar.setMax(progressBarMax); if (usingCheckbox) { CheckBox cb = (CheckBox) view.findViewById(R.id.progress_dialog_checkbox); cb.setVisibility(View.VISIBLE); cb.setText(checkboxText); cb.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { isChecked = ((CheckBox)v).isChecked(); } }); if (isChecked) { cb.toggle(); } } } private void setupCancelButton(View v) { Button b = (Button) v.findViewById(R.id.dialog_cancel_button); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ((CommCareActivity)getActivity()).cancelCurrentTask(); } }); b.setVisibility(View.VISIBLE); } public void updateMessage(String text) { this.message = text; AlertDialog pd = (AlertDialog) getDialog(); if (pd != null) { TextView tv = (TextView) pd.findViewById(R.id.progress_dialog_message); tv.setText(this.message); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(KEY_TITLE, this.title); outState.putString(KEY_MESSAGE, this.message); outState.putBoolean(KEY_USING_CB, this.usingCheckbox); outState.putBoolean(KEY_IS_CHECKED, this.isChecked); outState.putString(KEY_CB_TEXT, this.checkboxText); outState.putBoolean(KEY_USING_BUTTON, this.usingCancelButton); outState.putInt(KEY_TASK_ID, this.taskId); outState.putBoolean(KEY_CANCELABLE, this.isCancelable); outState.putBoolean(KEY_USING_PROGRESS_BAR, this.usingHorizontalProgressBar); outState.putInt(KEY_PROGRESS_BAR_PROGRESS, this.progressBarProgress); outState.putInt(KEY_PROGRESS_BAR_MAX, this.progressBarMax); } public void updateProgressBar(int progress, int max) { this.progressBarProgress = progress; this.progressBarMax = max; Dialog dialog = getDialog(); if (dialog != null) { ProgressBar bar = (ProgressBar) dialog.findViewById(R.id.progress_bar_horizontal); bar.setProgress(progress); bar.setMax(max); } } }
package org.intermine.bio.web.export; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.log4j.Logger; import org.intermine.api.results.ResultElement; import org.intermine.bio.io.gff3.GFF3Record; import org.intermine.bio.ontology.SequenceOntology; import org.intermine.bio.ontology.SequenceOntologyFactory; import org.intermine.model.bio.SequenceFeature; import org.intermine.objectstore.ObjectStoreException; import org.intermine.pathquery.Path; import org.intermine.util.IntPresentSet; import org.intermine.util.PropertiesUtil; import org.intermine.web.logic.export.ExportException; import org.intermine.web.logic.export.ExportHelper; import org.intermine.web.logic.export.Exporter; /** * Exports LocatedSequenceFeature objects in GFF3 format. * @author Kim Rutherford * @author Jakub Kulaviak */ public class GFF3Exporter implements Exporter { private static final Logger LOG = Logger.getLogger(GFF3Exporter.class); /** * the fields we don't want to display as attributes */ public static final Set<String> GFF_FIELDS = Collections .unmodifiableSet(new HashSet<String>(Arrays.asList("chromosome.primaryIdentifier", "primaryIdentifier", "score"))); /** * for the gff header, link to taxomony */ public static final String WORM_LINK = "http: /** * for the gff header, link to taxomony */ public static final String FLY_LINK = "http: PrintWriter out; private List<Integer> featureIndexes; private Map<String, String> soClassNames; private int writtenResultsCount = 0; private boolean headerPrinted = false; private IntPresentSet exportedIds = new IntPresentSet(); private List<String> attributesNames; private String sourceName; private Set<Integer> organisms; // this one to store the lower case class names of soClassNames, // for comparison with path elements classes. private Set<String> cNames = new HashSet<String>(); private boolean makeUcscCompatible = false; /** * Constructor. * @param out output stream * @param indexes index of column with exported sequence * @param soClassNames mapping * @param attributesNames names of attributes that are printed in record, * they are names of columns in results table, they are in the same order * as corresponding columns in results table * @param sourceName name of Mine to put in GFF source column * @param organisms taxon id of the organisms * @param makeUcscCompatible true if chromosome ids should be prefixed by 'chr' */ public GFF3Exporter(PrintWriter out, List<Integer> indexes, Map<String, String> soClassNames, List<String> attributesNames, String sourceName, Set<Integer> organisms, boolean makeUcscCompatible) { this.out = out; this.featureIndexes = indexes; this.soClassNames = soClassNames; this.attributesNames = attributesNames; this.sourceName = sourceName; this.organisms = organisms; this.makeUcscCompatible = makeUcscCompatible; for (String s : soClassNames.keySet()) { this.cNames.add(s.toLowerCase()); } } /** * to read genome and project versions * @return header further info about versions */ private String getHeaderParts() { StringBuffer header = new StringBuffer(); Properties props = PropertiesUtil.getProperties(); if (organisms != null) { for (Integer taxId : organisms) { if (taxId == 7227) { String fV = props.getProperty("genomeVersion.fly"); if (fV != null && fV.length() > 0) { header.append("\n##species " + FLY_LINK); header.append("\n##genome-build FlyBase r" + fV); } } } for (Integer taxId : organisms) { if (taxId == 6239) { String wV = props.getProperty("genomeVersion.worm"); if (wV != null && wV.length() > 0) { header.append("\n##species " + WORM_LINK); header.append("\n##genome-build WormBase ws" + wV); } } } // display only if organism is set String mV = props.getProperty("project.releaseVersion"); if (mV != null && mV.length() > 0) { header.append("\n#" + this.sourceName + " " + mV); header.append("\n# #index-subfeatures 1"); } } return header.toString(); } private String getHeader() { return "##gff-version 3" + getHeaderParts(); } /** * {@inheritDoc} */ public void export(Iterator<? extends List<ResultElement>> resultIt, Collection<Path> unionPathCollection, Collection<Path> newPathCollection) { if (featureIndexes.size() == 0) { throw new ExportException("No columns with sequence"); } try { // LOG.info("SOO:" + cNames.toString()); while (resultIt.hasNext()) { List<ResultElement> row = resultIt.next(); exportRow(row, unionPathCollection, newPathCollection); } finishLastRow(); if (writtenResultsCount == 0) { out.println("Nothing was found for export"); } out.flush(); } catch (Exception ex) { throw new ExportException("Export failed", ex); } } @Override public void export(Iterator<? extends List<ResultElement>> resultIt) { export(resultIt, Collections.EMPTY_LIST, Collections.EMPTY_LIST); } /* State for the exportRow method, to allow several rows to be merged. */ private Map<String, Integer> attributeVersions = new HashMap<String, Integer>(); private Integer lastLsfId = null; private SequenceFeature lastLsf = null; private Map<String, List<String>> attributes = null; private Map<String, Set<Integer>> seenAttributes = new HashMap<String, Set<Integer>>(); private void exportRow(List<ResultElement> row, Collection<Path> unionPathCollection, Collection<Path> newPathCollection) throws ObjectStoreException, IllegalAccessException { List<ResultElement> elWithObject = getResultElements(row); if (elWithObject == null) { return; } SequenceOntology so = SequenceOntologyFactory.getSequenceOntology(); Map<Integer, ResultsCell> resultsCells = new HashMap<Integer, ResultsCell>(); Map<String, Set<String>> classToParents = new HashMap<String, Set<String>>(); Set<String> classesInResults = new HashSet<String>(); if (so != null) { classesInResults.addAll(getCellTypes(elWithObject, so, resultsCells, classToParents)); } for (ResultElement re : elWithObject) { try { SequenceFeature lsf = (SequenceFeature) re.getObject(); if (exportedIds.contains(lsf.getId()) && !(lsf.getId().equals(lastLsfId))) { // TODO it's hard to add multiple parents to a feature, e.g. exon -> transcript, // since a feature can only be exported once, but parents need to be added up. continue; } // processing parent for last cell if ((lastLsfId != null) && !(lsf.getId().equals(lastLsfId))) { processParent(resultsCells, classToParents, classesInResults); makeRecord(); } if (lastLsfId == null) { attributes = new LinkedHashMap<String, List<String>>(); } List<ResultElement> newRow = filterResultRow(row, unionPathCollection, newPathCollection); boolean isCollection = re.getPath().containsCollections(); for (int i = 0; i < newRow.size(); i++) { ResultElement el = newRow.get(i); if (el == null) { continue; } // checks for attributes: if (isCollection && !el.getPath().containsCollections()) { // one is collection, the other is not: do not show continue; } if (!isCollection && el.getPath().containsCollections() && soClassNames.containsKey(el.getType())) { // show attributes only if they are not linked to features // (they will be displayed with the relevant one, see below) continue; } if (isCollection && el.getPath().containsCollections()) { // show only if of the same class Class<?> reType = re.getPath().getLastClassDescriptor().getType(); Class<?> elType = el.getPath().getLastClassDescriptor().getType(); if (!reType.isAssignableFrom(elType)) { continue; } } if ("location".equalsIgnoreCase(el.getPath() .getLastClassDescriptor().getUnqualifiedName())) { // don't show locations (they are already displayed parts of the element) continue; } if (el.getField() != null) { String unqualName = el.getPath() .getLastClassDescriptor().getUnqualifiedName(); String attributeName = trimAttribute(attributesNames.get(i), unqualName); checkAttribute(el, attributeName); } } lastLsfId = lsf.getId(); lastLsf = lsf; } catch (Exception ex) { LOG.error("Failed to write GFF3 file: " + ex); continue; } } } private Set<String> getCellTypes(List<ResultElement> elWithObject, SequenceOntology so, Map<Integer, ResultsCell> resultsCells, Map<String, Set<String>> classToParents) { Set<String> classesInResults = new HashSet<String>(); for (ResultElement el : elWithObject) { String className = null; if (el == null) { continue; } className = el.getPath().getLastClassDescriptor().getUnqualifiedName().toLowerCase(); classesInResults.add(className); Integer id = ((SequenceFeature) el.getObject()).getId(); ResultsCell cell = new ResultsCell(id, className, el); resultsCells.put(id, cell); if (classToParents.get(className) == null) { Set<String> parents = so.getAllPartOfs(className); classToParents.put(className, parents); } } return classesInResults; } private void processParent(Map<Integer, ResultsCell> resultsCells, Map<String, Set<String>> classToParents, Set<String> classesInResults) { String parent = null; ResultsCell r = resultsCells.get(lastLsf); if (r == null) { return; } // class name of the object in the cell String className = r.className; // list of parents for the object in the cell Set<String> parents = classToParents.get(className); if (parents != null) { for (String parentType : parents) { // if we have any of these type if (classesInResults.contains(parentType)) { // get parent ResultElement parentResultElment = r.re; parent = ((SequenceFeature) parentResultElment.getObject()) .getPrimaryIdentifier(); break; } } } if (parent != null) { List<String> addPar = new ArrayList<String>(); addPar.add(parent); attributes.put("Parent", addPar); } } private String trimAttribute(String attribute, String unqualName) { if (!attribute.contains(".")) { return attribute; } // check if a feature attribute (display only name) or not (display all path) if (cNames.contains(unqualName.toLowerCase())) { String plainAttribute = attribute.substring(attribute.lastIndexOf('.') + 1); // LOG.info("LCC: " +attribute+"->"+unqualName +"|"+ plainAttribute ); return plainAttribute; } // LOG.info("LCCno: " + attribute + "|" + unqualName); return attribute; } private void makeRecord() { GFF3Record gff3Record = GFF3Util.makeGFF3Record(lastLsf, soClassNames, sourceName, attributes, makeUcscCompatible); if (gff3Record != null) { // have a chromosome ref and chromosomeLocation ref if (!headerPrinted) { out.println(getHeader()); headerPrinted = true; } out.println(gff3Record.toGFF3()); exportedIds.add(lastLsf.getId()); writtenResultsCount++; } lastLsfId = null; attributeVersions.clear(); seenAttributes.clear(); } /** * @param el * @param attributeName */ private void checkAttribute(ResultElement el, String attributeName) { if (!GFF_FIELDS.contains(attributeName)) { Set<Integer> seenAttributeValues = seenAttributes.get(attributeName); if (seenAttributeValues == null) { seenAttributeValues = new HashSet<Integer>(); seenAttributes.put(attributeName, seenAttributeValues); } if (!seenAttributeValues.contains(el.getId())) { seenAttributeValues.add(el.getId()); Integer version = attributeVersions.get(attributeName); if (version == null) { version = new Integer(1); attributes.put(attributeName, formatElementValue(el)); } else { attributes.put(attributeName + version, formatElementValue(el)); } attributeVersions.put(attributeName, new Integer(version.intValue() + 1)); } } } private List<String> formatElementValue(ResultElement el) { List<String> ret = new ArrayList<String>(); String s; if (el == null) { s = "-"; } else { Object obj = el.getField(); if (obj == null) { s = "-"; } else { s = obj.toString(); } } ret.add(s); return ret; } private List<ResultElement> getResultElements(List<ResultElement> row) { List<ResultElement> els = new ArrayList<ResultElement>(); for (Integer index : featureIndexes) { if (row.get(index) != null) { els.add(row.get(index)); } } return els; } /** * {@inheritDoc} */ public boolean canExport(List<Class<?>> clazzes) { return canExportStatic(clazzes); } /* Method must have different name than canExport because canExport() method * is inherited from Exporter interface */ /** * @param clazzes classes of result row * @return true if this exporter can export result composed of specified classes */ public static boolean canExportStatic(List<Class<?>> clazzes) { return ExportHelper.getClassIndex(clazzes, SequenceFeature.class) >= 0; } /** * {@inheritDoc} */ public int getWrittenResultsCount() { return writtenResultsCount; } private void finishLastRow() { GFF3Record gff3Record = GFF3Util.makeGFF3Record(lastLsf, soClassNames, sourceName, attributes, makeUcscCompatible); if (gff3Record != null) { // have a chromsome ref and chromosomeLocation ref if (!headerPrinted) { out.println(getHeader()); headerPrinted = true; } out.println(gff3Record.toGFF3()); writtenResultsCount++; } lastLsfId = null; } /** * Remove the elements from row which are not in pathCollection * @param row * @param pathCollection * @return */ private List<ResultElement> filterResultRow(List<ResultElement> row, Collection<Path> unionPathCollection, Collection<Path> newPathCollection) { List<ResultElement> newRow = new ArrayList<ResultElement>(); if (newPathCollection != null && unionPathCollection.containsAll(newPathCollection)) { for (Path p : newPathCollection) { ResultElement el = row.get(((List<Path>) unionPathCollection).indexOf(p)); if (el != null) { newRow.add(el); } else { newRow.add(null); } } return newRow; } else { throw new RuntimeException("pathCollection: " + newPathCollection + ", elPathList contains pathCollection: " + unionPathCollection.containsAll(newPathCollection)); } } /** * Represents a cell in the results table */ public class ResultsCell { protected Integer intermineId; protected String className; protected ResultElement re; /** * Constructor * * @param intermineId ID for intermine object * @param className name of type, eg. gene or exon * @param re results element */ public ResultsCell(Integer intermineId, String className, ResultElement re) { this.intermineId = intermineId; this.className = className; this.re = re; } } }
package org.hd.d.edh; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; /**Graphics utilities, eg generating Web-friendly output icons/buttons/etc. */ public final class GraphicsUtils { /**Prevent creation of an instance. */ private GraphicsUtils() { } /**Minimum simple icon size (both dimensions) in pixels; strictly positive. */ public static final int MIN_ICON_SIZE_PX = 32; /**Write a simple PNG icon containing the current intensity and with the current traffic-light colour; never null. * This attempts to update the output atomically and leaving it globally readable at all times. * * The current intensity is usually expected to be (well) within the range [0,1000], * but this routine will attempt to behave gracefully for values &ge;1000. * * @param basename base path including file name stub at which icon is to be written; never null * @param sizePX icon output size (each side) in pixels; strictly positive and no less than MIN_ICON_SIZE_PX * @param status traffic-light status; null for unknown * @param currentIntensity current grid intensity in gCO2/kWh (kgCO2/MWh); non-negative * @return URL-friendly pure-printable-ASCII (no-'/') extension to add to basename for where PNG is written (does not vary with status/intensity arguments); never null nor empty. */ public static String writeSimpleIntensityIconPNG(final File basename, final int sizePX, final TrafficLight status, final int currentIntensity) throws IOException { if(null == basename) { throw new IllegalArgumentException(); } if(sizePX < MIN_ICON_SIZE_PX) { throw new IllegalArgumentException(); } if(currentIntensity < 0) { throw new IllegalArgumentException(); } final BufferedImage buffer = new BufferedImage(sizePX, sizePX, BufferedImage.TYPE_INT_RGB); final Graphics2D g = buffer.createGraphics(); try { Color bgColour = Color.WHITE; if(null != status) { switch(status) { case RED: bgColour = new Color(0xffcccc); break; case GREEN: bgColour = new Color(0xccffcc); break; case YELLOW: bgColour = new Color(0xffffcc); break; } } g.setColor(bgColour); g.fillRect(0,0,sizePX,sizePX); // TODO } finally { g.dispose(); } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(buffer, "png", baos); final String suffix = "intico1-" + sizePX + ".png"; DataUtils.replacePublishedFile(basename.getPath() + suffix, baos.toByteArray()); return(suffix); } }