answer
stringlengths
17
10.2M
package com.thaiopensource.validate; import com.thaiopensource.util.PropertyId; import com.thaiopensource.util.PropertyMap; import com.thaiopensource.util.PropertyMapBuilder; import com.thaiopensource.xml.sax.XMLReaderCreator; import org.xml.sax.ErrorHandler; import org.xml.sax.EntityResolver; /** * Provides common properties to control reading schemas and validation. * * @see Schema#createValidator * @see SchemaReader#createSchema * @see PropertyMap * @see PropertyId * @see com.thaiopensource.validate.rng.RngProperty * @see com.thaiopensource.validate.schematron.SchematronProperty */ public class ValidateProperty { /** * Property specifying ErrorHandler to be used for reporting errors. The value * to which this PropertyId maps must be an instance of ErrorHandler. * * @see ErrorHandler */ public static final ErrorHandlerPropertyId ERROR_HANDLER = new ErrorHandlerPropertyId("ERROR_HANDLER"); /** * Property specifying EntityResolver to be used for resolving entities. The value * to which this PropertyId maps must be an instance of EntityResolver. * * @see EntityResolver */ public static final EntityResolverPropertyId ENTITY_RESOLVER = new EntityResolverPropertyId("ENTITY_RESOLVER"); /** * Property specifying XMLReaderCreator used to create XMLReader objects needed for * parsing XML documents. The value to which this PropertyId maps must be an * instance of XMLReaderCreator. */ public static final XMLReaderCreatorPropertyId XML_READER_CREATOR = new XMLReaderCreatorPropertyId("XML_READER_CREATOR"); private ValidateProperty() { } /** * A PropertyId whose value is constrained to be an instance of * ErrorHandler. * * @see ErrorHandler */ public static class ErrorHandlerPropertyId extends PropertyId { public ErrorHandlerPropertyId(String name) { super(name, ErrorHandler.class); } /** * Returns the value of the property. This is a typesafe * version of <code>PropertyMap.get</code>. * * @param properties the PropertyMap to be used * @return the ErrorHandler to which the PropertyMap maps this PropertyId, * or <code>null</code> if this PropertyId is not in the PropertyMap * @see PropertyMap#get */ public ErrorHandler get(PropertyMap properties) { return (ErrorHandler)properties.get(this); } /** * Sets the value of the property. Modifies the PropertyMapBuilder * so that this PropertyId is mapped to the specified value. This * is a typesafe version of PropertyMapBuilder.put. * * @param builder the PropertyMapBuilder to be modified * @param value the ErrorHandler to which this PropertyId is to be mapped * @return the ErrorHandler to which this PropertyId was mapped before, * or <code>null</code> if it was not mapped * * @see PropertyMapBuilder#put */ public ErrorHandler put(PropertyMapBuilder builder, ErrorHandler value) { return (ErrorHandler)builder.put(this, value); } } /** * A PropertyId whose value is constrained to be an instance of * EntityResolver. * * @see EntityResolver */ public static class EntityResolverPropertyId extends PropertyId { public EntityResolverPropertyId(String name) { super(name, EntityResolver.class); } /** * Returns the value of the property. This is a typesafe * version of <code>PropertyMap.get</code>. * * @param properties the PropertyMap to be used * @return the EntityResolver to which the PropertyMap maps this PropertyId, * or <code>null</code> if this PropertyId is not in the PropertyMap * @see PropertyMap#get */ public EntityResolver get(PropertyMap properties) { return (EntityResolver)properties.get(this); } /** * Sets the value of the property. Modifies the PropertyMapBuilder * so that this PropertyId is mapped to the specified value. This * is a typesafe version of PropertyMapBuilder.put. * * @param builder the PropertyMapBuilder to be modified * @param value the EntityResolver to which this PropertyId is to be mapped * @return the EntityResolver to which this PropertyId was mapped before, * or <code>null</code> if it was not mapped * * @see PropertyMapBuilder#put */ public EntityResolver put(PropertyMapBuilder builder, EntityResolver value) { return (EntityResolver)builder.put(this, value); } } /** * A PropertyId whose value is constrained to be an instance of * XMLReaderCreator. * * @see XMLReaderCreator */ public static class XMLReaderCreatorPropertyId extends PropertyId { public XMLReaderCreatorPropertyId(String name) { super(name, XMLReaderCreator.class); } /** * Returns the value of the property. This is a typesafe * version of <code>PropertyMap.get</code>. * * @param properties the PropertyMap to be used * @return the XMLReaderCreator to which the PropertyMap maps this PropertyId, * or <code>null</code> if this PropertyId is not in the PropertyMap * @see PropertyMap#get */ public XMLReaderCreator get(PropertyMap properties) { return (XMLReaderCreator)properties.get(this); } /** * Sets the value of the property. Modifies the PropertyMapBuilder * so that this PropertyId is mapped to the specified value. This * is a typesafe version of PropertyMapBuilder.put. * * @param builder the PropertyMapBuilder to be modified * @param value the XMLReaderCreator to which this PropertyId is to be mapped * @return the XMLReaderCreator to which this PropertyId was mapped before, * or <code>null</code> if it was not mapped * * @see PropertyMapBuilder#put */ public XMLReaderCreator put(PropertyMapBuilder builder, XMLReaderCreator value) { return (XMLReaderCreator)builder.put(this, value); } } }
package com.github.twitch4j.pubsub; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.github.philippheuer.credentialmanager.domain.OAuth2Credential; import com.github.philippheuer.events4j.core.EventManager; import com.github.twitch4j.common.annotation.Unofficial; import com.github.twitch4j.common.enums.CommandPermission; import com.github.twitch4j.common.events.domain.EventUser; import com.github.twitch4j.common.events.user.PrivateMessageEvent; import com.github.twitch4j.common.util.CryptoUtils; import com.github.twitch4j.common.util.TimeUtils; import com.github.twitch4j.common.util.TwitchUtils; import com.github.twitch4j.common.util.TypeConvert; import com.github.twitch4j.pubsub.domain.*; import com.github.twitch4j.pubsub.enums.PubSubType; import com.github.twitch4j.pubsub.enums.TMIConnectionState; import com.github.twitch4j.pubsub.events.*; import com.neovisionaries.ws.client.WebSocket; import com.neovisionaries.ws.client.WebSocketAdapter; import com.neovisionaries.ws.client.WebSocketFactory; import com.neovisionaries.ws.client.WebSocketFrame; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; import lombok.Synchronized; import lombok.extern.slf4j.Slf4j; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.GregorianCalendar; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * Twitch PubSub */ @Slf4j public class TwitchPubSub implements AutoCloseable { /** * EventManager */ @Getter private final EventManager eventManager; /** * The WebSocket Server */ private static final String WEB_SOCKET_SERVER = "wss://pubsub-edge.twitch.tv:443"; /** * WebSocket Client */ @Setter(AccessLevel.NONE) private volatile WebSocket webSocket; /** * The connection state * Default: ({@link TMIConnectionState#DISCONNECTED}) */ private volatile TMIConnectionState connectionState = TMIConnectionState.DISCONNECTED; /** * Command Queue Thread */ protected final Future<?> queueTask; /** * Heartbeat Thread */ protected final Future<?> heartbeatTask; /** * is Closed? */ protected volatile boolean isClosed = false; /** * Command Queue */ protected final BlockingQueue<String> commandQueue = new ArrayBlockingQueue<>(200); /** * Holds the subscribed topics in case we need to reconnect */ protected final Set<PubSubRequest> subscribedTopics = ConcurrentHashMap.newKeySet(); /** * Last Ping send (1 minute delay before sending the first ping) */ protected volatile long lastPing = TimeUtils.getCurrentTimeInMillis() - 4 * 60 * 1000; /** * Last Pong received */ protected volatile long lastPong = TimeUtils.getCurrentTimeInMillis(); /** * Thread Pool Executor */ protected final ScheduledExecutorService taskExecutor; /** * Constructor * * @param eventManager EventManager * @param taskExecutor ScheduledThreadPoolExecutor */ public TwitchPubSub(EventManager eventManager, ScheduledThreadPoolExecutor taskExecutor) { this.taskExecutor = taskExecutor; this.eventManager = eventManager; // register with serviceMediator this.eventManager.getServiceMediator().addService("twitch4j-pubsub", this); // connect this.connect(); // Run heartbeat every 4 minutes heartbeatTask = taskExecutor.scheduleAtFixedRate(() -> { if (isClosed) return; PubSubRequest request = new PubSubRequest(); request.setType(PubSubType.PING); sendCommand(TypeConvert.objectToJson(request)); log.debug("PubSub: Sending PING!"); lastPing = TimeUtils.getCurrentTimeInMillis(); }, 0, 4L, TimeUnit.MINUTES); // queue command worker this.queueTask = taskExecutor.schedule(() -> { while (!isClosed) { try { // check for missing pong response if (TimeUtils.getCurrentTimeInMillis() >= lastPing + 10000 && lastPong < lastPing) { log.warn("PubSub: Didn't receive a PONG response in time, reconnecting to obtain a connection to a different server."); reconnect(); } // If connected, send one message from the queue String command = commandQueue.poll(1000L, TimeUnit.MILLISECONDS); if (command != null) { if (connectionState.equals(TMIConnectionState.CONNECTED)) { sendCommand(command); // Logging log.debug("Processed command from queue: [{}].", command); } } } catch (Exception ex) { log.error("PubSub: Unexpected error in worker thread", ex); } } }, 1L, TimeUnit.MILLISECONDS); log.debug("PubSub: Started Queue Worker Thread"); } /** * Connecting to IRC-WS */ @Synchronized public void connect() { if (connectionState.equals(TMIConnectionState.DISCONNECTED) || connectionState.equals(TMIConnectionState.RECONNECTING)) { try { // Change Connection State connectionState = TMIConnectionState.CONNECTING; // Recreate Socket if state does not equal CREATED createWebSocket(); // Connect to IRC WebSocket this.webSocket.connect(); } catch (Exception ex) { log.error("PubSub: Connection to Twitch PubSub failed: {} - Retrying ...", ex.getMessage()); // Sleep 1 second before trying to reconnect try { TimeUnit.SECONDS.sleep(1L); } catch (Exception ignored) { } finally { // reconnect reconnect(); } } } } /** * Disconnecting from WebSocket */ @Synchronized public void disconnect() { if (connectionState.equals(TMIConnectionState.CONNECTED)) { connectionState = TMIConnectionState.DISCONNECTING; } connectionState = TMIConnectionState.DISCONNECTED; // CleanUp this.webSocket.clearListeners(); this.webSocket.disconnect(); this.webSocket = null; } /** * Reconnecting to WebSocket */ @Synchronized public void reconnect() { connectionState = TMIConnectionState.RECONNECTING; disconnect(); connect(); } /** * Recreate the WebSocket and the listeners */ @Synchronized private void createWebSocket() { try { // WebSocket this.webSocket = new WebSocketFactory().createSocket(WEB_SOCKET_SERVER); // WebSocket Listeners this.webSocket.clearListeners(); this.webSocket.addListener(new WebSocketAdapter() { @Override public void onConnected(WebSocket ws, Map<String, List<String>> headers) { log.info("Connecting to Twitch PubSub {}", WEB_SOCKET_SERVER); // Connection Success connectionState = TMIConnectionState.CONNECTED; log.info("Connected to Twitch PubSub {}", WEB_SOCKET_SERVER); // resubscribe to all topics after disconnect subscribedTopics.forEach(topic -> listenOnTopic(topic)); } @Override public void onTextMessage(WebSocket ws, String text) { try { log.trace("Received WebSocketMessage: " + text); // parse message PubSubResponse message = TypeConvert.jsonToObject(text, PubSubResponse.class); if (message.getType().equals(PubSubType.MESSAGE)) { String topic = message.getData().getTopic(); String type = message.getData().getMessage().getType(); JsonNode msgData = message.getData().getMessage().getMessageData(); String rawMessage = message.getData().getMessage().getRawMessage(); // Handle Messages if (topic.startsWith("channel-bits-events-v2")) { eventManager.publish(new ChannelBitsEvent(TypeConvert.convertValue(msgData, ChannelBitsData.class))); } else if (topic.startsWith("channel-bits-badge-unlocks")) { eventManager.publish(new ChannelBitsBadgeUnlockEvent(TypeConvert.jsonToObject(rawMessage, BitsBadgeData.class))); } else if (topic.startsWith("channel-subscribe-events-v1")) { eventManager.publish(new ChannelSubscribeEvent(TypeConvert.jsonToObject(rawMessage, SubscriptionData.class))); } else if (topic.startsWith("channel-commerce-events-v1")) { eventManager.publish(new ChannelCommerceEvent(TypeConvert.jsonToObject(rawMessage, CommerceData.class))); } else if (topic.startsWith("whispers") && (type.equals("whisper_sent") || type.equals("whisper_received"))) { // Whisper data is escaped Json cast into a String JsonNode msgDataParsed = TypeConvert.jsonToObject(msgData.asText(), JsonNode.class); //TypeReference<T> allows type parameters (unlike Class<T>) and avoids needing @SuppressWarnings("unchecked") Map<String, Object> tags = TypeConvert.convertValue(msgDataParsed.path("tags"), new TypeReference<Map<String, Object>>() {}); String fromId = msgDataParsed.get("from_id").asText(); String displayName = (String) tags.get("display_name"); EventUser eventUser = new EventUser(fromId, displayName); String body = msgDataParsed.get("body").asText(); Set<CommandPermission> permissions = TwitchUtils.getPermissionsFromTags(tags); PrivateMessageEvent privateMessageEvent = new PrivateMessageEvent(eventUser, body, permissions); eventManager.publish(privateMessageEvent); } else if (topic.startsWith("community-points-channel-v1")) { String timestampText = msgData.path("timestamp").asText(); Instant instant = Instant.parse(timestampText); Calendar timestamp = GregorianCalendar.from( ZonedDateTime.ofInstant( instant, ZoneId.systemDefault() ) ); switch (type) { case "reward-redeemed": ChannelPointsRedemption redemption = TypeConvert.convertValue(msgData.path("redemption"), ChannelPointsRedemption.class); eventManager.publish(new RewardRedeemedEvent(timestamp, redemption)); break; case "redemption-status-update": ChannelPointsRedemption updatedRedemption = TypeConvert.convertValue(msgData.path("redemption"), ChannelPointsRedemption.class); eventManager.publish(new RedemptionStatusUpdateEvent(timestamp, updatedRedemption)); break; case "custom-reward-created": ChannelPointsReward newReward = TypeConvert.convertValue(msgData.path("new_reward"), ChannelPointsReward.class); eventManager.publish(new CustomRewardCreatedEvent(instant, newReward)); break; case "custom-reward-updated": ChannelPointsReward updatedReward = TypeConvert.convertValue(msgData.path("updated_reward"), ChannelPointsReward.class); eventManager.publish(new CustomRewardUpdatedEvent(instant, updatedReward)); break; case "custom-reward-deleted": ChannelPointsReward deletedReward = TypeConvert.convertValue(msgData.path("deleted_reward"), ChannelPointsReward.class); eventManager.publish(new CustomRewardDeletedEvent(instant, deletedReward)); break; case "update-redemption-statuses-progress": RedemptionProgress redemptionProgress = TypeConvert.convertValue(msgData.path("progress"), RedemptionProgress.class); eventManager.publish(new UpdateRedemptionProgressEvent(instant, redemptionProgress)); break; case "update-redemption-statuses-finished": RedemptionProgress redemptionFinished = TypeConvert.convertValue(msgData.path("progress"), RedemptionProgress.class); eventManager.publish(new UpdateRedemptionFinishedEvent(instant, redemptionFinished)); break; default: log.warn("Unparseable Message: " + message.getType() + "|" + message.getData()); break; } } else if (topic.startsWith("raid")) { switch (type) { case "raid_go_v2": eventManager.publish(TypeConvert.jsonToObject(rawMessage, RaidGoEvent.class)); break; case "raid_update_v2": eventManager.publish(TypeConvert.jsonToObject(rawMessage, RaidUpdateEvent.class)); break; case "raid_cancel_v2": eventManager.publish(TypeConvert.jsonToObject(rawMessage, RaidCancelEvent.class)); break; default: log.warn("Unparseable Message: " + message.getType() + "|" + message.getData()); break; } } else if (topic.startsWith("chat_moderator_actions")) { String channelId = topic.substring(topic.lastIndexOf('.') + 1); ChatModerationAction data = TypeConvert.convertValue(msgData, ChatModerationAction.class); eventManager.publish(new ChatModerationEvent(channelId, data)); } else if (topic.startsWith("following")) { final String channelId = topic.substring(topic.lastIndexOf('.') + 1); final FollowingData data = TypeConvert.jsonToObject(rawMessage, FollowingData.class); eventManager.publish(new FollowingEvent(channelId, data)); } else if (topic.startsWith("hype-train-events-v1")) { final String channelId = topic.substring(topic.lastIndexOf('.') + 1); switch (type) { case "hype-train-start": final HypeTrainStart startData = TypeConvert.convertValue(msgData, HypeTrainStart.class); eventManager.publish(new HypeTrainStartEvent(startData)); break; case "hype-train-progression": final HypeProgression progressionData = TypeConvert.convertValue(msgData, HypeProgression.class); eventManager.publish(new HypeTrainProgressionEvent(channelId, progressionData)); break; case "hype-train-level-up": final HypeLevelUp levelUpData = TypeConvert.convertValue(msgData, HypeLevelUp.class); eventManager.publish(new HypeTrainLevelUpEvent(channelId, levelUpData)); break; case "hype-train-end": final HypeTrainEnd endData = TypeConvert.convertValue(msgData, HypeTrainEnd.class); eventManager.publish(new HypeTrainEndEvent(channelId, endData)); break; case "hype-train-conductor-update": final HypeTrainConductor conductorData = TypeConvert.convertValue(msgData, HypeTrainConductor.class); eventManager.publish(new HypeTrainConductorUpdateEvent(channelId, conductorData)); break; case "hype-train-cooldown-expiration": eventManager.publish(new HypeTrainCooldownExpirationEvent(channelId)); break; default: log.warn("Unparseable Message: " + message.getType() + "|" + message.getData()); break; } } else if (topic.startsWith("community-points-user-v1")) { switch (type) { case "points-earned": final ChannelPointsEarned pointsEarned = TypeConvert.convertValue(msgData, ChannelPointsEarned.class); eventManager.publish(new PointsEarnedEvent(pointsEarned)); break; case "claim-available": final ClaimData claimAvailable = TypeConvert.convertValue(msgData, ClaimData.class); eventManager.publish(new ClaimAvailableEvent(claimAvailable)); break; case "claim-claimed": final ClaimData claimClaimed = TypeConvert.convertValue(msgData, ClaimData.class); eventManager.publish(new ClaimClaimedEvent(claimClaimed)); break; case "points-spent": final PointsSpent pointsSpent = TypeConvert.convertValue(msgData, PointsSpent.class); eventManager.publish(new PointsSpentEvent(pointsSpent)); break; case "reward-redeemed": final Calendar timestamp = GregorianCalendar.from(ZonedDateTime.ofInstant(Instant.parse(msgData.path("timestamp").asText()), ZoneId.systemDefault())); final ChannelPointsRedemption redemption = TypeConvert.convertValue(msgData.path("redemption"), ChannelPointsRedemption.class); eventManager.publish(new RewardRedeemedEvent(timestamp, redemption)); break; case "global-last-viewed-content-updated": case "channel-last-viewed-content-updated": // unimportant break; default: log.warn("Unparseable Message: " + message.getType() + "|" + message.getData()); break; } } else if (topic.startsWith("leaderboard-events-v1")) { final Leaderboard leaderboard = TypeConvert.jsonToObject(rawMessage, Leaderboard.class); switch (leaderboard.getIdentifier().getDomain()) { case "bits-usage-by-channel-v1": eventManager.publish(new BitsLeaderboardEvent(leaderboard)); break; case "sub-gifts-sent": eventManager.publish(new SubLeaderboardEvent(leaderboard)); break; default: log.warn("Unparseable Message: " + message.getType() + "|" + message.getData()); break; } } else if (topic.startsWith("polls")) { PollData pollData = TypeConvert.convertValue(msgData.path("poll"), PollData.class); eventManager.publish(new PollsEvent(type, pollData)); } else if (topic.startsWith("friendship")) { eventManager.publish(new FriendshipEvent(TypeConvert.jsonToObject(rawMessage, FriendshipData.class))); } else if (topic.startsWith("presence")) { if ("presence".equalsIgnoreCase(type)) { eventManager.publish(new UserPresenceEvent(TypeConvert.convertValue(msgData, PresenceData.class))); } else if ("settings".equalsIgnoreCase(type)) { String userId = topic.substring(topic.indexOf('.') + 1); PresenceSettings presenceSettings = TypeConvert.convertValue(msgData, PresenceSettings.class); eventManager.publish(new PresenceSettingsEvent(userId, presenceSettings)); } else { log.warn("Unparseable Message: " + message.getType() + "|" + message.getData()); } } else if (topic.startsWith("channel-sub-gifts-v1")) { eventManager.publish(new ChannelSubGiftEvent(TypeConvert.jsonToObject(rawMessage, SubGiftData.class))); } else if (topic.startsWith("channel-cheer-events-public-v1")) { String channelId = topic.substring(topic.indexOf('.') + 1); if ("cheerbomb".equalsIgnoreCase(type)) { CheerbombData cheerbomb = TypeConvert.convertValue(msgData, CheerbombData.class); eventManager.publish(new CheerbombEvent(channelId, cheerbomb)); } else { log.warn("Unparseable Message: " + message.getType() + "|" + message.getData()); } } else { log.warn("Unparseable Message: " + message.getType() + "|" + message.getData()); } } else if (message.getType().equals(PubSubType.RESPONSE)) { // topic subscription success or failed, response to listen command // System.out.println(message.toString()); if (message.getError().length() > 0) { if (message.getError().equalsIgnoreCase("ERR_BADAUTH")) { log.error("PubSub: You used a invalid oauth token to subscribe to the topic. Please use a token that is authorized for the specified channel."); } else { log.error("PubSub: Failed to subscribe to topic - [" + message.getError() + "]"); } } } else if (message.getType().equals(PubSubType.PONG)) { log.debug("PubSub: Received PONG response!"); lastPong = TimeUtils.getCurrentTimeInMillis(); } else if (message.getType().equals(PubSubType.RECONNECT)) { log.warn("PubSub: Server instance we're connected to will go down for maintenance soon, reconnecting to obtain a new connection!"); reconnect(); } else { // unknown message log.debug("PubSub: Unknown Message Type: " + message.toString()); } } catch (Exception ex) { log.warn("PubSub: Unparsable Message: " + text + " - [" + ex.getMessage() + "]"); ex.printStackTrace(); } } @Override public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) { if (!connectionState.equals(TMIConnectionState.DISCONNECTING)) { log.info("Connection to Twitch PubSub lost (WebSocket)! Retrying ..."); // connection lost - reconnecting reconnect(); } else { connectionState = TMIConnectionState.DISCONNECTED; log.info("Disconnected from Twitch PubSub (WebSocket)!"); } } }); } catch (Exception ex) { log.error(ex.getMessage(), ex); } } /** * Send WS Message * * @param command IRC Command */ private void sendCommand(String command) { // will send command if connection has been established if (connectionState.equals(TMIConnectionState.CONNECTED) || connectionState.equals(TMIConnectionState.CONNECTING)) { // command will be uppercase. this.webSocket.sendText(command); } else { log.warn("Can't send IRC-WS Command [{}]", command); } } /** * Queue PubSub request * * @param request PubSub request (or Topic) */ private void queueRequest(PubSubRequest request) { commandQueue.add(TypeConvert.objectToJson(request)); } /** * Send WS Message to subscribe to a topic * * @param request Topic * @return PubSubSubscription */ public PubSubSubscription listenOnTopic(PubSubRequest request) { if (subscribedTopics.add(request)) queueRequest(request); return new PubSubSubscription(request); } public PubSubSubscription listenOnTopic(PubSubType type, OAuth2Credential credential, List<String> topics) { PubSubRequest request = new PubSubRequest(); request.setType(type); request.setNonce(CryptoUtils.generateNonce(32)); request.getData().put("auth_token", credential != null ? credential.getAccessToken() : ""); request.getData().put("topics", topics); return listenOnTopic(request); } public PubSubSubscription listenOnTopic(PubSubType type, OAuth2Credential credential, String topic) { return listenOnTopic(type, credential, Collections.singletonList(topic)); } public PubSubSubscription listenOnTopic(PubSubType type, OAuth2Credential credential, String... topics) { return listenOnTopic(type, credential, Arrays.asList(topics)); } /** * Unsubscribe from a topic. * Usage example: * <pre> * PubSubSubscription subscription = twitchPubSub.listenForCheerEvents(...); * // ... * twitchPubSub.unsubscribeFromTopic(subscription); * </pre> * * @param subscription Subscription */ public void unsubscribeFromTopic(PubSubSubscription subscription) { PubSubRequest request = subscription.getRequest(); if (request.getType() != PubSubType.LISTEN) { log.warn("Cannot unsubscribe using request with unexpected type: {}", request.getType()); return; } boolean removed = subscribedTopics.remove(request); if (!removed) { log.warn("Not subscribed to topic: {}", request); return; } // use data from original request and send UNLISTEN PubSubRequest unlistenRequest = new PubSubRequest(); unlistenRequest.setType(PubSubType.UNLISTEN); unlistenRequest.setNonce(CryptoUtils.generateNonce(32)); unlistenRequest.setData(request.getData()); queueRequest(unlistenRequest); } /** * Event Listener: User earned a new Bits badge and shared the notification with chat * * @param credential Credential (for target user id, scope: bits:read) * @param userId Target User Id * @return PubSubSubscription */ public PubSubSubscription listenForBitsBadgeEvents(OAuth2Credential credential, String userId) { return listenOnTopic(PubSubType.LISTEN, credential, "channel-bits-badge-unlocks." + userId); } /** * Event Listener: Anyone cheers on a specified channel. * * @param credential Credential (for target user id, scope: bits:read) * @param userId Target User Id * @return PubSubSubscription */ public PubSubSubscription listenForCheerEvents(OAuth2Credential credential, String userId) { return listenOnTopic(PubSubType.LISTEN, credential, "channel-bits-events-v2." + userId); } /** * Event Listener: Anyone subscribes (first month), resubscribes (subsequent months), or gifts a subscription to a channel. * * @param credential Credential (for targetUserId, scope: channel_subscriptions) * @param userId Target User Id * @return PubSubSubscription */ public PubSubSubscription listenForSubscriptionEvents(OAuth2Credential credential, String userId) { return listenOnTopic(PubSubType.LISTEN, credential, "channel-subscribe-events-v1." + userId); } /** * Event Listener: Anyone makes a purchase on a channel. * * @param credential Credential (any) * @param userId Target User Id * @return PubSubSubscription */ @Deprecated public PubSubSubscription listenForCommerceEvents(OAuth2Credential credential, String userId) { return listenOnTopic(PubSubType.LISTEN, credential, "channel-commerce-events-v1." + userId); } /** * Event Listener: Anyone whispers the specified user. * * @param credential Credential (for targetUserId, scope: whispers:read) * @param userId Target User Id * @return PubSubSubscription */ public PubSubSubscription listenForWhisperEvents(OAuth2Credential credential, String userId) { return listenOnTopic(PubSubType.LISTEN, credential, "whispers." + userId); } /** * Event Listener: A moderator performs an action in the channel * * @param credential Credential (for channelId, scope: channel:moderate) * @param channelId Target Channel Id * @return PubSubSubscription */ public PubSubSubscription listenForModerationEvents(OAuth2Credential credential, String channelId) { return listenOnTopic(PubSubType.LISTEN, credential, "chat_moderator_actions." + channelId); } /** * Event Listener: A moderator performs an action in the channel * * @param credential Credential (for userId, scope: channel:moderate) * @param userId The user id associated with the credential * @param roomId The user id associated with the target channel * @return PubSubSubscription */ public PubSubSubscription listenForModerationEvents(OAuth2Credential credential, String userId, String roomId) { return listenForModerationEvents(credential, userId + "." + roomId); } /** * Event Listener: Anyone makes a channel points redemption on a channel. * * @param credential Credential (any) * @param channelId Target Channel Id * @return PubSubSubscription */ public PubSubSubscription listenForChannelPointsRedemptionEvents(OAuth2Credential credential, String channelId) { return listenOnTopic(PubSubType.LISTEN, credential, "community-points-channel-v1." + channelId); } /* * Undocumented topics - Use at your own risk */ @Unofficial @Deprecated public PubSubSubscription listenForAdsEvents(OAuth2Credential credential, String userId) { return listenOnTopic(PubSubType.LISTEN, credential, "ads." + userId); } @Unofficial @Deprecated public PubSubSubscription listenForAdPropertyRefreshEvents(OAuth2Credential credential, String userId) { return listenOnTopic(PubSubType.LISTEN, credential, "ad-property-refresh." + userId); } @Unofficial @Deprecated public PubSubSubscription listenForBountyBoardEvents(OAuth2Credential credential, String channelId) { return listenOnTopic(PubSubType.LISTEN, credential, "channel-bounty-board-events.cta." + channelId); } @Unofficial @Deprecated public PubSubSubscription listenForDashboardActivityFeedEvents(OAuth2Credential credential, String userId) { return listenOnTopic(PubSubType.LISTEN, credential, "dashboard-activity-feed." + userId); } @Unofficial public PubSubSubscription listenForUserChannelPointsEvents(OAuth2Credential credential, String userId) { return listenOnTopic(PubSubType.LISTEN, credential, "community-points-user-v1." + userId); } @Unofficial @Deprecated public PubSubSubscription listenForChannelDropEvents(OAuth2Credential credential, String channelId) { return listenOnTopic(PubSubType.LISTEN, credential, "channel-drop-events." + channelId); } @Unofficial public PubSubSubscription listenForChannelBitsLeaderboardEvents(OAuth2Credential credential, String channelId) { return listenOnTopic(PubSubType.LISTEN, credential, "leaderboard-events-v1.bits-usage-by-channel-v1-" + channelId + "-WEEK"); } @Unofficial @Deprecated public PubSubSubscription listenForChannelPrimeGiftStatusEvents(OAuth2Credential credential, String channelId) { return listenOnTopic(PubSubType.LISTEN, credential, "channel-prime-gifting-status." + channelId); } @Unofficial public PubSubSubscription listenForChannelSubLeaderboardEvents(OAuth2Credential credential, String channelId) { return listenOnTopic(PubSubType.LISTEN, credential, "leaderboard-events-v1.sub-gift-sent-" + channelId + "-WEEK"); } @Unofficial public PubSubSubscription listenForLeaderboardEvents(OAuth2Credential credential, String channelId) { return listenOnTopic(PubSubType.LISTEN, credential, "leaderboard-events-v1.bits-usage-by-channel-v1-" + channelId + "-WEEK", "leaderboard-events-v1.sub-gift-sent-" + channelId + "-WEEK"); } @Unofficial public PubSubSubscription listenForChannelSubGiftsEvents(OAuth2Credential credential, String channelId) { return listenOnTopic(PubSubType.LISTEN, credential, "channel-sub-gifts-v1." + channelId); } @Unofficial @Deprecated public PubSubSubscription listenForChannelSquadEvents(OAuth2Credential credential, String channelId) { return listenOnTopic(PubSubType.LISTEN, credential, "channel-squad-updates." + channelId); } @Unofficial public PubSubSubscription listenForRaidEvents(OAuth2Credential credential, String channelId) { return listenOnTopic(PubSubType.LISTEN, credential, "raid." + channelId); } @Unofficial @Deprecated public PubSubSubscription listenForChannelExtensionEvents(OAuth2Credential credential, String channelId) { return listenOnTopic(PubSubType.LISTEN, credential, "channel-ext-v1." + channelId); } @Unofficial @Deprecated public PubSubSubscription listenForExtensionControlEvents(OAuth2Credential credential, String channelId) { return listenOnTopic(PubSubType.LISTEN, credential, "extension-control." + channelId); } @Unofficial public PubSubSubscription listenForHypeTrainEvents(OAuth2Credential credential, String channelId) { return listenOnTopic(PubSubType.LISTEN, credential, "hype-train-events-v1." + channelId); } @Unofficial @Deprecated public PubSubSubscription listenForHypeTrainRewardEvents(OAuth2Credential credential, String channelId) { return listenOnTopic(PubSubType.LISTEN, credential, "hype-train-events-v1.rewards." + channelId); } @Unofficial @Deprecated public PubSubSubscription listenForBroadcastSettingUpdateEvents(OAuth2Credential credential, String channelId) { return listenOnTopic(PubSubType.LISTEN, credential, "broadcast-settings-update." + channelId); } @Unofficial @Deprecated public PubSubSubscription listenForCelebrationEvents(OAuth2Credential credential, String channelId) { return listenOnTopic(PubSubType.LISTEN, credential, "celebration-events-v1." + channelId); } @Unofficial public PubSubSubscription listenForPublicCheerEvents(OAuth2Credential credential, String channelId) { return listenOnTopic(PubSubType.LISTEN, credential, "channel-cheer-events-public-v1." + channelId); } @Unofficial @Deprecated public PubSubSubscription listenForStreamChangeEvents(OAuth2Credential credential, String channelId) { return listenOnTopic(PubSubType.LISTEN, credential, "stream-change-by-channel." + channelId); } @Unofficial @Deprecated public PubSubSubscription listenForStreamChatRoomEvents(OAuth2Credential credential, String channelId) { return listenOnTopic(PubSubType.LISTEN, credential, "stream-chat-room-v1." + channelId); } @Unofficial @Deprecated public PubSubSubscription listenForChannelChatroomEvents(OAuth2Credential credential, String channelId) { return listenOnTopic(PubSubType.LISTEN, credential, "chatrooms-channel-v1." + channelId); } @Unofficial @Deprecated public PubSubSubscription listenForUserChatroomEvents(OAuth2Credential credential, String userId) { return listenOnTopic(PubSubType.LISTEN, credential, "chatrooms-user-v1." + userId); } @Unofficial @Deprecated public PubSubSubscription listenForUserBitsUpdateEvents(OAuth2Credential credential, String userId) { return listenOnTopic(PubSubType.LISTEN, credential, "user-bits-updates-v1." + userId); } @Unofficial @Deprecated public PubSubSubscription listenForUserCampaignEvents(OAuth2Credential credential, String userId) { return listenOnTopic(PubSubType.LISTEN, credential, "user-campaign-events." + userId); } @Unofficial @Deprecated public PubSubSubscription listenForUserPropertiesUpdateEvents(OAuth2Credential credential, String userId) { return listenOnTopic(PubSubType.LISTEN, credential, "user-properties-update." + userId); } @Unofficial @Deprecated public PubSubSubscription listenForUserSubscribeEvents(OAuth2Credential credential, String userId) { return listenOnTopic(PubSubType.LISTEN, credential, "user-subscribe-events-v1." + userId); } @Unofficial @Deprecated public PubSubSubscription listenForUserImageUpdateEvents(OAuth2Credential credential, String userId) { return listenOnTopic(PubSubType.LISTEN, credential, "user-image-update." + userId); } /** * Event Listener: Anyone follows the specified channel. * * @param credential {@link OAuth2Credential} * @param channelId the id for the channel * @return PubSubSubscription */ @Unofficial public PubSubSubscription listenForFollowingEvents(OAuth2Credential credential, String channelId) { return listenOnTopic(PubSubType.LISTEN, credential, "following." + channelId); } @Unofficial public PubSubSubscription listenForFriendshipEvents(OAuth2Credential credential, String userId) { return listenOnTopic(PubSubType.LISTEN, credential, "friendship." + userId); } @Unofficial @Deprecated public PubSubSubscription listenForOnsiteNotificationEvents(OAuth2Credential credential, String userId) { return listenOnTopic(PubSubType.LISTEN, credential, "onsite-notifications." + userId); } @Unofficial public PubSubSubscription listenForPollEvents(OAuth2Credential credential, String channelId) { return listenOnTopic(PubSubType.LISTEN, credential, "polls." + channelId); } @Unofficial public PubSubSubscription listenForPresenceEvents(OAuth2Credential credential, String userId) { return listenOnTopic(PubSubType.LISTEN, credential, "presence." + userId); } @Unofficial @Deprecated public PubSubSubscription listenForVideoPlaybackEvents(OAuth2Credential credential, String channelId) { return listenOnTopic(PubSubType.LISTEN, credential, "video-playback." + channelId); } @Unofficial @Deprecated public PubSubSubscription listenForWatchPartyEvents(OAuth2Credential credential, String channelId) { return listenOnTopic(PubSubType.LISTEN, credential, "pv-watch-party-events." + channelId); } /** * Close */ public void close() { if (!isClosed) { isClosed = true; heartbeatTask.cancel(false); queueTask.cancel(false); disconnect(); } } }
package com.valkryst.VTerminal.printer; import com.valkryst.VTerminal.Tile; import lombok.Getter; import java.util.Arrays; import java.util.Optional; public enum RectangleType { NONE(new int[]{'', '', '', '', '', '', '', '', '', '', ''}), SIMPLE(new int[]{'+', '+', '+', '+', '|', '-', '+', '+', '+', '+', '+'}), THIN(new int[]{'', '', '', '', '', '', '', '', '', '', ''}), HEAVY(new int[]{'', '', '', '', '', '', '', '', '', '', ''}), MIXED_HEAVY_HORIZONTAL(new int[]{'', '', '', '', '', '', '', '', '', '', ''}), MIXED_HEAVY_VERTICAL(new int[]{'', '', '', '', '', '', '', '', '', '', ''}); /** The top left character of a rectangle. */ @Getter private final int topLeft; /** The top right character of a rectangle. */ @Getter private final int topRight; /** The bottom left character of a rectangle. */ @Getter private final int bottomLeft; /** The bottom right character of a rectangle. */ @Getter private final int bottomRight; /** The vertical character of a rectangle. */ @Getter private final int vertical; /** The horizontal character of a rectangle. */ @Getter private final int horizontal; /** The cross connector character of a rectangle. */ @Getter private final int connectorCross; /** The left connector character of a rectangle. */ @Getter private final int connectorLeft; /** The right connector character of a rectangle. */ @Getter private final int connectorRight; /** The downwards connector character of a rectangle. */ @Getter private final int connectorDown; /** The upwards connector character of a rectangle. */ @Getter private final int connectorUp; /** The set of characters that can appear above a RectangleType character. */ @Getter private final int[] validTopCharacters; /** The set of characters that can appear below a RectangleType character. */ @Getter private final int[] validBottomCharacters; /** * The set of characters that can appear to the left of a RectangleType * character. */ @Getter private final int[] validLeftCharacters; /** * The set of characters that can appear to the right of a RectangleType * character. */ @Getter private final int[] validRightCharacters; /** * Constructs a new RectangleType. * * @param boxCharacters * The characters of a rectangle. */ RectangleType(final int[] boxCharacters) { if (boxCharacters.length != 11) { throw new IllegalArgumentException("A RectangleType requires exactly 11 characters."); } topLeft = boxCharacters[0]; topRight = boxCharacters[1]; bottomLeft = boxCharacters[2]; bottomRight = boxCharacters[3]; vertical = boxCharacters[4]; horizontal = boxCharacters[5]; connectorCross = boxCharacters[6]; connectorLeft = boxCharacters[7]; connectorRight = boxCharacters[8]; connectorDown = boxCharacters[9]; connectorUp = boxCharacters[10]; validTopCharacters = new int[]{vertical, connectorCross, connectorLeft, connectorRight, connectorDown, topLeft, topRight}; validBottomCharacters = new int[]{vertical, connectorCross, connectorLeft, connectorRight, connectorUp, bottomLeft, bottomRight}; validLeftCharacters = new int[]{horizontal, connectorCross, connectorRight, connectorDown, connectorUp, topLeft, bottomLeft}; validRightCharacters = new int[]{horizontal, connectorCross, connectorLeft, connectorDown, connectorUp, topRight, bottomRight}; } /** * Determines if a character is in the set of characters that can appear above * a RectangleType character. * * @param asciiCharacter * The character. * * @return * If the character is in the set. */ public boolean isValidTopCharacter(final Tile asciiCharacter) { return asciiCharacter != null && isValidCharacter(asciiCharacter.getCharacter(), validTopCharacters); } /** * Determines if a character is in the set of characters that can appear below * a RectangleType character. * * @param asciiCharacter * The character. * * @return * If the character is in the set. */ public boolean isValidBottomCharacter(final Tile asciiCharacter) { return asciiCharacter != null && isValidCharacter(asciiCharacter.getCharacter(), validBottomCharacters); } /** * Determines if a character is in the set of characters that can appear to * the left of a RectangleType character. * * @param asciiCharacter * The character. * * @return * If the character is in the set. */ public boolean isValidLeftCharacter(final Tile asciiCharacter) { return asciiCharacter != null && isValidCharacter(asciiCharacter.getCharacter(), validLeftCharacters); } /** * Determines if a character is in the set of characters that can appear to * the right of a RectangleType character. * * @param asciiCharacter * The character. * * @return * If the character is in the set. */ public boolean isValidRightCharacter(final Tile asciiCharacter) { return asciiCharacter != null && isValidCharacter(asciiCharacter.getCharacter(), validRightCharacters); } /** * Determines if a character is in a set of characters. * * @param character * The character. * * @param validCharacters * The set. * * @return * If the character is in the set. */ private boolean isValidCharacter(final int character, final int[] validCharacters) { for (final int validCharacter : validCharacters) { if (character == validCharacter) { return true; } } return false; } /** * Retrieves a character by it's neighbour pattern. * * @param pattern * The pattern. * * @return * The character. */ public Optional<Integer> getCharacterByNeighbourPattern(final boolean[] pattern) { if (Arrays.equals(pattern, new boolean[]{false, false, true, true})) { return Optional.of(topRight); } if (Arrays.equals(pattern, new boolean[]{false, true, false, true})) { return Optional.of(vertical); } if (Arrays.equals(pattern, new boolean[]{false, true, true, false})) { return Optional.of(bottomRight); } if (Arrays.equals(pattern, new boolean[]{false, true, true, true})) { return Optional.of(connectorLeft); } if (Arrays.equals(pattern, new boolean[]{true, false, false, true})) { return Optional.of(topLeft); } if (Arrays.equals(pattern, new boolean[]{true, false, true, false})) { return Optional.of(horizontal); } if (Arrays.equals(pattern, new boolean[]{true, false, true, true})) { return Optional.of(connectorDown); } if (Arrays.equals(pattern, new boolean[]{true, true, false, false})) { return Optional.of(bottomLeft); } if (Arrays.equals(pattern, new boolean[]{true, true, false, true})) { return Optional.of(connectorRight); } if (Arrays.equals(pattern, new boolean[]{true, true, true, false})) { return Optional.of(connectorUp); } if (Arrays.equals(pattern, new boolean[]{true, true, true, true})) { return Optional.of(connectorCross); } return Optional.empty(); } }
package lobby.registration; import lobby.registration.order.*; import lobby.registration.order.Order.Status; import org.spine3.base.CommandContext; import org.spine3.server.Assign; import org.spine3.server.aggregate.Aggregate; import org.spine3.server.aggregate.Apply; import static com.google.common.base.Preconditions.checkState; import static lobby.registration.order.Order.Status.*; /** * The order aggregate root. * * @author Alexander Litus */ @SuppressWarnings("TypeMayBeWeakened") // not in handlers public class OrderAggregate extends Aggregate<OrderId, Order> { public OrderAggregate(OrderId id) { super(id); } @Override protected Order getDefaultState() { return Order.getDefaultInstance(); } @Assign public OrderPlaced handle(RegisterToConference command, CommandContext context) { validateCommand(command); final OrderPlaced result = OrderPlaced.newBuilder() .setOrderId(command.getOrderId()) .setConferenceId(command.getConferenceId()) .addAllSeat(command.getSeatList()) .build(); return result; } @Apply private void event(OrderPlaced event) { final Order newState = Order.newBuilder(getState()) .setId(event.getOrderId()) .setConferenceId(event.getConferenceId()) .addAllSeat(event.getSeatList()) .setStatus(CREATED) .build(); validate(newState); incrementState(newState); } @Apply private void event(OrderPaymentConfirmed event) { final Order newState = Order.newBuilder(getState()) .setId(event.getOrderId()) .setStatus(CONFIRMED) .build(); validate(newState); incrementState(newState); } private void validateCommand(RegisterToConference command) { if (command.getOrderId().getUuid().isEmpty()) { throw noOrderIdException(); } if (command.getConferenceId().getUuid().isEmpty()) { throw new IllegalArgumentException("No conference ID in the order."); } if (command.getSeatCount() == 0) { throw new IllegalArgumentException("No seats in the order."); } final Status status = getState().getStatus(); checkState(status == UNRECOGNIZED, status); } private void validateCommand(RejectOrder command) { if (command.getOrderId().getUuid().isEmpty()) { throw noOrderIdException(); } final Status status = getState().getStatus(); checkState(status == CREATED, status); } private static IllegalArgumentException noOrderIdException() { return new IllegalArgumentException("No order ID."); } }
package com.pxh.adapter; import android.text.Spanned; import android.util.Log; import com.pxh.RichEditText; import com.pxh.richedittext.TextSpanStatus; import com.pxh.richedittext.TextSpans; import com.pxh.span.HolderSpan; import com.pxh.span.RichQuoteSpan; public class QuoteSpanAdapter extends ParagraphAdapter { public QuoteSpanAdapter(RichEditText editor) { super(editor); leadingMarginSpan = new RichQuoteSpan(); } @Override public void enableSpan(boolean isEnable, TextSpanStatus state, int code) { int start = editor.getSelectionStart(); int end = editor.getSelectionEnd(); if (end < start) { start = start ^ end; end = start ^ end; start = start ^ end; } state.enableQuote(isEnable); if (start < end) { int quoteStart = getParagraphStart(start); int quoteEnd = getParagraphEnd(end); if (isEnable) { setSelectionTextSpan(true, new RichQuoteSpan(), quoteStart, quoteEnd); } else { removeSpan(RichQuoteSpan.class, quoteStart, quoteEnd); } } else { if (isEnable) { int quoteStart = getParagraphStart(start); int quoteEnd = getParagraphEnd(start); //if there is just a single line,insert a replacement span if (quoteStart == start && (getEditableText().length() == quoteStart || getEditableText().charAt(quoteStart) == '\n')) { if (leadingMarginSpan == null) { leadingMarginSpan = new RichQuoteSpan(); } insertReplacement(quoteStart); } else { //else set whole paragraph by quote span setSelectionTextSpan(true, new RichQuoteSpan(), quoteStart, quoteEnd); } } else { RichQuoteSpan span = getAssignSpan(RichQuoteSpan.class, start, end); getEditableText().removeSpan(span); removeReplacementIfExist(start); } } } @Override protected void setSelectionText(boolean isEnable, int start, int end) { } @Override public boolean changeStatusBySelectionChanged(int start, int end) { HolderSpan[] holderSpans = getAssignSpans(HolderSpan.class, start - 1, start); for (HolderSpan span : holderSpans) { if (span.getInnerSpan() instanceof RichQuoteSpan) { return true; } } RichQuoteSpan[] quoteSpans = getEditableText().getSpans(start - 1, start, RichQuoteSpan.class); return (quoteSpans.length != 0 && isRangeInSpan(quoteSpans[0], start, end)); } @Override public void changeSpanByTextChanged(int start, int lengthBefore, int lengthAfter) { if (changeReplacement) {//add replacement will not change span return; } if (lengthBefore > lengthAfter) {//when text delete RichQuoteSpan richQuoteSpan = getAssignSpan(RichQuoteSpan.class, start + lengthBefore - 1, start + lengthBefore + 1); if (spanDeletedIndex >= 0) { insertReplacement(spanDeletedIndex); spanDeletedIndex = -1; } if (richQuoteSpan == null) { return; } int sStart = getEditableText().getSpanStart(richQuoteSpan); int sEnd = getEditableText().getSpanEnd(richQuoteSpan); if (sEnd - sStart == 1) { if (getEditableText().subSequence(sStart, sEnd).toString().equals("\n")) { changeReplacement = true; getEditableText().delete(sStart, sEnd); changeReplacement = false; } } } else { //text insert or replace old text if (removeReplacementIfExist(start)) { start } RichQuoteSpan richQuoteSpan = getAssignSpan(RichQuoteSpan.class, start - 1, start); int sEnd = getEditableText().getSpanEnd(richQuoteSpan); if (start + lengthAfter >= 1 && getEditableText().charAt(start + lengthAfter - 1) == '\n' && editor.getSelectionStart() == sEnd + lengthAfter && !changeReplacement) { if (getEditableText().length() > sEnd + lengthAfter + 1 && getEditableText().charAt(sEnd + lengthAfter + 1) == '\n') { } //while '\n' input and there only this '\n' at tail of text, add another '\n' after text to show quote effect editor.setEnableStatusChangeBySelection(false); getEditableText().append("\n"); editor.setSelection(start + lengthAfter); editor.setEnableStatusChangeBySelection(true); lengthAfter++; } } setTextSpanByTextChanged(RichQuoteSpan.class, start, lengthAfter); if (start > 0 && lengthAfter == 1 && getEditableText().charAt(start) == '\n' && getEditableText().charAt(start - 1) == '\n') { RichQuoteSpan richQuoteSpan = getAssignSpan(RichQuoteSpan.class, start - 1, start); int sStart = getEditableText().getSpanStart(richQuoteSpan); getEditableText().removeSpan(richQuoteSpan); getEditableText().setSpan(richQuoteSpan, sStart, start, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } @Override public void changeSpanBeforeTextChanged(int start, int lengthBefore, int lengthAfter) { if (changeReplacement) {//add replacement will not change span return; } if (lengthBefore > lengthAfter) { RichQuoteSpan richQuoteSpan = getAssignSpan(RichQuoteSpan.class, start + lengthBefore - 1, start + lengthBefore + 1); if (richQuoteSpan == null) { return; } int sStart = getEditableText().getSpanStart(richQuoteSpan); if (sStart == start && lengthAfter == 0) { spanDeletedIndex = start; } } } @Override public int getSpanStatusCode() { return TextSpans.Quote; } }
package com.cloud.agent.manager; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import javax.ejb.Local; import javax.naming.ConfigurationException; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; import com.cloud.agent.api.CancelCommand; import com.cloud.agent.api.ChangeAgentCommand; import com.cloud.agent.api.Command; import com.cloud.agent.api.TransferAgentCommand; import com.cloud.agent.manager.AgentManagerImpl.SimulateStartTask; import com.cloud.agent.transport.Request; import com.cloud.agent.transport.Request.Version; import com.cloud.agent.transport.Response; import com.cloud.api.commands.UpdateHostPasswordCmd; import com.cloud.cluster.ClusterManager; import com.cloud.cluster.ClusterManagerListener; import com.cloud.cluster.ClusteredAgentRebalanceService; import com.cloud.cluster.ManagementServerHost; import com.cloud.cluster.ManagementServerHostVO; import com.cloud.cluster.StackMaid; import com.cloud.cluster.agentlb.AgentLoadBalancerPlanner; import com.cloud.cluster.agentlb.HostTransferMapVO; import com.cloud.cluster.agentlb.HostTransferMapVO.HostTransferState; import com.cloud.cluster.agentlb.dao.HostTransferMapDao; import com.cloud.cluster.dao.ManagementServerHostDao; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.OperationTimedoutException; import com.cloud.host.HostVO; import com.cloud.host.Status; import com.cloud.host.Status.Event; import com.cloud.resource.ServerResource; import com.cloud.storage.resource.DummySecondaryStorageResource; import com.cloud.user.User; import com.cloud.utils.DateUtil; import com.cloud.utils.NumbersUtil; import com.cloud.utils.component.Adapters; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.Inject; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; import com.cloud.utils.db.GlobalLock; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.nio.Link; import com.cloud.utils.nio.Task; @Local(value = { AgentManager.class, ClusteredAgentRebalanceService.class }) public class ClusteredAgentManagerImpl extends AgentManagerImpl implements ClusterManagerListener, ClusteredAgentRebalanceService { final static Logger s_logger = Logger.getLogger(ClusteredAgentManagerImpl.class); private static final ScheduledExecutorService s_transferExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Cluster-AgentTransferExecutor")); private final long rebalanceTimeOut = 300000; // 5 mins - after this time remove the agent from the transfer list public final static long STARTUP_DELAY = 5000; public final static long SCAN_INTERVAL = 90000; // 90 seconds, it takes 60 sec for xenserver to fail login public final static int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 5; // 5 seconds public long _loadSize = 100; protected Set<Long> _agentToTransferIds = new HashSet<Long>(); @Inject protected ClusterManager _clusterMgr = null; protected HashMap<String, SocketChannel> _peers; protected HashMap<String, SSLEngine> _sslEngines; private final Timer _timer = new Timer("ClusteredAgentManager Timer"); @Inject protected ManagementServerHostDao _mshostDao; @Inject protected HostTransferMapDao _hostTransferDao; @Inject(adapter = AgentLoadBalancerPlanner.class) protected Adapters<AgentLoadBalancerPlanner> _lbPlanners; protected ClusteredAgentManagerImpl() { super(); } @Override public boolean configure(String name, Map<String, Object> xmlParams) throws ConfigurationException { _peers = new HashMap<String, SocketChannel>(7); _sslEngines = new HashMap<String, SSLEngine>(7); _nodeId = _clusterMgr.getManagementNodeId(); ConfigurationDao configDao = ComponentLocator.getCurrentLocator().getDao(ConfigurationDao.class); Map<String, String> params = configDao.getConfiguration(xmlParams); String value = params.get(Config.DirectAgentLoadSize.key()); _loadSize = NumbersUtil.parseInt(value, 16); ClusteredAgentAttache.initialize(this); _clusterMgr.registerListener(this); return super.configure(name, xmlParams); } @Override public boolean start() { if (!super.start()) { return false; } _timer.schedule(new DirectAgentScanTimerTask(), STARTUP_DELAY, SCAN_INTERVAL); // schedule transfer scan executor - if agent LB is enabled if (_clusterMgr.isAgentRebalanceEnabled()) { s_transferExecutor.scheduleAtFixedRate(getTransferScanTask(), 60000, ClusteredAgentRebalanceService.DEFAULT_TRANSFER_CHECK_INTERVAL, TimeUnit.MILLISECONDS); } return true; } private void runDirectAgentScanTimerTask() { GlobalLock scanLock = GlobalLock.getInternLock("clustermgr.scan"); try { if (scanLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION)) { try { scanDirectAgentToLoad(); } finally { scanLock.unlock(); } } } finally { scanLock.releaseRef(); } } private void scanDirectAgentToLoad() { if (s_logger.isTraceEnabled()) { s_logger.trace("Begin scanning directly connected hosts"); } // for agents that are self-managed, threshold to be considered as disconnected is 3 ping intervals long cutSeconds = (System.currentTimeMillis() >> 10) - (_pingInterval * 3); List<HostVO> hosts = _hostDao.findDirectAgentToLoad(cutSeconds, _loadSize); if (hosts != null && hosts.size() == _loadSize) { //if list contains more than one cluster, exclude the last cluster from the list if (hosts.size() > 1 && hosts.get(0).getClusterId().longValue() != hosts.get(hosts.size()-1).getClusterId().longValue()) { Long clusterId = hosts.get((int) (_loadSize - 1)).getClusterId(); if (clusterId != null) { for (int i = (int) (_loadSize - 1); i > 0; i if (hosts.get(i).getClusterId().longValue() == clusterId.longValue()) { hosts.remove(i); } else { break; } } } } } if (hosts != null && hosts.size() > 0) { s_logger.debug("Found " + hosts.size() + " unmanaged direct hosts, processing connect for them..."); for (HostVO host : hosts) { try { AgentAttache agentattache = findAttache(host.getId()); if (agentattache != null) { // already loaded, skip if (agentattache.forForward()) { if (s_logger.isInfoEnabled()) { s_logger.info(host + " is detected down, but we have a forward attache running, disconnect this one before launching the host"); } removeAgent(agentattache, Status.Disconnected); } else { continue; } } if (s_logger.isDebugEnabled()) { s_logger.debug("Loading directly connected host " + host.getId() + "(" + host.getName() + ")"); } loadDirectlyConnectedHost(host, false); } catch (Throwable e) { s_logger.warn(" can not load directly connected host " + host.getId() + "(" + host.getName() + ") due to ",e); } } } if (s_logger.isTraceEnabled()) { s_logger.trace("End scanning directly connected hosts"); } } private class DirectAgentScanTimerTask extends TimerTask { @Override public void run() { try { runDirectAgentScanTimerTask(); } catch (Throwable e) { s_logger.error("Unexpected exception " + e.getMessage(), e); } } } @Override public Task create(Task.Type type, Link link, byte[] data) { return new ClusteredAgentHandler(type, link, data); } @Override public boolean cancelMaintenance(final long hostId) { try { Boolean result = _clusterMgr.propagateAgentEvent(hostId, Event.ResetRequested); if (result != null) { return result; } } catch (AgentUnavailableException e) { return false; } return super.cancelMaintenance(hostId); } protected AgentAttache createAttache(long id) { s_logger.debug("create forwarding ClusteredAgentAttache for " + id); final AgentAttache attache = new ClusteredAgentAttache(this, id); AgentAttache old = null; synchronized (_agents) { old = _agents.get(id); _agents.put(id, attache); } if (old != null) { old.disconnect(Status.Removed); } return attache; } @Override protected AgentAttache createAttache(long id, HostVO server, Link link) { s_logger.debug("create ClusteredAgentAttache for " + id); final AgentAttache attache = new ClusteredAgentAttache(this, id, link, server.getStatus() == Status.Maintenance || server.getStatus() == Status.ErrorInMaintenance || server.getStatus() == Status.PrepareForMaintenance); link.attach(attache); AgentAttache old = null; synchronized (_agents) { old = _agents.get(id); _agents.put(id, attache); } if (old != null) { old.disconnect(Status.Removed); } return attache; } @Override protected AgentAttache createAttache(long id, HostVO server, ServerResource resource) { if (resource instanceof DummySecondaryStorageResource) { return new DummyAttache(this, id, false); } s_logger.debug("create ClusteredDirectAgentAttache for " + id); final DirectAgentAttache attache = new ClusteredDirectAgentAttache(this, id, _nodeId, resource, server.getStatus() == Status.Maintenance || server.getStatus() == Status.ErrorInMaintenance || server.getStatus() == Status.PrepareForMaintenance, this); AgentAttache old = null; synchronized (_agents) { old = _agents.get(id); _agents.put(id, attache); } if (old != null) { old.disconnect(Status.Removed); } return attache; } @Override protected boolean handleDisconnect(AgentAttache attache, Status.Event event, boolean investigate) { return handleDisconnect(attache, event, investigate, true); } protected boolean handleDisconnect(AgentAttache agent, Status.Event event, boolean investigate, boolean broadcast) { if (agent == null) { return true; } if (super.handleDisconnect(agent, event, investigate)) { if (broadcast) { notifyNodesInCluster(agent); } return true; } else { return false; } } @Override public boolean executeUserRequest(long hostId, Event event) throws AgentUnavailableException { if (event == Event.AgentDisconnected) { if (s_logger.isDebugEnabled()) { s_logger.debug("Received agent disconnect event for host " + hostId); } AgentAttache attache = findAttache(hostId); if (attache != null) { handleDisconnect(attache, Event.AgentDisconnected, false, false); } return true; } else { return super.executeUserRequest(hostId, event); } } @Override public boolean maintain(final long hostId) throws AgentUnavailableException { Boolean result = _clusterMgr.propagateAgentEvent(hostId, Event.MaintenanceRequested); if (result != null) { return result; } return super.maintain(hostId); } @Override public boolean reconnect(final long hostId) throws AgentUnavailableException { Boolean result = _clusterMgr.propagateAgentEvent(hostId, Event.ShutdownRequested); if (result != null) { return result; } return super.reconnect(hostId); } @Override @DB public boolean deleteHost(long hostId, boolean isForced, User caller) { try { Boolean result = _clusterMgr.propagateAgentEvent(hostId, Event.Remove); if (result != null) { return result; } } catch (AgentUnavailableException e) { return false; } return super.deleteHost(hostId, isForced, caller); } @Override public boolean updateHostPassword(UpdateHostPasswordCmd upasscmd) { if (upasscmd.getClusterId() == null) { // update agent attache password try { Boolean result = _clusterMgr.propagateAgentEvent(upasscmd.getHostId(), Event.UpdatePassword); if (result != null) { return result; } } catch (AgentUnavailableException e) { } } else { // get agents for the cluster List<HostVO> hosts = _hostDao.listByCluster(upasscmd.getClusterId()); for (HostVO h : hosts) { try { Boolean result = _clusterMgr.propagateAgentEvent(h.getId(), Event.UpdatePassword); if (result != null) { return result; } } catch (AgentUnavailableException e) { } } } return super.updateHostPassword(upasscmd); } public void notifyNodesInCluster(AgentAttache attache) { s_logger.debug("Notifying other nodes of to disconnect"); Command[] cmds = new Command[] { new ChangeAgentCommand(attache.getId(), Event.AgentDisconnected) }; _clusterMgr.broadcast(attache.getId(), cmds); } protected static void logT(byte[] bytes, final String msg) { s_logger.trace("Seq " + Request.getAgentId(bytes) + "-" + Request.getSequence(bytes) + ": MgmtId " + Request.getManagementServerId(bytes) + ": " + (Request.isRequest(bytes) ? "Req: " : "Resp: ") + msg); } protected static void logD(byte[] bytes, final String msg) { s_logger.debug("Seq " + Request.getAgentId(bytes) + "-" + Request.getSequence(bytes) + ": MgmtId " + Request.getManagementServerId(bytes) + ": " + (Request.isRequest(bytes) ? "Req: " : "Resp: ") + msg); } protected static void logI(byte[] bytes, final String msg) { s_logger.info("Seq " + Request.getAgentId(bytes) + "-" + Request.getSequence(bytes) + ": MgmtId " + Request.getManagementServerId(bytes) + ": " + (Request.isRequest(bytes) ? "Req: " : "Resp: ") + msg); } public boolean routeToPeer(String peer, byte[] bytes) { int i = 0; SocketChannel ch = null; SSLEngine sslEngine = null; while (i++ < 5) { ch = connectToPeer(peer, ch); if (ch == null) { try { logD(bytes, "Unable to route to peer: " + Request.parse(bytes).toString()); } catch (Exception e) { } return false; } sslEngine = getSSLEngine(peer); if (sslEngine == null) { logD(bytes, "Unable to get SSLEngine of peer: " + peer); return false; } try { if (s_logger.isDebugEnabled()) { logD(bytes, "Routing to peer"); } Link.write(ch, new ByteBuffer[] { ByteBuffer.wrap(bytes) }, sslEngine); return true; } catch (IOException e) { try { logI(bytes, "Unable to route to peer: " + Request.parse(bytes).toString() + " due to " + e.getMessage()); } catch (Exception ex) { } } } return false; } public String findPeer(long hostId) { return _clusterMgr.getPeerName(hostId); } public SSLEngine getSSLEngine(String peerName) { return _sslEngines.get(peerName); } public void cancel(String peerName, long hostId, long sequence, String reason) { CancelCommand cancel = new CancelCommand(sequence, reason); Request req = new Request(hostId, _nodeId, cancel, true); req.setControl(true); routeToPeer(peerName, req.getBytes()); } public void closePeer(String peerName) { synchronized (_peers) { SocketChannel ch = _peers.get(peerName); if (ch != null) { try { ch.close(); } catch (IOException e) { s_logger.warn("Unable to close peer socket connection to " + peerName); } } _peers.remove(peerName); _sslEngines.remove(peerName); } } public SocketChannel connectToPeer(String peerName, SocketChannel prevCh) { synchronized (_peers) { SocketChannel ch = _peers.get(peerName); SSLEngine sslEngine = null; if (prevCh != null) { try { prevCh.close(); } catch (Exception e) { } } if (ch == null || ch == prevCh) { ManagementServerHostVO ms = _clusterMgr.getPeer(peerName); if (ms == null) { s_logger.info("Unable to find peer: " + peerName); return null; } String ip = ms.getServiceIP(); InetAddress addr; try { addr = InetAddress.getByName(ip); } catch (UnknownHostException e) { throw new CloudRuntimeException("Unable to resolve " + ip); } try { ch = SocketChannel.open(new InetSocketAddress(addr, _port)); ch.configureBlocking(true); // make sure we are working at blocking mode ch.socket().setKeepAlive(true); ch.socket().setSoTimeout(60 * 1000); try { SSLContext sslContext = Link.initSSLContext(true); sslEngine = sslContext.createSSLEngine(ip, _port); sslEngine.setUseClientMode(true); Link.doHandshake(ch, sslEngine, true); s_logger.info("SSL: Handshake done"); } catch (Exception e) { throw new IOException("SSL: Fail to init SSL! " + e); } if (s_logger.isDebugEnabled()) { s_logger.debug("Connection to peer opened: " + peerName + ", ip: " + ip); } _peers.put(peerName, ch); _sslEngines.put(peerName, sslEngine); } catch (IOException e) { s_logger.warn("Unable to connect to peer management server: " + peerName + ", ip: " + ip + " due to " + e.getMessage(), e); return null; } } if (s_logger.isTraceEnabled()) { s_logger.trace("Found open channel for peer: " + peerName); } return ch; } } public SocketChannel connectToPeer(long hostId, SocketChannel prevCh) { String peerName = _clusterMgr.getPeerName(hostId); if (peerName == null) { return null; } return connectToPeer(peerName, prevCh); } @Override protected AgentAttache getAttache(final Long hostId) throws AgentUnavailableException { assert (hostId != null) : "Who didn't check their id value?"; HostVO host = _hostDao.findById(hostId); if (host == null) { throw new AgentUnavailableException("Can't find the host ", hostId); } AgentAttache agent = findAttache(hostId); if (agent == null) { if (host.getStatus() == Status.Up && (host.getManagementServerId() != null && host.getManagementServerId() != _nodeId)) { agent = createAttache(hostId); } } if (agent == null) { throw new AgentUnavailableException("Host is not in the right state: " + host.getStatus() , hostId); } return agent; } @Override public boolean stop() { if (_peers != null) { for (SocketChannel ch : _peers.values()) { try { s_logger.info("Closing: " + ch.toString()); ch.close(); } catch (IOException e) { } } } _timer.cancel(); //cancel all transfer tasks s_transferExecutor.shutdownNow(); cleanupTransferMap(); return super.stop(); } @Override public void startDirectlyConnectedHosts() { // override and let it be dummy for purpose, we will scan and load direct agents periodically. // We may also pickup agents that have been left over from other crashed management server } public class ClusteredAgentHandler extends AgentHandler { public ClusteredAgentHandler(Task.Type type, Link link, byte[] data) { super(type, link, data); } @Override protected void doTask(final Task task) throws Exception { Transaction txn = Transaction.open(Transaction.CLOUD_DB); try { if (task.getType() != Task.Type.DATA) { super.doTask(task); return; } final byte[] data = task.getData(); Version ver = Request.getVersion(data); if (ver.ordinal() != Version.v1.ordinal() && ver.ordinal() != Version.v3.ordinal()) { s_logger.warn("Wrong version for clustered agent request"); super.doTask(task); return; } long hostId = Request.getAgentId(data); Link link = task.getLink(); if (Request.fromServer(data)) { AgentAttache agent = findAttache(hostId); if (Request.isControl(data)) { if (agent == null) { logD(data, "No attache to process cancellation"); return; } Request req = Request.parse(data); Command[] cmds = req.getCommands(); CancelCommand cancel = (CancelCommand) cmds[0]; if (s_logger.isDebugEnabled()) { logD(data, "Cancel request received"); } agent.cancel(cancel.getSequence()); return; } try { if (agent == null || agent.isClosed()) { throw new AgentUnavailableException("Unable to route to agent ", hostId); } if (Request.isRequest(data) && Request.requiresSequentialExecution(data)) { // route it to the agent. // But we have the serialize the control commands here so we have // to deserialize this and send it through the agent attache. Request req = Request.parse(data); agent.send(req, null); return; } else { if (agent instanceof Routable) { Routable cluster = (Routable) agent; cluster.routeToAgent(data); } else { agent.send(Request.parse(data)); } return; } } catch (AgentUnavailableException e) { logD(data, e.getMessage()); cancel(Long.toString(Request.getManagementServerId(data)), hostId, Request.getSequence(data), e.getMessage()); } } else { long mgmtId = Request.getManagementServerId(data); if (mgmtId != -1 && mgmtId != _nodeId) { routeToPeer(Long.toString(mgmtId), data); if (Request.requiresSequentialExecution(data)) { AgentAttache attache = (AgentAttache) link.attachment(); if (attache != null) { attache.sendNext(Request.getSequence(data)); } else if (s_logger.isDebugEnabled()) { logD(data, "No attache to process " + Request.parse(data).toString()); } } return; } else { if (Request.isRequest(data)) { super.doTask(task); } else { // received an answer. final Response response = Response.parse(data); AgentAttache attache = findAttache(response.getAgentId()); if (attache == null) { s_logger.info("SeqA " + response.getAgentId() + "-" + response.getSequence() + "Unable to find attache to forward " + response.toString()); return; } if (!attache.processAnswers(response.getSequence(), response)) { s_logger.info("SeqA " + attache.getId() + "-" + response.getSequence() + ": Response is not processed: " + response.toString()); } } return; } } } finally { txn.close(); } } } @Override public void onManagementNodeJoined(List<ManagementServerHostVO> nodeList, long selfNodeId) { } @Override public void onManagementNodeLeft(List<ManagementServerHostVO> nodeList, long selfNodeId) { for (ManagementServerHostVO vo : nodeList) { s_logger.info("Marking hosts as disconnected on Management server" + vo.getMsid()); _hostDao.markHostsAsDisconnected(vo.getMsid()); } } @Override public void onManagementNodeIsolated() { } @Override public void removeAgent(AgentAttache attache, Status nextState) { if (attache == null) { return; } super.removeAgent(attache, nextState); } @Override public boolean executeRebalanceRequest(long agentId, long currentOwnerId, long futureOwnerId, Event event) throws AgentUnavailableException, OperationTimedoutException { if (event == Event.RequestAgentRebalance) { return setToWaitForRebalance(agentId, currentOwnerId, futureOwnerId); } else if (event == Event.StartAgentRebalance) { return rebalanceHost(agentId, currentOwnerId, futureOwnerId); } return true; } @Override public void scheduleRebalanceAgents() { _timer.schedule(new AgentLoadBalancerTask(), 30000); } public class AgentLoadBalancerTask extends TimerTask { protected volatile boolean cancelled = false; public AgentLoadBalancerTask() { s_logger.debug("Agent load balancer task created"); } @Override public synchronized boolean cancel() { if (!cancelled) { cancelled = true; s_logger.debug("Agent load balancer task cancelled"); return super.cancel(); } return true; } @Override public synchronized void run() { if (!cancelled) { startRebalanceAgents(); if (s_logger.isInfoEnabled()) { s_logger.info("The agent load balancer task is now being cancelled"); } cancelled = true; } } } public void startRebalanceAgents() { s_logger.debug("Management server " + _nodeId + " is asking other peers to rebalance their agents"); List<ManagementServerHostVO> allMS = _mshostDao.listBy(ManagementServerHost.State.Up); List<HostVO> allManagedAgents = _hostDao.listManagedRoutingAgents(); int avLoad = 0; if (!allManagedAgents.isEmpty() && !allMS.isEmpty()) { avLoad = allManagedAgents.size() / allMS.size(); } else { if (s_logger.isDebugEnabled()) { s_logger.debug("There are no hosts to rebalance in the system. Current number of active management server nodes in the system is " + allMS.size() + "; number of managed agents is " + allManagedAgents.size()); } return; } if (avLoad == 0L) { if (s_logger.isDebugEnabled()) { s_logger.debug("As calculated average load is less than 1, rounding it to 1"); } avLoad = 1; } for (ManagementServerHostVO node : allMS) { if (node.getMsid() != _nodeId) { List<HostVO> hostsToRebalance = new ArrayList<HostVO>(); for (AgentLoadBalancerPlanner lbPlanner : _lbPlanners) { hostsToRebalance = lbPlanner.getHostsToRebalance(node.getMsid(), avLoad); if (hostsToRebalance != null && !hostsToRebalance.isEmpty()) { break; } else { s_logger.debug("Agent load balancer planner " + lbPlanner.getName() + " found no hosts to be rebalanced from management server " + node.getMsid()); } } if (hostsToRebalance != null && !hostsToRebalance.isEmpty()) { for (HostVO host : hostsToRebalance) { long hostId = host.getId(); s_logger.debug("Asking management server " + node.getMsid() + " to give away host id=" + hostId); boolean result = true; if (_hostTransferDao.findById(hostId) != null) { s_logger.warn("Somebody else is already rebalancing host id: " + hostId); continue; } HostTransferMapVO transfer = _hostTransferDao.startAgentTransfering(hostId, node.getMsid(), _nodeId); try { Answer[] answer = sendRebalanceCommand(node.getMsid(), hostId, node.getMsid(), _nodeId, Event.RequestAgentRebalance); if (answer == null) { s_logger.warn("Failed to get host id=" + hostId + " from management server " + node.getMsid()); result = false; } } catch (Exception ex) { s_logger.warn("Failed to get host id=" + hostId + " from management server " + node.getMsid(), ex); result = false; } finally { HostTransferMapVO transferState = _hostTransferDao.findByIdAndFutureOwnerId(transfer.getId(), _nodeId); if (!result && transferState != null && transferState.getState() == HostTransferState.TransferRequested) { if (s_logger.isDebugEnabled()) { s_logger.debug("Removing mapping from op_host_transfer as it failed to be set to transfer mode"); } //just remove the mapping as nothing was done on the peer management server yet _hostTransferDao.remove(transfer.getId()); } } } } else { s_logger.debug("Found no hosts to rebalance from the management server " + node.getMsid()); } } } } private Answer[] sendRebalanceCommand(long peer, long agentId, long currentOwnerId, long futureOwnerId, Event event) { TransferAgentCommand transfer = new TransferAgentCommand(agentId, currentOwnerId, futureOwnerId, event); Commands commands = new Commands(OnError.Stop); commands.addCommand(transfer); Command[] cmds = commands.toCommands(); try { if (s_logger.isDebugEnabled()) { s_logger.debug("Forwarding " + cmds[0].toString() + " to " + peer); } String peerName = Long.toString(peer); Answer[] answers = _clusterMgr.execute(peerName, agentId, cmds, true); return answers; } catch (Exception e) { s_logger.warn("Caught exception while talking to " + currentOwnerId, e); return null; } } private Runnable getTransferScanTask() { return new Runnable() { @Override public void run() { try { if (s_logger.isTraceEnabled()) { s_logger.trace("Clustered agent transfer scan check, management server id:" + _nodeId); } synchronized (_agentToTransferIds) { if (_agentToTransferIds.size() > 0) { s_logger.debug("Found " + _agentToTransferIds.size() + " agents to transfer"); //for (Long hostId : _agentToTransferIds) { for (Iterator<Long> iterator = _agentToTransferIds.iterator(); iterator.hasNext();) { Long hostId = iterator.next(); AgentAttache attache = findAttache(hostId); // if the thread: // 1) timed out waiting for the host to reconnect // 2) recipient management server is not active any more // remove the host from re-balance list and delete from op_host_transfer DB // no need to do anything with the real attache as we haven't modified it yet Date cutTime = DateUtil.currentGMTTime(); if (_hostTransferDao.isNotActive(hostId, new Date(cutTime.getTime() - rebalanceTimeOut))) { s_logger.debug("Timed out waiting for the host id=" + hostId + " to be ready to transfer, skipping rebalance for the host"); iterator.remove(); _hostTransferDao.completeAgentTransfer(hostId); continue; } HostTransferMapVO transferMap = _hostTransferDao.findByIdAndCurrentOwnerId(hostId, _nodeId); if (transferMap == null) { s_logger.debug("Can't transfer host id=" + hostId + "; record for the host no longer exists in op_host_transfer table"); iterator.remove(); _hostTransferDao.completeAgentTransfer(hostId); continue; } ManagementServerHostVO ms = _mshostDao.findByMsid(transferMap.getFutureOwner()); if (ms != null && ms.getState() != ManagementServerHost.State.Up) { s_logger.debug("Can't transfer host " + hostId + " as it's future owner is not in UP state: " + ms + ", skipping rebalance for the host"); iterator.remove(); _hostTransferDao.completeAgentTransfer(hostId); continue; } if (attache.getQueueSize() == 0 && attache.getNonRecurringListenersSize() == 0) { iterator.remove(); try { _executor.execute(new RebalanceTask(hostId, transferMap.getInitialOwner(), transferMap.getFutureOwner())); } catch (RejectedExecutionException ex) { s_logger.warn("Failed to submit rebalance task for host id=" + hostId + "; postponing the execution"); continue; } } else { s_logger.debug("Agent " + hostId + " can't be transfered yet as its request queue size is " + attache.getQueueSize() + " and listener queue size is " + attache.getNonRecurringListenersSize()); } } } else { if (s_logger.isTraceEnabled()) { s_logger.trace("Found no agents to be transfered by the management server " + _nodeId); } } } } catch (Throwable e) { s_logger.error("Problem with the clustered agent transfer scan check!", e); } } }; } private boolean setToWaitForRebalance(final long hostId, long currentOwnerId, long futureOwnerId) { s_logger.debug("Adding agent " + hostId + " to the list of agents to transfer"); synchronized (_agentToTransferIds) { return _agentToTransferIds.add(hostId); } } protected boolean rebalanceHost(final long hostId, long currentOwnerId, long futureOwnerId) throws AgentUnavailableException{ boolean result = true; if (currentOwnerId == _nodeId) { if (!startRebalance(hostId)) { s_logger.debug("Failed to start agent rebalancing"); failRebalance(hostId); return false; } try { Answer[] answer = sendRebalanceCommand(futureOwnerId, hostId, currentOwnerId, futureOwnerId, Event.StartAgentRebalance); if (answer == null || !answer[0].getResult()) { s_logger.warn("Host " + hostId + " failed to connect to the management server " + futureOwnerId + " as a part of rebalance process"); result = false; } } catch (Exception ex) { s_logger.warn("Host " + hostId + " failed to connect to the management server " + futureOwnerId + " as a part of rebalance process", ex); result = false; } if (result) { s_logger.debug("Successfully transfered host id=" + hostId + " to management server " + futureOwnerId); finishRebalance(hostId, futureOwnerId, Event.RebalanceCompleted); } else { s_logger.debug("Failed to transfer host id=" + hostId + " to management server " + futureOwnerId); finishRebalance(hostId, futureOwnerId, Event.RebalanceFailed); } } else if (futureOwnerId == _nodeId) { HostVO host = _hostDao.findById(hostId); try { if (s_logger.isDebugEnabled()) { s_logger.debug("Loading directly connected host " + host.getId() + "(" + host.getName() + ") as a part of rebalance process"); } result = loadDirectlyConnectedHost(host, true); } catch (Exception ex) { s_logger.warn("Unable to load directly connected host " + host.getId() + " as a part of rebalance due to exception: ", ex); result = false; } } return result; } protected void finishRebalance(final long hostId, long futureOwnerId, Event event) throws AgentUnavailableException{ boolean success = (event == Event.RebalanceCompleted) ? true : false; if (s_logger.isDebugEnabled()) { s_logger.debug("Finishing rebalancing for the agent " + hostId + " with result " + success); } AgentAttache attache = findAttache(hostId); if (attache == null || !(attache instanceof ClusteredAgentAttache)) { s_logger.debug("Unable to find forward attache for the host id=" + hostId + ", assuming that the agent disconnected already"); _hostTransferDao.completeAgentTransfer(hostId); return; } ClusteredAgentAttache forwardAttache = (ClusteredAgentAttache)attache; if (success) { //1) Set transfer mode to false - so the agent can start processing requests normally forwardAttache.setTransferMode(false); //2) Get all transfer requests and route them to peer Request requestToTransfer = forwardAttache.getRequestToTransfer(); while (requestToTransfer != null) { s_logger.debug("Forwarding request " + requestToTransfer.getSequence() + " held in transfer attache " + hostId + " from the management server " + _nodeId + " to " + futureOwnerId); boolean routeResult = routeToPeer(Long.toString(futureOwnerId), requestToTransfer.getBytes()); if (!routeResult) { logD(requestToTransfer.getBytes(), "Failed to route request to peer"); } requestToTransfer = forwardAttache.getRequestToTransfer(); } } else { failRebalance(hostId); } s_logger.debug("Management server " + _nodeId + " completed agent " + hostId + " rebalance"); _hostTransferDao.completeAgentTransfer(hostId); } protected void failRebalance(final long hostId) throws AgentUnavailableException{ s_logger.debug("Management server " + _nodeId + " failed to rebalance agent " + hostId); _hostTransferDao.completeAgentTransfer(hostId); reconnect(hostId); } @DB protected boolean startRebalance(final long hostId) { HostVO host = _hostDao.findById(hostId); if (host == null || host.getRemoved() != null) { s_logger.warn("Unable to find host record, fail start rebalancing process"); return false; } synchronized (_agents) { ClusteredDirectAgentAttache attache = (ClusteredDirectAgentAttache)_agents.get(hostId); if (attache != null && attache.getQueueSize() == 0 && attache.getNonRecurringListenersSize() == 0) { removeAgent(attache, Status.Rebalancing); ClusteredAgentAttache forwardAttache = (ClusteredAgentAttache)createAttache(hostId); if (forwardAttache == null) { s_logger.warn("Unable to create a forward attache for the host " + hostId + " as a part of rebalance process"); return false; } s_logger.debug("Putting agent id=" + hostId + " to transfer mode"); forwardAttache.setTransferMode(true); _agents.put(hostId, forwardAttache); } else { if (attache == null) { s_logger.warn("Attache for the agent " + hostId + " no longer exists on management server " + _nodeId + ", can't start host rebalancing"); } else { s_logger.warn("Attache for the agent " + hostId + " has request queue size= " + attache.getQueueSize() + " and listener queue size " + attache.getNonRecurringListenersSize() + ", can't start host rebalancing"); } return false; } } Transaction txn = Transaction.currentTxn(); txn.start(); s_logger.debug("Updating host id=" + hostId + " with the status " + Status.Rebalancing); host.setManagementServerId(null); _hostDao.updateStatus(host, Event.StartAgentRebalance, _nodeId); _hostTransferDao.startAgentTransfer(hostId); txn.commit(); return true; } protected void cleanupTransferMap() { List<HostTransferMapVO> hostsJoingingCluster = _hostTransferDao.listHostsJoiningCluster(_nodeId); for (HostTransferMapVO hostJoingingCluster : hostsJoingingCluster) { _hostTransferDao.remove(hostJoingingCluster.getId()); } List<HostTransferMapVO> hostsLeavingCluster = _hostTransferDao.listHostsLeavingCluster(_nodeId); for (HostTransferMapVO hostLeavingCluster : hostsLeavingCluster) { _hostTransferDao.remove(hostLeavingCluster.getId()); } } protected class RebalanceTask implements Runnable { Long hostId = null; Long currentOwnerId = null; Long futureOwnerId = null; public RebalanceTask(long hostId, long currentOwnerId, long futureOwnerId) { this.hostId = hostId; this.currentOwnerId = currentOwnerId; this.futureOwnerId = futureOwnerId; } @Override public void run() { try { if (s_logger.isDebugEnabled()) { s_logger.debug("Rebalancing host id=" + hostId); } rebalanceHost(hostId, currentOwnerId, futureOwnerId); } catch (Exception e) { s_logger.warn("Unable to rebalance host id=" + hostId, e); } finally { StackMaid.current().exitCleanup(); } } } }
package com.devicehive.model.updates; import com.devicehive.model.HiveEntity; import com.devicehive.model.NullableWrapper; import com.devicehive.model.User; import com.devicehive.model.enums.UserRole; import com.devicehive.model.enums.UserStatus; public class UserUpdate implements HiveEntity { private static final long serialVersionUID = -8353201743020153250L; private NullableWrapper<String> login; private NullableWrapper<Integer> role; private NullableWrapper<Integer> status; private NullableWrapper<String> password; private NullableWrapper<String> googleLogin; private NullableWrapper<String> facebookLogin; private NullableWrapper<String> githubLogin; public NullableWrapper<String> getLogin() { return login; } public void setLogin(NullableWrapper<String> login) { this.login = login; } public NullableWrapper<Integer> getRole() { return role; } public void setRole(NullableWrapper<Integer> role) { this.role = role; } public NullableWrapper<Integer> getStatus() { return status; } public void setStatus(NullableWrapper<Integer> status) { this.status = status; } public NullableWrapper<String> getPassword() { return password; } public void setPassword(NullableWrapper<String> password) { this.password = password; } public NullableWrapper<String> getGoogleLogin() { return googleLogin; } public void setGoogleLogin(NullableWrapper<String> googleLogin) { this.googleLogin = googleLogin; } public NullableWrapper<String> getFacebookLogin() { return facebookLogin; } public void setFacebookLogin(NullableWrapper<String> facebookLogin) { this.facebookLogin = facebookLogin; } public NullableWrapper<String> getGithubLogin() { return githubLogin; } public void setGithubLogin(NullableWrapper<String> githubLogin) { this.githubLogin = githubLogin; } public UserRole getRoleEnum() { if (role == null) { return null; } Integer roleValue = role.getValue(); if (roleValue == null) { return null; } return UserRole.values()[roleValue]; } public UserStatus getStatusEnum() { if (status == null) { return null; } Integer statusValue = status.getValue(); if (statusValue == null) { return null; } return UserStatus.values()[statusValue]; } public User convertTo() { User result = new User(); if (login != null) { result.setLogin(login.getValue()); } if (googleLogin != null) { result.setGoogleLogin(googleLogin.getValue()); } if (facebookLogin != null) { result.setFacebookLogin(facebookLogin.getValue()); } if (githubLogin != null) { result.setGithubLogin(githubLogin.getValue()); } result.setStatus(getStatusEnum()); result.setRole(getRoleEnum()); return result; } }
package fi.nls.oskari.service; import fi.nls.oskari.domain.GuestUser; import fi.nls.oskari.domain.Role; import fi.nls.oskari.domain.User; import fi.nls.oskari.log.LogFactory; import fi.nls.oskari.log.Logger; import fi.nls.oskari.util.PropertyUtil; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.UUID; /** * Common interface for managing users. * TODO: this interface is still under development and new methods will propably be added when needed. */ public abstract class UserService { private static final Logger log = LogFactory.getLogger(UserService.class); private static UserService instance = null; /** * Returns a concrete implementation of UserService. Class to be returned is defined with property "oskari.user.service". * @return * @throws ServiceException if class cannot be */ public static UserService getInstance() throws ServiceException { if(instance != null) { return instance; } final String className = PropertyUtil.getOptional("oskari.user.service"); if(className == null) { throw new ServiceException("User service implementation not defined, add 'oskari.user.service' property with a value of fully qualified classname extending " + UserService.class.getCanonicalName()); } try { instance = (UserService)Class.forName(className).newInstance(); instance.init(); return instance; } catch (Exception e) { throw new ServiceException("Error initializing UserService for classname: "+ className, e); } } public User getGuestUser() { return new GuestUser(); } /** * Optional initialize hook. Original init does nothing, so this is just a hook to do initialization on actual service implementations. * @throws ServiceException should be thrown if something goes wrong on init. */ public void init() throws ServiceException { } /** * Optional destroy hook. Original teardown does nothing, so this is just a hook for cleaning up on actual service implementations. * @throws ServiceException should be thrown if something goes wrong on teardown. */ public void teardown() throws ServiceException { } /** * Checks if the user exists in the system. * @param user username * @param pass password * @return logged in user if successful, null if user not found * @throws ServiceException if anything goes wrong internally. */ public abstract User login(String user, String pass) throws ServiceException; /** * Inserts role to a user * @param roleId String * @return something * @throws ServiceException if anything goes wrong internally. */ public Role insertRole(String roleId) throws ServiceException{ throw new ServiceException("Not Implemented Yet"); } /** * Deletes role from a user * @param roleId String * @return something * @throws ServiceException if anything goes wrong internally. */ public String deleteRole(int roleId) throws ServiceException{ throw new ServiceException("Not Implemented Yet"); } /** * Modifies a users role * @param roleId String * @return something * @throws ServiceException if anything goes wrong internally. */ public String modifyRole(String roleId, String userID) throws ServiceException{ throw new ServiceException("Not Implemented Yet"); } /** * Returns all roles that exist in the system * @param platformSpecificParams optional platform specific parameters needed to get/filter roles. If implementation doesnt need any an empty map can be used. * @return all roles from the system * @throws ServiceException if anything goes wrong internally. */ public abstract Role[] getRoles(Map<Object, Object> platformSpecificParams) throws ServiceException; /** * Generates UUID from unique user id * @param uid string that identifies user * @return uuid */ public String generateUuid(String uid) { if(uid == null) { return generateUuid(); } return UUID.nameUUIDFromBytes(uid.getBytes()).toString(); } /** * Generates random UUID * @return uuid */ public String generateUuid() { return UUID.randomUUID().toString(); } /** * Returns all roles that exist in the system. Convenience method for calling getRoles(Map) with empty map * @return * @throws ServiceException */ public Role[] getRoles() throws ServiceException { return getRoles(Collections.emptyMap()); } /** * Returns all roles that exist in the system. Convenience method for calling getRoles(Map) with empty map * @return * @throws ServiceException */ public Role getRoleByName(final String name) { try { // TODO: maybe some caching for roles? Role[] roles = getRoles(); for(Role role : roles) { if(role.getName().equals(name)) { return role; } } } catch (Exception ex) { log.error(ex, "Error getting roles from user service"); } return null; } /** * Return the user by username. This method should be overridden in concrete implementation. The * default implementation always throws an exception. * @param username * @return User user * @throws ServiceException */ public User getUser(String username) throws ServiceException { throw new ServiceException("Not implemented"); } /** * Return the user by id. This method should be overridden in concrete implementation. The * default implementation always throws an exception. * @param id * @return User user * @throws ServiceException */ public User getUser(long id) throws ServiceException { throw new ServiceException("Not implemented"); } /** * Return all users. This method should be overridden in concrete implementation. The * default implementation always throws an exception. * @return List<User> users * @throws ServiceException */ public List<User> getUsers() throws ServiceException { return Collections.emptyList(); } /** * Return all users. This method should be overridden in concrete implementation. The * default implementation always throws an exception. * @return List<User> users * @throws ServiceException */ public List<User> getUsersWithRoles() throws ServiceException { return Collections.emptyList(); } /** * Create a new user. This method should be overridden in concrete implementation. The * default implementation always throws an exception. * @param user User to be created * @return User created user * @throws ServiceException */ public User createUser(User user) throws ServiceException { throw new ServiceException("Not implemented"); } public User createUser(User user, String[] roleIds) throws ServiceException { throw new ServiceException("Not implemented"); } /** * Modify a user. This method should be overridden in concrete implementation. The * default implementation always throws an exception. * @param user Modified user * @return Modified user * @throws ServiceException */ public User modifyUser(User user) throws ServiceException { throw new ServiceException("Not implemented"); } public User modifyUserwithRoles(User user, String[] roleIds) throws ServiceException { throw new ServiceException("Not implemented"); } /** * Delete a user. This method should be overridden in concrete implementation. The * default implementation always throws an exception. * @param id User id * @throws ServiceException */ public void deleteUser(long id) throws ServiceException { throw new ServiceException("Not implemented"); } /** * Set a user's password. This method should be overridden in concrete implementation. The * default implementation always throws an exception. * @param screenname User name * @param password User password * @throws ServiceException */ public void setUserPassword(String screenname, String password) throws ServiceException { throw new ServiceException("Not implemented"); } /** * Updates a user's password. This method should be overridden in concrete implementation. The * default implementation always throws an exception. * @param screenname User name * @param password User password * @throws ServiceException */ public void updateUserPassword(String screenname, String password) throws ServiceException { throw new ServiceException("Not implemented"); } }
package com.commercetools.util; import org.apache.http.*; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.conn.ConnectionKeepAliveStrategy; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicHeaderElementIterator; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.net.ssl.SSLException; import java.io.IOException; import java.net.ConnectException; import java.net.UnknownHostException; import java.util.Arrays; import java.util.Objects; public final class HttpRequestUtil { static final int REQUEST_TIMEOUT = 10000; static final int RETRY_TIMES = 5; static final int CONNECTION_MAX_TOTAL = 200; static final int CONNECTION_MAX_PER_ROUTE = 20; /** * Don't resend request on connection exception once it has been successfully sent. */ static final boolean REQUEST_SENT_RETRY_ENABLED = false; /** * This retry handler implementation overrides default list of <i>nonRetriableClasses</i> excluding * {@link java.io.InterruptedIOException} and {@link ConnectException} so the client will retry on interruption and * socket timeouts. * <p> * The implementation will retry 3 times. */ private static final DefaultHttpRequestRetryHandler HTTP_REQUEST_RETRY_ON_SOCKET_TIMEOUT = new DefaultHttpRequestRetryHandler(RETRY_TIMES, REQUEST_SENT_RETRY_ENABLED, Arrays.asList( UnknownHostException.class, SSLException.class)) { // it is an anonymous class extension, but we don't need the functionality change, // we just need to access protected constructor // DefaultHttpRequestRetryHandler(int, boolean, Collection<Class<? extends IOException>>), // where we could specify reduced nonRetriableClasses list. // Thus the implementation is empty. }; private static final BasicResponseHandler BASIC_RESPONSE_HANDLER = new BasicResponseHandler(); private static ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() { public long getKeepAliveDuration(HttpResponse response, HttpContext context) { // Honor 'keep-alive' header HeaderElementIterator it = new BasicHeaderElementIterator( response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { try { return Long.parseLong(value) * 1000; } catch (NumberFormatException ignore) { } } } // Keep alive for 5 seconds only return 5000; } }; private static final CloseableHttpClient CLIENT = HttpClientBuilder.create() .setDefaultRequestConfig(RequestConfig.custom() .setConnectionRequestTimeout(REQUEST_TIMEOUT) .setSocketTimeout(REQUEST_TIMEOUT) .setConnectTimeout(REQUEST_TIMEOUT) .build()) .setRetryHandler(HTTP_REQUEST_RETRY_ON_SOCKET_TIMEOUT) .setKeepAliveStrategy(keepAliveStrategy) .setConnectionManager(buildDefaultConnectionManager()) .build(); private HttpRequestUtil() { } private static PoolingHttpClientConnectionManager buildDefaultConnectionManager() { final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(CONNECTION_MAX_TOTAL); connectionManager.setValidateAfterInactivity(0); connectionManager.setDefaultMaxPerRoute(CONNECTION_MAX_PER_ROUTE); return connectionManager; } /** * Execute retryable HTTP GET request with default {@link #REQUEST_TIMEOUT} * * @param url url to get * @return response from the {@code url} * @throws IOException in case of a problem or the connection was aborted */ public static HttpResponse executeGetRequest(@Nonnull String url) throws IOException { return executeReadAndCloseRequest(new HttpGet(url)); } /** * Make URL request and return a response string. * * @param url URL to get/query * @return response string from the request * @throws IOException in case of a problem or the connection was aborted */ public static String executeGetRequestToString(@Nonnull String url) throws IOException { return responseToString(executeGetRequest(url)); } /** * Execute retryable HTTP POST request with specified {@code timeoutMsec} * * @param url url to post * @param parameters list of values to send as URL encoded form data. If <b>null</b> - not data is sent, but * empty POST request is executed. * @return response from the {@code url} * @throws IOException in case of a problem or the connection was aborted */ public static HttpResponse executePostRequest(@Nonnull String url, @Nullable Iterable<? extends NameValuePair> parameters) throws IOException { final HttpPost request = new HttpPost(url); if (parameters != null) { request.setEntity(new UrlEncodedFormEntity(parameters, Consts.UTF_8)); } return executeReadAndCloseRequest(request); } /** * Make URL request and return a response string. * * @param url URL to post/query * @param parameters list of values to send as URL encoded form data. If <b>null</b> - not data is sent, but * empty POST request is executed. * @return response string from the request * @throws IOException in case of a problem or the connection was aborted */ public static String executePostRequestToString(@Nonnull String url, @Nullable Iterable<? extends NameValuePair> parameters) throws IOException { return responseToString(executePostRequest(url, parameters)); } /** * Read string content from {@link HttpResponse}. * * @param response response to read * @return string content of the response * @throws IOException in case of a problem or the connection was aborted */ public static String responseToString(@Nonnull final HttpResponse response) throws IOException { return BASIC_RESPONSE_HANDLER.handleResponse(response); } /** * Short {@link BasicNameValuePair} factory alias. * * @param name request argument name * @param value request argument value. If value is <b>null</b> - {@link BasicNameValuePair#value} set to * <b>null</b>, * otherwise {@link Object#toString()} is applied. * @return new instance of {@link BasicNameValuePair} with {@code name} and {@code value} */ public static BasicNameValuePair nameValue(@Nonnull final String name, @Nullable final Object value) { return new BasicNameValuePair(name, Objects.toString(value, null)); } /** * By default apache httpclient responses are not closed, thus we should explicitly read the stream and close the * connection. * <p> * The connection will be closed even if read exception occurs. * * @param request GET/POST/other request to execute, read and close * @return read and closed {@link CloseableHttpResponse} instance from * {@link CloseableHttpClient#execute(HttpUriRequest)} * where {@link HttpResponse#getEntity()} is set to read string value. * @throws IOException if reading failed. Note, even in case of exception the {@code response} will be closed. */ private static CloseableHttpResponse executeReadAndCloseRequest(@Nonnull final HttpUriRequest request) throws IOException { final CloseableHttpResponse response = CLIENT.execute(request); try { final HttpEntity entity = response.getEntity(); if (entity != null) { final ByteArrayEntity byteArrayEntity = new ByteArrayEntity(EntityUtils.toByteArray(entity)); final ContentType contentType = ContentType.getOrDefault(entity); byteArrayEntity.setContentType(contentType.toString()); response.setEntity(byteArrayEntity); } } finally { response.close(); } return response; } }
package com.commercetools.util; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.net.ssl.SSLException; import java.io.IOException; import java.net.ConnectException; import java.net.UnknownHostException; import java.util.Arrays; import java.util.Objects; /** * Util to make simple retryable HTTP GET/POST requests. * <p> * The http client options: <ul> * <li>reusable, e.g. one instance per application</li> * <li>multi-threading</li> * <li>socket/request/connect timeouts are 10 sec</li> * <li>retries on connections exceptions up to 3 times, if request has not been sent yet * (see {@link DefaultHttpRequestRetryHandler#isRequestSentRetryEnabled()} * and {@link #HTTP_REQUEST_RETRY_ON_SOCKET_TIMEOUT})</li> * </ul> * <p> * This util is intended to replace <i>Unirest</i> and <i>fluent-hc</i> dependencies, which don't propose any flexible * way to implement retry strategy. * <p> * Implementation notes (for developers):<ul> * <li>remember, the responses must be closed, otherwise the connections won't be return to the pool, * no new connections will be available and {@link org.apache.http.conn.ConnectionPoolTimeoutException} will be * thrown. See {@link #executeReadAndCloseRequest(HttpUriRequest)}</li> * <li>{@link UrlEncodedFormEntity} the charset should be explicitly set to UTF-8, otherwise * {@link HTTP#DEF_CONTENT_CHARSET ISO_8859_1} is used, which is not acceptable for German alphabet</li> * </ul> */ public final class HttpRequestUtil { public static final int REQUEST_TIMEOUT = 10000; public static final int RETRY_TIMES = 3; /** * This retry handler implementation override default list of <i>nonRetriableClasses</i> excluding * {@link java.io.InterruptedIOException} and {@link ConnectException} so the client will retry on interruption and * socket timeouts. * <p> * The implementation will retry 3 times. */ private static final DefaultHttpRequestRetryHandler HTTP_REQUEST_RETRY_ON_SOCKET_TIMEOUT = new DefaultHttpRequestRetryHandler(RETRY_TIMES, false, Arrays.asList( UnknownHostException.class, SSLException.class)) { // empty implementation, we just need to use protected constructor }; private static final CloseableHttpClient CLIENT = HttpClientBuilder.create() .setDefaultRequestConfig(RequestConfig.custom() .setConnectionRequestTimeout(REQUEST_TIMEOUT) .setSocketTimeout(REQUEST_TIMEOUT) .setConnectTimeout(REQUEST_TIMEOUT) .build()) .setRetryHandler(HTTP_REQUEST_RETRY_ON_SOCKET_TIMEOUT) .build(); private static final BasicResponseHandler BASIC_RESPONSE_HANDLER = new BasicResponseHandler(); /** * Execute retryable HTTP GET request with default {@link #REQUEST_TIMEOUT} * * @param url url to get * @return response from the {@code url} * @throws IOException in case of a problem or the connection was aborted */ public static HttpResponse executeGetRequest(@Nonnull String url) throws IOException { return executeReadAndCloseRequest(new HttpGet(url)); } /** * Make URL request and return a response string. * * @param url URL to get/query * @return response string from the request * @throws IOException in case of a problem or the connection was aborted */ public static String executeGetRequestToString(@Nonnull String url) throws IOException { return responseToString(executeGetRequest(url)); } /** * Execute retryable HTTP POST request with specified {@code timeoutMsec} * * @param url url to post * @param parameters list of values to send as URL encoded form data. If <b>null</b> - not data is sent, but * empty POST request is executed. * @return response from the {@code url} * @throws IOException in case of a problem or the connection was aborted */ public static HttpResponse executePostRequest(@Nonnull String url, @Nullable Iterable<? extends NameValuePair> parameters) throws IOException { final HttpPost request = new HttpPost(url); if (parameters != null) { request.setEntity(new UrlEncodedFormEntity(parameters, Consts.UTF_8)); } return executeReadAndCloseRequest(request); } /** * Make URL request and return a response string. * * @param url URL to post/query * @param parameters list of values to send as URL encoded form data. If <b>null</b> - not data is sent, but * empty POST request is executed. * @return response string from the request * @throws IOException in case of a problem or the connection was aborted */ public static String executePostRequestToString(@Nonnull String url, @Nullable Iterable<? extends NameValuePair> parameters) throws IOException { return responseToString(executePostRequest(url, parameters)); } /** * Read string content from {@link HttpResponse}. * * @param response response to read * @return string content of the response * @throws IOException in case of a problem or the connection was aborted */ public static String responseToString(@Nonnull final HttpResponse response) throws IOException { return BASIC_RESPONSE_HANDLER.handleResponse(response); } /** * Short {@link BasicNameValuePair} factory alias. * * @param name request argument name * @param value request argument value. If value is <b>null</b> - {@link BasicNameValuePair#value} set to <b>null</b>, * otherwise {@link Object#toString()} is applied. * @return new instance of {@link BasicNameValuePair} with {@code name} and {@code value} */ public static BasicNameValuePair nvPair(@Nonnull final String name, @Nullable final Object value) { return new BasicNameValuePair(name, Objects.toString(value, null)); } /** * Be default apache httpclient responses are not closed, thus we should explicitly read the stream and close the * connection. * <p> * The connection will be closed even if read exception occurs. * * @param request GET/POST/other request to execute, read and close * @return read and closed {@link CloseableHttpResponse} instance from {@link CloseableHttpClient#execute(HttpUriRequest)} * where {@link HttpResponse#getEntity()} is set to read string value. * @throws IOException if reading failed. Note, even in case of exception the {@code response} will be closed. */ private static CloseableHttpResponse executeReadAndCloseRequest(@Nonnull final HttpUriRequest request) throws IOException { final CloseableHttpResponse response = CLIENT.execute(request); try { final HttpEntity entity = response.getEntity(); if (entity != null) { final ByteArrayEntity byteArrayEntity = new ByteArrayEntity(EntityUtils.toByteArray(entity)); final ContentType contentType = ContentType.getOrDefault(entity); byteArrayEntity.setContentType(contentType.toString()); response.setEntity(byteArrayEntity); } } finally { response.close(); } return response; } private HttpRequestUtil() { } }
package org.gluu.oxtrust.service; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import org.gluu.model.GluuAttribute; import org.gluu.oxtrust.exception.DuplicateEmailException; import org.gluu.oxtrust.model.GluuCustomAttribute; import org.gluu.oxtrust.model.GluuCustomPerson; import org.gluu.oxtrust.model.User; import org.gluu.oxtrust.util.OxTrustConstants; import org.gluu.persist.PersistenceEntryManager; import org.gluu.persist.exception.operation.DuplicateEntryException; import org.gluu.persist.model.AttributeData; import org.gluu.persist.model.SearchScope; import org.gluu.persist.model.base.SimpleBranch; import org.gluu.persist.model.base.SimpleUser; import org.gluu.search.filter.Filter; import org.gluu.util.ArrayHelper; import org.gluu.util.OxConstants; import org.gluu.util.StringHelper; import org.joda.time.format.ISODateTimeFormat; import org.slf4j.Logger; @ApplicationScoped public class PersonService implements Serializable, IPersonService { private static final long serialVersionUID = 6685720517520443399L; @Inject private Logger log; @Inject private PersistenceEntryManager persistenceEntryManager; @Inject private AttributeService attributeService; @Inject private OrganizationService organizationService; private List<GluuCustomAttribute> mandatoryAttributes; /* * (non-Javadoc) * * @see * org.gluu.oxtrust.ldap.service.IPersonService#addCustomObjectClass(org.gluu. * oxtrust.model.GluuCustomPerson) */ @Override public void addCustomObjectClass(GluuCustomPerson person) { String customObjectClass = attributeService.getCustomOrigin(); String[] customObjectClassesArray = person.getCustomObjectClasses(); if (ArrayHelper.isNotEmpty(customObjectClassesArray)) { List<String> customObjectClassesList = Arrays.asList(customObjectClassesArray); if (!customObjectClassesList.contains(customObjectClass)) { List<String> customObjectClassesListUpdated = new ArrayList<String>(); customObjectClassesListUpdated.addAll(customObjectClassesList); customObjectClassesListUpdated.add(customObjectClass); customObjectClassesList = customObjectClassesListUpdated; } person.setCustomObjectClasses(customObjectClassesList.toArray(new String[0])); } else { person.setCustomObjectClasses(new String[] { customObjectClass }); } } /* * (non-Javadoc) * * @see * org.gluu.oxtrust.ldap.service.IPersonService#addPerson(org.gluu.oxtrust.model * .GluuCustomPerson) */ // TODO: Review this methods. We need to check if uid is unique in outside // method @Override public void addPerson(GluuCustomPerson person) throws Exception { try { GluuCustomPerson uidPerson = new GluuCustomPerson(); uidPerson.setUid(person.getUid()); List<GluuCustomPerson> persons = findPersons(uidPerson, 1); if (persons == null || persons.size() == 0) { person.setCreationDate(new Date()); persistenceEntryManager.persist(person); } else { throw new DuplicateEntryException("Duplicate UID value: " + person.getUid()); } } catch (Exception e) { if (e.getCause().getMessage().contains("unique attribute conflict was detected for attribute mail")) { throw new DuplicateEmailException("Email Already Registered"); } else { throw new Exception("Duplicate UID value: " + person.getUid()); } } } /* * (non-Javadoc) * * @see * org.gluu.oxtrust.ldap.service.IPersonService#updatePerson(org.gluu.oxtrust. * model.GluuCustomPerson) */ @Override public void updatePerson(GluuCustomPerson person) throws Exception { try { Date updateDate = new Date(); person.setUpdatedAt(updateDate); if (person.getAttribute("oxTrustMetaLastModified") != null) { person.setAttribute("oxTrustMetaLastModified", ISODateTimeFormat.dateTime().withZoneUTC().print(updateDate.getTime())); } persistenceEntryManager.merge(person); } catch (Exception e) { if (e.getCause().getMessage().contains("unique attribute conflict was detected for attribute mail")) { throw new DuplicateEmailException("Email Already Registered"); } else { throw new Exception("Duplicate UID value: " + person.getUid(), e); } } } /* * (non-Javadoc) * * @see * org.gluu.oxtrust.ldap.service.IPersonService#removePerson(org.gluu.oxtrust. * model.GluuCustomPerson) */ @Override public void removePerson(GluuCustomPerson person) { persistenceEntryManager.removeRecursively(person.getDn()); } /* * (non-Javadoc) * * @see * org.gluu.oxtrust.ldap.service.IPersonService#searchPersons(java.lang.String, * int) */ @Override public List<GluuCustomPerson> searchPersons(String pattern, int sizeLimit) { Filter searchFilter = buildFilter(pattern); return persistenceEntryManager.findEntries(getDnForPerson(null), GluuCustomPerson.class, searchFilter, sizeLimit); } /* * (non-Javadoc) * * @see * org.gluu.oxtrust.ldap.service.IPersonService#searchPersons(java.lang.String) */ @Override public List<GluuCustomPerson> searchPersons(String pattern) { Filter searchFilter = buildFilter(pattern); return persistenceEntryManager.findEntries(getDnForPerson(null), GluuCustomPerson.class, searchFilter); } private Filter buildFilter(String pattern) { String[] targetArray = new String[] { pattern }; Filter uidFilter = Filter.createSubstringFilter(OxConstants.UID, null, targetArray, null); Filter mailFilter = Filter.createSubstringFilter(OxTrustConstants.mail, null, targetArray, null); Filter nameFilter = Filter.createSubstringFilter(OxTrustConstants.displayName, null, targetArray, null); Filter ppidFilter = Filter.createSubstringFilter(OxTrustConstants.ppid, null, targetArray, null); Filter inumFilter = Filter.createSubstringFilter(OxTrustConstants.inum, null, targetArray, null); Filter snFilter = Filter.createSubstringFilter(OxTrustConstants.sn, null, targetArray, null); Filter searchFilter = Filter.createORFilter(uidFilter, mailFilter, nameFilter, ppidFilter, inumFilter, snFilter); return searchFilter; } /* * (non-Javadoc) * * @see * org.gluu.oxtrust.ldap.service.IPersonService#findPersons(org.gluu.oxtrust. * model.GluuCustomPerson, int) */ @Override public List<GluuCustomPerson> findPersons(GluuCustomPerson person, int sizeLimit) { person.setBaseDn(getDnForPerson(null)); return persistenceEntryManager.findEntries(person, sizeLimit); } /* * (non-Javadoc) * * @see * org.gluu.oxtrust.ldap.service.IPersonService#searchPersons(java.lang.String, * int, java.util.List) */ @Override public List<GluuCustomPerson> searchPersons(String pattern, int sizeLimit, List<GluuCustomPerson> excludedPersons) throws Exception { Filter orFilter = buildFilter(pattern); Filter searchFilter = orFilter; if (excludedPersons != null && excludedPersons.size() > 0) { List<Filter> excludeFilters = new ArrayList<Filter>(); for (GluuCustomPerson excludedPerson : excludedPersons) { Filter eqFilter = Filter.createEqualityFilter(OxConstants.UID, excludedPerson.getUid()); excludeFilters.add(eqFilter); } Filter orExcludeFilter = null; if (excludedPersons.size() == 1) { orExcludeFilter = excludeFilters.get(0); } else { orExcludeFilter = Filter.createORFilter(excludeFilters); } Filter notFilter = Filter.createNOTFilter(orExcludeFilter); searchFilter = Filter.createANDFilter(orFilter, notFilter); } return persistenceEntryManager.findEntries(getDnForPerson(null), GluuCustomPerson.class, searchFilter, sizeLimit); } /* * (non-Javadoc) * * @see * org.gluu.oxtrust.ldap.service.IPersonService#findAllPersons(java.lang.String[ * ]) */ @Override public List<GluuCustomPerson> findAllPersons(String[] returnAttributes) { return persistenceEntryManager.findEntries(getDnForPerson(null), GluuCustomPerson.class, null, returnAttributes); } /* * (non-Javadoc) * * @see * org.gluu.oxtrust.ldap.service.IPersonService#findPersonsByUids(java.util. * List, java.lang.String[]) */ @Override public List<GluuCustomPerson> findPersonsByUids(List<String> uids, String[] returnAttributes) throws Exception { List<Filter> uidFilters = new ArrayList<Filter>(); for (String uid : uids) { uidFilters.add(Filter.createEqualityFilter(OxConstants.UID, uid)); } Filter filter = Filter.createORFilter(uidFilters); return persistenceEntryManager.findEntries(getDnForPerson(null), GluuCustomPerson.class, filter, returnAttributes); } /* * (non-Javadoc) * * @see * org.gluu.oxtrust.ldap.service.IPersonService#findPersonsByMailds(java.util. * List, java.lang.String[]) */ @Override public List<GluuCustomPerson> findPersonsByMailids(List<String> mailids, String[] returnAttributes) throws Exception { List<Filter> mailidFilters = new ArrayList<Filter>(); for (String mailid : mailids) { mailidFilters.add(Filter.createEqualityFilter(OxTrustConstants.mail, mailid)); } Filter filter = Filter.createORFilter(mailidFilters); return persistenceEntryManager.findEntries(getDnForPerson(null), GluuCustomPerson.class, filter, returnAttributes); } /* * (non-Javadoc) * * @see * org.gluu.oxtrust.ldap.service.IPersonService#findPersonByDn(java.lang.String, * java.lang.String) */ @Override public GluuCustomPerson findPersonByDn(String dn, String... returnAttributes) { return persistenceEntryManager.find(dn, GluuCustomPerson.class, returnAttributes); } /* * (non-Javadoc) * * @see * org.gluu.oxtrust.ldap.service.IPersonService#containsPerson(org.gluu.oxtrust. * model.GluuCustomPerson) */ @SuppressWarnings("deprecation") @Override public boolean containsPerson(GluuCustomPerson person) { boolean result = false; try { result = persistenceEntryManager.contains(GluuCustomPerson.class); } catch (Exception e) { log.debug(e.getMessage(), e); } return result; } /* * (non-Javadoc) * * @see org.gluu.oxtrust.ldap.service.IPersonService#contains(java.lang.String) */ @Override public boolean contains(String dn) { return persistenceEntryManager.contains(dn, GluuCustomPerson.class); } /* * (non-Javadoc) * * @see * org.gluu.oxtrust.ldap.service.IPersonService#getPersonByDn(java.lang.String) */ @Override public GluuCustomPerson getPersonByDn(String dn) { GluuCustomPerson result = persistenceEntryManager.find(GluuCustomPerson.class, dn); return result; } /* * (non-Javadoc) * * @see org.gluu.oxtrust.ldap.service.IPersonService#getPersonByInum(java.lang. * String) */ @Override public GluuCustomPerson getPersonByInum(String inum) { GluuCustomPerson person = null; try { person = persistenceEntryManager.find(GluuCustomPerson.class, getDnForPerson(inum)); } catch (Exception e) { log.error("Failed to find Person by Inum " + inum, e); } return person; } public GluuCustomPerson getPersonByUid(String uid, String... returnAttributes) { List<GluuCustomPerson> entries = getPersonsByUid(uid, returnAttributes); if (entries.size() > 0) { return entries.get(0); } else { return null; } } /* * (non-Javadoc) * * @see org.gluu.oxtrust.ldap.service.IPersonService#countPersons() */ @Override public int countPersons() { String dn = getDnForPerson(null); Class<?> searchClass = GluuCustomPerson.class; if (persistenceEntryManager.hasBranchesSupport(dn)) { searchClass = SimpleBranch.class; } return persistenceEntryManager.countEntries(dn, searchClass, null, SearchScope.BASE); } /* * (non-Javadoc) * * @see org.gluu.oxtrust.ldap.service.IPersonService#generateInumForNewPerson() */ @Override public String generateInumForNewPerson() { GluuCustomPerson person = null; String newInum = null; String newDn = null; do { newInum = generateInumForNewPersonImpl(); newDn = getDnForPerson(newInum); person = new GluuCustomPerson(); person.setDn(newDn); } while (persistenceEntryManager.contains(newDn, GluuCustomPerson.class)); return newInum; } /** * Generate new inum for person * * @return New inum for person * @throws Exception */ private String generateInumForNewPersonImpl() { return UUID.randomUUID().toString(); } /* * (non-Javadoc) * * @see * org.gluu.oxtrust.ldap.service.IPersonService#getDnForPerson(java.lang.String) */ @Override public String getDnForPerson(String inum) { String orgDn = organizationService.getDnForOrganization(); if (StringHelper.isEmpty(inum)) { return String.format("ou=people,%s", orgDn); } return String.format("inum=%s,ou=people,%s", inum, orgDn); } /* * (non-Javadoc) * * @see * org.gluu.oxtrust.ldap.service.IPersonService#authenticate(java.lang.String, * java.lang.String) */ @Override public boolean authenticate(String userName, String password) { return persistenceEntryManager.authenticate(userName, password); } /* * (non-Javadoc) * * @see org.gluu.oxtrust.ldap.service.IPersonService#getMandatoryAtributes() */ @Override public List<GluuCustomAttribute> getMandatoryAtributes() { if (this.mandatoryAttributes == null) { mandatoryAttributes = new ArrayList<GluuCustomAttribute>(); mandatoryAttributes.add(new GluuCustomAttribute(OxConstants.UID, "", true, true)); mandatoryAttributes.add(new GluuCustomAttribute("givenName", "", true, true)); mandatoryAttributes.add(new GluuCustomAttribute("displayName", "", true, true)); mandatoryAttributes.add(new GluuCustomAttribute("sn", "", true, true)); mandatoryAttributes.add(new GluuCustomAttribute("mail", "", true, true)); mandatoryAttributes.add(new GluuCustomAttribute("userPassword", "", true, true)); mandatoryAttributes.add(new GluuCustomAttribute("gluuStatus", "", true, true)); } return mandatoryAttributes; } /* * (non-Javadoc) * * @see * org.gluu.oxtrust.ldap.service.IPersonService#getPersonUid(java.util.List) */ @Override public String getPersonUids(List<GluuCustomPerson> persons) throws Exception { StringBuilder sb = new StringBuilder(); for (Iterator<GluuCustomPerson> iterator = persons.iterator(); iterator.hasNext();) { GluuCustomPerson call = iterator.next(); sb.append('\'').append(call.getUid()).append('\''); if (iterator.hasNext()) { sb.append(", "); } } return sb.toString(); } /* * (non-Javadoc) * * @see * org.gluu.oxtrust.ldap.service.IPersonService#getPersonMailid(java.util.List) */ @Override public String getPersonMailids(List<GluuCustomPerson> persons) throws Exception { StringBuilder sb = new StringBuilder(); for (Iterator<GluuCustomPerson> iterator = persons.iterator(); iterator.hasNext();) { GluuCustomPerson call = iterator.next(); sb.append('\'').append(call.getMail()).append('\''); if (iterator.hasNext()) { sb.append(", "); } } return sb.toString(); } /* * (non-Javadoc) * * @see * org.gluu.oxtrust.ldap.service.IPersonService#createEntities(java.util.Map) */ @Override public List<GluuCustomPerson> createEntities(Map<String, List<AttributeData>> entriesAttributes) throws Exception { return persistenceEntryManager.createEntities(GluuCustomPerson.class, entriesAttributes); } /* * (non-Javadoc) * * @see org.gluu.oxtrust.ldap.service.IPersonService#getPersonByEmail(java.lang. * String) */ @Override public GluuCustomPerson getPersonByEmail(String mail, String... returnAttributes) { List<GluuCustomPerson> persons = getPersonsByEmail(mail, returnAttributes); if ((persons != null) && (persons.size() > 0)) { return persons.get(0); } return null; } /* * (non-Javadoc) * * @see org.gluu.oxtrust.ldap.service.IPersonService#getPersonsByUid(java.lang. * String) */ @Override public List<GluuCustomPerson> getPersonsByUid(String uid, String... returnAttributes) { log.debug("Getting user information from DB: userId = {}", uid); if (StringHelper.isEmpty(uid)) { return null; } Filter userUidFilter = Filter.createEqualityFilter(Filter.createLowercaseFilter(OxConstants.UID), StringHelper.toLowerCase(uid)); List<GluuCustomPerson> entries = persistenceEntryManager.findEntries(getDnForPerson(null), GluuCustomPerson.class, userUidFilter, returnAttributes); log.debug("Found {} entries for userId = {}", entries.size(), uid); return entries; } /* * (non-Javadoc) * * @see * org.gluu.oxtrust.ldap.service.IPersonService#getPersonsByEmail(java.lang. * String) */ @Override public List<GluuCustomPerson> getPersonsByEmail(String mail, String... returnAttributes) { log.debug("Getting user information from DB: mail = {}", mail); if (StringHelper.isEmpty(mail)) { return null; } Filter userMailFilter = Filter.createEqualityFilter(Filter.createLowercaseFilter("mail"), StringHelper.toLowerCase(mail)); boolean multiValued = false; GluuAttribute mailAttribute = attributeService.getAttributeByName("mail"); if ((mailAttribute != null) && (mailAttribute.getOxMultiValuedAttribute() != null) && mailAttribute.getOxMultiValuedAttribute()) { multiValued = true; } userMailFilter.multiValued(multiValued); List<GluuCustomPerson> entries = persistenceEntryManager.findEntries(getDnForPerson(null), GluuCustomPerson.class, userMailFilter, returnAttributes); log.debug("Found {} entries for mail = {}", entries.size(), mail); return entries; } /* * (non-Javadoc) * * @see * org.gluu.oxtrust.ldap.service.IPersonService#getPersonByAttribute(java.lang. * String, java.lang.String) */ @Override public GluuCustomPerson getPersonByAttribute(String attribute, String value) throws Exception { GluuCustomPerson person = new GluuCustomPerson(); person.setBaseDn(getDnForPerson(null)); person.setAttribute(attribute, value); List<GluuCustomPerson> persons = persistenceEntryManager.findEntries(person); if ((persons != null) && (persons.size() > 0)) { return persons.get(0); } return null; } /* * (non-Javadoc) * * @see * org.gluu.oxtrust.ldap.service.IPersonService#getUserByUid(java.lang.String) */ @Override public User getUserByUid(String uid) { Filter userUidFilter = Filter.createEqualityFilter(Filter.createLowercaseFilter(OxConstants.UID), StringHelper.toLowerCase(uid)); Filter userObjectClassFilter = Filter.createEqualityFilter(OxConstants.OBJECT_CLASS, "gluuPerson"); Filter filter = Filter.createANDFilter(userObjectClassFilter, userUidFilter); List<SimpleUser> users = persistenceEntryManager.findEntries(getDnForPerson(null), SimpleUser.class, filter, 1); if ((users != null) && (users.size() > 0)) { return persistenceEntryManager.find(User.class, users.get(0).getDn()); } return null; } /** * Get list of persons by attribute * * @param attribute * attribute * @param value * value * @return List <Person> */ @Override public List<GluuCustomPerson> getPersonsByAttribute(String attribute, String value) throws Exception { GluuCustomPerson person = new GluuCustomPerson(); person.setBaseDn(getDnForPerson(null)); person.setAttribute(attribute, value); List<GluuCustomPerson> persons = persistenceEntryManager.findEntries(person); if ((persons != null) && (persons.size() > 0)) { return persons; } return null; } }
package org.sfm.datastax; import com.datastax.driver.core.Session; import com.datastax.driver.mapping.annotations.Table; import org.junit.Test; import org.sfm.beans.DbObject; import org.sfm.datastax.beans.DbObjectWithAlias; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; public class DatastaxCrudTest extends AbstractDatastaxTest { @Test public void testCrud() throws Exception { testInSession(new Callback() { @Override public void call(Session session) throws Exception { DatastaxCrud<DbObject, Long> crud = DatastaxMapperFactory.newInstance().crud(DbObject.class, Long.class).to(session, "dbobjects"); testCrudDbObject(crud, DbObject.newInstance()); } }); } private <T extends DbObject> void testCrudDbObject(DatastaxCrud<T, Long> crud, T object) { assertNull(crud.read(object.getId())); crud.save(object); assertEquals(object, crud.read(object.getId())); object.setEmail("updated"); crud.save(object); assertEquals(object, crud.read(object.getId())); crud.delete(object.getId()); assertNull(crud.read(object.getId())); } @Test public void testCreateTTL() throws Exception { testInSession(new Callback() { @Override public void call(Session session) throws Exception { DatastaxCrud<DbObject, Long> crud = DatastaxMapperFactory.newInstance().crud(DbObject.class, Long.class).to(session, "dbobjects"); DbObject object = DbObject.newInstance(); crud.saveWithTtl(object, 2); Thread.sleep(500); assertEquals(object, crud.read(object.getId())); Thread.sleep(3000); assertNull(crud.read(object.getId())); DbObject object2 = DbObject.newInstance(); crud.save(object2, 2, System.currentTimeMillis()); Thread.sleep(500); assertEquals(object2, crud.read(object2.getId())); Thread.sleep(2000); assertNull(crud.read(object2.getId())); } }); } @Test public void testCreateDeleteTS() throws Exception { testInSession(new Callback() { @Override public void call(Session session) throws Exception { long ts = System.currentTimeMillis(); DatastaxCrud<DbObject, Long> crud = DatastaxMapperFactory.newInstance().crud(DbObject.class, Long.class).to(session, "dbobjects"); DbObject object = DbObject.newInstance(); crud.saveWithTimestamp(object, ts - 2000); assertEquals(object, crud.read(object.getId())); // delete before insert object.setEmail("Modified 1"); crud.saveWithTimestamp(object, ts); crud.delete(object.getId(), ts - 1000); assertEquals(object, crud.read(object.getId())); // insert before delete object.setEmail("Modified 2"); crud.delete(object.getId(), ts + 2000); crud.saveWithTimestamp(object, ts + 1000); assertNull(crud.read(object.getId())); } }); } @Test public void testTableAnnotation() throws Exception { testInSession(new Callback() { @Override public void call(Session session) throws Exception { DatastaxCrud<DbObjectTable, Long> crud = DatastaxMapperFactory.newInstance().crud(DbObjectTable.class, Long.class).to(session); testCrudDbObject(crud, DbObject.newInstance(new DbObjectTable())); } }); } @Test public void testClassNameMatching() throws Exception { testInSession(new Callback() { @Override public void call(Session session) throws Exception { DatastaxCrud<DbObjects, Long> crud = DatastaxMapperFactory.newInstance().crud(DbObjects.class, Long.class).to(session); testCrudDbObject(crud, DbObject.newInstance(new DbObjects())); } }); } @Test public void testCrudWithAlias() throws Exception { testInSession(new Callback() { @Override public void call(Session session) throws Exception { DatastaxCrud<DbObjectWithAlias, Long> crud = DatastaxMapperFactory.newInstance().crud(DbObjectWithAlias.class, Long.class).to(session, "dbobjects"); final DbObject object = DbObject.newInstance(); final DatastaxCrud<DbObject, Long> crud2 = DatastaxMapperFactory.newInstance().crud(DbObject.class, Long.class).to(session, "dbobjects"); crud2.save(object); DbObjectWithAlias dbObjectWithAlias = crud.read(object.getId()); assertNotNull(dbObjectWithAlias); assertEquals(object.getId(), dbObjectWithAlias.getIdWithAlias()); assertEquals(object.getCreationTime(), dbObjectWithAlias.getCreationTimeWithAlias()); assertEquals(object.getEmail(), dbObjectWithAlias.getEmailWithAlias()); assertEquals(object.getName(), dbObjectWithAlias.getNameWithAlias()); } }); } @Table(keyspace = "sfm", name = "dbobjects") public static class DbObjectTable extends DbObject { } public static class DbObjects extends DbObject { } }
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.Charset; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; import com.google.bitcoin.core.Address; import com.google.bitcoin.core.AddressFormatException; import com.google.bitcoin.core.Block; import com.google.bitcoin.core.BlockChain; import com.google.bitcoin.core.DumpedPrivateKey; import com.google.bitcoin.core.ECKey; import com.google.bitcoin.core.InsufficientMoneyException; import com.google.bitcoin.core.NetworkParameters; import com.google.bitcoin.core.PeerGroup; import com.google.bitcoin.core.PeerGroup.FilterRecalculateMode; import com.google.bitcoin.core.Transaction.SigHash; import com.google.bitcoin.core.ScriptException; import com.google.bitcoin.core.Sha256Hash; import com.google.bitcoin.core.StoredBlock; import com.google.bitcoin.core.Transaction; import com.google.bitcoin.core.TransactionInput; import com.google.bitcoin.core.TransactionOutPoint; import com.google.bitcoin.core.TransactionOutput; import com.google.bitcoin.core.UnsafeByteArrayOutputStream; import com.google.bitcoin.core.Wallet; import com.google.bitcoin.crypto.TransactionSignature; import com.google.bitcoin.net.discovery.DnsDiscovery; import com.google.bitcoin.params.MainNetParams; import com.google.bitcoin.script.Script; import com.google.bitcoin.script.ScriptBuilder; import com.google.bitcoin.script.ScriptChunk; import com.google.bitcoin.script.ScriptOpCodes; import com.google.bitcoin.store.BlockStore; import com.google.bitcoin.store.BlockStoreException; import com.google.bitcoin.store.H2FullPrunedBlockStore; import com.google.bitcoin.wallet.WalletTransaction; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.ListenableFuture; import com.sun.org.apache.xpath.internal.compiler.OpCodes; public class Blocks implements Runnable { public NetworkParameters params; public Logger logger = LoggerFactory.getLogger(Blocks.class); private static Blocks instance = null; public Wallet wallet; public String walletFile = "resources/db/wallet"; public PeerGroup peerGroup; public BlockChain blockChain; public BlockStore blockStore; public Boolean working = false; public Boolean parsing = false; public Integer parsingBlock = 0; public Integer versionCheck = 0; public Integer bitcoinBlock = 0; public Integer chancecoinBlock = 0; public Double priceBTC = 0.0; public Double priceCHA = 0.0; public String statusMessage = ""; public static Blocks getInstanceSkipVersionCheck() { if(instance == null) { instance = new Blocks(); } return instance; } public static Blocks getInstanceFresh() { if(instance == null) { instance = new Blocks(); instance.versionCheck(); } return instance; } public static Blocks getInstanceAndWait() { if(instance == null) { instance = new Blocks(); instance.versionCheck(); instance.init(); } instance.follow(); return instance; } public static Blocks getInstance() { if(instance == null) { instance = new Blocks(); instance.versionCheck(); instance.init(); } new Thread() { public void run() {instance.follow();}}.start(); return instance; } public void versionCheck() { versionCheck(true); } public void versionCheck(Boolean autoUpdate) { Integer minMajorVersion = Util.getMinMajorVersion(); Integer minMinorVersion = Util.getMinMinorVersion(); if (Config.majorVersion<minMajorVersion || (Config.majorVersion.equals(minMajorVersion) && Config.minorVersion<minMinorVersion)) { if (autoUpdate) { statusMessage = "Version is out of date, updating now"; logger.info(statusMessage); try { Runtime.getRuntime().exec("java -jar update/update.jar"); } catch (Exception ex) { ex.printStackTrace(); } } else { logger.info("Version is out of date. Please upgrade to version "+Util.getMinVersion()+"."); } System.exit(0); } } @Override public void run() { while (true) { Blocks.getInstance(); try { logger.info("Looping blocks"); Thread.sleep(1000*60); //once a minute, we run blocks.follow() } catch (InterruptedException e) { logger.info(e.toString()); } } } public void init() { Locale.setDefault(new Locale("en", "US")); params = MainNetParams.get(); try { if ((new File(walletFile)).exists()) { statusMessage = "Found wallet file"; logger.info(statusMessage); wallet = Wallet.loadFromFile(new File(walletFile)); } else { statusMessage = "Creating new wallet file"; logger.info(statusMessage); wallet = new Wallet(params); ECKey newKey = new ECKey(); newKey.setCreationTimeSeconds(Config.burnCreationTime); wallet.addKey(newKey); } String fileBTCdb = Config.dbPath+Config.appName.toLowerCase()+".h2.db"; if (!new File(fileBTCdb).exists()) { statusMessage = "Downloading BTC database"; logger.info(statusMessage); Util.downloadToFile(Config.downloadUrl+Config.appName.toLowerCase()+".h2.db", fileBTCdb); } String fileCHAdb = Database.dbFile; if (!new File(fileCHAdb).exists()) { statusMessage = "Downloading CHA database"; logger.info(statusMessage); Util.downloadToFile(Config.downloadUrl+Config.appName.toLowerCase()+"-"+Config.majorVersionDB.toString()+".db", fileCHAdb); } statusMessage = "Downloading Bitcoin blocks"; blockStore = new H2FullPrunedBlockStore(params, Config.dbPath+Config.appName.toLowerCase(), 2000); blockChain = new BlockChain(params, wallet, blockStore); peerGroup = new PeerGroup(params, blockChain); peerGroup.addWallet(wallet); peerGroup.setFastCatchupTimeSecs(Config.burnCreationTime); wallet.autosaveToFile(new File(walletFile), 1, TimeUnit.MINUTES, null); peerGroup.addPeerDiscovery(new DnsDiscovery(params)); peerGroup.startAndWait(); peerGroup.addEventListener(new ChancecoinPeerEventListener()); peerGroup.downloadBlockChain(); } catch (Exception e) { logger.error(e.toString()); } } public void follow() { follow(false); } public void follow(Boolean force) { logger.info("Working status: "+working); if (!working || force) { statusMessage = "Checking block height"; logger.info(statusMessage); if (!force) { working = true; } try { //get BTC, CHA prices try { priceCHA = Util.getTradesPoloniex().get(0).rate; priceBTC = Util.getBTCPrice(); } catch (Exception e) { } //catch Chancecoin up to Bitcoin Integer blockHeight = blockStore.getChainHead().getHeight(); Integer lastBlock = Util.getLastBlock(); bitcoinBlock = blockHeight; chancecoinBlock = lastBlock; if (lastBlock == 0) { lastBlock = Config.firstBlock - 1; } Integer nextBlock = lastBlock + 1; logger.info("Bitcoin block height: "+blockHeight); logger.info("Chancecoin block height: "+lastBlock); if (lastBlock < blockHeight) { //traverse new blocks parsing = true; Database db = Database.getInstance(); Integer blocksToScan = blockHeight - lastBlock; List<Sha256Hash> blockHashes = new ArrayList<Sha256Hash>(); Block block = peerGroup.getDownloadPeer().getBlock(blockStore.getChainHead().getHeader().getHash()).get(30, TimeUnit.SECONDS); while (blockStore.get(block.getHash()).getHeight()>lastBlock) { blockHashes.add(block.getHash()); block = blockStore.get(block.getPrevBlockHash()).getHeader(); } for (int i = blockHashes.size()-1; i>=0; i--) { //traverse blocks in reverse order block = peerGroup.getDownloadPeer().getBlock(blockHashes.get(i)).get(30, TimeUnit.SECONDS); blockHeight = blockStore.get(block.getHash()).getHeight(); chancecoinBlock = blockHeight; statusMessage = "Catching Chancecoin up to Bitcoin "+Util.format((blockHashes.size() - i)/((double) blockHashes.size())*100.0)+"%"; logger.info("Catching Chancecoin up to Bitcoin (block "+blockHeight.toString()+"): "+Util.format((blockHashes.size() - i)/((double) blockHashes.size())*100.0)+"%"); importBlock(block, blockHeight); } if (getDBMinorVersion()<Config.minorVersionDB){ reparse(true); updateMinorVersion(); }else{ parseFrom(nextBlock, true); } Bet.resolve(); Order.expire(); parsing = false; } } catch (Exception e) { logger.error(e.toString()); } if (!force) { working = false; } } } public void reDownloadBlockTransactions(Integer blockHeight) { Database db = Database.getInstance(); ResultSet rs = db.executeQuery("select * from blocks where block_index='"+blockHeight.toString()+"';"); try { if (rs.next()) { Block block = peerGroup.getDownloadPeer().getBlock(new Sha256Hash(rs.getString("block_hash"))).get(); db.executeUpdate("delete from transactions where block_index='"+blockHeight.toString()+"';"); for (Transaction tx : block.getTransactions()) { importTransaction(tx, block, blockHeight); } } } catch (Exception e) { } } public void importBlock(Block block, Integer blockHeight) { statusMessage = "Importing block "+blockHeight; logger.info(statusMessage); Database db = Database.getInstance(); ResultSet rs = db.executeQuery("select * from blocks where block_hash='"+block.getHashAsString()+"';"); try { if (!rs.next()) { db.executeUpdate("INSERT INTO blocks(block_index,block_hash,block_time) VALUES('"+blockHeight.toString()+"','"+block.getHashAsString()+"','"+block.getTimeSeconds()+"')"); } for (Transaction tx : block.getTransactions()) { importTransaction(tx, block, blockHeight); } Bet.resolve(); Order.expire(); } catch (SQLException e) { } } public void importTransaction(Transaction tx, Block block, Integer blockHeight) { BigInteger fee = BigInteger.ZERO; String destination = ""; BigInteger btcAmount = BigInteger.ZERO; List<Byte> dataArrayList = new ArrayList<Byte>(); byte[] data = null; String source = ""; Database db = Database.getInstance(); //check to see if this is a burn for (TransactionOutput out : tx.getOutputs()) { try { Script script = out.getScriptPubKey(); Address address = script.getToAddress(params); if (address.toString().equals(Config.burnAddress)) { destination = address.toString(); btcAmount = out.getValue(); } } catch(ScriptException e) { } } for (TransactionOutput out : tx.getOutputs()) { //fee = fee.subtract(out.getValue()); //TODO, turn this on try { Script script = out.getScriptPubKey(); List<ScriptChunk> asm = script.getChunks(); if (asm.size()==2 && asm.get(0).equalsOpCode(106)) { //OP_RETURN for (byte b : asm.get(1).data) dataArrayList.add(b); } else if (asm.size()>=5 && asm.get(0).equalsOpCode(81) && asm.get(3).equalsOpCode(82) && asm.get(4).equalsOpCode(174)) { //MULTISIG for (int i=1; i<asm.get(2).data[0]+1; i++) dataArrayList.add(asm.get(2).data[i]); } if (destination.equals("") && btcAmount==BigInteger.ZERO && dataArrayList.size()==0) { Address address = script.getToAddress(params); destination = address.toString(); btcAmount = out.getValue(); } } catch(ScriptException e) { } } if (destination.equals(Config.burnAddress)) { } else if (dataArrayList.size()>Config.prefix.length()) { byte[] prefixBytes = Config.prefix.getBytes(); byte[] dataPrefixBytes = Util.toByteArray(dataArrayList.subList(0, Config.prefix.length())); dataArrayList = dataArrayList.subList(Config.prefix.length(), dataArrayList.size()); data = Util.toByteArray(dataArrayList); if (!Arrays.equals(prefixBytes,dataPrefixBytes)) { return; } } else { return; } for (TransactionInput in : tx.getInputs()) { if (in.isCoinBase()) return; try { Script script = in.getScriptSig(); //fee = fee.add(in.getValue()); //TODO, turn this on //Script scriptOutput = in.getParentTransaction().getOutput((int) in.getOutpoint().getIndex()).getScriptPubKey(); Address address = null; //if (scriptOutput.isSentToAddress()) { address = script.getFromAddress(params); if (source.equals("")) { source = address.toString(); }else if (!source.equals(address.toString()) && !destination.equals(Config.burnAddress)){ //require all sources to be the same unless this is a burn return; } } catch(ScriptException e) { } } logger.info("Incoming transaction from "+source+" to "+destination+" ("+tx.getHashAsString()+")"); if (!source.equals("") && (destination.equals(Config.burnAddress) || dataArrayList.size()>0)) { String dataString = ""; if (destination.equals(Config.burnAddress)) { }else{ try { dataString = new String(data,"ISO-8859-1"); } catch (UnsupportedEncodingException e) { } } db.executeUpdate("delete from transactions where tx_hash='"+tx.getHashAsString()+"' and block_index<0"); ResultSet rs = db.executeQuery("select * from transactions where tx_hash='"+tx.getHashAsString()+"';"); try { if (!rs.next()) { if (block!=null) { PreparedStatement ps = db.connection.prepareStatement("INSERT INTO transactions(tx_index, tx_hash, block_index, block_time, source, destination, btc_amount, fee, data) VALUES('"+(Util.getLastTxIndex()+1)+"','"+tx.getHashAsString()+"','"+blockHeight+"','"+block.getTimeSeconds()+"','"+source+"','"+destination+"','"+btcAmount.toString()+"','"+fee.toString()+"',?)"); ps.setString(1, dataString); ps.execute(); }else{ PreparedStatement ps = db.connection.prepareStatement("INSERT INTO transactions(tx_index, tx_hash, block_index, block_time, source, destination, btc_amount, fee, data) VALUES('"+(Util.getLastTxIndex()+1)+"','"+tx.getHashAsString()+"','-1','','"+source+"','"+destination+"','"+btcAmount.toString()+"','"+fee.toString()+"',?)"); ps.setString(1, dataString); ps.execute(); } } } catch (SQLException e) { logger.error(e.toString()); } } } public void reparse() { reparse(false); } public void reparse(final Boolean force) { Database db = Database.getInstance(); db.executeUpdate("delete from debits;"); db.executeUpdate("delete from credits;"); db.executeUpdate("delete from balances;"); db.executeUpdate("delete from sends;"); db.executeUpdate("delete from orders;"); db.executeUpdate("delete from order_matches;"); db.executeUpdate("delete from btcpays;"); db.executeUpdate("delete from bets;"); db.executeUpdate("delete from burns;"); db.executeUpdate("delete from cancels;"); db.executeUpdate("delete from order_expirations;"); db.executeUpdate("delete from order_match_expirations;"); db.executeUpdate("delete from messages;"); new Thread() { public void run() {parseFrom(0, force);}}.start(); } public void parseFrom(Integer blockNumber) { parseFrom(blockNumber, false); } public void parseFrom(Integer blockNumber, Boolean force) { if (!working || force) { parsing = true; if (!force) { working = true; } Database db = Database.getInstance(); ResultSet rs = db.executeQuery("select * from blocks where block_index>="+blockNumber.toString()+" order by block_index asc;"); try { while (rs.next()) { Integer blockIndex = rs.getInt("block_index"); parseBlock(blockIndex); Bet.resolve(); Order.expire(blockIndex); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (!force) { working = false; } parsing = false; } } public List<Byte> getMessageFromTransaction(String txDataString) { byte[] data; List<Byte> message = null; try { data = txDataString.getBytes("ISO-8859-1"); List<Byte> dataArrayList = Util.toByteArrayList(data); message = dataArrayList.subList(4, dataArrayList.size()); return message; } catch (UnsupportedEncodingException e) { } return message; } public List<Byte> getMessageTypeFromTransaction(String txDataString) { byte[] data; List<Byte> messageType = null; try { data = txDataString.getBytes("ISO-8859-1"); List<Byte> dataArrayList = Util.toByteArrayList(data); messageType = dataArrayList.subList(0, 4); return messageType; } catch (UnsupportedEncodingException e) { } return messageType; } public void parseBlock(Integer blockIndex) { Database db = Database.getInstance(); ResultSet rsTx = db.executeQuery("select * from transactions where block_index="+blockIndex.toString()+" order by tx_index asc;"); parsingBlock = blockIndex; statusMessage = "Parsing block "+blockIndex.toString(); logger.info(statusMessage); try { while (rsTx.next()) { Integer txIndex = rsTx.getInt("tx_index"); String source = rsTx.getString("source"); String destination = rsTx.getString("destination"); BigInteger btcAmount = BigInteger.valueOf(rsTx.getInt("btc_amount")); String dataString = rsTx.getString("data"); if (destination.equals(Config.burnAddress)) { //parse Burn Burn.parse(txIndex); } else { List<Byte> messageType = getMessageTypeFromTransaction(dataString); List<Byte> message = getMessageFromTransaction(dataString); if (messageType!=null && messageType.size()>=4 && message!=null) { if (messageType.get(3)==Bet.id.byteValue()) { Bet.parse(txIndex, message); } else if (messageType.get(3)==Send.id.byteValue()) { Send.parse(txIndex, message); } else if (messageType.get(3)==Order.id.byteValue()) { Order.parse(txIndex, message); } else if (messageType.get(3)==Cancel.id.byteValue()) { Cancel.parse(txIndex, message); } else if (messageType.get(3)==BTCPay.id.byteValue()) { BTCPay.parse(txIndex, message); } } } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void deletePending() { Database db = Database.getInstance(); db.executeUpdate("delete from transactions where block_index<0 and tx_index<(select max(tx_index) from transactions)-10;"); } public void createTables() { Database db = Database.getInstance(); try { // Blocks db.executeUpdate("CREATE TABLE IF NOT EXISTS blocks(block_index INTEGER PRIMARY KEY, block_hash TEXT UNIQUE, block_time INTEGER)"); db.executeUpdate("CREATE INDEX IF NOT EXISTS blocks_block_index_idx ON blocks (block_index)"); // Transactions db.executeUpdate("CREATE TABLE IF NOT EXISTS transactions(tx_index INTEGER PRIMARY KEY, tx_hash TEXT UNIQUE, block_index INTEGER, block_time INTEGER, source TEXT, destination TEXT, btc_amount INTEGER, fee INTEGER, data BLOB, supported BOOL DEFAULT 1)"); db.executeUpdate("CREATE INDEX IF NOT EXISTS transactions_block_index_idx ON transactions (block_index)"); db.executeUpdate("CREATE INDEX IF NOT EXISTS transactions_tx_index_idx ON transactions (tx_index)"); db.executeUpdate("CREATE INDEX IF NOT EXISTS transactions_tx_hash_idx ON transactions (tx_hash)"); // (Valid) debits db.executeUpdate("CREATE TABLE IF NOT EXISTS debits(block_index INTEGER, address TEXT, asset TEXT, amount INTEGER, calling_function TEXT, event TEXT)"); db.executeUpdate("CREATE INDEX IF NOT EXISTS debits_address_idx ON debits (address)"); // (Valid) credits db.executeUpdate("CREATE TABLE IF NOT EXISTS credits(block_index INTEGER, address TEXT, asset TEXT, amount INTEGER, calling_function TEXT, event TEXT)"); db.executeUpdate("CREATE INDEX IF NOT EXISTS credits_address_idx ON credits (address)"); // Balances db.executeUpdate("CREATE TABLE IF NOT EXISTS balances(address TEXT, asset TEXT, amount INTEGER)"); db.executeUpdate("CREATE INDEX IF NOT EXISTS address_idx ON balances (address)"); db.executeUpdate("CREATE INDEX IF NOT EXISTS asset_idx ON balances (asset)"); // Sends db.executeUpdate("CREATE TABLE IF NOT EXISTS sends(tx_index INTEGER PRIMARY KEY, tx_hash TEXT UNIQUE, block_index INTEGER, source TEXT, destination TEXT, asset TEXT, amount INTEGER, validity TEXT)"); db.executeUpdate("CREATE INDEX IF NOT EXISTS sends_block_index_idx ON sends (block_index)"); // Orders db.executeUpdate("CREATE TABLE IF NOT EXISTS orders(tx_index INTEGER PRIMARY KEY, tx_hash TEXT UNIQUE, block_index INTEGER, source TEXT, give_asset TEXT, give_amount INTEGER, give_remaining INTEGER, get_asset TEXT, get_amount INTEGER, get_remaining INTEGER, expiration INTEGER, expire_index INTEGER, fee_required INTEGER, fee_provided INTEGER, fee_remaining INTEGER, validity TEXT)"); db.executeUpdate("CREATE INDEX IF NOT EXISTS block_index_idx ON orders (block_index)"); db.executeUpdate("CREATE INDEX IF NOT EXISTS expire_index_idx ON orders (expire_index)"); // Order Matches db.executeUpdate("CREATE TABLE IF NOT EXISTS order_matches(id TEXT PRIMARY KEY, tx0_index INTEGER, tx0_hash TEXT, tx0_address TEXT, tx1_index INTEGER, tx1_hash TEXT, tx1_address TEXT, forward_asset TEXT, forward_amount INTEGER, backward_asset TEXT, backward_amount INTEGER, tx0_block_index INTEGER, tx1_block_index INTEGER, tx0_expiration INTEGER, tx1_expiration INTEGER, match_expire_index INTEGER, validity TEXT)"); db.executeUpdate("CREATE INDEX IF NOT EXISTS match_expire_index_idx ON order_matches (match_expire_index)"); // BTCpays db.executeUpdate("CREATE TABLE IF NOT EXISTS btcpays(tx_index INTEGER PRIMARY KEY, tx_hash TEXT UNIQUE, block_index INTEGER, source TEXT, destination TEXT, btc_amount INTEGER, order_match_id TEXT, validity TEXT)"); db.executeUpdate("CREATE INDEX IF NOT EXISTS block_index_idx ON btcpays (block_index)"); // Bets db.executeUpdate("CREATE TABLE IF NOT EXISTS bets(tx_index INTEGER PRIMARY KEY, tx_hash TEXT UNIQUE, block_index INTEGER, source TEXT, bet INTEGER, chance REAL, payout REAL, profit INTEGER, cha_supply INTEGER, rolla REAL, rollb REAL, roll REAL, resolved TEXT, validity TEXT)"); db.executeUpdate("CREATE INDEX IF NOT EXISTS block_index_idx ON bets (block_index)"); // Burns db.executeUpdate("CREATE TABLE IF NOT EXISTS burns(tx_index INTEGER PRIMARY KEY, tx_hash TEXT UNIQUE, block_index INTEGER, source TEXT, burned INTEGER, earned INTEGER, validity TEXT)"); db.executeUpdate("CREATE INDEX IF NOT EXISTS validity_idx ON burns (validity)"); db.executeUpdate("CREATE INDEX IF NOT EXISTS address_idx ON burns (address)"); // Cancels db.executeUpdate("CREATE TABLE IF NOT EXISTS cancels(tx_index INTEGER PRIMARY KEY, tx_hash TEXT UNIQUE, block_index INTEGER, source TEXT, offer_hash TEXT, validity TEXT)"); db.executeUpdate("CREATE INDEX IF NOT EXISTS cancels_block_index_idx ON cancels (block_index)"); // Order Expirations db.executeUpdate("CREATE TABLE IF NOT EXISTS order_expirations(order_index INTEGER PRIMARY KEY, order_hash TEXT UNIQUE, source TEXT, block_index INTEGER)"); db.executeUpdate("CREATE INDEX IF NOT EXISTS block_index_idx ON order_expirations (block_index)"); // Order Match Expirations db.executeUpdate("CREATE TABLE IF NOT EXISTS order_match_expirations(order_match_id TEXT PRIMARY KEY, tx0_address TEXT, tx1_address TEXT, block_index INTEGER)"); db.executeUpdate("CREATE INDEX IF NOT EXISTS block_index_idx ON order_match_expirations (block_index)"); // Messages db.executeUpdate("CREATE TABLE IF NOT EXISTS messages(message_index INTEGER PRIMARY KEY, block_index INTEGER, command TEXT, category TEXT, bindings TEXT)"); db.executeUpdate("CREATE INDEX IF NOT EXISTS block_index_idx ON messages (block_index)"); updateMinorVersion(); } catch (Exception e) { logger.error(e.toString()); } } public Integer getDBMinorVersion() { Database db = Database.getInstance(); ResultSet rs = db.executeQuery("PRAGMA user_version;"); try { while(rs.next()) { return rs.getInt("user_version"); } } catch (SQLException e) { } return 0; } public void updateMinorVersion() { // Update minor version Database db = Database.getInstance(); db.executeUpdate("PRAGMA user_version = "+Config.minorVersionDB.toString()); } public Integer getHeight() { try { Integer height = blockStore.getChainHead().getHeight(); return height; } catch (BlockStoreException e) { } return 0; } public String importPrivateKey(ECKey key) throws Exception { String address = ""; logger.info("Importing private key"); address = key.toAddress(params).toString(); logger.info("Importing address "+address); if (wallet.getKeys().contains(key)) { wallet.removeKey(key); } wallet.addKey(key); /* try { importTransactionsFromAddress(address); } catch (Exception e) { throw new Exception(e.getMessage()); } */ return address; } public String importPrivateKey(String privateKey) throws Exception { DumpedPrivateKey dumpedPrivateKey; String address = ""; ECKey key = null; logger.info("Importing private key"); try { dumpedPrivateKey = new DumpedPrivateKey(params, privateKey); key = dumpedPrivateKey.getKey(); return importPrivateKey(key); } catch (AddressFormatException e) { throw new Exception(e.getMessage()); } } /* public void importTransactionsFromAddress(String address) throws Exception { logger.info("Importing transactions"); try { wallet.addWatchedAddress(new Address(params, address)); } catch (AddressFormatException e) { } List<Map.Entry<String,String>> txsInfo = Util.getTransactions(address); BigInteger balance = BigInteger.ZERO; BigInteger balanceSent = BigInteger.ZERO; BigInteger balanceReceived = BigInteger.ZERO; Integer transactionCount = 0; for (Map.Entry<String,String> txHashBlockHash : txsInfo) { String txHash = txHashBlockHash.getKey(); String blockHash = txHashBlockHash.getValue(); try { Block block = peerGroup.getDownloadPeer().getBlock(new Sha256Hash(blockHash)).get(); List<Transaction> txs = block.getTransactions(); for (Transaction tx : txs) { if (tx.getHashAsString().equals(txHash)){// && wallet.isPendingTransactionRelevant(tx)) { transactionCount ++; wallet.receivePending(tx, peerGroup.getDownloadPeer().downloadDependencies(tx).get()); balanceReceived = balanceReceived.add(tx.getValueSentToMe(wallet)); balanceSent = balanceSent.add(tx.getValueSentFromMe(wallet)); balance = balance.add(tx.getValueSentToMe(wallet)); balance = balance.subtract(tx.getValueSentFromMe(wallet)); } } } catch (InterruptedException e) { throw new Exception(e.getMessage()); } catch (ExecutionException e) { throw new Exception(e.getMessage()); } } logger.info("Address balance: "+balance); } */ public Transaction transaction(String source, String destination, BigInteger btcAmount, BigInteger fee, String dataString) throws Exception { Transaction tx = new Transaction(params); if (destination.equals("") || btcAmount.compareTo(BigInteger.valueOf(Config.dustSize))>=0) { byte[] data = null; List<Byte> dataArrayList = new ArrayList<Byte>(); try { data = dataString.getBytes("ISO-8859-1"); dataArrayList = Util.toByteArrayList(data); } catch (UnsupportedEncodingException e) { } BigInteger totalOutput = fee; BigInteger totalInput = BigInteger.ZERO; try { if (!destination.equals("") && btcAmount.compareTo(BigInteger.ZERO)>0) { totalOutput = totalOutput.add(btcAmount); tx.addOutput(btcAmount, new Address(params, destination)); } } catch (AddressFormatException e) { } for (int i = 0; i < dataArrayList.size(); i+=32) { List<Byte> chunk = new ArrayList<Byte>(dataArrayList.subList(i, Math.min(i+32, dataArrayList.size()))); chunk.add(0, (byte) chunk.size()); while (chunk.size()<32+1) { chunk.add((byte) 0); } List<ECKey> keys = new ArrayList<ECKey>(); for (ECKey key : wallet.getKeys()) { try { if (key.toAddress(params).equals(new Address(params, source))) { keys.add(key); break; } } catch (AddressFormatException e) { } } keys.add(new ECKey(null, Util.toByteArray(chunk))); Script script = ScriptBuilder.createMultiSigOutputScript(1, keys); tx.addOutput(BigInteger.valueOf(Config.dustSize), script); totalOutput = totalOutput.add(BigInteger.valueOf(Config.dustSize)); } List<UnspentOutput> unspents = Util.getUnspents(source); List<Script> inputScripts = new ArrayList<Script>(); List<ECKey> inputKeys = new ArrayList<ECKey>(); Boolean atLeastOneRegularInput = false; for (UnspentOutput unspent : unspents) { String txHash = unspent.txid; byte[] scriptBytes = Hex.decode(unspent.scriptPubKey.hex.getBytes(Charset.forName("UTF-8"))); Script script = new Script(scriptBytes); //if it's sent to an address and we don't yet have enough inputs or we don't yet have at least one regular input, or if it's sent to a multisig //in other words, we sweep up any unused multisig inputs with every transaction try { if ((script.isSentToAddress() && (totalOutput.compareTo(totalInput)>0 || !atLeastOneRegularInput)) || (script.isSentToMultiSig())) { //if we have this transaction in our wallet already, we shall confirm that it is not already spent if (wallet.getTransaction(new Sha256Hash(txHash))==null || wallet.getTransaction(new Sha256Hash(txHash)).getOutput(unspent.vout).isAvailableForSpending()) { if (script.isSentToAddress()) { atLeastOneRegularInput = true; } Sha256Hash sha256Hash = new Sha256Hash(txHash); TransactionOutPoint txOutPt = new TransactionOutPoint(params, unspent.vout, sha256Hash); for (ECKey key : wallet.getKeys()) { try { if (key.toAddress(params).equals(new Address(params, source))) { //System.out.println("Spending "+sha256Hash+" "+unspent.vout); totalInput = totalInput.add(BigDecimal.valueOf(unspent.amount*Config.unit).toBigInteger()); TransactionInput input = new TransactionInput(params, tx, new byte[]{}, txOutPt); tx.addInput(input); inputScripts.add(script); inputKeys.add(key); break; } } catch (AddressFormatException e) { } } } } } catch (Exception e) { logger.error(e.toString()); } } if (!atLeastOneRegularInput) { throw new Exception("Not enough standard unspent outputs to cover transaction."); } if (totalInput.compareTo(totalOutput)<0) { logger.info("Not enough inputs. Output: "+totalOutput.toString()+", input: "+totalInput.toString()); throw new Exception("Not enough BTC to cover transaction of "+String.format("%.8f",totalOutput.doubleValue()/Config.unit)+" BTC."); } BigInteger totalChange = totalInput.subtract(totalOutput); try { if (totalChange.compareTo(BigInteger.ZERO)>0) { tx.addOutput(totalChange, new Address(params, source)); } } catch (AddressFormatException e) { } //sign inputs for (int i = 0; i<tx.getInputs().size(); i++) { Script script = inputScripts.get(i); ECKey key = inputKeys.get(i); TransactionInput input = tx.getInput(i); TransactionSignature txSig = tx.calculateSignature(i, key, script, SigHash.ALL, false); if (script.isSentToAddress()) { input.setScriptSig(ScriptBuilder.createInputScript(txSig, key)); } else if (script.isSentToMultiSig()) { //input.setScriptSig(ScriptBuilder.createMultiSigInputScript(txSig)); ScriptBuilder builder = new ScriptBuilder(); builder.smallNum(0); builder.data(txSig.encodeToBitcoin()); input.setScriptSig(builder.build()); } } } tx.verify(); return tx; } public Boolean sendTransaction(Transaction tx) throws Exception { try { //System.out.println(tx); byte[] rawTxBytes = tx.bitcoinSerialize(); String rawTx = new BigInteger(1, rawTxBytes).toString(16); rawTx = "0" + rawTx; //System.out.println(rawTx); //System.exit(0); Blocks blocks = Blocks.getInstance(); //blocks.wallet.commitTx(txBet); ListenableFuture<Transaction> future = null; try { logger.info("Broadcasting transaction: "+tx.getHashAsString()); future = peerGroup.broadcastTransaction(tx); int tries = 10; Boolean success = false; while (tries>0 && !success) { tries if (Util.getTransaction(tx.getHashAsString())!=null) { success = true; } Thread.sleep(5000); } if (!success) { throw new Exception("Transaction timed out. Please try again."); } //future.get(60, TimeUnit.SECONDS); //} catch (TimeoutException e) { // logger.error(e.toString()); // future.cancel(true); } catch (Exception e) { throw new Exception("Transaction timed out. Please try again."); } logger.info("Importing transaction (assigning block number -1)"); blocks.importTransaction(tx, null, null); return true; } catch (Exception e) { throw new Exception(e.getMessage()); } } }
package nxt.util; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.junit.Assert; import org.junit.Test; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; public class JsonMessageTest { @Test public void message() { validate("{\n \"type\": \"dividend\",\n \"contractId\": \"2112610727280991058\",\n \"height\": 260315,\n \"total\": \"42700000000\",\n \"percentage\": \"0%\",\n \"shares\": 50\n}"); validate("{\\n \"type\": \"dividend\",\\n \"contractId\": \"2112610727280991058\",\\n \"height\": 260315,\\n \"total\": \"42700000000\",\\n \"percentage\": \"0%\",\\n \"shares\": 50\\n}"); validate("{\n" + " \"type\": \"dividend\",\n" + " \"contractId\": \"11263051911300205537\",\n" + " \"height\": 260315,\n" + " \"total\": \"42700000000\",\n" + " \"percentage\": \"0.1%\",\n" + " \"shares\": 1000\n" + "}"); validate("{\n" + " \"type\": \"dividend\",\n" + " \"contractId\": \"11263051911300205537\",\n" + " \"height\": 260315,\n" + " \"total\": \"42700000000\",\n" + " \"percentage\": \"0.01%\",\n" + " \"shares\": 70\n" + "}"); validate("{\n" + " \"type\": \"dividend\",\n" + " \"contractId\": \"2112610727280991058\",\n" + " \"height\": 260315,\n" + " \"total\": \"42700000000\",\n" + " \"percentage\": \"0.33%\",\n" + " \"shares\": 5383\n" + "}"); validate("{\n" + " \"type\": \"dividend\",\n" + " \"contractId\": \"11263051911300205537\",\n" + " \"height\": 260315,\n" + " \"total\": \"42700000000\",\n" + " \"percentage\": \"0.1%\",\n" + " \"shares\": 1000\n" + "}"); validate("{\n" + " \"type\": \"dividend\",\n" + " \"contractId\": \"2112610727280991058\",\n" + " \"height\": 260315,\n" + " \"total\": \"42700000000\",\n" + " \"percentage\": \"0.18%\",\n" + " \"shares\": 3000\n" + "}"); } private void validate(String message) { JSONObject request = new JSONObject(); request.put("message", message); JSONObject response; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { try (Writer writer = new OutputStreamWriter(byteArrayOutputStream, "UTF-8")) { request.writeJSONString(writer); } ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); try (Reader reader = new BufferedReader(new InputStreamReader(byteArrayInputStream, "UTF-8"))) { response = (JSONObject) JSONValue.parse(reader); } } catch (IOException e) { throw new IllegalStateException(e); } Assert.assertEquals(message, response.get("message")); } }
package lab4; import java.awt.Color; /** * * @author usuario */ public class Dragon extends Pieza{ public Dragon() { } public Dragon(Color color, String material) { super(color, material); } @Override public String toString() { return "F"; } @Override public Pieza[][] movimiento(Pieza[][] tablero, int i, int j, int x, int y) throws Excepcion { if(tablero[i][j].getColor().equals(tablero[x][y].getColor())){ throw new Excepcion("Pieza del mismo equipo en esa posicion. No se movio!"); }else if(i!=x && j!=y){ tablero[x][y] = tablero[i][j]; tablero[i][j] = new Espacio(); }else{ throw new Excepcion("Movimiento no valido, no se movio"); } return tablero; } public Pieza[][] comer(Pieza[][] tablero, int i, int j, int x, int y) throws Excepcion{ if(i+1>9||i-1<0||j+1>9||j-1<0||i+2>9||i-2<0||j+2>9||j-2<0){ throw new Excepcion("Se salio de la matriz"); }else if(!tablero[i+1][j].getColor().equals(tablero[i][j].getColor())){ tablero[i+1][j] = new Espacio(); }else if(!tablero[i-1][j].getColor().equals(tablero[i][j].getColor())){ tablero[i-1][j] = new Espacio(); }else if(!tablero[i][j+1].getColor().equals(tablero[i][j].getColor())){ tablero[i][j+1] = new Espacio(); }else if(!tablero[i][j-1].getColor().equals(tablero[i][j].getColor())){ tablero[i][j-1] = new Espacio(); }else if(!tablero[i+2][j+2].getColor().equals(tablero[i][j].getColor())){ tablero[i+2][j+2] = new Espacio(); }else if(!tablero[i-2][j-2].getColor().equals(tablero[i][j].getColor())){ tablero[i-2][j-2] = new Espacio(); }else if(!tablero[i+2][j-2].getColor().equals(tablero[i][j].getColor())){ tablero[i+2][j-2] = new Espacio(); }else if(!tablero[i-2][j+2].getColor().equals(tablero[i][j].getColor())){ tablero[i-2][j+2] = new Espacio(); } return tablero; } }
package dr.inference.operators; import dr.evomodel.continuous.LatentFactorModel; import dr.inference.distribution.DistributionLikelihood; import dr.inference.model.MatrixParameter; import dr.inference.model.Parameter; import dr.math.MathUtils; import dr.math.distributions.MultivariateNormalDistribution; import dr.math.distributions.NormalDistribution; import dr.math.matrixAlgebra.CholeskyDecomposition; import dr.math.matrixAlgebra.IllegalDimension; import dr.math.matrixAlgebra.SymmetricMatrix; import java.util.ArrayList; import java.util.ListIterator; public class LoadingsGibbsOperator extends SimpleMCMCOperator implements GibbsOperator { NormalDistribution prior; LatentFactorModel LFM; ArrayList<double[][]> precisionArray; ArrayList<double[]> meanMidArray; ArrayList<double[]> meanArray; boolean randomScan; double priorPrecision; double priorMeanPrecision; public LoadingsGibbsOperator(LatentFactorModel LFM, DistributionLikelihood prior, double weight, boolean randomScan) { setWeight(weight); this.prior = (NormalDistribution) prior.getDistribution(); this.LFM = LFM; precisionArray = new ArrayList<double[][]>(); double[][] temp; this.randomScan = randomScan; meanArray = new ArrayList<double[]>(); meanMidArray = new ArrayList<double[]>(); double[] tempMean; if (!randomScan) { for (int i = 0; i < LFM.getFactorDimension(); i++) { temp = new double[i + 1][i + 1]; precisionArray.add(temp); } for (int i = 0; i < LFM.getFactorDimension(); i++) { tempMean = new double[i + 1]; meanArray.add(tempMean); } for (int i = 0; i < LFM.getFactorDimension(); i++) { tempMean = new double[i + 1]; meanMidArray.add(tempMean); } } else { for (int i = 0; i < LFM.getFactorDimension(); i++) { temp = new double[LFM.getFactorDimension()-i][LFM.getFactorDimension() - i]; precisionArray.add(temp); } for (int i = 0; i < LFM.getFactorDimension(); i++) { tempMean = new double[LFM.getFactorDimension() - i]; meanArray.add(tempMean); } for (int i = 0; i < LFM.getFactorDimension(); i++) { tempMean = new double[LFM.getFactorDimension() - i]; meanMidArray.add(tempMean); } } // vectorProductAnswer=new MatrixParameter[LFM.getLoadings().getRowDimension()]; // for (int i = 0; i <vectorProductAnswer.length ; i++) { // vectorProductAnswer[i]=new MatrixParameter(null); // vectorProductAnswer[i].setDimensions(i+1, 1); // priorMeanVector=new MatrixParameter[LFM.getLoadings().getRowDimension()]; // for (int i = 0; i <priorMeanVector.length ; i++) { // priorMeanVector[i]=new MatrixParameter(null, i+1, 1, this.prior.getMean()/(this.prior.getSD()*this.prior.getSD())); priorPrecision = 1 / (this.prior.getSD() * this.prior.getSD()); priorMeanPrecision = this.prior.getMean() * priorPrecision; } private void getPrecisionOfTruncated(MatrixParameter full, int newRowDimension, int row, double[][] answer) { // MatrixParameter answer=new MatrixParameter(null); // answer.setDimensions(this.getRowDimension(), Right.getRowDimension()); // System.out.println(answer.getRowDimension()); // System.out.println(answer.getColumnDimension()); int p = full.getColumnDimension(); for (int i = 0; i < newRowDimension; i++) { for (int j = i; j < newRowDimension; j++) { double sum = 0; for (int k = 0; k < p; k++) sum += full.getParameterValue(i, k) * full.getParameterValue(j, k); answer[i][j] = sum * LFM.getColumnPrecision().getParameterValue(row, row); if (i == j) { answer[i][j] += priorPrecision; } else { answer[j][i] = answer[i][j]; } } } } private void getTruncatedMean(int newRowDimension, int dataColumn, double[][] variance, double[] midMean, double[] mean) { // MatrixParameter answer=new MatrixParameter(null); // answer.setDimensions(this.getRowDimension(), Right.getRowDimension()); // System.out.println(answer.getRowDimension()); // System.out.println(answer.getColumnDimension()); MatrixParameter data = LFM.getScaledData(); MatrixParameter Left = LFM.getFactors(); int p = data.getColumnDimension(); for (int i = 0; i < newRowDimension; i++) { double sum = 0; for (int k = 0; k < p; k++) sum += Left.getParameterValue(i, k) * data.getParameterValue(dataColumn, k); sum = sum * LFM.getColumnPrecision().getParameterValue(dataColumn, dataColumn); sum += priorMeanPrecision; midMean[i] = sum; } for (int i = 0; i < newRowDimension; i++) { double sum = 0; for (int k = 0; k < newRowDimension; k++) sum += variance[i][k] * midMean[k]; mean[i] = sum; } } private void getPrecision(int i, double[][] answer) { int size = LFM.getFactorDimension(); if (i < size) { getPrecisionOfTruncated(LFM.getFactors(), i + 1, i, answer); } else { getPrecisionOfTruncated(LFM.getFactors(), size, i, answer); } } private void getMean(int i, double[][] variance, double[] midMean, double[] mean) { // Matrix factors=null; int size = LFM.getFactorDimension(); // double[] scaledDataColumn=LFM.getScaledData().getRowValues(i); // Vector dataColumn=null; // Vector priorVector=null; // Vector temp=null; // Matrix data=new Matrix(LFM.getScaledData().getParameterAsMatrix()); if (i < size) { getTruncatedMean(i + 1, i, variance, midMean, mean); // dataColumn=new Vector(data.toComponents()[i]); // try { // answer=precision.inverse().product(new Matrix(priorMeanVector[i].add(vectorProductAnswer[i]).getParameterAsMatrix())); } else { getTruncatedMean(size, i, variance, midMean, mean); // dataColumn=new Vector(data.toComponents()[i]); // try { // answer=precision.inverse().product(new Matrix(priorMeanVector[size-1].add(vectorProductAnswer[size-1]).getParameterAsMatrix())); } } private void copy(int i, double[] random) { Parameter changing = LFM.getLoadings().getParameter(i); for (int j = 0; j < random.length; j++) { changing.setParameterValueQuietly(j, random[j]); } } private void drawI(int i, ListIterator<double[][]> currentPrecision, ListIterator<double[]> currentMidMean, ListIterator<double[]> currentMean) { double[] draws = null; double[][] precision = null; double[][] variance; double[] midMean = null; double[] mean = null; double[][] cholesky = null; if (currentPrecision.hasNext()) { precision = currentPrecision.next(); } if (currentMidMean.hasNext()) { midMean = currentMidMean.next(); } if (currentMean.hasNext()) { mean = currentMean.next(); } getPrecision(i, precision); variance = (new SymmetricMatrix(precision)).inverse().toComponents(); try { cholesky = new CholeskyDecomposition(variance).getL(); } catch (IllegalDimension illegalDimension) { illegalDimension.printStackTrace(); } getMean(i, variance, mean, midMean); draws = MultivariateNormalDistribution.nextMultivariateNormalCholesky(mean, cholesky); // if(i<draws.length) // while (draws[i] < 0) { // draws = MultivariateNormalDistribution.nextMultivariateNormalCholesky(mean, cholesky); if (i < draws.length) { if (draws[i] > 0) { copy(i, draws); } } else{ copy(i, draws); } // copy(i, draws); } @Override public int getStepCount() { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getPerformanceSuggestion() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getOperatorName() { return "loadingsGibbsOperator"; //To change body of implemented methods use File | Settings | File Templates. } @Override public double doOperation() throws OperatorFailedException { int size = LFM.getLoadings().getColumnDimension(); if(!randomScan) { ListIterator<double[][]> currentPrecision = precisionArray.listIterator(); ListIterator<double[]> currentMidMean = meanMidArray.listIterator(); ListIterator<double[]> currentMean = meanArray.listIterator(); for (int i = 0; i < size; i++) { drawI(i, currentPrecision, currentMidMean, currentMean); } LFM.getLoadings().fireParameterChangedEvent(); } else{ int i= MathUtils.nextInt(LFM.getLoadings().getColumnDimension()); ListIterator<double[][]> currentPrecision; ListIterator<double[]> currentMidMean; ListIterator<double[]> currentMean; if(i<LFM.getFactorDimension()){ currentPrecision = precisionArray.listIterator(LFM.getFactorDimension()-i-1); currentMidMean = meanMidArray.listIterator(LFM.getFactorDimension()-i-1); currentMean = meanArray.listIterator(LFM.getFactorDimension()-i-1); } else{ currentPrecision = precisionArray.listIterator(); currentMidMean = meanMidArray.listIterator(); currentMean = meanArray.listIterator(); } drawI(i, currentPrecision, currentMidMean, currentMean); LFM.getLoadings().fireParameterChangedEvent(); } return 0; } }
package org.slc.sli.api.resources; import static org.junit.Assert.*; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; 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.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; import org.slc.sli.api.WebContextTestExecutionListener; import org.slc.sli.api.representation.CollectionResponse; import org.slc.sli.api.representation.CollectionResponse.EntityReference; import org.slc.sli.api.representation.EntityBody; /** * Unit tests for the generic Resource class. * * @author Ryan Farris <rfarris@wgen.net> * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "/spring/applicationContext-test.xml" }) @TestExecutionListeners({ WebContextTestExecutionListener.class, DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class }) public class ResourceTest { @Autowired Resource api; public Map<String, Object> createTestEntity() { Map<String, Object> entity = new HashMap<String, Object>(); entity.put("field1", 1); entity.put("field2", 2); return entity; } public Map<String, Object> createTestAssoication(String studentId, String schoolId) { Map<String, Object> entity = new HashMap<String, Object>(); entity.put("studentId", studentId); entity.put("schoolId", schoolId); entity.put("entryGradeLevel", "First grade"); return entity; } @Test public void testResourceMethods() { // post some data Map<String, String> ids = new HashMap<String, String>(); Response createResponse = api.createEntity("students", new EntityBody(createTestEntity())); assertNotNull(createResponse); assertEquals(Status.CREATED.getStatusCode(), createResponse.getStatus()); String studentId1 = parseIdFromLocation(createResponse); ids.put(studentId1, (String) createResponse.getMetadata().get("Location").get(0)); Response createResponse2 = api.createEntity("students", new EntityBody(createTestEntity())); assertNotNull(createResponse2); assertEquals(Status.CREATED.getStatusCode(), createResponse2.getStatus()); String studentId2 = parseIdFromLocation(createResponse2); ids.put(studentId2, (String) createResponse2.getMetadata().get("Location").get(0)); Response createResponse3 = api.createEntity("schools", new EntityBody(createTestEntity())); assertNotNull(createResponse3); assertEquals(Status.CREATED.getStatusCode(), createResponse3.getStatus()); String schoolId = parseIdFromLocation(createResponse3); Response createResponse4 = api.createEntity("student-enrollments", new EntityBody(createTestAssoication(studentId1, schoolId))); assertNotNull(createResponse4); String assocId1 = parseIdFromLocation(createResponse4); Response createResponse5 = api.createEntity("student-enrollments", new EntityBody(createTestAssoication(studentId2, schoolId))); assertNotNull(createResponse5); String assocId2 = parseIdFromLocation(createResponse5); // test the get collection method Response studentEntities = api.getCollection("students", 0, 100); CollectionResponse response = (CollectionResponse) studentEntities.getEntity(); assertNotNull(response); assertEquals(2, response.size()); for (EntityReference er : response) { assertNotNull(er.getId()); assertNotNull(er.getLink()); assertEquals("student", er.getLink().getType()); assertEquals("self", er.getLink().getRel()); assertTrue(ids.containsKey(er.getId())); assertNotNull(ids.get(er.getId()), er.getLink().getHref()); } assertEquals(1, ((CollectionResponse) api.getCollection("students", 0, 1).getEntity()).size()); assertEquals(1, ((CollectionResponse) api.getCollection("students", 1, 1).getEntity()).size()); // test get for (String id : ids.keySet()) { Response r = api.getEntityOrAssociations("students", id, 0, 100); EntityBody body = (EntityBody) r.getEntity(); assertNotNull(body); assertEquals(id, body.get("id")); assertEquals(1, body.get("field1")); assertEquals(2, body.get("field2")); } // test associations for (String id : new String[] { assocId1, assocId2 }) { Response r = api.getEntityOrAssociations("student-enrollments", id, 0, 10); EntityBody assoc = (EntityBody) r.getEntity(); assertNotNull(assoc); assertEquals(id, assoc.get("id")); assertEquals("First grade", assoc.get("entryGradeLevel")); assertEquals(schoolId, assoc.get("schoolId")); assertNotNull(assoc.get("studentId")); if (!(assoc.get("studentId").equals(studentId1) || assoc.get("studentId").equals(studentId2))) { fail(); } } // test freaky association uri for (String id : new String[] { studentId1, studentId2 }) { Response r = api.getEntityOrAssociations("student-enrollments", id, 0, 10); CollectionResponse cr = (CollectionResponse) r.getEntity(); assertNotNull(cr); assertEquals(1, cr.size()); assertNotNull(cr.get(0).getId()); if (!(cr.get(0).getId().equals(assocId1) || cr.get(0).getId().equals(assocId2))) { fail(); } assertNotNull(cr.get(0).getLink()); assertNotNull("self", cr.get(0).getLink().getRel()); assertNotNull(cr.get(0).getLink().getHref()); assertTrue(cr.get(0).getLink().getHref().contains(cr.get(0).getId())); } // test update/get/delete for (String id : ids.keySet()) { Response r = api.getEntityOrAssociations("students", id, 0, 100); EntityBody body = (EntityBody) r.getEntity(); body.put("field1", 99); Response r2 = api.updateEntity("students", id, body); assertEquals(Status.NO_CONTENT.getStatusCode(), r2.getStatus()); Response r3 = api.getEntityOrAssociations("students", id, 0, 100); EntityBody body3 = (EntityBody) r3.getEntity(); assertNotNull(body3); assertEquals(body, body3); Response d = api.deleteEntity("students", id); assertNull(d.getEntity()); assertEquals(Status.NO_CONTENT.getStatusCode(), d.getStatus()); Response r4 = api.getEntityOrAssociations("students", id, 0, 100); assertEquals(Status.NOT_FOUND.getStatusCode(), r4.getStatus()); } Response r5 = api.getCollection("students", 0, 100); CollectionResponse empty = (CollectionResponse) r5.getEntity(); assertNotNull(empty); assertEquals(0, empty.size()); } private static String parseIdFromLocation(Response response) { List<Object> locationHeaders = response.getMetadata().get("Location"); assertNotNull(locationHeaders); assertEquals(1, locationHeaders.size()); Pattern regex = Pattern.compile(".+/(\\d+)$"); Matcher matcher = regex.matcher((String) locationHeaders.get(0)); matcher.find(); assertEquals(1, matcher.groupCount()); return matcher.group(1); } }
package uk.ac.ebi.quickgo.ff.files; import uk.ac.ebi.quickgo.ff.files.ontology.ECOSourceFiles; import uk.ac.ebi.quickgo.ff.files.ontology.GOSourceFiles; import uk.ac.ebi.quickgo.ff.reader.Progress; import uk.ac.ebi.quickgo.ff.reader.RowIterator; import uk.ac.ebi.quickgo.ff.reader.TSVRowReader; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class SourceFiles { public static final String VERSION = "100"; File baseDirectory; public SourceFiles(File directory) { this.baseDirectory = directory; goSourceFiles = new GOSourceFiles(baseDirectory); ecoSourceFiles = new ECOSourceFiles(baseDirectory); gpDataFileList = new NamedFile(baseDirectory, "GPAD_SOURCE_FILES"); taxonomy = new TSVDataFile<>(baseDirectory, "TAXONOMY"); sequenceSource = new TSVDataFile<>(baseDirectory, "sequences"); publications = new TSVDataFile<>(baseDirectory, "PUBLICATIONS"); annotationGuidelines = new TSVDataFile<>(baseDirectory, "ANNOTATION_GUIDELINES"); annotationBlacklist = new TSVDataFile<>(baseDirectory, "ANNOTATION_BLACKLIST"); postProcessingRules = new TSVDataFile<>(baseDirectory, "POST_PROCESSING_RULES"); xrfAbbsInfo = new TSVDataFile<>(baseDirectory, "XRF_ABBS"); evidenceInfo = new TSVDataFile<>(baseDirectory, "CV_ECO2GO"); } public File getBaseDirectory() { return baseDirectory; } public static NamedFile[] holder(NamedFile... files) { return files; } public static NamedFile[] holder(NamedFile[]... files) { List<NamedFile> list = new ArrayList<>(); for (NamedFile[] f : files) { list.addAll(Arrays.asList(f)); } return list.toArray(new NamedFile[list.size()]); } public static class NamedFile { public File directory; public String name; public NamedFile(File directory, String name) { this.directory = directory; this.name = name; } public File file() { return new File(directory, name); } public String getName() { return name; } public File getDirectory() { return directory; } } public static class TSVDataFile<X extends Enum<X>> extends NamedFile { public TSVDataFile(File directory, String name) { super(directory, name + ".dat.gz"); } @SuppressWarnings("unchecked") public RowIterator reader(X... columns) throws Exception { String[] names = new String[columns.length]; for (int i = 0; i < columns.length; i++) { names[i] = columns[i].name(); } return new RowIterator(Progress.monitor(name, new TSVRowReader(file(), names, true, true, null))); } } // source files for the ontologies that we index public GOSourceFiles goSourceFiles; public ECOSourceFiles ecoSourceFiles; // Reference information // Reference: Source data public enum EPublication { PUBMED_ID, TITLE } public TSVDataFile<EPublication> publications; NamedFile[] referenceSource = holder(publications); // Protein information // Protein: Source data public enum ETaxon { TAXON_ID, NAME, ANCESTRY } public TSVDataFile<ETaxon> taxonomy; public enum ESequence { protein, sequence } public TSVDataFile<ESequence> sequenceSource; NamedFile[] proteinSource = holder(taxonomy, sequenceSource); // Controlled vocabularies public enum EEvidenceCode { ECO_ID, NAME, GO_EVIDENCE, SORT_ORDER } public TSVDataFile<EEvidenceCode> evidenceInfo; public enum EGORef { NAME, GO_REF } public TSVDataFile<EGORef> goRefInfo = new TSVDataFile<>(baseDirectory, "CV_GO_REFS"); public enum EXrfAbbsEntry { ABBREVIATION, DATABASE, GENERIC_URL, URL_SYNTAX } public TSVDataFile<EXrfAbbsEntry> xrfAbbsInfo; public enum EProteinSet { NAME, DESCRIPTION, PROJECT_URL } public TSVDataFile<EProteinSet> proteinSetsInfo = new TSVDataFile<>(baseDirectory, "CV_PROTEIN_SETS"); public enum EGOEvidence2ECOTranslation { CODE, GO_REF, ECO_ID } public TSVDataFile<EGOEvidence2ECOTranslation> evidence2ECO = new TSVDataFile<>(baseDirectory, "EVIDENCE2ECO"); public enum EAnnotationBlacklistEntry { PROTEIN_AC, TAXON_ID, GO_ID, REASON, METHOD_ID, CATEGORY, ENTRY_TYPE } public TSVDataFile<EAnnotationBlacklistEntry> annotationBlacklist; public enum EAnnotationGuidelineEntry { GO_ID, TITLE, URL } public TSVDataFile<EAnnotationGuidelineEntry> annotationGuidelines; public enum EPostProcessingRule { RULE_ID, ANCESTOR_GO_ID, ANCESTOR_TERM, RELATIONSHIP, TAXON_NAME, ORIGINAL_GO_ID, ORIGINAL_TERM, CLEANUP_ACTION, AFFECTED_TAX_GROUP, SUBSTITUTED_GO_ID, SUBSTITUTED_TERM, CURATOR_NOTES } public TSVDataFile<EPostProcessingRule> postProcessingRules; NamedFile[] controlledVocabs = holder(evidenceInfo, goRefInfo, xrfAbbsInfo, proteinSetsInfo, evidence2ECO, annotationBlacklist, postProcessingRules); // Controlled vocabularies: derived data public enum EGP2ProteinDB { CODE, IS_DB } public TSVDataFile<EGP2ProteinDB> gp2proteinDb = new TSVDataFile<>(baseDirectory, "GP2PROTEIN_DB"); NamedFile[] controlledVocabsDerived = holder(gp2proteinDb); // Annotation: source data NamedFile gpDataFileList; NamedFile[] annotationSource = holder(gpDataFileList); // Prerequisite file set protected NamedFile[] prerequisite = holder(annotationSource, referenceSource, proteinSource, controlledVocabs); // Archive file set protected NamedFile[] archive = holder(controlledVocabs, controlledVocabsDerived); public NamedFile[] requiredFiles() { return prerequisite; } public NamedFile[] archiveFiles() { return archive; } public NamedFile[] getGPDataFiles() { return getFiles(gpDataFileList, null); } public NamedFile[] getFiles(NamedFile listFile, final String prefix) { List<NamedFile> list = new ArrayList<NamedFile>(); try { BufferedReader reader = new BufferedReader(new FileReader(listFile.file())); String fileName; while ((fileName = reader.readLine()) != null) { if (!"".equals(fileName) && (prefix == null || fileName.startsWith(prefix))) { list.add(new NamedFile(baseDirectory, fileName)); } } } catch (IOException e) { e.printStackTrace(); } return list.toArray(new NamedFile[list.size()]); } // Download files public final static String stampName = "quickgo-stamp-v" + VERSION + ".txt"; }
package com.takusemba.spotlight; import android.app.Activity; import android.content.Context; import android.graphics.Point; import android.graphics.PointF; import android.support.annotation.NonNull; import android.view.View; import android.view.ViewTreeObserver; import android.view.WindowManager; import android.widget.LinearLayout; import android.widget.TextView; /** * Position Target * * @author takusemba * @since 26/06/2017 **/ public class SimpleTarget implements Target { private PointF point; private float radius; private View view; private OnTargetStateChangedListener listener; /** * Constructor */ private SimpleTarget(PointF point, float radius, View view, OnTargetStateChangedListener listener) { this.point = point; this.radius = radius; this.view = view; this.listener = listener; } @Override public PointF getPoint() { return point; } @Override public float getRadius() { return radius; } @Override public View getView() { return view; } @Override public OnTargetStateChangedListener getListener() { return listener; } /** * Builder class which makes it easier to create {@link SimpleTarget} */ public static class Builder extends AbstractBuilder<Builder, SimpleTarget> { @Override protected Builder self() { return this; } private static final int ABOVE_SPOTLIGHT = 0; private static final int BELOW_SPOTLIGHT = 1; private CharSequence title; private CharSequence description; /** * Constructor */ public Builder(@NonNull Activity context) { super(context); } /** * Set the title text shown on Spotlight * * @param title title shown on Spotlight * @return This Builder */ public Builder setTitle(CharSequence title) { this.title = title; return this; } /** * Set the description text shown on Spotlight * * @param description title shown on Spotlight * @return This Builder */ public Builder setDescription(CharSequence description) { this.description = description; return this; } /** * Create the {@link SimpleTarget} * * @return the created SimpleTarget */ @Override public SimpleTarget build() { if (getContext() == null) { throw new RuntimeException("context is null"); } View view = getContext().getLayoutInflater().inflate(R.layout.layout_spotlight, null); ((TextView) view.findViewById(R.id.title)).setText(title); ((TextView) view.findViewById(R.id.description)).setText(description); PointF point = new PointF(startX, startY); calculatePosition(point, radius, view); return new SimpleTarget(point, radius, view, listener); } /** * calculate the position of title and description based off of where the spotlight reveals */ private void calculatePosition(final PointF point, final float radius, View spotlightView) { float[] areas = new float[2]; Point screenSize = new Point(); ((WindowManager) spotlightView.getContext() .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getSize(screenSize); areas[ABOVE_SPOTLIGHT] = point.y / screenSize.y; areas[BELOW_SPOTLIGHT] = (screenSize.y - point.y) / screenSize.y; int largest; if (areas[ABOVE_SPOTLIGHT] > areas[BELOW_SPOTLIGHT]) { largest = ABOVE_SPOTLIGHT; } else { largest = BELOW_SPOTLIGHT; } final LinearLayout layout = spotlightView.findViewById(R.id.container); layout.setPadding(100, 0, 100, 0); switch (largest) { case ABOVE_SPOTLIGHT: spotlightView.getViewTreeObserver() .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { layout.setY(point.y - radius - 100 - layout.getHeight()); } }); break; case BELOW_SPOTLIGHT: layout.setY((int) (point.y + radius + 100)); break; } } } }
package org.opencms.ade.galleries.client.ui; import org.opencms.ade.galleries.client.CmsCategoriesTabHandler; import org.opencms.ade.galleries.client.Messages; import org.opencms.ade.galleries.shared.CmsGallerySearchBean; import org.opencms.ade.galleries.shared.I_CmsGalleryProviderConstants.GalleryTabId; import org.opencms.ade.galleries.shared.I_CmsGalleryProviderConstants.SortParams; import org.opencms.gwt.client.ui.CmsSimpleListItem; import org.opencms.gwt.client.ui.input.CmsCheckBox; import org.opencms.gwt.client.ui.input.category.CmsDataValue; import org.opencms.gwt.client.ui.tree.CmsTreeItem; import org.opencms.gwt.shared.CmsCategoryBean; import org.opencms.gwt.shared.CmsCategoryTreeEntry; import org.opencms.gwt.shared.CmsIconUtil; import org.opencms.util.CmsStringUtil; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.google.gwt.event.dom.client.DoubleClickEvent; import com.google.gwt.user.client.ui.Label; /** * Provides the widget for the categories tab.<p> * * It displays the available categories in the given sort order. * * @since 8.0. */ public class CmsCategoriesTab extends A_CmsListTab { /** * Handles the change of the item selection.<p> */ private class SelectionHandler extends A_SelectionHandler { /** The category path as id for the selected category. */ private String m_categoryPath; /** * Constructor.<p> * * @param categoryPath as id for the selected category * @param checkBox the reference to the checkbox */ public SelectionHandler(String categoryPath, CmsCheckBox checkBox) { super(checkBox); m_categoryPath = categoryPath; } /** * @see org.opencms.ade.galleries.client.ui.A_CmsListTab.A_SelectionHandler#onSelectionChange() */ @Override protected void onSelectionChange() { if (getCheckBox().isChecked()) { getTabHandler().onSelectCategory(m_categoryPath); } else { getTabHandler().onDeselectCategory(m_categoryPath); } } } /** The category icon CSS classes. */ private static final String CATEGORY_ICON_CLASSES = CmsIconUtil.getResourceIconClasses("folder", false); /** Text metrics key. */ private static final String TM_CATEGORY_TAB = "CategoryTab"; /** Map of the categories by path. */ private Map<String, CmsCategoryBean> m_categories; /** The flag to indicate when the categories are opened for the fist time. */ private boolean m_isInitOpen; /** The tab handler. */ private CmsCategoriesTabHandler m_tabHandler; /** * Constructor.<p> * * @param tabHandler the tab handler */ public CmsCategoriesTab(CmsCategoriesTabHandler tabHandler) { super(GalleryTabId.cms_tab_categories); m_scrollList.truncate(TM_CATEGORY_TAB, CmsGalleryDialog.DIALOG_WIDTH); m_tabHandler = tabHandler; m_isInitOpen = false; init(); } /** * Fill the content of the categories tab panel.<p> * * @param categoryRoot the category tree root entry */ public void fillContent(List<CmsCategoryTreeEntry> categoryRoot) { setInitOpen(true); updateContentTree(categoryRoot, null); } /** * @see org.opencms.ade.galleries.client.ui.A_CmsTab#getParamPanels(org.opencms.ade.galleries.shared.CmsGallerySearchBean) */ @Override public List<CmsSearchParamPanel> getParamPanels(CmsGallerySearchBean searchObj) { List<CmsSearchParamPanel> result = new ArrayList<CmsSearchParamPanel>(); for (String categoryPath : searchObj.getCategories()) { CmsCategoryBean categoryItem = m_categories.get(categoryPath); String title = categoryItem.getTitle(); if (CmsStringUtil.isEmptyOrWhitespaceOnly(title)) { title = categoryItem.getPath(); } CmsSearchParamPanel panel = new CmsSearchParamPanel(Messages.get().key( Messages.GUI_PARAMS_LABEL_CATEGORIES_0), this); panel.setContent(title, categoryPath); result.add(panel); } return result; } /** * Returns the isInitOpen.<p> * * @return the isInitOpen */ public boolean isInitOpen() { return m_isInitOpen; } /** * Opens the first level in the categories tree.<p> */ public void openFirstLevel() { if (!m_categories.isEmpty()) { for (int i = 0; i < m_scrollList.getWidgetCount(); i++) { CmsTreeItem item = (CmsTreeItem)m_scrollList.getItem(i); item.setOpen(true); } } } /** * Sets the isInitOpen.<p> * * @param isInitOpen the isInitOpen to set */ public void setInitOpen(boolean isInitOpen) { m_isInitOpen = isInitOpen; } /** * Deselect the categories in the category list.<p> * * @param categories the categories to deselect */ public void uncheckCategories(List<String> categories) { for (String category : categories) { CmsTreeItem item = searchTreeItem(m_scrollList, category); item.getCheckBox().setChecked(false); } } /** * Updates the content of the categories list.<p> * * @param categoriesBeans the updates list of categories tree item beans * @param selectedCategories the categories to select in the list by update */ public void updateContentList(List<CmsCategoryBean> categoriesBeans, List<String> selectedCategories) { clearList(); if (m_categories == null) { m_categories = new HashMap<String, CmsCategoryBean>(); } if ((categoriesBeans != null) && !categoriesBeans.isEmpty()) { for (CmsCategoryBean categoryBean : categoriesBeans) { m_categories.put(categoryBean.getPath(), categoryBean); // set the list item widget CmsDataValue dataValue = new CmsDataValue( 600, 3, categoryBean.getTitle(), CmsStringUtil.isNotEmptyOrWhitespaceOnly(categoryBean.getDescription()) ? categoryBean.getDescription() : categoryBean.getPath()); // the checkbox CmsCheckBox checkBox = new CmsCheckBox(); if ((selectedCategories != null) && selectedCategories.contains(categoryBean.getPath())) { checkBox.setChecked(true); } SelectionHandler selectionHandler = new SelectionHandler(categoryBean.getPath(), checkBox); checkBox.addClickHandler(selectionHandler); dataValue.addDomHandler(selectionHandler, DoubleClickEvent.getType()); // set the category list item and add to list CmsTreeItem listItem = new CmsTreeItem(false, checkBox, dataValue); listItem.setSmallView(true); listItem.setId(categoryBean.getPath()); addWidgetToList(listItem); } } else { showIsEmptyLabel(); } } /** * Updates the content of th categories tree.<p> * * @param treeEntries the root category entry * @param selectedCategories the categories to select after update */ public void updateContentTree(List<CmsCategoryTreeEntry> treeEntries, List<String> selectedCategories) { clearList(); if (m_categories == null) { m_categories = new HashMap<String, CmsCategoryBean>(); } if ((treeEntries != null) && !treeEntries.isEmpty()) { // add the first level and children for (CmsCategoryTreeEntry category : treeEntries) { // set the category tree item and add to list CmsTreeItem treeItem = buildTreeItem(category, selectedCategories); addChildren(treeItem, category.getChildren(), selectedCategories); addWidgetToList(treeItem); treeItem.setOpen(true); } } else { showIsEmptyLabel(); } } /** * @see org.opencms.ade.galleries.client.ui.A_CmsListTab#getSortList() */ @Override protected LinkedHashMap<String, String> getSortList() { LinkedHashMap<String, String> list = new LinkedHashMap<String, String>(); list.put(SortParams.tree.name(), Messages.get().key(Messages.GUI_SORT_LABEL_HIERARCHIC_0)); list.put(SortParams.title_asc.name(), Messages.get().key(Messages.GUI_SORT_LABEL_TITLE_ASC_0)); list.put(SortParams.title_desc.name(), Messages.get().key(Messages.GUI_SORT_LABEL_TITLE_DECS_0)); return list; } /** * @see org.opencms.ade.galleries.client.ui.A_CmsListTab#getTabHandler() */ @Override protected CmsCategoriesTabHandler getTabHandler() { return m_tabHandler; } /** * @see org.opencms.ade.galleries.client.ui.A_CmsListTab#hasQuickFilter() */ @Override protected boolean hasQuickFilter() { // allow filter if not in tree mode return SortParams.tree != SortParams.valueOf(m_sortSelectBox.getFormValueAsString()); } /** * Adds children item to the category tree and select the categories.<p> * * @param parent the parent item * @param children the list of children * @param selectedCategories the list of categories to select */ private void addChildren(CmsTreeItem parent, List<CmsCategoryTreeEntry> children, List<String> selectedCategories) { if (children != null) { for (CmsCategoryTreeEntry child : children) { // set the category tree item and add to parent tree item CmsTreeItem treeItem = buildTreeItem(child, selectedCategories); if ((selectedCategories != null) && selectedCategories.contains(child.getPath())) { parent.setOpen(true); openParents(parent); } parent.addChild(treeItem); addChildren(treeItem, child.getChildren(), selectedCategories); } } } /** * Builds a tree item for the given category.<p> * * @param category the category * @param selectedCategories the selected categories * * @return the tree item widget */ private CmsTreeItem buildTreeItem(CmsCategoryTreeEntry category, List<String> selectedCategories) { m_categories.put(category.getPath(), category); // set the list item widget CmsDataValue dataValue = new CmsDataValue( 600, 3, category.getTitle(), CmsStringUtil.isNotEmptyOrWhitespaceOnly(category.getDescription()) ? category.getDescription() : category.getPath()); // the checkbox CmsCheckBox checkBox = new CmsCheckBox(); if ((selectedCategories != null) && selectedCategories.contains(category.getPath())) { checkBox.setChecked(true); } SelectionHandler selectionHandler = new SelectionHandler(category.getPath(), checkBox); checkBox.addClickHandler(selectionHandler); dataValue.addDomHandler(selectionHandler, DoubleClickEvent.getType()); dataValue.addButton(createSelectButton(selectionHandler)); // set the category tree item and add to list CmsTreeItem treeItem = new CmsTreeItem(true, checkBox, dataValue); treeItem.setSmallView(true); treeItem.setId(category.getPath()); return treeItem; } /** * Goes up the tree and opens the parents of the item.<p> * * @param item the child item to start from */ private void openParents(CmsTreeItem item) { if (item != null) { item.setOpen(true); openParents(item.getParentItem()); } } /** * Shows the tab list is empty label.<p> */ private void showIsEmptyLabel() { CmsSimpleListItem item = new CmsSimpleListItem(); Label isEmptyLabel = new Label(Messages.get().key(Messages.GUI_TAB_CATEGORIES_IS_EMPTY_0)); item.add(isEmptyLabel); m_scrollList.add(item); } }
package org.pentaho.di.ui.job.entries.xslt; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.pentaho.di.core.Const; import org.pentaho.di.job.JobMeta; import org.pentaho.di.ui.core.gui.WindowProperty; import org.pentaho.di.ui.core.widget.TextVar; import org.pentaho.di.ui.job.dialog.JobDialog; import org.pentaho.di.ui.job.entry.JobEntryDialog; import org.pentaho.di.job.entry.JobEntryDialogInterface; import org.pentaho.di.job.entry.JobEntryInterface; import org.pentaho.di.repository.Repository; import org.pentaho.di.ui.trans.step.BaseStepDialog; import org.pentaho.di.job.entries.xslt.JobEntryXSLT; import org.pentaho.di.job.entries.xslt.Messages; /** * This dialog allows you to edit the XSLT job entry settings. * * @author Samatar Hassan * @since 02-03-2007 */ public class JobEntryXSLTDialog extends JobEntryDialog implements JobEntryDialogInterface { private static final String[] FILETYPES_XML = new String[] { Messages.getString("JobEntryXSLT.Filetype.Xml"), Messages.getString("JobEntryXSLT.Filetype.All") }; private static final String[] FILETYPES_XSL = new String[] { Messages.getString("JobEntryXSLT.Filetype.Xsl"), Messages.getString("JobEntryXSLT.Filetype.Xslt"), Messages.getString("JobEntryXSLT.Filetype.All")}; private Label wlName; private Text wName; private FormData fdlName, fdName; private Label wlxmlFilename; private Button wbxmlFilename; private TextVar wxmlFilename; private FormData fdlxmlFilename, fdbxmlFilename, fdxmlFilename; private Label wlxslFilename; private Button wbxslFilename; private TextVar wxslFilename; private FormData fdlxslFilename, fdbxslFilename, fdxslFilename; private Label wlOutputFilename; private TextVar wOutputFilename; private FormData fdlOutputFilename, fdOutputFilename; private Label wlIfFileExists; private CCombo wIfFileExists; private FormData fdlIfFileExists, fdIfFileExists; private Button wOK, wCancel; private Listener lsOK, lsCancel; private JobEntryXSLT jobEntry; private Shell shell; private SelectionAdapter lsDef; private boolean changed; // Add File to result private Group wFileResult; private FormData fdFileResult; private Label wlAddFileToResult; private Button wAddFileToResult; private FormData fdlAddFileToResult, fdAddFileToResult; public JobEntryXSLTDialog(Shell parent, JobEntryInterface jobEntryInt, Repository rep, JobMeta jobMeta) { super(parent, jobEntryInt, rep, jobMeta); jobEntry = (JobEntryXSLT) jobEntryInt; if (this.jobEntry.getName() == null) this.jobEntry.setName(Messages.getString("JobEntryXSLT.Name.Default")); } public JobEntryInterface open() { Shell parent = getParent(); Display display = parent.getDisplay(); shell = new Shell(parent, props.getJobsDialogStyle()); props.setLook(shell); JobDialog.setShellImage(shell, jobEntry); ModifyListener lsMod = new ModifyListener() { public void modifyText(ModifyEvent e) { jobEntry.setChanged(); } }; changed = jobEntry.hasChanged(); FormLayout formLayout = new FormLayout (); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout(formLayout); shell.setText(Messages.getString("JobEntryXSLT.Title")); int middle = props.getMiddlePct(); int margin = Const.MARGIN; // Name line wlName=new Label(shell, SWT.RIGHT); wlName.setText(Messages.getString("JobEntryXSLT.Name.Label")); props.setLook(wlName); fdlName=new FormData(); fdlName.left = new FormAttachment(0, 0); fdlName.right= new FormAttachment(middle, -margin); fdlName.top = new FormAttachment(0, margin); wlName.setLayoutData(fdlName); wName=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wName); wName.addModifyListener(lsMod); fdName=new FormData(); fdName.left = new FormAttachment(middle, 0); fdName.top = new FormAttachment(0, margin); fdName.right= new FormAttachment(100, 0); wName.setLayoutData(fdName); // Filename 1 line wlxmlFilename=new Label(shell, SWT.RIGHT); wlxmlFilename.setText(Messages.getString("JobEntryXSLT.xmlFilename.Label")); props.setLook(wlxmlFilename); fdlxmlFilename=new FormData(); fdlxmlFilename.left = new FormAttachment(0, 0); fdlxmlFilename.top = new FormAttachment(wName, margin); fdlxmlFilename.right= new FormAttachment(middle, -margin); wlxmlFilename.setLayoutData(fdlxmlFilename); wbxmlFilename=new Button(shell, SWT.PUSH| SWT.CENTER); props.setLook(wbxmlFilename); wbxmlFilename.setText(Messages.getString("System.Button.Browse")); fdbxmlFilename=new FormData(); fdbxmlFilename.right= new FormAttachment(100, 0); fdbxmlFilename.top = new FormAttachment(wName, 0); wbxmlFilename.setLayoutData(fdbxmlFilename); wxmlFilename=new TextVar(jobMeta, shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wxmlFilename); wxmlFilename.addModifyListener(lsMod); fdxmlFilename=new FormData(); fdxmlFilename.left = new FormAttachment(middle, 0); fdxmlFilename.top = new FormAttachment(wName, margin); fdxmlFilename.right= new FormAttachment(wbxmlFilename, -margin); wxmlFilename.setLayoutData(fdxmlFilename); wxmlFilename.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { wxmlFilename.setToolTipText(jobMeta.environmentSubstitute( wxmlFilename.getText() ) ); } } ); wbxmlFilename.addSelectionListener ( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { FileDialog dialog = new FileDialog(shell, SWT.OPEN); dialog.setFilterExtensions(new String[] {"*.xml;*.XML", "*"}); if (wxmlFilename.getText()!=null) { dialog.setFileName(jobMeta.environmentSubstitute(wxmlFilename.getText()) ); } dialog.setFilterNames(FILETYPES_XML); if (dialog.open()!=null) { wxmlFilename.setText(dialog.getFilterPath()+Const.FILE_SEPARATOR+dialog.getFileName()); } } } ); // Filename 2 line wlxslFilename=new Label(shell, SWT.RIGHT); wlxslFilename.setText(Messages.getString("JobEntryXSLT.xslFilename.Label")); props.setLook(wlxslFilename); fdlxslFilename=new FormData(); fdlxslFilename.left = new FormAttachment(0, 0); fdlxslFilename.top = new FormAttachment(wxmlFilename, margin); fdlxslFilename.right= new FormAttachment(middle, -margin); wlxslFilename.setLayoutData(fdlxslFilename); wbxslFilename=new Button(shell, SWT.PUSH| SWT.CENTER); props.setLook(wbxslFilename); wbxslFilename.setText(Messages.getString("System.Button.Browse")); fdbxslFilename=new FormData(); fdbxslFilename.right= new FormAttachment(100, 0); fdbxslFilename.top = new FormAttachment(wxmlFilename, 0); wbxslFilename.setLayoutData(fdbxslFilename); wxslFilename=new TextVar(jobMeta, shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wxslFilename); wxslFilename.addModifyListener(lsMod); fdxslFilename=new FormData(); fdxslFilename.left = new FormAttachment(middle, 0); fdxslFilename.top = new FormAttachment(wxmlFilename, margin); fdxslFilename.right= new FormAttachment(wbxslFilename, -margin); wxslFilename.setLayoutData(fdxslFilename); wxslFilename.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { wxslFilename.setToolTipText(jobMeta.environmentSubstitute( wxslFilename.getText() ) ); } } ); wbxslFilename.addSelectionListener ( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { FileDialog dialog = new FileDialog(shell, SWT.OPEN); dialog.setFilterExtensions(new String[] {"*.xsl;*.XSL", "*.xslt;*.XSLT", "*"}); if (wxslFilename.getText()!=null) { dialog.setFileName(jobMeta.environmentSubstitute(wxslFilename.getText()) ); } dialog.setFilterNames(FILETYPES_XSL); if (dialog.open()!=null) { wxslFilename.setText(dialog.getFilterPath()+Const.FILE_SEPARATOR+dialog.getFileName()); } } } ); // OutputFilename wlOutputFilename = new Label(shell, SWT.RIGHT); wlOutputFilename.setText(Messages.getString("JobEntryXSLT.OutputFilename.Label")); props.setLook(wlOutputFilename); fdlOutputFilename = new FormData(); fdlOutputFilename.left = new FormAttachment(0, 0); fdlOutputFilename.top = new FormAttachment(wxslFilename, margin); fdlOutputFilename.right = new FormAttachment(middle, -margin); wlOutputFilename.setLayoutData(fdlOutputFilename); wOutputFilename = new TextVar(jobMeta, shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wOutputFilename); wOutputFilename.addModifyListener(lsMod); fdOutputFilename = new FormData(); fdOutputFilename.left = new FormAttachment(middle, 0); fdOutputFilename.top = new FormAttachment(wxslFilename, margin); fdOutputFilename.right = new FormAttachment(100, 0); wOutputFilename.setLayoutData(fdOutputFilename); wOutputFilename.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { wOutputFilename.setToolTipText(jobMeta.environmentSubstitute( wOutputFilename.getText() ) ); } } ); //IF File Exists wlIfFileExists = new Label(shell, SWT.RIGHT); wlIfFileExists.setText(Messages.getString("JobEntryXSLT.IfZipFileExists.Label")); props.setLook(wlIfFileExists); fdlIfFileExists = new FormData(); fdlIfFileExists.left = new FormAttachment(0, 0); fdlIfFileExists.right = new FormAttachment(middle, 0); fdlIfFileExists.top = new FormAttachment(wOutputFilename, margin); wlIfFileExists.setLayoutData(fdlIfFileExists); wIfFileExists = new CCombo(shell, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); wIfFileExists.add(Messages.getString("JobEntryXSLT.Create_NewFile_IfFileExists.Label")); wIfFileExists.add(Messages.getString("JobEntryXSLT.Do_Nothing_IfFileExists.Label")); wIfFileExists.add(Messages.getString("JobEntryXSLT.Fail_IfFileExists.Label")); wIfFileExists.select(1); // +1: starts at -1 props.setLook(wIfFileExists); fdIfFileExists= new FormData(); fdIfFileExists.left = new FormAttachment(middle, 0); fdIfFileExists.top = new FormAttachment(wOutputFilename, margin); fdIfFileExists.right = new FormAttachment(100, 0); wIfFileExists.setLayoutData(fdIfFileExists); fdIfFileExists = new FormData(); fdIfFileExists.left = new FormAttachment(middle, 0); fdIfFileExists.top = new FormAttachment(wOutputFilename, margin); fdIfFileExists.right = new FormAttachment(100, 0); wIfFileExists.setLayoutData(fdIfFileExists); // fileresult grouping? // START OF LOGGING GROUP/// wFileResult = new Group(shell, SWT.SHADOW_NONE); props.setLook(wFileResult); wFileResult.setText(Messages.getString("JobEntryXSLT.FileResult.Group.Label")); FormLayout groupLayout = new FormLayout(); groupLayout.marginWidth = 10; groupLayout.marginHeight = 10; wFileResult.setLayout(groupLayout); //Add file to result wlAddFileToResult = new Label(wFileResult, SWT.RIGHT); wlAddFileToResult.setText(Messages.getString("JobEntryXSLT.AddFileToResult.Label")); props.setLook(wlAddFileToResult); fdlAddFileToResult = new FormData(); fdlAddFileToResult.left = new FormAttachment(0, 0); fdlAddFileToResult.top = new FormAttachment(wIfFileExists, margin); fdlAddFileToResult.right = new FormAttachment(middle, -margin); wlAddFileToResult.setLayoutData(fdlAddFileToResult); wAddFileToResult = new Button(wFileResult, SWT.CHECK); props.setLook(wAddFileToResult); wAddFileToResult.setToolTipText(Messages.getString("JobEntryXSLT.AddFileToResult.Tooltip")); fdAddFileToResult = new FormData(); fdAddFileToResult.left = new FormAttachment(middle, 0); fdAddFileToResult.top = new FormAttachment(wIfFileExists, margin); fdAddFileToResult.right = new FormAttachment(100, 0); wAddFileToResult.setLayoutData(fdAddFileToResult); wAddFileToResult.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { jobEntry.setChanged(); } }); fdFileResult = new FormData(); fdFileResult.left = new FormAttachment(0, margin); fdFileResult.top = new FormAttachment(wIfFileExists, margin); //fdFileResult.bottom = new FormAttachment(wOK, -margin); fdFileResult.right = new FormAttachment(100, -margin); wFileResult.setLayoutData(fdFileResult); // / END OF FileResult GROUP wOK = new Button(shell, SWT.PUSH); wOK.setText(Messages.getString("System.Button.OK")); wCancel = new Button(shell, SWT.PUSH); wCancel.setText(Messages.getString("System.Button.Cancel")); BaseStepDialog.positionBottomButtons(shell, new Button[] { wOK, wCancel }, margin, wFileResult); // Add listeners lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } }; lsOK = new Listener() { public void handleEvent(Event e) { ok(); } }; wCancel.addListener(SWT.Selection, lsCancel); wOK.addListener (SWT.Selection, lsOK ); lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } }; wName.addSelectionListener( lsDef ); wxmlFilename.addSelectionListener( lsDef ); wxslFilename.addSelectionListener( lsDef ); // Detect X or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } ); getData(); BaseStepDialog.setSize(shell); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } return jobEntry; } public void dispose() { WindowProperty winprop = new WindowProperty(shell); props.setScreen(winprop); shell.dispose(); } /** * Copy information from the meta-data input to the dialog fields. */ public void getData() { if (jobEntry.getName() != null) wName.setText( jobEntry.getName() ); wName.selectAll(); if (jobEntry.getxmlFilename()!= null) wxmlFilename.setText( jobEntry.getxmlFilename() ); if (jobEntry.getxslFilename()!= null) wxslFilename.setText( jobEntry.getxslFilename() ); if (jobEntry.getoutputFilename()!= null) wOutputFilename.setText( jobEntry.getoutputFilename() ); if (jobEntry.iffileexists>=0) { wIfFileExists.select(jobEntry.iffileexists ); } else { wIfFileExists.select(2); // NOTHING } wAddFileToResult.setSelection(jobEntry.isAddFileToResult()); } private void cancel() { jobEntry.setChanged(changed); jobEntry=null; dispose(); } private void ok() { jobEntry.setName(wName.getText()); jobEntry.setxmlFilename(wxmlFilename.getText()); jobEntry.setxslFilename(wxslFilename.getText()); jobEntry.setoutputFilename(wOutputFilename.getText()); jobEntry.iffileexists = wIfFileExists.getSelectionIndex(); jobEntry.setAddFileToResult(wAddFileToResult.getSelection()); dispose(); } public String toString() { return this.getClass().getName(); } public boolean evaluates() { return true; } public boolean isUnconditional() { return false; } }
package lombok.ast.ecj; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumMap; import java.util.EnumSet; import java.util.List; import java.util.Locale; import java.util.Map; import lombok.SneakyThrows; import lombok.ast.AnnotationDeclaration; import lombok.ast.AnnotationValueArray; import lombok.ast.AstVisitor; import lombok.ast.BinaryOperator; import lombok.ast.Comment; import lombok.ast.ForwardingAstVisitor; import lombok.ast.Identifier; import lombok.ast.JavadocContainer; import lombok.ast.KeywordModifier; import lombok.ast.Modifiers; import lombok.ast.Node; import lombok.ast.Position; import lombok.ast.RawListAccessor; import lombok.ast.UnaryOperator; import lombok.ast.VariableReference; import lombok.ast.grammar.SourceStructure; import org.eclipse.jdt.core.compiler.CategorizedProblem; import org.eclipse.jdt.core.compiler.CharOperation; import org.eclipse.jdt.internal.compiler.CompilationResult; import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy; import org.eclipse.jdt.internal.compiler.IProblemFactory; import org.eclipse.jdt.internal.compiler.ast.AND_AND_Expression; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.AbstractVariableDeclaration; import org.eclipse.jdt.internal.compiler.ast.AllocationExpression; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.AnnotationMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.ArrayAllocationExpression; import org.eclipse.jdt.internal.compiler.ast.ArrayInitializer; import org.eclipse.jdt.internal.compiler.ast.ArrayQualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.ArrayReference; import org.eclipse.jdt.internal.compiler.ast.ArrayTypeReference; import org.eclipse.jdt.internal.compiler.ast.AssertStatement; import org.eclipse.jdt.internal.compiler.ast.Assignment; import org.eclipse.jdt.internal.compiler.ast.BinaryExpression; import org.eclipse.jdt.internal.compiler.ast.Block; import org.eclipse.jdt.internal.compiler.ast.BreakStatement; import org.eclipse.jdt.internal.compiler.ast.CaseStatement; import org.eclipse.jdt.internal.compiler.ast.CastExpression; import org.eclipse.jdt.internal.compiler.ast.CharLiteral; import org.eclipse.jdt.internal.compiler.ast.ClassLiteralAccess; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.CompoundAssignment; import org.eclipse.jdt.internal.compiler.ast.ConditionalExpression; import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration; import org.eclipse.jdt.internal.compiler.ast.ContinueStatement; import org.eclipse.jdt.internal.compiler.ast.DoStatement; import org.eclipse.jdt.internal.compiler.ast.DoubleLiteral; import org.eclipse.jdt.internal.compiler.ast.EmptyStatement; import org.eclipse.jdt.internal.compiler.ast.EqualExpression; import org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.ExtendedStringLiteral; import org.eclipse.jdt.internal.compiler.ast.FalseLiteral; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.FieldReference; import org.eclipse.jdt.internal.compiler.ast.FloatLiteral; import org.eclipse.jdt.internal.compiler.ast.ForStatement; import org.eclipse.jdt.internal.compiler.ast.ForeachStatement; import org.eclipse.jdt.internal.compiler.ast.IfStatement; import org.eclipse.jdt.internal.compiler.ast.ImportReference; import org.eclipse.jdt.internal.compiler.ast.Initializer; import org.eclipse.jdt.internal.compiler.ast.InstanceOfExpression; import org.eclipse.jdt.internal.compiler.ast.IntLiteral; import org.eclipse.jdt.internal.compiler.ast.IntLiteralMinValue; import org.eclipse.jdt.internal.compiler.ast.Javadoc; import org.eclipse.jdt.internal.compiler.ast.LabeledStatement; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.LongLiteral; import org.eclipse.jdt.internal.compiler.ast.LongLiteralMinValue; import org.eclipse.jdt.internal.compiler.ast.MarkerAnnotation; import org.eclipse.jdt.internal.compiler.ast.MemberValuePair; import org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.NameReference; import org.eclipse.jdt.internal.compiler.ast.NormalAnnotation; import org.eclipse.jdt.internal.compiler.ast.NullLiteral; import org.eclipse.jdt.internal.compiler.ast.OR_OR_Expression; import org.eclipse.jdt.internal.compiler.ast.OperatorIds; import org.eclipse.jdt.internal.compiler.ast.ParameterizedQualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.ParameterizedSingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.PostfixExpression; import org.eclipse.jdt.internal.compiler.ast.PrefixExpression; import org.eclipse.jdt.internal.compiler.ast.QualifiedAllocationExpression; import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedSuperReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedThisReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.ReturnStatement; import org.eclipse.jdt.internal.compiler.ast.SingleMemberAnnotation; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.StringLiteral; import org.eclipse.jdt.internal.compiler.ast.StringLiteralConcatenation; import org.eclipse.jdt.internal.compiler.ast.SuperReference; import org.eclipse.jdt.internal.compiler.ast.SwitchStatement; import org.eclipse.jdt.internal.compiler.ast.SynchronizedStatement; import org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.eclipse.jdt.internal.compiler.ast.ThrowStatement; import org.eclipse.jdt.internal.compiler.ast.TrueLiteral; import org.eclipse.jdt.internal.compiler.ast.TryStatement; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeParameter; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.ast.UnaryExpression; import org.eclipse.jdt.internal.compiler.ast.WhileStatement; import org.eclipse.jdt.internal.compiler.ast.Wildcard; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.eclipse.jdt.internal.compiler.lookup.Binding; import org.eclipse.jdt.internal.compiler.lookup.ExtraCompilerModifiers; import org.eclipse.jdt.internal.compiler.parser.JavadocParser; import org.eclipse.jdt.internal.compiler.parser.Parser; import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; import org.eclipse.jdt.internal.compiler.problem.ProblemReporter; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import static lombok.ast.ConversionPositionInfo.getConversionPositionInfo; /** * Turns {@code lombok.ast} based ASTs into eclipse/ecj's {@code org.eclipse.jdt.internal.compiler.ast.ASTNode} model. */ public class EcjTreeBuilder { private static final int VISIBILITY_MASK = 7; static final char[] PACKAGE_INFO = "package-info".toCharArray(); private final Map<lombok.ast.Node, Collection<SourceStructure>> sourceStructures; private List<? extends ASTNode> result = null; private final String rawInput; private final ProblemReporter reporter; private final ProblemReporter silentProblemReporter; private final CompilationResult compilationResult; private final CompilerOptions options; private final EnumSet<BubblingFlags> bubblingFlags = EnumSet.noneOf(BubblingFlags.class); private final EnumSet<BubblingFlags> AUTO_REMOVABLE_BUBBLING_FLAGS = EnumSet.of(BubblingFlags.LOCALTYPE); private enum BubblingFlags { ASSERT, LOCALTYPE, ABSTRACT_METHOD } private enum VariableKind { UNSUPPORTED { AbstractVariableDeclaration create() { throw new UnsupportedOperationException(); } }, FIELD { AbstractVariableDeclaration create() { return new FieldDeclaration(); } }, LOCAL { AbstractVariableDeclaration create() { return new LocalDeclaration(null, 0, 0); } }, ARGUMENT { AbstractVariableDeclaration create() { return new Argument(null, 0, null, 0); } }; abstract AbstractVariableDeclaration create(); static VariableKind kind(lombok.ast.VariableDefinition node) { //TODO rewrite this whole thing. lombok.ast.Node parent = node.getParent(); if (parent instanceof lombok.ast.VariableDeclaration) { if (parent.getParent() instanceof lombok.ast.TypeBody || parent.getParent() instanceof lombok.ast.EnumTypeBody) { return FIELD; } else { return LOCAL; } } if (parent instanceof lombok.ast.For || parent instanceof lombok.ast.ForEach){ return LOCAL; } if (parent instanceof lombok.ast.Catch || parent instanceof lombok.ast.MethodDeclaration || parent instanceof lombok.ast.ConstructorDeclaration){ return ARGUMENT; } return UNSUPPORTED; } } private static final IProblemFactory SILENT_PROBLEM_FACTORY = new IProblemFactory() { @Override public String getLocalizedMessage(int problemId, int elaborationId, String[] messageArguments) { return null; } @Override public String getLocalizedMessage(int problemId, String[] messageArguments) { return null; } @Override public Locale getLocale() { return Locale.getDefault(); } @Override public CategorizedProblem createProblem(char[] originatingFileName, int problemId, String[] problemArguments, int elaborationId, String[] messageArguments, int severity, int startPosition, int endPosition, int lineNumber, int columnNumber) { return null; } @Override public CategorizedProblem createProblem(char[] originatingFileName, int problemId, String[] problemArguments, String[] messageArguments, int severity, int startPosition, int endPosition, int lineNumber, int columnNumber) { return null; } }; public EcjTreeBuilder(lombok.ast.grammar.Source source, CompilerOptions options) { this(source, createDefaultProblemReporter(options), createSilentProblemReporter(options), new CompilationResult(source.getName().toCharArray(), 0, 0, 0)); } public EcjTreeBuilder(String rawInput, String name, CompilerOptions options) { this(rawInput, createDefaultProblemReporter(options), createSilentProblemReporter(options), new CompilationResult(name.toCharArray(), 0, 0, 0)); } private static ProblemReporter createDefaultProblemReporter(CompilerOptions options) { return new ProblemReporter(new IErrorHandlingPolicy() { public boolean proceedOnErrors() { return true; } public boolean stopOnFirstError() { return false; } }, options, new DefaultProblemFactory(Locale.ENGLISH)); } private static ProblemReporter createSilentProblemReporter(CompilerOptions options) { return new ProblemReporter(new IErrorHandlingPolicy() { public boolean proceedOnErrors() { return true; } public boolean stopOnFirstError() { return false; } }, options, SILENT_PROBLEM_FACTORY); } public EcjTreeBuilder(lombok.ast.grammar.Source source, ProblemReporter reporter, ProblemReporter silentProblemReporter, CompilationResult compilationResult) { this.options = reporter.options; this.sourceStructures = source.getSourceStructures(); this.rawInput = source.getRawInput(); this.reporter = reporter; this.silentProblemReporter = silentProblemReporter; this.compilationResult = compilationResult; } public EcjTreeBuilder(String rawInput, ProblemReporter reporter, ProblemReporter silentProblemReporter, CompilationResult compilationResult) { this.options = reporter.options; this.sourceStructures = null; this.rawInput = rawInput; this.reporter = reporter; this.silentProblemReporter = silentProblemReporter; this.compilationResult = compilationResult; } private EcjTreeBuilder(EcjTreeBuilder parent) { this.reporter = parent.reporter; this.silentProblemReporter = parent.silentProblemReporter; this.options = parent.options; this.rawInput = parent.rawInput; this.compilationResult = parent.compilationResult; this.sourceStructures = parent.sourceStructures; } private EcjTreeBuilder create() { return new EcjTreeBuilder(this); } private Expression toExpression(lombok.ast.Node node) { return (Expression) toTree(node); } private Statement toStatement(lombok.ast.Node node) { return (Statement) toTree(node); } private ASTNode toTree(lombok.ast.Node node) { if (node == null) return null; EcjTreeBuilder newBuilder = create(); node.accept(newBuilder.visitor); bubblingFlags.addAll(newBuilder.bubblingFlags); try { return newBuilder.get(); } catch (RuntimeException e) { System.err.printf("Node '%s' (%s) did not produce any results\n", node, node.getClass().getSimpleName()); throw e; } } private char[] toName(lombok.ast.Identifier node) { if (node == null) { return null; } return node.astValue().toCharArray(); } private <T extends ASTNode> T[] toArray(Class<T> type, List<T> list) { if (list.isEmpty()) return null; @SuppressWarnings("unchecked") T[] emptyArray = (T[]) Array.newInstance(type, 0); return list.toArray(emptyArray); } private <T extends ASTNode> T[] toArray(Class<T> type, lombok.ast.Node node) { return toArray(type, toList(type, node)); } private <T extends ASTNode> T[] toArray(Class<T> type, lombok.ast.StrictListAccessor<?, ?> accessor) { List<T> list = Lists.newArrayList(); for (lombok.ast.Node node : accessor) { EcjTreeBuilder newBuilder = create(); node.accept(newBuilder.visitor); bubblingFlags.addAll(newBuilder.bubblingFlags); List<? extends ASTNode> values; values = newBuilder.getAll(); for (ASTNode value : values) { if (value != null && !type.isInstance(value)) { throw new ClassCastException(value.getClass().getName() + " cannot be cast to " + type.getName()); } list.add(type.cast(value)); } } return toArray(type, list); } private <T extends ASTNode> List<T> toList(Class<T> type, lombok.ast.Node node) { if (node == null) return Lists.newArrayList(); EcjTreeBuilder newBuilder = create(); node.accept(newBuilder.visitor); bubblingFlags.addAll(newBuilder.bubblingFlags); @SuppressWarnings("unchecked") List<T> all = (List<T>)newBuilder.getAll(); return Lists.newArrayList(all); } public void visit(lombok.ast.Node node) { node.accept(visitor); } public ASTNode get() { if (result.isEmpty()) { return null; } if (result.size() == 1) { return result.get(0); } throw new RuntimeException("Expected only one result but got " + result.size()); } public List<? extends ASTNode> getAll() { return result; } private static <T extends ASTNode> T posParen(T in, lombok.ast.Node node) { if (in == null) return null; if (node instanceof lombok.ast.Expression) { List<Position> parensPositions = ((lombok.ast.Expression)node).astParensPositions(); if (!parensPositions.isEmpty()) { in.sourceStart = parensPositions.get(parensPositions.size() - 1).getStart(); in.sourceEnd = parensPositions.get(parensPositions.size() - 1).getEnd() - 1; } } return in; } private static boolean isExplicitlyAbstract(Modifiers m) { for (KeywordModifier keyword : m.astKeywords()) { if ("abstract".equals(keyword.astName())) return true; } return false; } private static final EnumMap<UnaryOperator, Integer> UNARY_OPERATORS = Maps.newEnumMap(UnaryOperator.class); static { UNARY_OPERATORS.put(UnaryOperator.BINARY_NOT, OperatorIds.TWIDDLE); UNARY_OPERATORS.put(UnaryOperator.LOGICAL_NOT, OperatorIds.NOT); UNARY_OPERATORS.put(UnaryOperator.UNARY_PLUS, OperatorIds.PLUS); UNARY_OPERATORS.put(UnaryOperator.PREFIX_INCREMENT, OperatorIds.PLUS); UNARY_OPERATORS.put(UnaryOperator.UNARY_MINUS, OperatorIds.MINUS); UNARY_OPERATORS.put(UnaryOperator.PREFIX_DECREMENT, OperatorIds.MINUS); UNARY_OPERATORS.put(UnaryOperator.POSTFIX_INCREMENT, OperatorIds.PLUS); UNARY_OPERATORS.put(UnaryOperator.POSTFIX_DECREMENT, OperatorIds.MINUS); } private static final EnumMap<BinaryOperator, Integer> BINARY_OPERATORS = Maps.newEnumMap(BinaryOperator.class); static { BINARY_OPERATORS.put(BinaryOperator.PLUS_ASSIGN, OperatorIds.PLUS); BINARY_OPERATORS.put(BinaryOperator.MINUS_ASSIGN, OperatorIds.MINUS); BINARY_OPERATORS.put(BinaryOperator.MULTIPLY_ASSIGN, OperatorIds.MULTIPLY); BINARY_OPERATORS.put(BinaryOperator.DIVIDE_ASSIGN, OperatorIds.DIVIDE); BINARY_OPERATORS.put(BinaryOperator.REMAINDER_ASSIGN, OperatorIds.REMAINDER); BINARY_OPERATORS.put(BinaryOperator.AND_ASSIGN, OperatorIds.AND); BINARY_OPERATORS.put(BinaryOperator.XOR_ASSIGN, OperatorIds.XOR); BINARY_OPERATORS.put(BinaryOperator.OR_ASSIGN, OperatorIds.OR); BINARY_OPERATORS.put(BinaryOperator.SHIFT_LEFT_ASSIGN, OperatorIds.LEFT_SHIFT); BINARY_OPERATORS.put(BinaryOperator.SHIFT_RIGHT_ASSIGN, OperatorIds.RIGHT_SHIFT); BINARY_OPERATORS.put(BinaryOperator.BITWISE_SHIFT_RIGHT_ASSIGN, OperatorIds.UNSIGNED_RIGHT_SHIFT); BINARY_OPERATORS.put(BinaryOperator.LOGICAL_OR, OperatorIds.OR_OR); BINARY_OPERATORS.put(BinaryOperator.LOGICAL_AND, OperatorIds.AND_AND); BINARY_OPERATORS.put(BinaryOperator.BITWISE_OR, OperatorIds.OR); BINARY_OPERATORS.put(BinaryOperator.BITWISE_XOR, OperatorIds.XOR); BINARY_OPERATORS.put(BinaryOperator.BITWISE_AND, OperatorIds.AND); BINARY_OPERATORS.put(BinaryOperator.EQUALS, OperatorIds.EQUAL_EQUAL); BINARY_OPERATORS.put(BinaryOperator.NOT_EQUALS, OperatorIds.NOT_EQUAL); BINARY_OPERATORS.put(BinaryOperator.GREATER, OperatorIds.GREATER); BINARY_OPERATORS.put(BinaryOperator.GREATER_OR_EQUAL, OperatorIds.GREATER_EQUAL); BINARY_OPERATORS.put(BinaryOperator.LESS, OperatorIds.LESS); BINARY_OPERATORS.put(BinaryOperator.LESS_OR_EQUAL, OperatorIds.LESS_EQUAL); BINARY_OPERATORS.put(BinaryOperator.SHIFT_LEFT, OperatorIds.LEFT_SHIFT); BINARY_OPERATORS.put(BinaryOperator.SHIFT_RIGHT, OperatorIds.RIGHT_SHIFT); BINARY_OPERATORS.put(BinaryOperator.BITWISE_SHIFT_RIGHT, OperatorIds.UNSIGNED_RIGHT_SHIFT); BINARY_OPERATORS.put(BinaryOperator.PLUS, OperatorIds.PLUS); BINARY_OPERATORS.put(BinaryOperator.MINUS, OperatorIds.MINUS); BINARY_OPERATORS.put(BinaryOperator.MULTIPLY, OperatorIds.MULTIPLY); BINARY_OPERATORS.put(BinaryOperator.DIVIDE, OperatorIds.DIVIDE); BINARY_OPERATORS.put(BinaryOperator.REMAINDER, OperatorIds.REMAINDER); } private final AstVisitor visitor = new ForwardingAstVisitor() { @Override public boolean visitCompilationUnit(lombok.ast.CompilationUnit node) { int sourceLength = rawInput == null ? 0 : rawInput.length(); CompilationUnitDeclaration cud = new CompilationUnitDeclaration(reporter, compilationResult, sourceLength); cud.bits |= ASTNode.HasAllMethodBodies; cud.currentPackage = (ImportReference) toTree(node.astPackageDeclaration()); cud.imports = toArray(ImportReference.class, node.astImportDeclarations()); cud.types = toArray(TypeDeclaration.class, node.astTypeDeclarations()); if (CharOperation.equals(PACKAGE_INFO, cud.getMainTypeName())) { TypeDeclaration[] newTypes; if (cud.types == null) { newTypes = new TypeDeclaration[1]; } else { newTypes = new TypeDeclaration[cud.types.length + 1]; System.arraycopy(cud.types, 0, newTypes, 1, cud.types.length); } TypeDeclaration decl = new TypeDeclaration(compilationResult); decl.name = PACKAGE_INFO.clone(); decl.modifiers = ClassFileConstants.AccDefault | ClassFileConstants.AccInterface; newTypes[0] = decl; cud.types = newTypes; lombok.ast.PackageDeclaration pkgDeclaration = node.astPackageDeclaration(); Comment javadoc = pkgDeclaration == null ? null : pkgDeclaration.astJavadoc(); if (javadoc != null) { boolean markDep = javadoc.isMarkedDeprecated(); cud.javadoc = (Javadoc) toTree(javadoc); if (markDep) decl.modifiers |= ClassFileConstants.AccDeprecated; decl.javadoc = cud.javadoc; } } bubblingFlags.remove(BubblingFlags.ASSERT); bubblingFlags.removeAll(AUTO_REMOVABLE_BUBBLING_FLAGS); if (!bubblingFlags.isEmpty()) { throw new RuntimeException("Unhandled bubbling flags left: " + bubblingFlags); } return set(node, cud); } private boolean set(lombok.ast.Node node, ASTNode value) { if (result != null) throw new IllegalStateException("result is already set"); if (node instanceof lombok.ast.Expression) { int parens = ((lombok.ast.Expression)node).getIntendedParens(); value.bits |= (parens << ASTNode.ParenthesizedSHIFT) & ASTNode.ParenthesizedMASK; posParen(value, node); } if (value instanceof NameReference) { updateRestrictionFlags(node, (NameReference)value); } List<ASTNode> result = Lists.newArrayList(); if (value != null) result.add(value); EcjTreeBuilder.this.result = result; return true; } private boolean set(lombok.ast.Node node, List<? extends ASTNode> values) { if (values.isEmpty()) System.err.printf("Node '%s' (%s) did not produce any results\n", node, node.getClass().getSimpleName()); if (result != null) throw new IllegalStateException("result is already set"); result = values; return true; } private int calculateExplicitDeclarations(Iterable<lombok.ast.Statement> statements) { int explicitDeclarations = 0; if (statements != null) { for (lombok.ast.Statement s : statements) { if (s instanceof lombok.ast.VariableDeclaration) explicitDeclarations++; if (s instanceof lombok.ast.ClassDeclaration) explicitDeclarations++; } } return explicitDeclarations; } @Override public boolean visitPackageDeclaration(lombok.ast.PackageDeclaration node) { long[] pos = partsToPosArray(node.rawParts()); ImportReference pkg = new ImportReference(chain(node.astParts()), pos, true, ClassFileConstants.AccDefault); pkg.annotations = toArray(Annotation.class, node.astAnnotations()); pkg.declarationSourceStart = jstart(node); pkg.declarationSourceEnd = pkg.declarationEnd = end(node); return set(node, pkg); } //TODO Create a test file with a whole bunch of comments. Possibly in a separate non-idempotency subdir, as printing comments idempotently is a rough nut to crack. @Override public boolean visitImportDeclaration(lombok.ast.ImportDeclaration node) { int staticFlag = node.astStaticImport() ? ClassFileConstants.AccStatic : ClassFileConstants.AccDefault; long[] pos = partsToPosArray(node.rawParts()); ImportReference imp = new ImportReference(chain(node.astParts()), pos, node.astStarImport(), staticFlag); imp.declarationSourceStart = start(node); imp.declarationSourceEnd = imp.declarationEnd = end(node); return set(node, imp); } @Override public boolean visitClassDeclaration(lombok.ast.ClassDeclaration node) { TypeDeclaration decl = createTypeBody(node.astBody().astMembers(), node, true, 0); decl.annotations = toArray(Annotation.class, node.astModifiers().astAnnotations()); decl.superclass = (TypeReference) toTree(node.astExtending()); decl.superInterfaces = toArray(TypeReference.class, node.astImplementing()); markTypeReferenceIsSuperType(decl); decl.typeParameters = toArray(TypeParameter.class, node.astTypeVariables()); decl.name = toName(node.astName()); updateTypeBits(node.getParent(), decl, false); setupJavadoc(decl, node); //TODO test inner types. Give em everything - (abstract) methods, initializers, static initializers, MULTIPLE initializers. return set(node, decl); } private void updateTypeBits(lombok.ast.Node parent, TypeDeclaration decl, boolean isEnum) { if (parent == null) { return; } if (parent instanceof lombok.ast.CompilationUnit) { char[] mainTypeName = new CompilationUnitDeclaration(reporter, compilationResult, 0).getMainTypeName(); if (!CharOperation.equals(decl.name, mainTypeName)) { decl.bits |= ASTNode.IsSecondaryType; } return; } if (parent instanceof lombok.ast.TypeBody || parent instanceof lombok.ast.EnumTypeBody) { decl.bits |= ASTNode.IsMemberType; return; } //TODO test if a type declared in an enum constant is possible decl.bits |= ASTNode.IsLocalType; bubblingFlags.add(BubblingFlags.LOCALTYPE); } private void markTypeReferenceIsSuperType(TypeDeclaration decl) { if (decl.superclass != null) { decl.superclass.bits |= ASTNode.IsSuperType; } if (decl.superInterfaces != null) { for (TypeReference t : decl.superInterfaces) { t.bits |= ASTNode.IsSuperType; } } } @Override public boolean visitInterfaceDeclaration(lombok.ast.InterfaceDeclaration node) { TypeDeclaration decl = createTypeBody(node.astBody().astMembers(), node, false, ClassFileConstants.AccInterface); decl.annotations = toArray(Annotation.class, node.astModifiers().astAnnotations()); decl.superInterfaces = toArray(TypeReference.class, node.astExtending()); markTypeReferenceIsSuperType(decl); decl.typeParameters = toArray(TypeParameter.class, node.astTypeVariables()); decl.name = toName(node.astName()); updateTypeBits(node.getParent(), decl, false); setupJavadoc(decl, node); return set(node, decl); } @Override public boolean visitEnumDeclaration(lombok.ast.EnumDeclaration node) { FieldDeclaration[] fields = null; if (node.astBody() != null) { fields = toArray(FieldDeclaration.class, node.astBody().astConstants()); } TypeDeclaration decl = createTypeBody(node.astBody().astMembers(), node, true, ClassFileConstants.AccEnum, fields); decl.annotations = toArray(Annotation.class, node.astModifiers().astAnnotations()); decl.superInterfaces = toArray(TypeReference.class, node.astImplementing()); markTypeReferenceIsSuperType(decl); decl.name = toName(node.astName()); updateTypeBits(node.getParent(), decl, true); setupJavadoc(decl, node); return set(node, decl); } @Override public boolean visitEnumConstant(lombok.ast.EnumConstant node) { //TODO check where the javadoc and annotations go: the field or the type FieldDeclaration decl = new FieldDeclaration(); decl.annotations = toArray(Annotation.class, node.astAnnotations()); decl.name = toName(node.astName()); decl.sourceStart = start(node.astName()); decl.sourceEnd = end(node.astName()); decl.declarationSourceStart = decl.modifiersSourceStart = jstart(node); decl.declarationSourceEnd = decl.declarationEnd = end(node); Position ecjDeclarationSourcePos = getConversionPositionInfo(node, "declarationSource"); if (ecjDeclarationSourcePos != null) decl.declarationSourceEnd = ecjDeclarationSourcePos.getEnd() - 1; AllocationExpression init; if (node.astBody() == null) { init = new AllocationExpression(); init.enumConstant = decl; } else { TypeDeclaration type = createTypeBody(node.astBody().astMembers(), null, false, 0); type.sourceStart = type.sourceEnd = start(node.astBody()); type.bodyEnd type.declarationSourceStart = type.sourceStart; type.declarationSourceEnd = end(node); type.name = CharOperation.NO_CHAR; type.bits &= ~ASTNode.IsMemberType; decl.bits |= ASTNode.HasLocalType; type.bits |= ASTNode.IsLocalType | ASTNode.IsAnonymousType; init = new QualifiedAllocationExpression(type); init.enumConstant = decl; } init.arguments = toArray(Expression.class, node.astArguments()); decl.initialization = init; if (bubblingFlags.remove(BubblingFlags.LOCALTYPE)) { decl.bits |= ASTNode.HasLocalType; } setupJavadoc(decl, node); return set(node, decl); } @Override public boolean visitAnnotationDeclaration(lombok.ast.AnnotationDeclaration node) { TypeDeclaration decl = createTypeBody(node.astBody().astMembers(), node, false, ClassFileConstants.AccAnnotation | ClassFileConstants.AccInterface); decl.annotations = toArray(Annotation.class, node.astModifiers().astAnnotations()); decl.name = toName(node.astName()); updateTypeBits(node.getParent(), decl, false); setupJavadoc(decl, node); return set(node, decl); } private void setupJavadoc(ASTNode node, lombok.ast.JavadocContainer container) { if (container != null && container.rawJavadoc() instanceof lombok.ast.Comment) { lombok.ast.Comment javadoc = (Comment) container.rawJavadoc(); boolean markDep = javadoc.isMarkedDeprecated(); if (node instanceof AbstractMethodDeclaration) { AbstractMethodDeclaration decl = (AbstractMethodDeclaration) node; decl.javadoc = (Javadoc) toTree(javadoc); if (markDep) decl.modifiers |= ClassFileConstants.AccDeprecated; } if (node instanceof FieldDeclaration) { FieldDeclaration decl = (FieldDeclaration) node; decl.javadoc = (Javadoc) toTree(javadoc); if (markDep) decl.modifiers |= ClassFileConstants.AccDeprecated; } if (node instanceof TypeDeclaration) { TypeDeclaration decl = (TypeDeclaration) node; decl.javadoc = (Javadoc) toTree(javadoc); if (markDep) decl.modifiers |= ClassFileConstants.AccDeprecated; } } } @Override public boolean visitConstructorDeclaration(lombok.ast.ConstructorDeclaration node) { ConstructorDeclaration decl = new ConstructorDeclaration(compilationResult); decl.bodyStart = start(node.rawBody()) + 1; decl.bodyEnd = end(node.rawBody()) - 1; decl.declarationSourceStart = jstart(node); decl.declarationSourceEnd = end(node); decl.sourceStart = start(node.astTypeName()); /* set sourceEnd */ { Position ecjPos = getConversionPositionInfo(node, "signature"); decl.sourceEnd = ecjPos == null ? posOfStructure(node, ")", Integer.MAX_VALUE, false) - 1 : ecjPos.getEnd() - 1; if (!node.rawThrownTypeReferences().isEmpty()) { decl.sourceEnd = end(node.rawThrownTypeReferences().last()); } } decl.annotations = toArray(Annotation.class, node.astModifiers().astAnnotations()); decl.modifiers = toModifiers(node.astModifiers()); decl.typeParameters = toArray(TypeParameter.class, node.astTypeVariables()); decl.arguments = toArray(Argument.class, node.astParameters()); decl.thrownExceptions = toArray(TypeReference.class, node.astThrownTypeReferences()); decl.statements = toArray(Statement.class, node.astBody().astContents()); decl.selector = toName(node.astTypeName()); setupJavadoc(decl, node); if (decl.statements == null || decl.statements.length == 0 || !(decl.statements[0] instanceof ExplicitConstructorCall)) { decl.constructorCall = new ExplicitConstructorCall(ExplicitConstructorCall.ImplicitSuper); decl.constructorCall.sourceStart = decl.sourceStart; decl.constructorCall.sourceEnd = decl.sourceEnd; } else { //TODO check how super() and this() work decl.constructorCall = (ExplicitConstructorCall)decl.statements[0]; if (decl.statements.length > 1) { Statement[] newStatements = new Statement[decl.statements.length - 1]; System.arraycopy(decl.statements, 1, newStatements, 0, newStatements.length); decl.statements = newStatements; } else { decl.statements = null; } } if (bubblingFlags.remove(BubblingFlags.LOCALTYPE)) { decl.bits |= ASTNode.HasLocalType; } // Unlike other method(-like) constructs, while ConstructorDeclaration has a // explicitDeclarations field, its kept at 0, so we don't need to calculate that value here. if (isUndocumented(node.astBody())) decl.bits |= ASTNode.UndocumentedEmptyBlock; setupJavadoc(decl, node); return set(node, decl); } @Override public boolean visitMethodDeclaration(lombok.ast.MethodDeclaration node) { MethodDeclaration decl = new MethodDeclaration(compilationResult); decl.declarationSourceStart = jstart(node); decl.declarationSourceEnd = end(node); decl.sourceStart = start(node.astMethodName()); boolean setOriginalPosOnType = false; /* set sourceEnd */ { Position ecjPos = getConversionPositionInfo(node, "signature"); decl.sourceEnd = ecjPos == null ? posOfStructure(node, ")", Integer.MAX_VALUE, false) - 1: ecjPos.getEnd() - 1; int postDims = posOfStructure(node, "]", Integer.MAX_VALUE, false) - 1; if (postDims > decl.sourceEnd) { decl.sourceEnd = postDims; setOriginalPosOnType = true; } if (!node.rawThrownTypeReferences().isEmpty()) { decl.sourceEnd = end(node.rawThrownTypeReferences().last()); } } if (node.rawBody() == null) { decl.bodyStart = decl.sourceEnd + 1; decl.bodyEnd = end(node) - 1; } else { decl.bodyStart = start(node.rawBody()) + 1; decl.bodyEnd = end(node.rawBody()) - 1; } decl.annotations = toArray(Annotation.class, node.astModifiers().astAnnotations()); decl.modifiers = toModifiers(node.astModifiers()); decl.returnType = (TypeReference) toTree(node.astReturnTypeReference()); if (setOriginalPosOnType) { if (decl.returnType instanceof ArrayTypeReference) { ((ArrayTypeReference)decl.returnType).originalSourceEnd = end(node.rawReturnTypeReference()); } } decl.typeParameters = toArray(TypeParameter.class, node.astTypeVariables()); decl.arguments = toArray(Argument.class, node.astParameters()); decl.selector = toName(node.astMethodName()); decl.thrownExceptions = toArray(TypeReference.class, node.astThrownTypeReferences()); if (node.astBody() == null) { decl.modifiers |= ExtraCompilerModifiers.AccSemicolonBody; } else { decl.statements = toArray(Statement.class, node.astBody().astContents()); decl.explicitDeclarations = calculateExplicitDeclarations(node.astBody().astContents()); } if (bubblingFlags.remove(BubblingFlags.LOCALTYPE)) { decl.bits |= ASTNode.HasLocalType; } if (isExplicitlyAbstract(node.astModifiers())) { bubblingFlags.add(BubblingFlags.ABSTRACT_METHOD); } if (isUndocumented(node.astBody())) decl.bits |= ASTNode.UndocumentedEmptyBlock; setupJavadoc(decl, node); return set(node, decl); } @Override public boolean visitAnnotationMethodDeclaration(lombok.ast.AnnotationMethodDeclaration node) { AnnotationMethodDeclaration decl = new AnnotationMethodDeclaration(compilationResult); decl.modifiers = toModifiers(node.astModifiers()) + ExtraCompilerModifiers.AccSemicolonBody; decl.declarationSourceStart = jstart(node); decl.declarationSourceEnd = end(node); decl.sourceStart = start(node.astMethodName()); boolean setOriginalPosOnType = false; /* set sourceEnd */ { Position ecjSigPos = getConversionPositionInfo(node, "signature"); Position ecjExtDimPos = getConversionPositionInfo(node, "extendedDimensions"); if (ecjSigPos != null && ecjExtDimPos != null) { decl.sourceEnd = ecjSigPos.getEnd() - 1; decl.extendedDimensions = ecjExtDimPos.getStart(); } else { decl.sourceEnd = posOfStructure(node, ")", Integer.MAX_VALUE, false) - 1; int postDims = posOfStructure(node, "]", Integer.MAX_VALUE, false) - 1; decl.extendedDimensions = countStructure(node, "]"); if (postDims > decl.sourceEnd) { decl.sourceEnd = postDims; setOriginalPosOnType = true; } } } decl.bodyStart = end(node); decl.bodyEnd = end(node); if (node.astDefaultValue() != null) { decl.modifiers |= ClassFileConstants.AccAnnotationDefault; } decl.annotations = toArray(Annotation.class, node.astModifiers().astAnnotations()); decl.defaultValue = toExpression(node.astDefaultValue()); decl.selector = toName(node.astMethodName()); decl.returnType = (TypeReference) toTree(node.astReturnTypeReference()); if (setOriginalPosOnType) { if (decl.returnType instanceof ArrayTypeReference) { ((ArrayTypeReference)decl.returnType).originalSourceEnd = end(node.rawReturnTypeReference()); } } if (isExplicitlyAbstract(node.astModifiers())) { bubblingFlags.add(BubblingFlags.ABSTRACT_METHOD); } setupJavadoc(decl, node); return set(node, decl); } private TypeDeclaration createTypeBody(lombok.ast.StrictListAccessor<lombok.ast.TypeMember, ?> members, lombok.ast.TypeDeclaration type, boolean canHaveConstructor, int extraModifiers, FieldDeclaration... initialFields) { TypeDeclaration decl = new TypeDeclaration(compilationResult); decl.modifiers = (type == null ? 0 : toModifiers(type.astModifiers())) | extraModifiers; if (members.isEmpty() && isUndocumented(members.owner())) decl.bits |= ASTNode.UndocumentedEmptyBlock; if (type != null) { decl.sourceStart = start(type.astName()); decl.sourceEnd = end(type.astName()); decl.declarationSourceStart = jstart(type); decl.declarationSourceEnd = end(type); if (!(type instanceof AnnotationDeclaration) || !type.astModifiers().isEmpty() || type.rawJavadoc() != null) { decl.modifiersSourceStart = jstart(type.astModifiers()); } else { decl.modifiersSourceStart = -1; } } decl.bodyStart = start(members.owner()) + 1; decl.bodyEnd = end(members.owner()); boolean hasExplicitConstructor = false; List<AbstractMethodDeclaration> methods = Lists.newArrayList(); List<FieldDeclaration> fields = Lists.newArrayList(); List<TypeDeclaration> types = Lists.newArrayList(); if (initialFields != null) fields.addAll(Arrays.asList(initialFields)); for (lombok.ast.TypeMember member : members) { if (member instanceof lombok.ast.ConstructorDeclaration) { hasExplicitConstructor = true; AbstractMethodDeclaration method =(AbstractMethodDeclaration)toTree(member); methods.add(method); } else if (member instanceof lombok.ast.MethodDeclaration || member instanceof lombok.ast.AnnotationMethodDeclaration) { AbstractMethodDeclaration method =(AbstractMethodDeclaration)toTree(member); methods.add(method); } else if (member instanceof lombok.ast.VariableDeclaration) { for (FieldDeclaration field : toList(FieldDeclaration.class, member)) { fields.add(field); } } else if (member instanceof lombok.ast.StaticInitializer) { fields.add((FieldDeclaration) toTree(member)); } else if (member instanceof lombok.ast.InstanceInitializer) { fields.add((FieldDeclaration) toTree(member)); } else if (member instanceof lombok.ast.TypeDeclaration) { TypeDeclaration innerType = (TypeDeclaration) toTree(member); //TODO check if you need to do this too for static inners. if (innerType != null) { innerType.enclosingType = decl; types.add(innerType); } } else { throw new RuntimeException("Unhandled member type " + member.getClass().getSimpleName()); } } if (!hasExplicitConstructor && canHaveConstructor) { ConstructorDeclaration defaultConstructor = new ConstructorDeclaration(compilationResult); defaultConstructor.bits |= ASTNode.IsDefaultConstructor; defaultConstructor.constructorCall = new ExplicitConstructorCall(ExplicitConstructorCall.ImplicitSuper); defaultConstructor.modifiers = decl.modifiers & VISIBILITY_MASK; defaultConstructor.selector = toName(type.astName()); defaultConstructor.sourceStart = defaultConstructor.declarationSourceStart = defaultConstructor.constructorCall.sourceStart = start(type.astName()); defaultConstructor.sourceEnd = defaultConstructor.bodyEnd = defaultConstructor.constructorCall.sourceEnd = defaultConstructor.declarationSourceEnd = end(type.astName()); methods.add(0, defaultConstructor); } decl.memberTypes = toArray(TypeDeclaration.class, types); decl.methods = toArray(AbstractMethodDeclaration.class, methods); decl.fields = toArray(FieldDeclaration.class, fields); if (bubblingFlags.contains(BubblingFlags.ASSERT)) { decl.bits |= ASTNode.ContainsAssertion; } if (bubblingFlags.remove(BubblingFlags.ABSTRACT_METHOD)) { decl.bits |= ASTNode.HasAbstractMethods; } decl.addClinit(); return decl; } @Override public boolean visitExpressionStatement(lombok.ast.ExpressionStatement node) { Statement statement = toStatement(node.astExpression()); try { Field f = statement.getClass().getField("statementEnd"); f.set(statement, end(node)); } catch (Exception ignore) { // Not all these classes may have a statementEnd. } return set(node, statement); } @Override public boolean visitConstructorInvocation(lombok.ast.ConstructorInvocation node) { AllocationExpression inv; if (node.astQualifier() != null || node.astAnonymousClassBody() != null) { if (node.astAnonymousClassBody() != null) { TypeDeclaration decl = createTypeBody(node.astAnonymousClassBody().astMembers(), null, false, 0); Position ecjSigPos = getConversionPositionInfo(node, "signature"); decl.sourceStart = ecjSigPos == null ? start(node.rawTypeReference()) : ecjSigPos.getStart(); decl.sourceEnd = ecjSigPos == null ? posOfStructure(node, ")", Integer.MAX_VALUE, false) - 1 : ecjSigPos.getEnd() - 1; decl.declarationSourceStart = decl.sourceStart; decl.declarationSourceEnd = end(node); decl.name = CharOperation.NO_CHAR; decl.bits |= ASTNode.IsAnonymousType | ASTNode.IsLocalType; bubblingFlags.add(BubblingFlags.LOCALTYPE); inv = new QualifiedAllocationExpression(decl); } else { inv = new QualifiedAllocationExpression(); } if (node.astQualifier() != null) { ((QualifiedAllocationExpression)inv).enclosingInstance = toExpression(node.astQualifier()); } } else { inv = new AllocationExpression(); } if (!node.astConstructorTypeArguments().isEmpty()) { inv.typeArguments = toArray(TypeReference.class, node.astConstructorTypeArguments()); } inv.type = (TypeReference) toTree(node.astTypeReference()); inv.arguments = toArray(Expression.class, node.astArguments()); inv.sourceStart = start(node); inv.sourceEnd = end(node); return set(node, inv); } @Override public boolean visitAlternateConstructorInvocation(lombok.ast.AlternateConstructorInvocation node) { ExplicitConstructorCall inv = new ExplicitConstructorCall(ExplicitConstructorCall.This); inv.sourceStart = posOfStructure(node, "this", 0, true); inv.sourceEnd = end(node); // inv.modifiers = decl.modifiers & VISIBILITY_MASK; if (!node.astConstructorTypeArguments().isEmpty()) { inv.typeArguments = toArray(TypeReference.class, node.astConstructorTypeArguments()); Position ecjTypeArgsPos = getConversionPositionInfo(node, "typeArguments"); inv.typeArgumentsSourceStart = ecjTypeArgsPos == null ? posOfStructure(node, "<", 0, true) : ecjTypeArgsPos.getStart(); } inv.arguments = toArray(Expression.class, node.astArguments()); return set(node, inv); } @Override public boolean visitSuperConstructorInvocation(lombok.ast.SuperConstructorInvocation node) { ExplicitConstructorCall inv = new ExplicitConstructorCall(ExplicitConstructorCall.Super); inv.sourceStart = start(node); inv.sourceEnd = end(node); // inv.modifiers = decl.modifiers & VISIBILITY_MASK; if (!node.astConstructorTypeArguments().isEmpty()) { inv.typeArguments = toArray(TypeReference.class, node.astConstructorTypeArguments()); Position ecjTypeArgsPos = getConversionPositionInfo(node, "typeArguments"); inv.typeArgumentsSourceStart = ecjTypeArgsPos == null ? posOfStructure(node, "<", 0, true) : ecjTypeArgsPos.getStart(); } inv.arguments = toArray(Expression.class, node.astArguments()); inv.qualification = toExpression(node.astQualifier()); return set(node, inv); } @Override public boolean visitMethodInvocation(lombok.ast.MethodInvocation node) { MessageSend inv = new MessageSend(); inv.sourceStart = start(node); inv.sourceEnd = end(node); inv.nameSourcePosition = pos(node.astName()); inv.arguments = toArray(Expression.class, node.astArguments()); inv.receiver = toExpression(node.astOperand()); if (inv.receiver instanceof NameReference) { inv.receiver.bits |= Binding.TYPE; } //TODO do we have an implicit this style call somewhere in our test sources? if (inv.receiver == null) { inv.receiver = new ThisReference(0, 0); inv.receiver.bits |= ASTNode.IsImplicitThis; } if (!node.astMethodTypeArguments().isEmpty()) inv.typeArguments = toArray(TypeReference.class, node.astMethodTypeArguments()); inv.selector = toName(node.astName()); return set(node, inv); } @Override public boolean visitSuper(lombok.ast.Super node) { if (node.astQualifier() == null) { return set(node, new SuperReference(start(node), end(node))); } return set(node, new QualifiedSuperReference((TypeReference) toTree(node.astQualifier()), start(node), end(node))); } @Override public boolean visitUnaryExpression(lombok.ast.UnaryExpression node) { if (node.astOperator() == UnaryOperator.UNARY_MINUS) { if (node.astOperand() instanceof lombok.ast.IntegralLiteral && node.astOperand().getParens() == 0) { lombok.ast.IntegralLiteral lit = (lombok.ast.IntegralLiteral)node.astOperand(); if (!lit.astMarkedAsLong() && lit.astIntValue() == Integer.MIN_VALUE) { IntLiteralMinValue minLiteral = new IntLiteralMinValue(); minLiteral.sourceStart = start(node); minLiteral.sourceEnd = end(node); return set(node, minLiteral); } if (lit.astMarkedAsLong() && lit.astLongValue() == Long.MIN_VALUE) { LongLiteralMinValue minLiteral = new LongLiteralMinValue(); minLiteral.sourceStart = start(node); minLiteral.sourceEnd = end(node); return set(node, minLiteral); } } } Expression operand = toExpression(node.astOperand()); int ecjOperator = UNARY_OPERATORS.get(node.astOperator()); switch (node.astOperator()) { case PREFIX_INCREMENT: case PREFIX_DECREMENT: return set(node, new PrefixExpression(operand, IntLiteral.One, ecjOperator, start(node))); case POSTFIX_INCREMENT: case POSTFIX_DECREMENT: return set(node, new PostfixExpression(operand, IntLiteral.One, ecjOperator, end(node))); default: UnaryExpression expr = new UnaryExpression(toExpression(node.astOperand()), ecjOperator); expr.sourceStart = start(node); expr.sourceEnd = end(node); return set(node, expr); } } @Override public boolean visitBinaryExpression(lombok.ast.BinaryExpression node) { Expression lhs = toExpression(node.astLeft()); Expression rhs = toExpression(node.astRight()); if (node.astOperator() == BinaryOperator.ASSIGN) { return set(node, posParen(new Assignment(lhs, rhs, end(node)), node)); } //TODO add a test with 1 + 2 + 3 + "" + 4 + 5 + 6 + "foo"; as well as 5 + 2 + 3 - 5 - 8 -7 - 8 * 10 + 20; int ecjOperator = BINARY_OPERATORS.get(node.astOperator()); if (node.astOperator().isAssignment()) { return set(node, posParen(new CompoundAssignment(lhs, rhs, ecjOperator, end(node)), node)); } else if (node.astOperator() == BinaryOperator.EQUALS || node.astOperator() == BinaryOperator.NOT_EQUALS) { return set(node, posParen(new EqualExpression(lhs, rhs, ecjOperator), node)); } else if (node.astOperator() == BinaryOperator.LOGICAL_AND) { return set(node, posParen(new AND_AND_Expression(lhs, rhs, ecjOperator), node)); } else if (node.astOperator() == BinaryOperator.LOGICAL_OR) { return set(node, posParen(new OR_OR_Expression(lhs, rhs, ecjOperator), node)); } else if (node.astOperator() == BinaryOperator.PLUS && node.astLeft().getParens() == 0) { Expression stringConcatExpr = posParen(tryStringConcat(lhs, rhs), node); if (stringConcatExpr != null) return set(node, stringConcatExpr); } return set(node, posParen(new BinaryExpression(lhs, rhs, ecjOperator), node)); } private Expression tryStringConcat(Expression lhs, Expression rhs) { if (options.parseLiteralExpressionsAsConstants) { if (lhs instanceof ExtendedStringLiteral) { if (rhs instanceof CharLiteral) { return ((ExtendedStringLiteral)lhs).extendWith((CharLiteral)rhs); } else if (rhs instanceof StringLiteral) { return ((ExtendedStringLiteral)lhs).extendWith((StringLiteral)rhs); } } else if (lhs instanceof StringLiteral) { if (rhs instanceof CharLiteral) { return new ExtendedStringLiteral((StringLiteral)lhs, (CharLiteral)rhs); } else if (rhs instanceof StringLiteral) { return new ExtendedStringLiteral((StringLiteral)lhs, (StringLiteral)rhs); } } } else { if (lhs instanceof StringLiteralConcatenation) { if (rhs instanceof StringLiteral) { return ((StringLiteralConcatenation)lhs).extendsWith((StringLiteral)rhs); } } else if (lhs instanceof StringLiteral) { if (rhs instanceof StringLiteral) { return new StringLiteralConcatenation((StringLiteral) lhs, (StringLiteral) rhs); } } } return null; } @Override public boolean visitCast(lombok.ast.Cast node) { Expression typeRef = toExpression(node.astTypeReference()); Expression operand = toExpression(node.astOperand()); CastExpression expr = createCastExpression(typeRef, operand); Position ecjTypePos = getConversionPositionInfo(node, "type"); typeRef.sourceStart = ecjTypePos == null ? posOfStructure(node, "(", 0, true) + 1 : ecjTypePos.getStart(); typeRef.sourceEnd = ecjTypePos == null ? posOfStructure(node, ")", 0, false) - 2 : ecjTypePos.getEnd() - 1; expr.sourceStart = start(node); expr.sourceEnd = end(node); return set(node, expr); } @SneakyThrows private CastExpression createCastExpression(Expression typeRef, Expression operand) { try { return (CastExpression) CastExpression.class.getConstructors()[0].newInstance(operand, typeRef); } catch (InvocationTargetException e) { throw e.getCause(); } } @Override public boolean visitInstanceOf(lombok.ast.InstanceOf node) { return set(node, new InstanceOfExpression(toExpression(node.astObjectReference()), (TypeReference) toTree(node.astTypeReference()))); } @Override public boolean visitInlineIfExpression(lombok.ast.InlineIfExpression node) { return set(node, new ConditionalExpression(toExpression(node.astCondition()), toExpression(node.astIfTrue()), toExpression(node.astIfFalse()))); } @Override public boolean visitSelect(lombok.ast.Select node) { //TODO for something like ("" + "").foo.bar; /* try chain-of-identifiers */ { List<lombok.ast.Identifier> selects = Lists.newArrayList(); List<Long> pos = Lists.newArrayList(); lombok.ast.Select current = node; while (true) { selects.add(current.astIdentifier()); pos.add(pos(current.astIdentifier())); if (current.astOperand() instanceof lombok.ast.Select) current = (lombok.ast.Select) current.astOperand(); else if (current.astOperand() instanceof lombok.ast.VariableReference) { selects.add(((lombok.ast.VariableReference) current.astOperand()).astIdentifier()); pos.add(pos(current.rawOperand())); Collections.reverse(selects); long[] posArray = new long[pos.size()]; for (int i = 0; i < posArray.length; i++) posArray[i] = pos.get(posArray.length - i - 1); char[][] tokens = chain(selects, selects.size()); QualifiedNameReference ref = new QualifiedNameReference(tokens, posArray, start(node), end(node)); return set(node, ref); } else { break; } } } FieldReference ref = new FieldReference(toName(node.astIdentifier()), pos(node)); ref.nameSourcePosition = pos(node.astIdentifier()); ref.receiver = toExpression(node.astOperand()); //TODO ("" + 10).a.b = ... DONT forget to doublecheck var/type restriction flags return set(node, ref); } @Override public boolean visitTypeReference(lombok.ast.TypeReference node) { // TODO make sure there's a test case that covers every eclipsian type ref: hierarchy on "org.eclipse.jdt.internal.compiler.ast.TypeReference". Wildcard wildcard = null; TypeReference ref = null; switch (node.astWildcard()) { case UNBOUND: wildcard = new Wildcard(Wildcard.UNBOUND); wildcard.sourceStart = start(node); wildcard.sourceEnd = end(node); return set(node, wildcard); case EXTENDS: wildcard = new Wildcard(Wildcard.EXTENDS); break; case SUPER: wildcard = new Wildcard(Wildcard.SUPER); break; } char[][] qualifiedName = null; char[] singleName = null; boolean qualified = node.astParts().size() != 1; int dims = node.astArrayDimensions(); TypeReference[][] params = new TypeReference[node.astParts().size()][]; boolean hasGenerics = false; if (!qualified) { singleName = toName(node.astParts().first().astIdentifier()); } else { List<lombok.ast.Identifier> identifiers = Lists.newArrayList(); for (lombok.ast.TypeReferencePart part : node.astParts()) identifiers.add(part.astIdentifier()); qualifiedName = chain(identifiers, identifiers.size()); } { int ctr = 0; for (lombok.ast.TypeReferencePart part : node.astParts()) { params[ctr] = new TypeReference[part.astTypeArguments().size()]; int ctr2 = 0; boolean partHasGenerics = false; for (lombok.ast.TypeReference x : part.astTypeArguments()) { hasGenerics = true; partHasGenerics = true; params[ctr][ctr2++] = (TypeReference) toTree(x); } if (!partHasGenerics) params[ctr] = null; ctr++; } } if (!qualified) { if (!hasGenerics) { if (dims == 0) { ref = new SingleTypeReference(singleName, partsToPosArray(node.rawParts())[0]); } else { ref = new ArrayTypeReference(singleName, dims, 0L); ref.sourceStart = start(node); ref.sourceEnd = end(node); ((ArrayTypeReference)ref).originalSourceEnd = end(node.rawParts().last()); } } else { ref = new ParameterizedSingleTypeReference(singleName, params[0], dims, partsToPosArray(node.rawParts())[0]); if (dims > 0) ref.sourceEnd = end(node); } } else { if (!hasGenerics) { if (dims == 0) { long[] pos = partsToPosArray(node.rawParts()); ref = new QualifiedTypeReference(qualifiedName, pos); } else { long[] pos = partsToPosArray(node.rawParts()); ref = new ArrayQualifiedTypeReference(qualifiedName, dims, pos); ref.sourceEnd = end(node); } } else { //TODO test what happens with generic types that also have an array dimension or two. long[] pos = partsToPosArray(node.rawParts()); ref = new ParameterizedQualifiedTypeReference(qualifiedName, params, dims, pos); if (dims > 0) ref.sourceEnd = end(node); } } if (wildcard != null) { wildcard.bound = ref; ref = wildcard; ref.sourceStart = start(node); ref.sourceEnd = wildcard.bound.sourceEnd; } return set(node, ref); } @Override public boolean visitTypeVariable(lombok.ast.TypeVariable node) { // TODO test multiple bounds on a variable, e.g. <T extends A & B & C> TypeParameter param = new TypeParameter(); param.declarationSourceStart = start(node); param.declarationSourceEnd = end(node); param.sourceStart = start(node.astName()); param.sourceEnd = end(node.astName()); param.name = toName(node.astName()); if (!node.astExtending().isEmpty()) { TypeReference[] p = toArray(TypeReference.class, node.astExtending()); for (TypeReference t : p) t.bits |= ASTNode.IsSuperType; param.type = p[0]; if (p.length > 1) { param.bounds = new TypeReference[p.length - 1]; System.arraycopy(p, 1, param.bounds, 0, p.length - 1); } param.declarationSourceEnd = p[p.length - 1].sourceEnd; } return set(node, param); } @Override public boolean visitStaticInitializer(lombok.ast.StaticInitializer node) { Initializer init = new Initializer((Block) toTree(node.astBody()), ClassFileConstants.AccStatic); init.declarationSourceStart = start(node); init.sourceStart = start(node.astBody()); init.sourceEnd = init.declarationSourceEnd = end(node); init.bodyStart = init.sourceStart + 1; init.bodyEnd = init.sourceEnd - 1; return set(node, init); } @Override public boolean visitInstanceInitializer(lombok.ast.InstanceInitializer node) { Initializer init = new Initializer((Block) toTree(node.astBody()), 0); if (bubblingFlags.remove(BubblingFlags.LOCALTYPE)) { init.bits |= ASTNode.HasLocalType; } init.sourceStart = init.declarationSourceStart = start(node); init.sourceEnd = init.declarationSourceEnd = end(node); init.bodyStart = init.sourceStart + 1; init.bodyEnd = init.sourceEnd - 1; return set(node, init); } @Override public boolean visitIntegralLiteral(lombok.ast.IntegralLiteral node) { if (node.astMarkedAsLong()) { return set(node, new LongLiteral(node.rawValue().toCharArray(), start(node), end(node))); } return set(node, new IntLiteral(node.rawValue().toCharArray(), start(node), end(node))); } @Override public boolean visitFloatingPointLiteral(lombok.ast.FloatingPointLiteral node) { if (node.astMarkedAsFloat()) { return set(node, new FloatLiteral(node.rawValue().toCharArray(), start(node), end(node))); } return set(node, new DoubleLiteral(node.rawValue().toCharArray(), start(node), end(node))); } @Override public boolean visitBooleanLiteral(lombok.ast.BooleanLiteral node) { return set(node, node.astValue() ? new TrueLiteral(start(node), end(node)) : new FalseLiteral(start(node), end(node))); } @Override public boolean visitNullLiteral(lombok.ast.NullLiteral node) { return set(node, new NullLiteral(start(node), end(node))); } @Override public boolean visitVariableReference(VariableReference node) { SingleNameReference ref = new SingleNameReference(toName(node.astIdentifier()), pos(node)); return set(node, ref); } @Override public boolean visitIdentifier(lombok.ast.Identifier node) { SingleNameReference ref = new SingleNameReference(toName(node), pos(node)); return set(node, ref); } @Override public boolean visitCharLiteral(lombok.ast.CharLiteral node) { return set(node, new CharLiteral(node.rawValue().toCharArray(), start(node), end(node))); } @Override public boolean visitStringLiteral(lombok.ast.StringLiteral node) { return set(node, new StringLiteral(node.astValue().toCharArray(), start(node), end(node), 0)); } @Override public boolean visitBlock(lombok.ast.Block node) { Block block = new Block(0); block.statements = toArray(Statement.class, node.astContents()); if (block.statements == null) { if (isUndocumented(node)) block.bits |= ASTNode.UndocumentedEmptyBlock; } else { block.explicitDeclarations = calculateExplicitDeclarations(node.astContents()); } block.sourceStart = start(node); block.sourceEnd = end(node); return set(node, block); } @Override public boolean visitAnnotationValueArray(AnnotationValueArray node) { ArrayInitializer init = new ArrayInitializer(); init.sourceStart = start(node); init.sourceEnd = end(node); init.expressions = toArray(Expression.class, node.astValues()); return set(node, init); } @Override public boolean visitArrayInitializer(lombok.ast.ArrayInitializer node) { ArrayInitializer init = new ArrayInitializer(); init.sourceStart = start(node); init.sourceEnd = end(node); init.expressions = toArray(Expression.class, node.astExpressions()); return set(node, init); } @Override public boolean visitArrayCreation(lombok.ast.ArrayCreation node) { ArrayAllocationExpression aae = new ArrayAllocationExpression(); aae.sourceStart = start(node); aae.sourceEnd = end(node); aae.type = (TypeReference) toTree(node.astComponentTypeReference()); // TODO uncompilable parser test: new Type<Generics>[]... // TODO uncompilable parser test: new Type[][expr][][expr]... aae.type.bits |= ASTNode.IgnoreRawTypeCheck; int i = 0; Expression[] dimensions = new Expression[node.astDimensions().size()]; for (lombok.ast.ArrayDimension dim : node.astDimensions()) { dimensions[i++] = (Expression) toTree(dim.astDimension()); } aae.dimensions = dimensions; aae.initializer = (ArrayInitializer) toTree(node.astInitializer()); return set(node, aae); } @Override public boolean visitArrayDimension(lombok.ast.ArrayDimension node) { return set(node, toExpression(node.astDimension())); } @Override public boolean visitThis(lombok.ast.This node) { if (node.astQualifier() == null) { return set(node, new ThisReference(start(node), end(node))); } return set(node, new QualifiedThisReference((TypeReference) toTree(node.astQualifier()), start(node), end(node))); } @Override public boolean visitClassLiteral(lombok.ast.ClassLiteral node) { return set(node, new ClassLiteralAccess(end(node), (TypeReference) toTree(node.astTypeReference()))); } @Override public boolean visitArrayAccess(lombok.ast.ArrayAccess node) { ArrayReference ref = new ArrayReference(toExpression(node.astOperand()), toExpression(node.astIndexExpression())); ref.sourceEnd = end(node); return set(node, ref); } @Override public boolean visitAssert(lombok.ast.Assert node) { //TODO check the flags after more test have been added: asserts in constructors, methods etc. bubblingFlags.add(BubblingFlags.ASSERT); if (node.astMessage() == null) { return set(node, new AssertStatement(toExpression(node.astAssertion()), start(node))); } return set(node, new AssertStatement(toExpression(node.astMessage()), toExpression(node.astAssertion()), start(node))); } @Override public boolean visitDoWhile(lombok.ast.DoWhile node) { return set(node, new DoStatement(toExpression(node.astCondition()), toStatement(node.astStatement()), start(node), end(node))); } @Override public boolean visitContinue(lombok.ast.Continue node) { return set(node, new ContinueStatement(toName(node.astLabel()), start(node), end(node))); } @Override public boolean visitBreak(lombok.ast.Break node) { return set(node, new BreakStatement(toName(node.astLabel()), start(node), end(node))); } @Override public boolean visitForEach(lombok.ast.ForEach node) { ForeachStatement forEach = new ForeachStatement((LocalDeclaration) toTree(node.astVariable()), start(node)); forEach.sourceEnd = end(node); forEach.collection = toExpression(node.astIterable()); forEach.action = toStatement(node.astStatement()); return set(node, forEach); } @Override public boolean visitVariableDeclaration(lombok.ast.VariableDeclaration node) { List<AbstractVariableDeclaration> list = toList(AbstractVariableDeclaration.class, node.astDefinition()); if (list.size() > 0) setupJavadoc(list.get(0), node); return set(node, list); } @Override public boolean visitVariableDefinition(lombok.ast.VariableDefinition node) { List<AbstractVariableDeclaration> values = Lists.newArrayList(); Annotation[] annotations = toArray(Annotation.class, node.astModifiers().astAnnotations()); int modifiers = toModifiers(node.astModifiers()); TypeReference base = (TypeReference) toTree(node.astTypeReference()); AbstractVariableDeclaration prevDecl = null, firstDecl = null; for (lombok.ast.VariableDefinitionEntry entry : node.astVariables()) { VariableKind kind = VariableKind.kind(node); AbstractVariableDeclaration decl = kind.create(); decl.annotations = annotations; decl.initialization = toExpression(entry.astInitializer()); decl.modifiers = modifiers; decl.name = toName(entry.astName()); if (entry.astArrayDimensions() == 0 && !node.astVarargs()) { decl.type = base; } else if (entry.astArrayDimensions() > 0 || node.astVarargs()) { decl.type = (TypeReference) toTree(entry.getEffectiveTypeReference()); decl.type.sourceStart = base.sourceStart; Position ecjTypeSourcePos = getConversionPositionInfo(entry, "typeSourcePos"); if (ecjTypeSourcePos != null) { decl.type.sourceEnd = ecjTypeSourcePos.getEnd() - 1; } else { // This makes no sense whatsoever but eclipse wants it this way. if (firstDecl == null && (base.dimensions() > 0 || node.getParent() instanceof lombok.ast.ForEach)) { decl.type.sourceEnd = posOfStructure(entry, "]", Integer.MAX_VALUE, false) - 1; } else if (firstDecl != null) { // This replicates an eclipse bug; the end pos of the type of b in: int[] a[][], b[]; is in fact the second closing ] of a. decl.type.sourceEnd = firstDecl.type.sourceEnd; } else decl.type.sourceEnd = base.sourceEnd; // Yet another eclipse inconsistency. if (kind == VariableKind.FIELD && base instanceof ArrayQualifiedTypeReference) { long[] poss = ((ArrayQualifiedTypeReference)base).sourcePositions; decl.type.sourceEnd = (int) poss[poss.length - 1]; } } if (node.astVarargs()) { if (decl.type instanceof ArrayTypeReference) { ((ArrayTypeReference)decl.type).originalSourceEnd = decl.type.sourceEnd; } Position ecjTyperefPos = getConversionPositionInfo(node, "typeref"); decl.type.sourceEnd = ecjTyperefPos == null ? posOfStructure(node, "...", Integer.MAX_VALUE, false) - 1 : ecjTyperefPos.getEnd() - 1; } else { if (decl.type instanceof ArrayTypeReference) { ((ArrayTypeReference)decl.type).originalSourceEnd = decl.type.sourceEnd; } if (decl.type instanceof ArrayQualifiedTypeReference) { ((ArrayQualifiedTypeReference)decl.type).sourcePositions = ((QualifiedTypeReference)base).sourcePositions.clone(); } } } if (node.astVarargs()) { decl.type.bits |= ASTNode.IsVarArgs; } if (decl instanceof FieldDeclaration) { if (bubblingFlags.remove(BubblingFlags.LOCALTYPE)) { decl.bits |= ASTNode.HasLocalType; } } decl.sourceStart = start(entry.astName()); decl.sourceEnd = end(entry.astName()); decl.declarationSourceStart = jstart(node); switch (kind) { case LOCAL: int end; if (node.getParent() instanceof lombok.ast.VariableDeclaration) end = end(node.getParent()); else { if (entry.rawInitializer() != null) end = end(entry.rawInitializer()); else end = end(entry.astName()); } decl.declarationSourceEnd = decl.declarationEnd = end; Position ecjDeclarationSourcePos = getConversionPositionInfo(entry, "declarationSource"); if (ecjDeclarationSourcePos != null) decl.declarationSourceEnd = ecjDeclarationSourcePos.getEnd() - 1; break; case ARGUMENT: decl.declarationSourceEnd = decl.declarationEnd = end(entry.astName()); ecjDeclarationSourcePos = getConversionPositionInfo(entry, "declarationSource"); if (ecjDeclarationSourcePos != null) decl.declarationSourceEnd = ecjDeclarationSourcePos.getEnd() - 1; break; case FIELD: decl.declarationSourceEnd = decl.declarationEnd = end(node.getParent()); ecjDeclarationSourcePos = getConversionPositionInfo(entry, "declarationSource"); Position ecjPart1Pos = getConversionPositionInfo(entry, "varDeclPart1"); Position ecjPart2Pos = getConversionPositionInfo(entry, "varDeclPart2"); if (ecjDeclarationSourcePos != null) decl.declarationSourceEnd = ecjDeclarationSourcePos.getEnd() - 1; ((FieldDeclaration)decl).endPart1Position = ecjPart1Pos == null ? end(node.rawTypeReference()) + 1 : ecjPart1Pos.getEnd() - 1; ((FieldDeclaration)decl).endPart2Position = ecjPart2Pos == null ? end(node.getParent()) : ecjPart2Pos.getEnd() - 1; if (ecjPart2Pos == null && prevDecl instanceof FieldDeclaration) { ((FieldDeclaration)prevDecl).endPart2Position = start(entry) - 1; } break; } values.add(decl); prevDecl = decl; if (firstDecl == null) firstDecl = decl; } return set(node, values); } @Override public boolean visitIf(lombok.ast.If node) { if (node.astElseStatement() == null) { return set(node, new IfStatement(toExpression(node.astCondition()), toStatement(node.astStatement()), start(node), end(node))); } return set(node, new IfStatement(toExpression(node.astCondition()), toStatement(node.astStatement()), toStatement(node.astElseStatement()), start(node), end(node))); } @Override public boolean visitLabelledStatement(lombok.ast.LabelledStatement node) { return set(node, new LabeledStatement(toName(node.astLabel()), toStatement(node.astStatement()), pos(node.astLabel()), end(node))); } @Override public boolean visitFor(lombok.ast.For node) { //TODO make test for modifiers on variable declarations //TODO make test for empty for/foreach etc. if(node.isVariableDeclarationBased()) { return set(node, new ForStatement(toArray(Statement.class, node.astVariableDeclaration()), toExpression(node.astCondition()), toArray(Statement.class, node.astUpdates()), toStatement(node.astStatement()), true, start(node), end(node))); } return set(node, new ForStatement(toArray(Statement.class, node.astExpressionInits()), toExpression(node.astCondition()), toArray(Statement.class, node.astUpdates()), toStatement(node.astStatement()), false, start(node), end(node))); } @Override public boolean visitSwitch(lombok.ast.Switch node) { SwitchStatement value = new SwitchStatement(); value.sourceStart = start(node); value.sourceEnd = end(node); value.blockStart = start(node.rawBody()); value.expression = toExpression(node.astCondition()); value.statements = toArray(Statement.class, node.astBody().astContents()); if (value.statements == null) { if (isUndocumented(node.astBody())) value.bits |= ASTNode.UndocumentedEmptyBlock; } else { value.explicitDeclarations = calculateExplicitDeclarations(node.astBody().astContents()); } return set(node, value); } @Override public boolean visitSynchronized(lombok.ast.Synchronized node) { return set(node, new SynchronizedStatement(toExpression(node.astLock()), (Block) toTree(node.astBody()), start(node), end(node))); } @Override public boolean visitTry(lombok.ast.Try node) { TryStatement tryStatement = new TryStatement(); tryStatement.sourceStart = start(node); tryStatement.sourceEnd = end(node); tryStatement.tryBlock = (Block) toTree(node.astBody()); int catchSize = node.astCatches().size(); if (catchSize > 0) { tryStatement.catchArguments = new Argument[catchSize]; tryStatement.catchBlocks = new Block[catchSize]; int i = 0; for (lombok.ast.Catch c : node.astCatches()) { tryStatement.catchArguments[i] = (Argument)toTree(c.astExceptionDeclaration()); tryStatement.catchBlocks[i] = (Block) toTree(c.astBody()); i++; } } tryStatement.finallyBlock = (Block) toTree(node.astFinally()); return set(node, tryStatement); } @Override public boolean visitThrow(lombok.ast.Throw node) { return set(node, new ThrowStatement(toExpression(node.astThrowable()), start(node), end(node))); } @Override public boolean visitWhile(lombok.ast.While node) { return set(node, new WhileStatement(toExpression(node.astCondition()), toStatement(node.astStatement()), start(node), end(node))); } @Override public boolean visitReturn(lombok.ast.Return node) { return set(node, new ReturnStatement(toExpression(node.astValue()), start(node), end(node))); } @Override public boolean visitAnnotation(lombok.ast.Annotation node) { //TODO add test where the value is the result of string concatenation TypeReference type = (TypeReference) toTree(node.astAnnotationTypeReference()); boolean isEcjNormal = Position.UNPLACED == getConversionPositionInfo(node, "isNormalAnnotation"); if (node.astElements().isEmpty() && countStructure(node, "(") == 0 && !isEcjNormal) { MarkerAnnotation ann = new MarkerAnnotation(type, start(node)); ann.declarationSourceEnd = end(node); return set(node, ann); } MemberValuePair[] values = toArray(MemberValuePair.class, node.astElements()); if (values != null && (values.length == 1 && values[0].name == null)) { SingleMemberAnnotation ann = new SingleMemberAnnotation(type, start(node)); ann.declarationSourceEnd = end(node); ann.memberValue = values[0].value; return set(node, ann); } NormalAnnotation ann = new NormalAnnotation(type, start(node)); ann.declarationSourceEnd = end(node); ann.memberValuePairs = values; return set(node, ann); } @Override public boolean visitAnnotationElement(lombok.ast.AnnotationElement node) { //TODO make a test where the array initializer is the default value MemberValuePair pair = new MemberValuePair(toName(node.astName()), start(node), end(node.astName()), null); // giving the value to the constructor will set the ASTNode.IsAnnotationDefaultValue flag pair.value = toExpression(node.astValue()); if (pair.name != null && pair.value instanceof ArrayInitializer) { pair.value.bits |= ASTNode.IsAnnotationDefaultValue; } return set(node, pair); } @Override public boolean visitCase(lombok.ast.Case node) { // end and start args are switched around on CaseStatement, presumably because the API designer was drunk at the time. return set(node, new CaseStatement(toExpression(node.astCondition()), end(node.rawCondition()), start(node))); } @Override public boolean visitDefault(lombok.ast.Default node) { // end and start args are switched around on CaseStatement, presumably because the API designer was drunk at the time. return set(node, new CaseStatement(null, posOfStructure(node, "default", 0, false) - 1, start(node))); } @Override public boolean visitComment(lombok.ast.Comment node) { if (!node.isJavadoc()) { throw new RuntimeException("Only javadoc expected here"); } Node parent = node.getParent(); parent = parent == null ? null : parent.getParent(); while (parent != null && !(parent instanceof lombok.ast.TypeDeclaration)) parent = parent.getParent(); String typeName = null; if (parent instanceof lombok.ast.TypeDeclaration) { Identifier identifier = ((lombok.ast.TypeDeclaration)parent).astName(); if (identifier != null) typeName = identifier.astValue(); } if (typeName == null) { typeName = getTypeNameFromFileName(compilationResult.getFileName()); } return set(node, new JustJavadocParser(silentProblemReporter, typeName).parse(rawInput, node.getPosition().getStart(), node.getPosition().getEnd())); } @Override public boolean visitEmptyStatement(lombok.ast.EmptyStatement node) { return set(node, new EmptyStatement(start(node), end(node))); } @Override public boolean visitEmptyDeclaration(lombok.ast.EmptyDeclaration node) { return set(node, (ASTNode)null); } private int toModifiers(lombok.ast.Modifiers modifiers) { return modifiers.getExplicitModifierFlags(); } @Override public boolean visitNode(lombok.ast.Node node) { throw new UnsupportedOperationException(String.format("Unhandled node '%s' (%s)", node, node.getClass().getSimpleName())); } private char[][] chain(lombok.ast.StrictListAccessor<lombok.ast.Identifier, ?> parts) { return chain(parts, parts.size()); } private char[][] chain(Iterable<lombok.ast.Identifier> parts, int size) { char[][] c = new char[size][]; int i = 0; for (lombok.ast.Identifier part : parts) { c[i++] = part.astValue().toCharArray(); } return c; } private void updateRestrictionFlags(lombok.ast.Node node, NameReference ref) { ref.bits &= ~ASTNode.RestrictiveFlagMASK; ref.bits |= Binding.VARIABLE; if (node.getParent() instanceof lombok.ast.MethodInvocation) { if (((lombok.ast.MethodInvocation)node.getParent()).astOperand() == node) { ref.bits |= Binding.TYPE; } } if (node.getParent() instanceof lombok.ast.Select) { if (((lombok.ast.Select)node.getParent()).astOperand() == node) { ref.bits |= Binding.TYPE; } } } // Only works for TypeBody, EnumTypeBody and Block private boolean isUndocumented(lombok.ast.Node block) { if (block == null) return false; if (rawInput == null) return false; lombok.ast.Position pos = block.getPosition(); if (pos.isUnplaced() || pos.size() < 3) return true; String content = rawInput.substring(pos.getStart() + 1, pos.getEnd() - 1); return content.trim().isEmpty(); } }; private static class JustJavadocParser extends JavadocParser { private static final char[] GENERIC_JAVA_CLASS_SUFFIX = "class Y{}".toCharArray(); JustJavadocParser(ProblemReporter reporter, String mainTypeName) { super(makeDummyParser(reporter, mainTypeName)); } private static Parser makeDummyParser(ProblemReporter reporter, String mainTypeName) { Parser parser = new Parser(reporter, false); CompilationResult cr = new CompilationResult((mainTypeName + ".java").toCharArray(), 0, 1, 0); parser.compilationUnit = new CompilationUnitDeclaration(reporter, cr, 0); return parser; } Javadoc parse(String rawInput, int from, int to) { char[] rawContent; rawContent = new char[to + GENERIC_JAVA_CLASS_SUFFIX.length]; Arrays.fill(rawContent, 0, from, ' '); System.arraycopy(rawInput.substring(from, to).toCharArray(), 0, rawContent, from, to - from); // Eclipse crashes if there's no character following the javadoc. System.arraycopy(GENERIC_JAVA_CLASS_SUFFIX, 0, rawContent, to, GENERIC_JAVA_CLASS_SUFFIX.length); this.sourceLevel = ClassFileConstants.JDK1_6; this.scanner.setSource(rawContent); this.source = rawContent; this.javadocStart = from; this.javadocEnd = to; this.reportProblems = true; this.docComment = new Javadoc(this.javadocStart, this.javadocEnd); commentParse(); this.docComment.valuePositions = -1; this.docComment.sourceEnd return docComment; } } private static int jstart(lombok.ast.Node node) { if (node == null) return 0; int start = start(node); if (node instanceof lombok.ast.JavadocContainer) { lombok.ast.Node javadoc = ((lombok.ast.JavadocContainer)node).rawJavadoc(); if (javadoc != null) return Math.min(start, start(javadoc)); } if (node instanceof lombok.ast.VariableDefinition && node.getParent() instanceof lombok.ast.VariableDeclaration) { lombok.ast.Node javadoc = ((lombok.ast.JavadocContainer)node.getParent()).rawJavadoc(); if (javadoc != null) return Math.min(start, start(javadoc)); } if (node instanceof lombok.ast.Modifiers && node.getParent() instanceof JavadocContainer) { lombok.ast.Node javadoc = ((lombok.ast.JavadocContainer)node.getParent()).rawJavadoc(); if (javadoc != null) return Math.min(start, start(javadoc)); } return start; } private static int start(lombok.ast.Node node) { if (node == null || node.getPosition().isUnplaced()) return 0; return node.getPosition().getStart(); } private static int end(lombok.ast.Node node) { if (node == null || node.getPosition().isUnplaced()) return 0; return node.getPosition().getEnd() - 1; } private static long pos(lombok.ast.Node n) { return (((long)start(n)) << 32) | end(n); } private static long[] partsToPosArray(RawListAccessor<?, ?> parts) { long[] pos = new long[parts.size()]; int idx = 0; for (lombok.ast.Node n : parts) { if (n instanceof lombok.ast.TypeReferencePart) { pos[idx++] = pos(((lombok.ast.TypeReferencePart) n).astIdentifier()); } else { pos[idx++] = pos(n); } } return pos; } private int countStructure(lombok.ast.Node node, String structure) { int result = 0; if (sourceStructures != null && sourceStructures.containsKey(node)) { for (SourceStructure struct : sourceStructures.get(node)) { if (structure.equals(struct.getContent())) result++; } } return result; } private int posOfStructure(lombok.ast.Node node, String structure, int idx, boolean atStart) { int start = node.getPosition().getStart(); int end = node.getPosition().getEnd(); Integer result = null; if (sourceStructures != null && sourceStructures.containsKey(node)) { for (SourceStructure struct : sourceStructures.get(node)) { if (structure.equals(struct.getContent())) { result = atStart ? struct.getPosition().getStart() : struct.getPosition().getEnd(); if (idx-- <= 0) break; } } } if (result != null) return result; return atStart ? start : end; } private static String getTypeNameFromFileName(char[] fileName) { String f = new String(fileName); int start = Math.max(f.lastIndexOf('/'), f.lastIndexOf('\\')); int end = f.lastIndexOf('.'); if (end == -1) end = f.length(); return f.substring(start + 1, end); } }
package edu.cmu.cs.diamond.opendiamond; import java.io.File; import java.io.FilenameFilter; import java.io.InputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class BundleFactory { private List<File> bundleDirs; private List<File> memberDirs; public BundleFactory(List<File> dirs) { this(dirs, dirs); } public BundleFactory(List<File> bundleDirs, List<File> memberDirs) { this.bundleDirs = new ArrayList<File>(bundleDirs); this.memberDirs = Collections.unmodifiableList(new ArrayList<File>(memberDirs)); } public List<Bundle> getSearchBundles() { List<Bundle> bundles = new ArrayList<Bundle>(); FilenameFilter filter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".search"); } }; for (File dir : bundleDirs) { for (File file : dir.listFiles(filter)) { try { bundles.add(getBundle(file)); } catch (IOException e) { e.printStackTrace(); } } } return bundles; } // Does not cache the contents of the file. The file is reloaded when // getFilters() is called. public Bundle getBundle(File file) throws IOException { return Bundle.getBundle(file, memberDirs); } // Caches the contents of the file in memory. For use when we may not // be able to load the file again later (e.g., it is an URL). public Bundle getBundle(InputStream in) throws IOException { return Bundle.getBundle(in, memberDirs); } }
package edu.mit.streamjit.impl.compiler2; import edu.mit.streamjit.impl.blob.Blob.Token; /** * A StorageSlot represents a slot in a storage: whether it's live or not, and * if it is, where it should go when we drain. * @author Jeffrey Bosboom <jeffreybosboom@gmail.com> * @since 11/29/2013 */ public abstract class StorageSlot { public static StorageSlot live(Token token, int index) { assert token != null; assert index >= 0 : index; return new LiveStorageSlot(token, index); } public static StorageSlot hole() { return HoleStorageSlot.INSTANCE; } public abstract boolean isLive(); public abstract boolean isHole(); public abstract boolean isDrainable(); public abstract StorageSlot duplify(); public abstract Token token(); public abstract int index(); @Override public abstract String toString(); private static final class HoleStorageSlot extends StorageSlot { private static final HoleStorageSlot INSTANCE = new HoleStorageSlot(); private HoleStorageSlot() {} @Override public boolean isLive() { return false; } @Override public boolean isHole() { return true; } @Override public boolean isDrainable() { return false; } @Override public StorageSlot duplify() { return this; //a hole duplicate is just a hole } @Override public Token token() { throw new AssertionError("called token() on a hole"); } @Override public int index() { throw new AssertionError("called index() on a hole"); } @Override public String toString() { return "(hole)"; } } private static class LiveStorageSlot extends StorageSlot { private final Token token; private final int index; protected LiveStorageSlot(Token token, int index) { this.token = token; this.index = index; } @Override public boolean isLive() { return true; } @Override public boolean isHole() { return false; } @Override public boolean isDrainable() { return true; } @Override public StorageSlot duplify() { return DuplicateStorageSlot.INSTANCE; } @Override public Token token() { return token; } @Override public int index() { return index; } @Override public String toString() { return String.format("%s[%d]", token(), index()); } } private static final class DuplicateStorageSlot extends StorageSlot { private static final DuplicateStorageSlot INSTANCE = new DuplicateStorageSlot(); private DuplicateStorageSlot() {} @Override public boolean isLive() { return true; } @Override public boolean isHole() { return false; } @Override public boolean isDrainable() { return false; } @Override public StorageSlot duplify() { return this; } @Override public Token token() { throw new AssertionError("called token() on a duplicate"); } @Override public int index() { throw new AssertionError("called index() on a duplicate"); } @Override public String toString() { return String.format("(dup)"); } } protected StorageSlot() {} }
package emergencylanding.k.library.lwjgl.render; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.util.Arrays; import k.core.util.classes.StackTraceInfo; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL30; import emergencylanding.k.library.internalstate.Victor; import emergencylanding.k.library.lwjgl.tex.ELTexture; import emergencylanding.k.library.util.LUtils; /** * A virtual buffer/array object, used for speedy rendering. * * * @author Kenzie Togami * */ public class VBAO implements Cloneable { /** * Index of the position attribute in the {@link VBAO#vbo vbo} */ public static final int POS_VBO_INDEX = GLData.POSITION_INDEX; /** * Index of the color attribute in the {@link VBAO#vbo vbo} */ public static final int COLOR_VBO_INDEX = GLData.COLOR_INDEX; /** * Index of the texCoord attribute in the {@link VBAO#vbo vbo} */ public static final int TEX_VBO_INDEX = GLData.TEX_INDEX; /** * The amount of VBOs used */ public static final int VBO_COUNT = 2; /** * An empty VBAO for returning valid values for invalid input. */ public static final VBAO EMPTY = new VBAO( new VertexData[] { new VertexData() }, new byte[] { 0, 1, 2 }, true); /** * The vertex data */ private FloatBuffer vertData = BufferUtils.createFloatBuffer(0); /** * The IC data */ private ByteBuffer indexData = BufferUtils.createByteBuffer(0); /** * The amount of vertices */ private int verticesCount = 0; /** * The ID of the VAO array */ private int vaoId = GLData.NONE; /** * The VBO id that holds the interleaved data. */ private int vbo = GLData.NONE; /** * The VBO id that holds the IC data. */ private int vbo_i = GLData.NONE; /** * Determines if this data is used with {@link GL15#GL_STATIC_DRAW} or * {@link GL15#GL_DYNAMIC_DRAW}. */ private boolean staticdata = false; /** * The texture used by this VBAO, if any. */ public ELTexture tex = null; /** * The original data. */ public VertexData[] data = {}; /** * The original data. */ public byte[] icdata = {}; /** * The offset for drawing (like doing glTanslate) */ public Victor xyzoffset = new Victor(); public VBAO(VertexData[] verts, byte[] indexControl, boolean stat) { this(verts, indexControl, null, stat); } public VBAO(VertexData[] verts, byte[] indexControl, ELTexture t, boolean stat) { data = verts; icdata = indexControl; vertData = VertexData.toFB(verts); indexData = BufferUtils.createByteBuffer(indexControl.length); indexData.put(indexControl); indexData.flip(); verticesCount = indexControl.length; staticdata = stat; tex = t; init(); if (LUtils.debugLevel >= 1) { GLData.notifyOnGLError(StackTraceInfo.getCurrentMethodName()); } } public VBAO setTexture(ELTexture t) { tex = t; return this; } public VBAO setXYZOff(Victor pos) { if (staticdata) { throw new IllegalStateException("static data"); } xyzoffset = pos; VertexData[] newDataTemp = new VertexData[data.length]; for (int i = 0; i < newDataTemp.length; i++) { VertexData old = data[i]; VertexData v = new VertexData() .setXYZW(old.verts[0] + pos.x, old.verts[1] + pos.y, old.verts[2] + pos.z, old.verts[3]) .setRGBA(old.colors[0], old.colors[1], old.colors[2], old.colors[3]) .setUV(old.texCoords[0], old.texCoords[1]); newDataTemp[i] = v; } updateData(newDataTemp, icdata); return this; } public VBAO updateData(VertexData[] verts, byte[] indexControl) { if (staticdata) { throw new IllegalStateException("static data"); } vertData = VertexData.toFB(verts); indexData = BufferUtils.createByteBuffer(indexControl.length); indexData.put(indexControl); indexData.flip(); verticesCount = indexControl.length; // Overwrite data GL30.glBindVertexArray(vaoId); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); // null pointer the original data GL15.glBufferData(GL15.GL_ARRAY_BUFFER, (FloatBuffer) null, GL15.GL_DYNAMIC_DRAW); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, vertData, GL15.GL_DYNAMIC_DRAW); if (LUtils.debugLevel >= 1) { GLData.notifyOnGLError("updateData -> overwrite vertData"); } GL30.glBindVertexArray(GLData.NONE); GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, vbo_i); GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, indexData, GL15.GL_STATIC_DRAW); GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, GLData.NONE); if (LUtils.debugLevel >= 1) { GLData.notifyOnGLError("updateData -> overwrite IC"); } return this; } private void init() { // Create a new Vertex Array Object in memory and select it (bind) // A VAO can have up to 16 attributes (VBO's) assigned to it by default vaoId = GL30.glGenVertexArrays(); GL30.glBindVertexArray(vaoId); // Create the vertex VBO createVertexVBO(); // Deselect (bind to 0) the VAO GL30.glBindVertexArray(GLData.NONE); // Create the IC VBO createIndexControlVBO(); if (LUtils.debugLevel >= 1) { GLData.notifyOnGLError(StackTraceInfo.getCurrentMethodName()); } } private void createVertexVBO() { // Create a new Vertex Buffer Object in memory and select it (bind) // A VBO is a collection of Vectors used to represent data vbo = GL15.glGenBuffers(); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, vertData, GL15.GL_STATIC_DRAW); // Put the VBO in the attributes list at index 0 (position) GL20.glVertexAttribPointer(POS_VBO_INDEX, VertexData.FLOATS_PER_POSTITON, GL11.GL_FLOAT, false, VertexData.VERTEX_SIZE, 0); // Put the VBO in the attributes list at index 1 (color) GL20.glVertexAttribPointer(COLOR_VBO_INDEX, VertexData.FLOATS_PER_COLOR, GL11.GL_FLOAT, false, VertexData.VERTEX_SIZE, VertexData.POSITION_SIZE); // Put the VBO in the attributes list at index 2 (tex) GL20.glVertexAttribPointer(TEX_VBO_INDEX, VertexData.FLOATS_PER_TEXTURE, GL11.GL_FLOAT, false, VertexData.VERTEX_SIZE, VertexData.POSITION_SIZE + VertexData.COLOR_SIZE); // Deselect (bind to 0) the VBO GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, GLData.NONE); if (LUtils.debugLevel >= 1) { GLData.notifyOnGLError(StackTraceInfo.getCurrentMethodName()); } } private void createIndexControlVBO() { vbo_i = GL15.glGenBuffers(); GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, vbo_i); GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, indexData, GL15.GL_STATIC_DRAW); GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, GLData.NONE); if (LUtils.debugLevel >= 1) { GLData.notifyOnGLError(StackTraceInfo.getCurrentMethodName()); } } public VBAO draw() { if (tex != null) { tex.bind(); } GL20.glUniform1f(GLData.uniformTexEnabler, (tex == null ? 0 : 1)); // Bind to the VAO that has all the information about the vertices GL30.glBindVertexArray(vaoId); GL20.glEnableVertexAttribArray(POS_VBO_INDEX); GL20.glEnableVertexAttribArray((tex == null) ? COLOR_VBO_INDEX : TEX_VBO_INDEX); GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, vbo_i); vertexDraw(); GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, GLData.NONE); // Put everything back to default (deselect) GL20.glDisableVertexAttribArray(POS_VBO_INDEX); GL20.glDisableVertexAttribArray((tex == null) ? COLOR_VBO_INDEX : TEX_VBO_INDEX); GL30.glBindVertexArray(GLData.NONE); if (tex != null) { tex.unbind(); } if (LUtils.debugLevel >= 1) { GLData.notifyOnGLError(StackTraceInfo.getCurrentMethodName()); } return this; } private void vertexDraw() { // Draw the vertices GL11.glDrawElements(GL11.GL_TRIANGLES, verticesCount, GL11.GL_UNSIGNED_BYTE, 0); if (LUtils.debugLevel >= 1) { GLData.notifyOnGLError(StackTraceInfo.getCurrentMethodName()); } } public void destroy() { // Disable the VBO index from the VAO attributes list GL20.glDisableVertexAttribArray(POS_VBO_INDEX); GL20.glDisableVertexAttribArray(COLOR_VBO_INDEX); GL20.glDisableVertexAttribArray(TEX_VBO_INDEX); deleteVertexVBO(); // Delete the VAO GL30.glBindVertexArray(GLData.NONE); GL30.glDeleteVertexArrays(vaoId); if (LUtils.debugLevel >= 1) { GLData.notifyOnGLError(StackTraceInfo.getCurrentMethodName()); } } private void deleteVertexVBO() { // Delete the VBO GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, GLData.NONE); GL15.glDeleteBuffers(vbo); if (LUtils.debugLevel >= 1) { GLData.notifyOnGLError(StackTraceInfo.getCurrentMethodName()); } } @Override public String toString() { return Arrays.toString(data) + "->" + Arrays.toString(icdata) + " (" + (staticdata ? "static" : "dynamic") + ")"; } @Override public VBAO clone() { VBAO c = null; try { c = (VBAO) super.clone(); c.data = data.clone(); c.icdata = icdata.clone(); c.indexData = indexData.duplicate(); c.tex = tex; c.vaoId = vaoId; c.vbo = vbo; c.vbo_i = vbo_i; c.vertData = vertData.duplicate(); c.verticesCount = verticesCount; c.xyzoffset = xyzoffset; c.staticdata = staticdata; } catch (CloneNotSupportedException e) { throw new InternalError("not clonable"); } return c; } }
package eu.seebetter.ini.chips.davis; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.Rectangle2D; import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuItem; import net.sf.jaer.aemonitor.AEPacketRaw; import net.sf.jaer.biasgen.BiasgenHardwareInterface; import net.sf.jaer.chip.Chip; import net.sf.jaer.chip.RetinaExtractor; import net.sf.jaer.event.ApsDvsEvent; import net.sf.jaer.event.ApsDvsEventPacket; import net.sf.jaer.event.EventPacket; import net.sf.jaer.event.OutputEventIterator; import net.sf.jaer.event.TypedEvent; import net.sf.jaer.graphics.AEFrameChipRenderer; import net.sf.jaer.graphics.ChipRendererDisplayMethodRGBA; import net.sf.jaer.graphics.DisplayMethod; import net.sf.jaer.hardwareinterface.HardwareInterface; import net.sf.jaer.hardwareinterface.HardwareInterfaceException; import net.sf.jaer.util.RemoteControlCommand; import net.sf.jaer.util.RemoteControlled; import net.sf.jaer.util.histogram.AbstractHistogram; import com.jogamp.opengl.GL; import com.jogamp.opengl.GL2; import com.jogamp.opengl.GLAutoDrawable; import com.jogamp.opengl.glu.GLU; import com.jogamp.opengl.glu.GLUquadric; import com.jogamp.opengl.util.awt.TextRenderer; import eu.seebetter.ini.chips.DavisChip; import eu.seebetter.ini.chips.davis.imu.IMUSample; import java.awt.Color; import java.awt.Shape; import java.awt.font.FontRenderContext; import net.sf.jaer.util.TextRendererScale; /** * Abstract base camera class for SeeBetter DAVIS cameras. * * @author tobi */ abstract public class DavisBaseCamera extends DavisChip implements RemoteControlled { public static final String HELP_URL_RETINA = "http://inilabs.com/support/overview-of-dynamic-vision-sensors"; public static final String USER_GUIDE_URL_FLASHY = "https://docs.google.com/a/longi.li/document/d/1LuO-i8u-Y7Nf0zQ-N-Z2LRiKiQMO-EkD3Ln2bmnjhmQ/edit?usp=sharing"; public static final String USER_GUIDE_URL_DAVIS240 = "http: protected final int ADC_NUMBER_OF_TRAILING_ZEROS = Integer.numberOfTrailingZeros(DavisChip.ADC_READCYCLE_MASK); protected final String CMD_EXPOSURE = "exposure"; // protected final String CMD_EXPOSURE_CC = "exposureCC"; // protected final String CMD_RS_SETTLE_CC = "resetSettleCC"; // can be added to sub cameras again if needed, or exposed in DavisDisplayConfigInterface by methods protected AEFrameChipRenderer apsDVSrenderer; protected final AutoExposureController autoExposureController; protected int autoshotThresholdEvents = getPrefs().getInt("autoshotThresholdEvents", 0); protected JMenu chipMenu = null; JFrame controlFrame = null; protected int exposureDurationUs; // internal measured variable, set during rendering. Duration of frame expsosure in /** * holds measured variable in ms for GUI rendering */ protected float exposureMs; /** * Holds count of frames obtained by end of frame events */ protected int frameCount = 0; // reset released) protected int frameExposureEndTimestampUs; // end of exposureControlRegister (first events of signal read) protected int frameExposureStartTimestampUs = 0; // timestamp of first sample from frame (first sample read after protected int frameIntervalUs; // internal measured variable, set during rendering. Time between this frame and // previous one. /** * holds measured variable in Hz for GUI rendering of rate */ protected float frameRateHz; JComponent helpMenuItem1 = null; JComponent helpMenuItem2 = null; JComponent helpMenuItem3 = null; protected IMUSample imuSample; // latest IMUSample from sensor protected boolean isTimestampMaster = true; protected boolean showImageHistogram = getPrefs().getBoolean("showImageHistogram", false); protected boolean snapshot = false; protected JMenuItem syncEnabledMenuItem = null; protected DavisDisplayMethod davisDisplayMethod = null; public DavisBaseCamera() { setName("DAVISBaseCamera"); setEventClass(ApsDvsEvent.class); setNumCellTypes(3); // two are polarity and last is intensity setPixelHeightUm(18.5f); setPixelWidthUm(18.5f); setEventExtractor(new DavisEventExtractor(this)); davisDisplayMethod = new DavisDisplayMethod(this); getCanvas().addDisplayMethod(davisDisplayMethod); getCanvas().setDisplayMethod(davisDisplayMethod); if (getRemoteControl() != null) { getRemoteControl() .addCommandListener(this, CMD_EXPOSURE, CMD_EXPOSURE + " val - sets exposure. val in ms."); // getRemoteControl().addCommandListener(this, CMD_EXPOSURE_CC, // CMD_EXPOSURE_CC + " val - sets exposureControlRegister. val in clock cycles"); // getRemoteControl().addCommandListener(this, CMD_RS_SETTLE_CC, // CMD_RS_SETTLE_CC + " val - sets reset settling time. val in clock cycles"); } autoExposureController = new AutoExposureController(this); } @Override public void controlExposure() { getAutoExposureController().controlExposure(); } /** * Enables or disable DVS128 menu in AEViewer * * @param yes true to enable it */ protected void enableChipMenu(final boolean yes) { if (yes) { if (chipMenu == null) { chipMenu = new JMenu(this.getClass().getSimpleName()); chipMenu.getPopupMenu().setLightWeightPopupEnabled(false); // to paint on GLCanvas chipMenu.setToolTipText("Specialized menu for DAVIS chip"); } if (syncEnabledMenuItem == null) { syncEnabledMenuItem = new JCheckBoxMenuItem("Timestamp master"); syncEnabledMenuItem.setToolTipText("<html>Sets this device as timestamp master"); syncEnabledMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent evt) { Chip.log.info("setting sync/timestamp master to " + syncEnabledMenuItem.isSelected()); isTimestampMaster = syncEnabledMenuItem.isSelected(); updateTSMasterState(); } }); syncEnabledMenuItem.setSelected(isTimestampMaster); updateTSMasterState(); chipMenu.add(syncEnabledMenuItem); } if (getAeViewer() != null) { getAeViewer().addMenu(chipMenu); } } else { // disable menu if (chipMenu != null) { getAeViewer().removeMenu(chipMenu); } } } /** * @return the autoExposureController */ public AutoExposureController getAutoExposureController() { return autoExposureController; } /** * Returns threshold for auto-shot. * * @return events to shoot frame */ @Override public int getAutoshotThresholdEvents() { return autoshotThresholdEvents; } /** * Returns measured exposure time. * * @return exposure time in ms */ @Override public float getMeasuredExposureMs() { return exposureMs; } /** * Returns the frame counter. This value is set on each end-of-frame sample. * It increases without bound and is not affected by rewinding a played-back * recording, for instance. * * @return the frameCount */ @Override public int getFrameCount() { return frameCount; } @Override public int getFrameExposureEndTimestampUs() { return frameExposureEndTimestampUs; } @Override public int getFrameExposureStartTimestampUs() { return frameExposureStartTimestampUs; } @Override public float getFrameRateHz() { return frameRateHz; } /** * Returns the current Inertial Measurement Unit sample. * * @return the imuSample, or null if there is no sample */ public IMUSample getImuSample() { return imuSample; } @Override public int getMaxADC() { return DavisChip.MAX_ADC; } /** * Returns the preferred DisplayMethod, or ChipRendererDisplayMethod if null * preference. * * @return the method, or null. * @see #setPreferredDisplayMethod */ @Override public DisplayMethod getPreferredDisplayMethod() { return new ChipRendererDisplayMethodRGBA(getCanvas()); } @Override public boolean isAutoExposureEnabled() { return getAutoExposureController().isAutoExposureEnabled(); } @Override public boolean isShowImageHistogram() { return showImageHistogram; } public boolean firstFrameAddress(short x, short y) { return (x == (getSizeX() - 1)) && (y == (getSizeY() - 1)); } public boolean lastFrameAddress(short x, short y) { return (x == 0) && (y == 0); //To change body of generated methods, choose Tools | Templates. } @Override public void onDeregistration() { super.onDeregistration(); if (getAeViewer() == null) { return; } getAeViewer().removeHelpItem(helpMenuItem1); getAeViewer().removeHelpItem(helpMenuItem2); getAeViewer().removeHelpItem(helpMenuItem3); enableChipMenu(false); } @Override public void onRegistration() { super.onRegistration(); if (getAeViewer() == null) { return; } helpMenuItem1 = getAeViewer().addHelpURLItem(HELP_URL_RETINA, "Product overview", "Opens product overview guide"); helpMenuItem2 = getAeViewer().addHelpURLItem(USER_GUIDE_URL_DAVIS240, "DAVIS240 user guide", "Opens DAVIS240 user guide"); helpMenuItem3 = getAeViewer().addHelpURLItem(USER_GUIDE_URL_FLASHY, "Flashy user guide", "User guide for external tool flashy for firmware/logic updates to devices using the libusb driver"); enableChipMenu(true); } @Override public String processRemoteControlCommand(final RemoteControlCommand command, final String input) { Chip.log.log(Level.INFO, "processing RemoteControlCommand {0} with input={1}", new Object[]{command, input}); if (command == null) { return null; } final String[] tokens = input.split(" "); if (tokens.length < 2) { return input + ": unknown command - did you forget the argument?"; } if ((tokens[1] == null) || (tokens[1].length() == 0)) { return input + ": argument too short - need a number"; } float v = 0; try { v = Float.parseFloat(tokens[1]); } catch (final NumberFormatException e) { return input + ": bad argument? Caught " + e.toString(); } final String c = command.getCmdName(); if (c.equals(CMD_EXPOSURE)) { getDavisConfig().setExposureDelayMs(v); } else { return input + ": unknown command"; } return "successfully processed command " + input; } @Override public void setAutoExposureEnabled(final boolean yes) { getAutoExposureController().setAutoExposureEnabled(yes); } /** * Sets the measured exposureControlRegister. Does not change parameters, * only used for recording measured quantity. * * @param exposureMs the exposureMs to set */ protected void setMeasuredExposureMs(final float exposureMs) { final float old = this.exposureMs; this.exposureMs = exposureMs; getSupport().firePropertyChange(DavisChip.PROPERTY_MEASURED_EXPOSURE_MS, old, this.exposureMs); } /** * Sets the measured frame rate. Does not change parameters, only used for * recording measured quantity and informing GUI listeners. * * @param frameRateHz the frameRateHz to set */ protected void setFrameRateHz(final float frameRateHz) { final float old = this.frameRateHz; this.frameRateHz = frameRateHz; getSupport().firePropertyChange(DavisChip.PROPERTY_FRAME_RATE_HZ, old, this.frameRateHz); } /** * overrides the Chip setHardware interface to construct a biasgen if one * doesn't exist already. Sets the hardware interface and the bias * generators hardware interface * * @param hardwareInterface the interface */ @Override public void setHardwareInterface(final HardwareInterface hardwareInterface) { this.hardwareInterface = hardwareInterface; try { if (getBiasgen() == null) { setBiasgen(new DavisConfig(this)); // now we can addConfigValue the control panel } else { getBiasgen().setHardwareInterface((BiasgenHardwareInterface) hardwareInterface); } } catch (final ClassCastException e) { Chip.log.warning(e.getMessage() + ": probably this chip object has a biasgen but the hardware interface doesn't, ignoring"); } } @Override public void setShowImageHistogram(final boolean yes) { showImageHistogram = yes; getPrefs().putBoolean("showImageHistogram", yes); } protected void updateTSMasterState() { // Check which logic we are and send the TS Master/Slave command if we are old logic. // TODO: this needs to be done. } /** * The event extractor. Each pixel has two polarities 0 and 1. * * <p> * The bits in the raw data coming from the device are as follows. * <p> * Bit 0 is polarity, on=1, off=0<br> * Bits 1-9 are x address (max value 320)<br> * Bits 10-17 are y address (max value 240) <br> * <p> */ public class DavisEventExtractor extends RetinaExtractor { protected static final long serialVersionUID = 3890914720599660376L; protected int autoshotEventsSinceLastShot = 0; // autoshot counter protected int warningCount = 0; protected static final int WARNING_COUNT_DIVIDER = 10000; public DavisEventExtractor(final DavisBaseCamera chip) { super(chip); } protected IMUSample.IncompleteIMUSampleException incompleteIMUSampleException = null; protected static final int IMU_WARNING_INTERVAL = 1000; protected int missedImuSampleCounter = 0; protected int badImuDataCounter = 0; /** * extracts the meaning of the raw events. * * @param in the raw events, can be null * @return out the processed events. these are partially processed * in-place. empty packet is returned if null is supplied as in. */ @Override synchronized public EventPacket extractPacket(final AEPacketRaw in) { if (!(chip instanceof DavisChip)) { return null; } if (out == null) { out = new ApsDvsEventPacket(chip.getEventClass()); } else { out.clear(); } out.setRawPacket(in); if (in == null) { return out; } final int n = in.getNumEvents(); // addresses.length; int sx1 = chip.getSizeX() - 1; int sy1 = chip.getSizeY() - 1; final int[] datas = in.getAddresses(); final int[] timestamps = in.getTimestamps(); final OutputEventIterator outItr = out.outputIterator(); // NOTE we must make sure we write ApsDvsEvents when we want them, not reuse the IMUSamples // at this point the raw data from the USB IN packet has already been digested to extract timestamps, // including timestamp wrap events and timestamp resets. // The datas array holds the data, which consists of a mixture of AEs and ADC values. // Here we extract the datas and leave the timestamps alone. // TODO entire rendering / processing approach is not very efficient now // System.out.println("Extracting new packet "+out); for (int i = 0; i < n; i++) { // TODO implement skipBy/subsampling, but without missing the frame start/end // events and still delivering frames final int data = datas[i]; if ((incompleteIMUSampleException != null) || ((DavisChip.ADDRESS_TYPE_IMU & data) == DavisChip.ADDRESS_TYPE_IMU)) { if (IMUSample.extractSampleTypeCode(data) == 0) { // / only start getting an IMUSample at code 0, // the first sample type try { final IMUSample possibleSample = IMUSample.constructFromAEPacketRaw(in, i, incompleteIMUSampleException); i += IMUSample.SIZE_EVENTS - 1; incompleteIMUSampleException = null; imuSample = possibleSample; // asking for sample from AEChip now gives this value, but no // access to intermediate IMU samples imuSample.imuSampleEvent = true; outItr.writeToNextOutput(imuSample); // also write the event out to the next output event // slot continue; } catch (final IMUSample.IncompleteIMUSampleException ex) { incompleteIMUSampleException = ex; if ((missedImuSampleCounter++ % DavisEventExtractor.IMU_WARNING_INTERVAL) == 0) { Chip.log.warning(String.format("%s (obtained %d partial samples so far)", ex.toString(), missedImuSampleCounter)); } break; // break out of loop because this packet only contained part of an IMUSample and // formed the end of the packet anyhow. Next time we come back here we will complete // the IMUSample } catch (final IMUSample.BadIMUDataException ex2) { if ((badImuDataCounter++ % DavisEventExtractor.IMU_WARNING_INTERVAL) == 0) { Chip.log.warning(String.format("%s (%d bad samples so far)", ex2.toString(), badImuDataCounter)); } incompleteIMUSampleException = null; continue; // continue because there may be other data } } } else if ((data & DavisChip.ADDRESS_TYPE_MASK) == DavisChip.ADDRESS_TYPE_DVS) { // DVS event final ApsDvsEvent e = nextApsDvsEvent(outItr); if ((data & DavisChip.EVENT_TYPE_MASK) == DavisChip.EXTERNAL_INPUT_EVENT_ADDR) { e.adcSample = -1; // TODO hack to mark as not an ADC sample e.special = true; // TODO special is set here when capturing frames which will mess us up if // this is an IMUSample used as a plain ApsDvsEvent e.address = data; e.timestamp = (timestamps[i]); e.setIsDVS(true); } else { e.adcSample = -1; // TODO hack to mark as not an ADC sample e.special = false; e.address = data; e.timestamp = (timestamps[i]); e.polarity = (data & DavisChip.POLMASK) == DavisChip.POLMASK ? ApsDvsEvent.Polarity.On : ApsDvsEvent.Polarity.Off; e.type = (byte) ((data & DavisChip.POLMASK) == DavisChip.POLMASK ? 1 : 0); e.x = (short) (sx1 - ((data & DavisChip.XMASK) >>> DavisChip.XSHIFT)); e.y = (short) ((data & DavisChip.YMASK) >>> DavisChip.YSHIFT); e.setIsDVS(true); // System.out.println(data); // autoshot triggering autoshotEventsSinceLastShot++; // number DVS events captured here } } else if ((data & DavisChip.ADDRESS_TYPE_MASK) == DavisChip.ADDRESS_TYPE_APS) { // APS event // We first calculate the positions, so we can put events such as StartOfFrame at their // right place, before the actual APS event denoting (0, 0) for example. final int timestamp = timestamps[i]; final short x = (short) (((data & DavisChip.XMASK) >>> DavisChip.XSHIFT)); final short y = (short) ((data & DavisChip.YMASK) >>> DavisChip.YSHIFT); final boolean pixFirst = firstFrameAddress(x, y); // First event of frame (addresses get flipped) final boolean pixLast = lastFrameAddress(x, y); // Last event of frame (addresses get flipped) ApsDvsEvent.ReadoutType readoutType = ApsDvsEvent.ReadoutType.Null; switch ((data & DavisChip.ADC_READCYCLE_MASK) >> ADC_NUMBER_OF_TRAILING_ZEROS) { case 0: readoutType = ApsDvsEvent.ReadoutType.ResetRead; break; case 1: readoutType = ApsDvsEvent.ReadoutType.SignalRead; break; case 3: Chip.log.warning("Event with readout cycle null was sent out!"); break; default: if ((warningCount < 10) || ((warningCount % DavisEventExtractor.WARNING_COUNT_DIVIDER) == 0)) { Chip.log .warning("Event with unknown readout cycle was sent out! You might be reading a file that had the deprecated C readout mode enabled."); } warningCount++; break; } if (pixFirst && (readoutType == ApsDvsEvent.ReadoutType.ResetRead)) { createApsFlagEvent(outItr, ApsDvsEvent.ReadoutType.SOF, timestamp); if (!getDavisConfig().getApsReadoutControl().isGlobalShutterMode()) { // rolling shutter start of exposureControlRegister (SOE) createApsFlagEvent(outItr, ApsDvsEvent.ReadoutType.SOE, timestamp); frameIntervalUs = timestamp - frameExposureStartTimestampUs; frameExposureStartTimestampUs = timestamp; } } if (pixLast && (readoutType == ApsDvsEvent.ReadoutType.ResetRead) && getDavisConfig().getApsReadoutControl().isGlobalShutterMode()) { // global shutter start of exposureControlRegister (SOE) createApsFlagEvent(outItr, ApsDvsEvent.ReadoutType.SOE, timestamp); frameIntervalUs = timestamp - frameExposureStartTimestampUs; frameExposureStartTimestampUs = timestamp; } final ApsDvsEvent e = nextApsDvsEvent(outItr); e.adcSample = data & DavisChip.ADC_DATA_MASK; e.readoutType = readoutType; e.special = false; e.timestamp = timestamp; e.address = data; e.x = x; e.y = y; e.type = (byte) (2); // end of exposureControlRegister, same for both if (pixFirst && (readoutType == ApsDvsEvent.ReadoutType.SignalRead)) { createApsFlagEvent(outItr, ApsDvsEvent.ReadoutType.EOE, timestamp); frameExposureEndTimestampUs = timestamp; exposureDurationUs = timestamp - frameExposureStartTimestampUs; } if (pixLast && (readoutType == ApsDvsEvent.ReadoutType.SignalRead)) { // if we use ResetRead+SignalRead+C readout, OR, if we use ResetRead-SignalRead readout and we // are at last APS pixel, then write EOF event // insert a new "end of frame" event not present in original data createApsFlagEvent(outItr, ApsDvsEvent.ReadoutType.EOF, timestamp); if (snapshot) { snapshot = false; getDavisConfig().getApsReadoutControl().setAdcEnabled(false); } setFrameCount(getFrameCount() + 1); } } } if ((getAutoshotThresholdEvents() > 0) && (autoshotEventsSinceLastShot > getAutoshotThresholdEvents())) { takeSnapshot(); autoshotEventsSinceLastShot = 0; } return out; } // extractPacket // TODO hack to reuse IMUSample events as ApsDvsEvents holding only APS or DVS data by using the special flags protected ApsDvsEvent nextApsDvsEvent(final OutputEventIterator outItr) { final ApsDvsEvent e = (ApsDvsEvent) outItr.nextOutput(); e.special = false; e.adcSample = -1; if (e instanceof IMUSample) { ((IMUSample) e).imuSampleEvent = false; } return e; } /** * creates a special ApsDvsEvent in output packet just for flagging APS * frame markers such as start of frame, reset, end of frame. * * @param outItr * @param flag * @param timestamp * @return */ protected ApsDvsEvent createApsFlagEvent(final OutputEventIterator outItr, final ApsDvsEvent.ReadoutType flag, final int timestamp) { final ApsDvsEvent a = nextApsDvsEvent(outItr); a.adcSample = 0; // set this effectively as ADC sample even though fake a.timestamp = timestamp; a.x = -1; a.y = -1; a.readoutType = flag; return a; } @Override public AEPacketRaw reconstructRawPacket(final EventPacket packet) { if (raw == null) { raw = new AEPacketRaw(); } if (!(packet instanceof ApsDvsEventPacket)) { return null; } final ApsDvsEventPacket apsDVSpacket = (ApsDvsEventPacket) packet; raw.ensureCapacity(packet.getSize()); raw.setNumEvents(0); final int[] a = raw.addresses; final int[] ts = raw.timestamps; apsDVSpacket.getSize(); final Iterator evItr = apsDVSpacket.fullIterator(); int k = 0; while (evItr.hasNext()) { final ApsDvsEvent e = (ApsDvsEvent) evItr.next(); // not writing out these EOF events (which were synthesized on extraction) results in reconstructed // packets with giant time gaps, reason unknown if (e.isEndOfFrame()) { continue; // these EOF events were synthesized from data in first place } ts[k] = e.timestamp; a[k++] = reconstructRawAddressFromEvent(e); } raw.setNumEvents(k); return raw; } /** * To handle filtered ApsDvsEvents, this method rewrites the fields of * the raw address encoding x and y addresses to reflect the event's x * and y fields. * * @param e the ApsDvsEvent * @return the raw address */ @Override public int reconstructRawAddressFromEvent(final TypedEvent e) { int address = e.address; // if(e.x==0 && e.y==0){ // log.info("start of frame event "+e); // if(e.x==-1 && e.y==-1){ // log.info("end of frame event "+e); // e.x came from e.x = (short) (chip.getSizeX()-1-((data & XMASK) >>> XSHIFT)); // for DVS event, no x flip // if APS event if (((ApsDvsEvent) e).adcSample >= 0) { address = (address & ~DavisChip.XMASK) | ((e.x) << DavisChip.XSHIFT); } else { address = (address & ~DavisChip.XMASK) | ((getSizeX() - 1 - e.x) << DavisChip.XSHIFT); } // e.y came from e.y = (short) ((data & YMASK) >>> YSHIFT); address = (address & ~DavisChip.YMASK) | (e.y << DavisChip.YSHIFT); return address; } protected void setFrameCount(final int i) { frameCount = i; } } // extractor /** * Displays data from DAVIS camera * * @author Tobi */ public class DavisDisplayMethod extends ChipRendererDisplayMethodRGBA { private static final int FONTSIZE = 10; private static final int FRAME_COUNTER_BAR_LENGTH_FRAMES = 10; private TextRenderer exposureRenderer = null; public DavisDisplayMethod(final DavisBaseCamera chip) { super(chip.getCanvas()); } @Override public void display(final GLAutoDrawable drawable) { getCanvas().setBorderSpacePixels(50); super.display(drawable); if (exposureRenderer == null) { exposureRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, DavisDisplayMethod.FONTSIZE), true, true); } if (isTimestampMaster == false) { exposureRenderer.setColor(Color.WHITE); exposureRenderer.begin3DRendering(); exposureRenderer.draw3D("Slave camera", 0, -(DavisDisplayMethod.FONTSIZE / 2), 0, .5f); exposureRenderer.end3DRendering(); } if ((getDavisConfig().getVideoControl() != null) && getDavisConfig().getVideoControl().isDisplayFrames()) { final GL2 gl = drawable.getGL().getGL2(); exposureRender(gl); } // draw sample histogram if (showImageHistogram && (renderer instanceof AEFrameChipRenderer)) { // System.out.println("drawing hist"); final int size = 100; final AbstractHistogram hist = ((AEFrameChipRenderer) renderer).getAdcSampleValueHistogram(); final GL2 gl = drawable.getGL().getGL2(); gl.glPushAttrib(GL.GL_COLOR_BUFFER_BIT); gl.glColor3f(0, 0, 1); gl.glLineWidth(1f); hist.draw(drawable, exposureRenderer, (sizeX / 2) - (size / 2), (sizeY / 2) + (size / 2), size, size); gl.glPopAttrib(); } // Draw last IMU output if ((getDavisConfig() != null) && getDavisConfig().isDisplayImu() && (chip instanceof DavisBaseCamera)) { final IMUSample imuSample = ((DavisBaseCamera) chip).getImuSample(); if (imuSample != null) { imuRender(drawable, imuSample); } } } TextRenderer imuTextRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 36)); GLUquadric accelCircle = null; private void imuRender(final GLAutoDrawable drawable, final IMUSample imuSample) { // System.out.println("on rendering: "+imuSample.toString()); final GL2 gl = drawable.getGL().getGL2(); gl.glPushMatrix(); gl.glTranslatef(chip.getSizeX() / 2, chip.getSizeY() / 2, 0); gl.glLineWidth(3); final float vectorScale = 1.5f; final float textScale = TextRendererScale.draw3dScale(imuTextRenderer, "XXX.XXf,%XXX.XXf dps", getChipCanvas().getScale(), getSizeX(), .3f); final float trans = .7f; float x, y; // acceleration x,y x = (vectorScale * imuSample.getAccelX() * getSizeX()) / IMUSample.getFullScaleAccelG(); y = (vectorScale * imuSample.getAccelY() * getSizeY()) / IMUSample.getFullScaleAccelG(); gl.glColor3f(0, 1, 0); gl.glBegin(GL.GL_LINES); gl.glVertex2f(0, 0); gl.glVertex2f(x, y); gl.glEnd(); imuTextRenderer.begin3DRendering(); imuTextRenderer.setColor(0, .5f, 0, trans); imuTextRenderer.draw3D(String.format("%.2f,%.2f g", imuSample.getAccelX(), imuSample.getAccelY()), x, y, 0, textScale); // x,y,z, scale factor imuTextRenderer.end3DRendering(); // acceleration z, drawn as circle if (glu == null) { glu = new GLU(); } if (accelCircle == null) { accelCircle = glu.gluNewQuadric(); } final float az = ((vectorScale * imuSample.getAccelZ() * getSizeY())) / IMUSample.getFullScaleAccelG(); final float rim = .5f; glu.gluQuadricDrawStyle(accelCircle, GLU.GLU_FILL); glu.gluDisk(accelCircle, az - rim, az + rim, 16, 1); imuTextRenderer.begin3DRendering(); imuTextRenderer.setColor(0, .5f, 0, trans); final String saz = String.format("%.2f g", imuSample.getAccelZ()); final Rectangle2D rect = imuTextRenderer.getBounds(saz); imuTextRenderer.draw3D(saz, az, -(float) rect.getHeight() * textScale * 0.5f, 0, textScale); imuTextRenderer.end3DRendering(); // gyro pan/tilt gl.glColor3f(1f, 0, 1); gl.glBegin(GL.GL_LINES); gl.glVertex2f(0, 0); x = (vectorScale * imuSample.getGyroYawY() * getSizeY()) / IMUSample.getFullScaleGyroDegPerSec(); y = (vectorScale * imuSample.getGyroTiltX() * getSizeX()) / IMUSample.getFullScaleGyroDegPerSec(); gl.glVertex2f(x, y); gl.glEnd(); imuTextRenderer.begin3DRendering(); imuTextRenderer.setColor(1f, 0, 1, trans); imuTextRenderer.draw3D(String.format("%.2f,%.2f dps", imuSample.getGyroYawY(), imuSample.getGyroTiltX()), x, y + 5, 0, textScale); // x,y,z, scale factor imuTextRenderer.end3DRendering(); // gyro roll x = (vectorScale * imuSample.getGyroRollZ() * getSizeY()) / IMUSample.getFullScaleGyroDegPerSec(); y = chip.getSizeY() * .25f; gl.glBegin(GL.GL_LINES); gl.glVertex2f(0, y); gl.glVertex2f(x, y); gl.glEnd(); imuTextRenderer.begin3DRendering(); imuTextRenderer.draw3D(String.format("%.2f dps", imuSample.getGyroRollZ()), x, y, 0, textScale); imuTextRenderer.end3DRendering(); // color annotation to show what is being rendered imuTextRenderer.begin3DRendering(); imuTextRenderer.setColor(1, 1, 1, trans); final String ratestr = String.format("IMU: timestamp=%-+9.3fs last dtMs=%-6.1fms avg dtMs=%-6.1fms", 1e-6f * imuSample.getTimestampUs(), imuSample.getDeltaTimeUs() * .001f, IMUSample.getAverageSampleIntervalUs() / 1000); final Rectangle2D raterect = imuTextRenderer.getBounds(ratestr); imuTextRenderer.draw3D(ratestr, -(float) raterect.getWidth() * textScale * 0.5f * .7f, -12, 0, textScale * .7f); // x,y,z, scale factor imuTextRenderer.end3DRendering(); gl.glPopMatrix(); } private void exposureRender(final GL2 gl) { gl.glPushMatrix(); exposureRenderer.setColor(Color.WHITE); exposureRenderer.begin3DRendering(); if (frameIntervalUs > 0) { setFrameRateHz((float) 1000000 / frameIntervalUs); } setMeasuredExposureMs((float) exposureDurationUs / 1000); final String s = String.format("Frame: %d; Exposure %.2f ms; Frame rate: %.2f Hz", getFrameCount(), exposureMs, frameRateHz); float scale = TextRendererScale.draw3dScale(exposureRenderer, s, getChipCanvas().getScale(), getSizeX(), .75f); // determine width of string in pixels and scale accordingly exposureRenderer.draw3D(s, 0, getSizeY() + (DavisDisplayMethod.FONTSIZE / 2), 0, scale); exposureRenderer.end3DRendering(); final int nframes = frameCount % DavisDisplayMethod.FRAME_COUNTER_BAR_LENGTH_FRAMES; final int rectw = getSizeX() / DavisDisplayMethod.FRAME_COUNTER_BAR_LENGTH_FRAMES; gl.glColor4f(1, 1, 1, .5f); for (int i = 0; i < nframes; i++) { gl.glRectf(nframes * rectw, getSizeY() + 1, ((nframes + 1) * rectw) - 3, (getSizeY() + (DavisDisplayMethod.FONTSIZE / 2)) - 1); } gl.glPopMatrix(); } } /** * A convenience method that returns the Biasgen object cast to DavisConfig. * This object contains all configuration of the camera. This method was * added for use in all configuration classes of subclasses fo * DavisBaseCamera. * * @return the configuration object * @author tobi */ protected DavisConfig getDavisConfig() { return (DavisConfig) getBiasgen(); } @Override public void setPowerDown(final boolean powerDown) { getDavisConfig().powerDown.set(powerDown); try { getDavisConfig().sendOnChipConfigChain(); } catch (final HardwareInterfaceException ex) { Logger.getLogger(DavisBaseCamera.class.getName()).log(Level.SEVERE, null, ex); } } /** * Sets threshold for shooting a frame automatically * * @param thresholdEvents the number of events to trigger shot on. Less than * or equal to zero disables auto-shot. */ @Override public void setAutoshotThresholdEvents(int thresholdEvents) { if (thresholdEvents < 0) { thresholdEvents = 0; } autoshotThresholdEvents = thresholdEvents; getPrefs().putInt("DAViS240.autoshotThresholdEvents", thresholdEvents); if (autoshotThresholdEvents == 0) { getDavisConfig().runAdc.set(true); } } @Override public void setADCEnabled(final boolean adcEnabled) { getDavisConfig().getApsReadoutControl().setAdcEnabled(adcEnabled); } /** * Triggers shot of one APS frame */ @Override public void takeSnapshot() { snapshot = true; getDavisConfig().getApsReadoutControl().setAdcEnabled(true); } }
package com.ForgeEssentials.core.misc; import com.ForgeEssentials.core.ForgeEssentials; import com.ForgeEssentials.core.compat.CompatReiMinimap; //import com.ForgeEssentials.economy.Wallet; import com.ForgeEssentials.util.FEChatFormatCodes; import com.ForgeEssentials.util.OutputHandler; import com.ForgeEssentials.economy.Wallet; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.server.MinecraftServer; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.util.ArrayList; import java.util.Date; import cpw.mods.fml.common.FMLCommonHandler; public class LoginMessage { private static ArrayList<String> messageList = new ArrayList<String> (); private static MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); public static void loadFile() { messageList.clear(); File file = new File(ForgeEssentials.FEDIR, "MOTD.txt"); if(file.exists()) { try { FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); while(br.ready()) { String line = br.readLine().trim(); if(!(line.startsWith("#") || line.isEmpty())) { messageList.add(line); } } br.close(); fr.close(); } catch (Exception e) { OutputHandler.info("Error reading the MOTD file."); e.printStackTrace(); } } else { try { file.createNewFile(); PrintWriter pw = new PrintWriter(file); pw.println("# This file contains the message sent to the player on login."); pw.println("# Lines starting with # are not read."); pw.println("# There are several codes that can be used to format the text."); pw.println("# If you want to use color, use this symbol & (ALT code 21) to indicate a color."); pw.println(" pw.println("# Other codes:"); pw.println("# %playername% => The name of the player the message is send to"); //pw.println("# %balance% => Prints the users balance (economy)"); pw.println("# %players% => Amount of players online."); pw.println("# %uptime% => Current server uptime."); pw.println("# %uniqueplayers% => Amount of unique player logins."); pw.println("# %time% => Local server time. All in one string."); pw.println("# %hour% ; %min% ; %sec% => Local server time."); pw.println("# %day% ; %month% ; %year% => Local server date."); pw.println(" pw.println(" pw.println(""); pw.println("Welcome %playername%, to a server running ForgeEssentials."); //personal welcome is nicer :) pw.println("There are %players% players online, and we have had %uniqueplayers% unique players."); pw.println("Server time: %time%. Uptime: %uptime%"); pw.close(); } catch (Exception e) { OutputHandler.info("Error reading the MOTD file."); e.printStackTrace(); } } } public static void sendLoginMessage(ICommandSender sender) { for(int id = 0; id < messageList.size(); id++)//String line : messageList) { if(id == 0) { if(sender instanceof EntityPlayer) { sender.sendChatToPlayer(CompatReiMinimap.reimotd((EntityPlayer) sender) + Format(messageList.get(id),sender.getCommandSenderName()));//only sending the name of the player, going to fix this later so I'm sending everything } else { sender.sendChatToPlayer(Format(messageList.get(id),sender.getCommandSenderName())); } } else { sender.sendChatToPlayer(Format(messageList.get(id),sender.getCommandSenderName())); } } } /** * Formats the chat, replacing given strings by their values * * @param String to parse * the amount to add to the wallet * */ private static String Format(String line,String playerName) //replaces the variables with data { EntityPlayer player = FMLCommonHandler.instance().getSidedDelegate().getServer().getConfigurationManager().getPlayerForUsername(playerName); Date now = new Date(); //int wallet = Wallet.getWallet(player); //needed to return wallet info return line .replaceAll("&", FEChatFormatCodes.CODE.toString()) //color codes .replaceAll("%playername%",player.username) .replaceAll("%players%", online()) //players //.replaceAll("%balance%",wallet + " " + Wallet.currency(wallet))//can be usefull for the user .replaceAll("%uptime%", getUptime()) //uptime .replaceAll("%uniqueplayers%", uniqueplayers()) //unique players .replaceAll("%time%", now.toLocaleString()).replaceAll("%hour%", now.getHours() + "").replaceAll("%min%", now.getMinutes() + "").replaceAll("%sec%", now.getSeconds() + "") //time .replaceAll("%day%", now.getDate() + "").replaceAll("%month%", now.getMonth() + "").replaceAll("%year%", now.getYear() + ""); //date } private static String online() { int online = 0; try { online = server.getCurrentPlayerCount(); } catch (Exception e){} return "" + online; } private static String uniqueplayers() { int logins = 0; try { logins = server.getConfigurationManager().getAvailablePlayerDat().length; } catch (Exception e){} return "" + logins; } private static String getUptime() { String uptime = ""; RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean(); int secsIn = (int) (rb.getUptime() / 1000); int hours = secsIn / 3600, remainder = secsIn % 3600, minutes = remainder / 60, seconds = remainder % 60; uptime += ((hours < 10 ? "0" : "") + hours + " h " + (minutes < 10 ? "0" : "") + minutes + " min " + (seconds < 10 ? "0" : "") + seconds + " sec."); return uptime; } }
package org.voltdb.processtools; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.concurrent.atomic.AtomicBoolean; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; public class ProcessData { private final Session m_ssh_session; private final Channel m_channel; private final StreamWatcher m_out; private final StreamWatcher m_err; private Thread m_sshThread; public enum Stream { STDERR, STDOUT; } public static class OutputLine { public OutputLine(String processName, Stream stream, String value) { this.processName = processName; this.stream = stream; this.message = value; } public final String processName; public final Stream stream; public final String message; } class StreamWatcher extends Thread { final BufferedReader m_reader; final String m_processName; final Stream m_stream; final OutputHandler m_handler; final AtomicBoolean m_expectDeath = new AtomicBoolean(false); StreamWatcher(BufferedReader reader, String processName, Stream stream, OutputHandler handler) { assert(reader != null); m_reader = reader; m_processName = processName; m_stream = stream; m_handler = handler; } void setExpectDeath(boolean expectDeath) { m_expectDeath.set(expectDeath); } @Override public void run() { while (true) { String line = null; try { line = m_reader.readLine(); } catch (IOException e) { if (!m_expectDeath.get()) { e.printStackTrace(); System.err.print("Err Stream monitoring thread exiting."); System.err.flush(); } return; } if (line != null) { OutputLine ol = new OutputLine(m_processName, m_stream, line); if (m_handler != null) { m_handler.update(ol); } else { final long now = (System.currentTimeMillis() / 1000) - 1256158053; System.out.println("(" + now + ")" + m_processName + ": " + line); } } else { return; } } } } ProcessData(String processName, OutputHandler handler, Session ssh_session, final String command) throws JSchException, IOException { m_ssh_session = ssh_session; m_channel=ssh_session.openChannel("exec"); ((ChannelExec)m_channel).setCommand(command); // Set up the i/o streams m_channel.setInputStream(null); BufferedReader out = new BufferedReader(new InputStreamReader(m_channel.getInputStream())); BufferedReader err = new BufferedReader(new InputStreamReader(((ChannelExec) m_channel).getErrStream())); m_out = new StreamWatcher(out, processName, Stream.STDOUT, handler); m_err = new StreamWatcher(err, processName, Stream.STDERR, handler); /* * Execute the command non-blocking. */ m_sshThread = new Thread() { @Override public void run() { try { m_channel.connect(); m_out.start(); m_err.start(); } catch (Exception e) { e.printStackTrace(); System.err.print("Err SSH long-running execution thread exiting."); System.err.flush(); } } }; m_sshThread.start(); } public int kill() { m_out.m_expectDeath.set(true); m_err.m_expectDeath.set(true); int retval = -255; synchronized(m_channel) { m_channel.disconnect(); m_ssh_session.disconnect(); } m_sshThread.interrupt(); return retval; } public boolean isAlive() { synchronized(m_channel) { return (m_ssh_session.isConnected() && m_channel.getExitStatus() == -1); } } }
package com.ecyrd.jspwiki; import java.util.Properties; import javax.servlet.*; import java.io.*; /** * Simple test engine that always assumes pages are found. */ public class TestEngine extends WikiEngine { public TestEngine( Properties props ) throws NoRequiredPropertyException, ServletException { super( props ); } public boolean pageExists( String page ) { return true; } /** * Deletes all files under this directory, and does them recursively. */ public static void deleteAll( File file ) { if( file.isDirectory() ) { File[] files = file.listFiles(); for( int i = 0; i < files.length; i++ ) { if( files[i].isDirectory() ) { deleteAll(files[i]); } files[i].delete(); } } file.delete(); } }
package jade.tools.SocketProxyAgent; import jade.core.Agent; import jade.lang.acl.*; import jade.core.behaviours.SimpleBehaviour; import java.net.*; import java.io.*; import java.util.*; /** Javadoc documentation for the file @author Fabio Bellifemine - CSELT S.p.A @version $Date$ $Revision$ */ public class SocketProxyAgent extends Agent { BufferedWriter logFile; BufferedReader in; Server s; protected void setup() { try { in = new BufferedReader(new FileReader(getLocalName()+".inf")); logFile = new BufferedWriter(new FileWriter(getLocalName()+".log")); int portNumber = Integer.parseInt(in.readLine()); Vector agentNames = new Vector(); StringTokenizer st = new StringTokenizer(in.readLine()); while (st.hasMoreTokens()) agentNames.add(st.nextToken()); s = new Server(portNumber, this, agentNames); } catch(Exception e) { System.err.println(getLocalName()+" NEEDS THE FILE "+getLocalName()+".inf IN THE WORKING DIRECTORY WITH ITS PARAMETERS (port number and agent names)"); e.printStackTrace(); doDelete(); } } protected void takeDown(){ try { if (in != null) in.close(); } catch (Exception e) {} try { if (logFile != null) logFile.close(); } catch (Exception e) {} try { if (s != null) s.stop(); } catch (Exception e) {} } public synchronized void log(String str) { try { logFile.write(str,0,str.length()); } catch (IOException e) { e.printStackTrace(); doDelete(); } } } class Server extends Thread { private final static int DEFAULT_PORT = 6789; private ServerSocket listen_socket; private Agent myAgent; private Vector myOnlyReceivers; /** * Constructor of the class. * It creates a ServerSocket to listen for connections on. * @param port is the port number to listen for. If 0, then it uses * the default port number. * @param a is the pointer to agent to be used to send messages. * @param receiver is the vector with the names of all the agents that * wish to receive messages through this proxy. */ Server(int port, Agent a, Vector receivers) { if (port == 0) port = DEFAULT_PORT; myAgent = a; myOnlyReceivers = receivers; try { listen_socket = new ServerSocket(port); } catch (IOException e) {e.printStackTrace(); myAgent.doDelete(); return;} String str = myAgent.getLocalName()+" is listening on port "+port+" to proxy messages to agents ("; for (int i=0; i<myOnlyReceivers.size(); i++) str.concat((String)myOnlyReceivers.elementAt(i)+" "); str.concat(")"); System.out.println(str); ((SocketProxyAgent)myAgent).log(str); start(); } Socket client_socket; Connection c; /** * The body of the server thread. It is executed when the start() method * of the server object is called. * Loops forever, listening for and accepting connections from clients. * For each connection, creates a Connection object to handle communication * through the new Socket. Each Connection object is a new thread. * The maximum queue length for incoming connection indications * (a request to connect) is set to 50 (that is the default for the * ServerSocket constructor). If a connection indication * arrives when the queue is full, the connection is refused. */ public void run() { try { while (true) { client_socket = listen_socket.accept(); ((SocketProxyAgent)myAgent).log("New Connection with "+client_socket.getInetAddress().toString()+" on remote port "+client_socket.getPort()); c = new Connection(client_socket,myAgent,myOnlyReceivers); } } catch (IOException e) {e.printStackTrace(); myAgent.doDelete();} } protected void finalize() { try { if (listen_socket != null) listen_socket.close(); } catch (Exception e) {} try { if (client_socket != null) client_socket.close(); } catch (Exception e) {} try { if (c != null) c.stop(); } catch (Exception e) {} } } class Connection extends Thread { private Agent myAgent; private Socket client; private DataInputStream in; private PrintStream out; /** Name of the agents who intend to receive any message from this agent */ private Vector myOnlyReceivers; Connection(Socket client_socket, Agent a, Vector receivers) { myAgent = a; client = client_socket; myOnlyReceivers = receivers; try { in = new DataInputStream(client.getInputStream()); out = new PrintStream(client.getOutputStream(),true); } catch (IOException e) { try { client.close();} catch (IOException e2) {} e.printStackTrace(); return; } start(); } private boolean myOnlyReceiversContains(String aName) { for (int i=0; i<myOnlyReceivers.size(); i++) if ( ((String)myOnlyReceivers.elementAt(i)).equalsIgnoreCase(aName) ) return true; return false; } public void run() { String line; try { //ACLParser parser = new ACLParser(in); ACLMessage msg; while (true) { msg = ACLMessage.fromText(new InputStreamReader(in)); // parser.Message(); if (myOnlyReceiversContains(msg.getDest())) { msg.setSource(myAgent.getLocalName()); if ((msg.getReplyWith() == null) || (msg.getReplyWith().length()<1)) msg.setReplyWith(myAgent.getLocalName()+"."+getName()+"."+java.lang.System.currentTimeMillis()); myAgent.send(msg); myAgent.addBehaviour(new WaitAnswersBehaviour(myAgent,msg,out)); } else { out.println("(refuse :content unauthorised)"); close(null); return; } } } catch(ParseException e) { close(e); return; } } void close(Exception e){ try { client.close(); } catch (IOException e2) {} e.printStackTrace(); } protected void finalize() { try { if (client != null) client.close(); } catch (Exception e) {} try { if (in != null) in.close(); } catch (Exception e) {} try { if (out != null) out.close(); } catch (Exception e) {} } } class WaitAnswersBehaviour extends SimpleBehaviour { ACLMessage msg; PrintStream out; long timeout,blockTime,endingTime; final static long DEFAULT_TIMEOUT = 600000; // 10 minutes boolean finished; MessageTemplate mt; WaitAnswersBehaviour(Agent a, ACLMessage m, PrintStream o) { super(a); out = o; mt = MessageTemplate.and(MessageTemplate.MatchSource(m.getDest()),MessageTemplate.MatchReplyTo(m.getReplyWith())); timeout = m.getReplyByDate().getTime()-(new Date()).getTime(); if (timeout <= 1000) timeout = DEFAULT_TIMEOUT; endingTime = System.currentTimeMillis() + timeout; finished = false; } public void action() { msg = myAgent.receive(mt); if (msg == null) { blockTime = endingTime - System.currentTimeMillis(); if (blockTime <= 0) finished=true; else block(blockTime); return; } out.println(msg.toString()); //System.err.println(myAgent.getLocalName()+" sent "+msg.toString()); } public boolean done() { return finished; } }
package com.threerings.jme.input; import com.jme.math.FastMath; import com.jme.math.Matrix3f; import com.jme.math.Vector3f; import com.jme.renderer.Camera; import com.jme.input.InputHandler; import com.jme.input.InputSystem; import com.jme.input.KeyBindingManager; import com.jme.input.KeyInput; import com.jme.input.RelativeMouse; import com.jme.input.action.*; import com.jme.input.action.InputActionEvent; import com.threerings.jme.JmeApp; import com.threerings.jme.Log; /** * Sets up camera controls for moving around from a top-down perspective, * suitable for strategy games and their ilk. The "ground" is assumed to * be the XY plane. */ public class GodViewHandler extends InputHandler { /** * Creates the handler. * * @param cam The camera to move with this handler. * @param api The API from which to create a KeyBindingManager. */ public GodViewHandler (Camera cam, String api) { _camera = cam; setKeyBindings(api); addActions(cam); } /** * Configures the minimum and maximum z-axis elevation allowed for the * camera. */ public void setZoomLimits (float minZ, float maxZ) { _minZ = minZ; _maxZ = maxZ; } /** * Configures limits on the camera roll. */ public void setRollLimits (float minAngle, float maxAngle) { _minRoll = minAngle; _maxRoll = maxAngle; } /** * Configures limits on the distance the camera can be panned. */ public void setPanLimits (float minX, float minY, float maxX, float maxY) { _minX = minX; _minY = minY; _maxX = maxX; _maxY = maxY; } /** * Sets the camera zoom level to a value between zero (zoomed in * maximally) and 1 (zoomed out maximally). Zoom limits must have * already been set up via a call to {@link #setZoomLimits}. */ public void setZoomLevel (float level) { // Log.info("Zoom " + level + " " + _camera.getLocation()); level = Math.max(0f, Math.min(level, 1f)); _camera.getLocation().z = _minZ + (_maxZ - _minZ) * level; _camera.update(); } /** * Returns the current camera zoom level. */ public float getZoomLevel () { return (_camera.getLocation().z - _minZ) / (_maxZ - _minZ); } /** * Swings the camera around the point on the ground at which it is * "looking", by the requested angle (in radians). */ public void rotateCamera (float deltaAngle) { rotateCamera(_groundNormal, deltaAngle); } protected void setKeyBindings (String api) { KeyBindingManager keyboard = KeyBindingManager.getKeyBindingManager(); InputSystem.createInputSystem(api); keyboard.setKeyInput(InputSystem.getKeyInput()); // the key bindings for the pan actions keyboard.set("forward", KeyInput.KEY_W); keyboard.set("backward", KeyInput.KEY_S); keyboard.set("left", KeyInput.KEY_A); keyboard.set("right", KeyInput.KEY_D); // the key bindings for the zoom actions keyboard.set("zoomIn", KeyInput.KEY_UP); keyboard.set("zoomOut", KeyInput.KEY_DOWN); // the key bindings for the orbit actions keyboard.set("turnRight", KeyInput.KEY_RIGHT); keyboard.set("turnLeft", KeyInput.KEY_LEFT); // the key bindings for the roll actions keyboard.set("rollForward", KeyInput.KEY_HOME); keyboard.set("rollBack", KeyInput.KEY_END); keyboard.set("screenshot", KeyInput.KEY_F12); setKeyBindingManager(keyboard); } protected void addActions (Camera cam) { KeyScreenShotAction screen = new KeyScreenShotAction(); screen.setKey("screenshot"); addAction(screen); addPanActions(cam); addZoomActions(cam); addOrbitActions(cam); addRollActions(cam); } /** * Adds actions for panning the camera around the scene. */ protected void addPanActions (Camera cam) { CameraAction forward = new CameraAction(cam, 0.5f) { public void performAction (InputActionEvent evt) { Vector3f loc = _camera.getLocation(); loc.addLocal(_rydir.mult(speed * evt.getTime(), _temp)); _camera.setLocation(boundPan(loc)); _camera.update(); } }; forward.setKey("forward"); addAction(forward); CameraAction backward = new CameraAction(cam, 0.5f) { public void performAction (InputActionEvent evt) { Vector3f loc = _camera.getLocation(); loc.subtractLocal(_rydir.mult(speed * evt.getTime(), _temp)); _camera.setLocation(boundPan(loc)); _camera.update(); } }; backward.setKey("backward"); addAction(backward); CameraAction left = new CameraAction(cam, 0.5f) { public void performAction (InputActionEvent evt) { Vector3f loc = _camera.getLocation(); loc.subtractLocal(_rxdir.mult(speed * evt.getTime(), _temp)); _camera.setLocation(boundPan(loc)); _camera.update(); } }; left.setKey("left"); addAction(left); CameraAction right = new CameraAction(cam, 0.5f) { public void performAction (InputActionEvent evt) { Vector3f loc = _camera.getLocation(); loc.addLocal(_rxdir.mult(speed * evt.getTime(), _temp)); _camera.setLocation(boundPan(loc)); _camera.update(); } }; right.setKey("right"); addAction(right); } /** * Adds actions for zooming the camaera in and out. */ protected void addZoomActions (Camera cam) { CameraAction zoomIn = new CameraAction(cam, 0.5f) { public void performAction (InputActionEvent evt) { Vector3f loc = _camera.getLocation(); if (loc.z > _minZ) { _camera.getDirection().mult(speed * evt.getTime(), _temp); loc.addLocal(_temp); _camera.setLocation(boundPan(loc)); _camera.update(); } } }; zoomIn.setKey("zoomIn"); addAction(zoomIn); CameraAction zoomOut = new CameraAction(cam, 0.5f) { public void performAction (InputActionEvent evt) { Vector3f loc = _camera.getLocation(); if (loc.z < _maxZ) { _camera.getDirection().mult(speed * evt.getTime(), _temp); loc.subtractLocal(_temp); _camera.setLocation(boundPan(loc)); _camera.update(); } } }; zoomOut.setKey("zoomOut"); addAction(zoomOut); } /** * Adds actions for orbiting the camera around the viewpoint. */ protected void addOrbitActions (Camera cam) { OrbitAction orbitRight = new OrbitAction(-FastMath.PI / 2); orbitRight.setKey("turnRight"); addAction(orbitRight); OrbitAction orbitLeft = new OrbitAction(FastMath.PI / 2); orbitLeft.setKey("turnLeft"); addAction(orbitLeft); } /** * Adds actions for rolling the camera around the yaw axis. */ protected void addRollActions (Camera cam) { RollAction rollForward = new RollAction(-FastMath.PI / 2); rollForward.setKey("rollForward"); addAction(rollForward); RollAction rollBack = new RollAction(FastMath.PI / 2); rollBack.setKey("rollBack"); addAction(rollBack); } /** * Locates the point on the ground at which the camera is "looking" * and rotates the camera from that point around the specified vector * by the specified angle. */ protected void rotateCamera (Vector3f around, float deltaAngle) { // locate the point at which the camera is "pointing" on // the ground plane Vector3f camloc = _camera.getLocation(); Vector3f center = groundPoint(_camera); // get a vector from the camera's position to the point // around which we're going to orbit Vector3f direction = camloc.subtract(center); // create a rotation matrix _rotm.fromAxisAngle(around, deltaAngle); // rotate the center to camera vector and the camera itself _rotm.mult(direction, direction); _rotm.mult(_camera.getUp(), _camera.getUp()); _rotm.mult(_camera.getLeft(), _camera.getLeft()); _rotm.mult(_camera.getDirection(), _camera.getDirection()); if (around == _groundNormal) { _rotm.mult(_rxdir, _rxdir); _rotm.mult(_rydir, _rydir); } // and move the camera to its new location _camera.setLocation(boundPan(center.add(direction))); _camera.update(); } protected static Vector3f groundPoint (Camera camera) { float dist = -1f * _groundNormal.dot(camera.getLocation()) / _groundNormal.dot(camera.getDirection()); return camera.getLocation().add(camera.getDirection().mult(dist)); } protected Vector3f boundPan (Vector3f loc) { loc.x = Math.max(Math.min(loc.x, _maxX), _minX); loc.y = Math.max(Math.min(loc.y, _maxY), _minY); return loc; } protected abstract class CameraAction extends KeyInputAction { public CameraAction (Camera camera, float speed) { _camera = camera; this.speed = speed; } /** The camera to manipulate. */ protected Camera _camera; /** A temporary vector. */ protected Vector3f _temp = new Vector3f(); } protected class OrbitAction extends KeyInputAction { public OrbitAction (float radPerSec) { _radPerSec = radPerSec; } public void performAction (InputActionEvent evt) { rotateCamera(_groundNormal, _radPerSec * evt.getTime()); } protected float _radPerSec; } protected class RollAction extends KeyInputAction { public RollAction (float radPerSec) { _radPerSec = radPerSec; } public void performAction (InputActionEvent evt) { rotateCamera(_camera.getLeft(), _radPerSec * evt.getTime()); } protected float _radPerSec; } protected Camera _camera; protected Matrix3f _rotm = new Matrix3f(); protected float _minX = Float.MIN_VALUE, _maxX = Float.MAX_VALUE; protected float _minY = Float.MIN_VALUE, _maxY = Float.MAX_VALUE; protected float _minZ = Float.MIN_VALUE, _maxZ = Float.MAX_VALUE; protected float _minRoll = Float.MIN_VALUE, _maxRoll = Float.MAX_VALUE; protected static final Vector3f _xdir = new Vector3f(1, 0, 0); protected static final Vector3f _ydir = new Vector3f(0, 1, 0); protected static final Vector3f _rxdir = new Vector3f(1, 0, 0); protected static final Vector3f _rydir = new Vector3f(0, 1, 0); protected static final Vector3f _groundNormal = new Vector3f(0, 0, 1); }
// $Id: IsoUtil.java,v 1.36 2002/06/27 01:27:13 ray Exp $ package com.threerings.miso.scene.util; import java.awt.Point; import java.awt.Polygon; import java.awt.Rectangle; import com.samskivert.swing.SmartPolygon; import com.threerings.media.sprite.Sprite; import com.threerings.media.tile.ObjectTile; import com.threerings.media.util.MathUtil; import com.threerings.util.DirectionCodes; import com.threerings.util.DirectionUtil; import com.threerings.miso.Log; import com.threerings.miso.scene.IsoSceneViewModel; import com.threerings.miso.scene.MisoCharacterSprite; /** * The <code>IsoUtil</code> class is a holding place for miscellaneous * isometric-display-related utility routines. */ public class IsoUtil implements DirectionCodes { /** * Sets the given character sprite's tile and fine coordinate * locations within the scene based on the sprite's current screen * pixel coordinates. This method should be called whenever a * {@link MisoCharacterSprite} is first created, but after its * location has been set via {@link Sprite#setLocation}. */ public static void setSpriteSceneLocation ( IsoSceneViewModel model, MisoCharacterSprite sprite) { // get the sprite's position in full coordinates Point fpos = new Point(); screenToFull(model, sprite.getX(), sprite.getY(), fpos); // set the sprite's tile and fine coordinates sprite.setTileLocation( IsoUtil.fullToTile(fpos.x), IsoUtil.fullToTile(fpos.y)); sprite.setFineLocation( IsoUtil.fullToFine(fpos.x), IsoUtil.fullToFine(fpos.y)); } /** * Returns a polygon bounding all footprint tiles of the given * object tile. * * @param model the scene view model. * @param tx the x tile-coordinate of the object tile. * @param ty the y tile-coordinate of the object tile. * @param tile the object tile. * * @return the bounding polygon. */ public static Polygon getObjectFootprint ( IsoSceneViewModel model, int tx, int ty, ObjectTile tile) { Polygon boundsPoly = new SmartPolygon(); Point tpos = tileToScreen(model, tx, ty, new Point()); int bwid = tile.getBaseWidth(), bhei = tile.getBaseHeight(); int oox = tpos.x + model.tilehwid, ooy = tpos.y + model.tilehei; int rx = oox, ry = ooy; // bottom-center point boundsPoly.addPoint(rx, ry); // left point rx -= bwid * model.tilehwid; ry -= bwid * model.tilehhei; boundsPoly.addPoint(rx, ry); // top-center point rx += bhei * model.tilehwid; ry -= bhei * model.tilehhei; boundsPoly.addPoint(rx, ry); // right point rx += bwid * model.tilehwid; ry += bwid * model.tilehhei; boundsPoly.addPoint(rx, ry); // bottom-center point boundsPoly.addPoint(rx, ry); return boundsPoly; } /** * Returns a polygon bounding the given object tile display image, * with the bottom of the polygon shaped to conform to the known * object dimensions. This is currently not used. * * @param model the scene view model. * @param tx the x tile-coordinate of the object tile. * @param ty the y tile-coordinate of the object tile. * @param tile the object tile. * * @return the bounding polygon. */ public static Polygon getTightObjectBounds ( IsoSceneViewModel model, int tx, int ty, ObjectTile tile) { Point tpos = tileToScreen(model, tx, ty, new Point()); // if the tile has an origin, use that, otherwise compute the // origin based on the tile footprint int tox = tile.getOriginX(), toy = tile.getOriginY(); if (tox == -1 || toy == -1) { tox = tile.getBaseWidth() * model.tilehwid; toy = tile.getHeight(); } float slope = (float)model.tilehei / (float)model.tilewid; int oox = tpos.x + model.tilehwid, ooy = tpos.y + model.tilehei; int sx = oox - tox, sy = ooy - toy; Polygon boundsPoly = new SmartPolygon(); int rx = sx, ry = sy; // top-left point boundsPoly.addPoint(rx, ry); // top-right point rx = sx + tile.getWidth(); boundsPoly.addPoint(rx, ry); // bottom-right point ry = ooy - (int)((rx-oox) * slope); boundsPoly.addPoint(rx, ry); // bottom-middle point boundsPoly.addPoint(tpos.x + model.tilehwid, tpos.y + model.tilehei); // bottom-left point rx = sx; ry = ooy - (int)(tox * slope); boundsPoly.addPoint(rx, ry); // top-left point boundsPoly.addPoint(sx, sy); return boundsPoly; } /** * Returns a rectangle that encloses the entire object image, with the * upper left set to the appropriate values for rendering the object * image. * * @param model the scene view model. * @param tx the x tile-coordinate of the object tile. * @param ty the y tile-coordinate of the object tile. * @param tile the object tile. * * @return the bounding rectangle. */ public static Rectangle getObjectBounds ( IsoSceneViewModel model, int tx, int ty, ObjectTile tile) { Point tpos = tileToScreen(model, tx, ty, new Point()); // if the tile has an origin, use that, otherwise compute the // origin based on the tile footprint int tox = tile.getOriginX(), toy = tile.getOriginY(); if (tox == Integer.MIN_VALUE) { tox = tile.getBaseWidth() * model.tilehwid; } if (toy == Integer.MIN_VALUE) { toy = tile.getHeight(); } int oox = tpos.x + model.tilehwid, ooy = tpos.y + model.tilehei; int sx = oox - tox, sy = ooy - toy; return new Rectangle(sx, sy, tile.getWidth(), tile.getHeight()); } /** * Returns true if the footprints of the two object tiles overlap when * the objects occupy the specified coordinates, false if not. */ public static boolean objectFootprintsOverlap ( ObjectTile tile1, int x1, int y1, ObjectTile tile2, int x2, int y2) { return (x2 > x1 - tile1.getBaseWidth() && x1 > x2 - tile2.getBaseWidth() && y2 > y1 - tile1.getBaseHeight() && y1 > y2 - tile2.getBaseHeight()); } /** * Given two points in screen pixel coordinates, return the * compass direction that point B lies in from point A from an * isometric perspective. * * @param ax the x-position of point A. * @param ay the y-position of point A. * @param bx the x-position of point B. * @param by the y-position of point B. * * @return the direction specified as one of the <code>Sprite</code> * class's direction constants. */ public static int getDirection ( IsoSceneViewModel model, int ax, int ay, int bx, int by) { Point afpos = new Point(), bfpos = new Point(); // convert screen coordinates to full coordinates to get both // tile coordinates and fine coordinates screenToFull(model, ax, ay, afpos); screenToFull(model, bx, by, bfpos); // pull out the tile coordinates for each point int tax = afpos.x / FULL_TILE_FACTOR; int tay = afpos.y / FULL_TILE_FACTOR; int tbx = bfpos.x / FULL_TILE_FACTOR; int tby = bfpos.y / FULL_TILE_FACTOR; // compare tile coordinates to determine direction int dir = getIsoDirection(tax, tay, tbx, tby); if (dir != DirectionCodes.NONE) { return dir; } // destination point is in the same tile as the // origination point, so consider fine coordinates // pull out the fine coordinates for each point int fax = afpos.x - (tax * FULL_TILE_FACTOR); int fay = afpos.y - (tay * FULL_TILE_FACTOR); int fbx = bfpos.x - (tbx * FULL_TILE_FACTOR); int fby = bfpos.y - (tby * FULL_TILE_FACTOR); // compare fine coordinates to determine direction dir = getIsoDirection(fax, fay, fbx, fby); // arbitrarily return southwest if fine coords were also equivalent return (dir == -1) ? SOUTHWEST : dir; } /** * Given two points in an isometric coordinate system (in which {@link * NORTH} is in the direction of the negative x-axis and {@link WEST} * in the direction of the negative y-axis), return the compass * direction that point B lies in from point A. This method is used * to determine direction for both tile coordinates and fine * coordinates within a tile, since the coordinate systems are the * same. * * @param ax the x-position of point A. * @param ay the y-position of point A. * @param bx the x-position of point B. * @param by the y-position of point B. * * @return the direction specified as one of the <code>Sprite</code> * class's direction constants, or <code>DirectionCodes.NONE</code> if * point B is equivalent to point A. */ public static int getIsoDirection (int ax, int ay, int bx, int by) { // head off a div by 0 at the pass.. if (bx == ax) { if (by == ay) { return DirectionCodes.NONE; } return (by < ay) ? EAST : WEST; } // figure direction base on the slope of the line float slope = ((float) (ay - by)) / ((float) Math.abs(ax - bx)); if (slope > 2f) { return EAST; } if (slope > .5f) { return (bx < ax) ? NORTHEAST : SOUTHEAST; } if (slope > -.5f) { return (bx < ax) ? NORTH : SOUTH; } if (slope > -2f) { return (bx < ax) ? NORTHWEST : SOUTHWEST; } return WEST; } /** * Given two points in screen coordinates, return the isometrically * projected compass direction that point B lies in from point A. * * @param ax the x-position of point A. * @param ay the y-position of point A. * @param bx the x-position of point B. * @param by the y-position of point B. * * @return the direction specified as one of the <code>Sprite</code> * class's direction constants, or <code>DirectionCodes.NONE</code> if * point B is equivalent to point A. */ public static int getProjectedIsoDirection (int ax, int ay, int bx, int by) { return toIsoDirection(DirectionUtil.getDirection(ax, ay, bx, by)); } /** * Converts a non-isometric orientation (where north points toward the * top of the screen) to an isometric orientation where north points * toward the upper-left corner of the screen. */ public static int toIsoDirection (int dir) { if (dir != DirectionCodes.NONE) { // rotate the direction clockwise (ie. change SOUTHEAST to // SOUTH) dir = DirectionUtil.rotateCW(dir, 2); } return dir; } /** * Returns the tile coordinate of the given full coordinate. */ public static int fullToTile (int val) { return (val / FULL_TILE_FACTOR); } /** * Returns the fine coordinate of the given full coordinate. */ public static int fullToFine (int val) { return (val - ((val / FULL_TILE_FACTOR) * FULL_TILE_FACTOR)); } /** * Convert the given screen-based pixel coordinates to their * corresponding tile-based coordinates. Converted coordinates * are placed in the given point object. * * @param sx the screen x-position pixel coordinate. * @param sy the screen y-position pixel coordinate. * @param tpos the point object to place coordinates in. * * @return the point instance supplied via the <code>tpos</code> * parameter. */ public static Point screenToTile ( IsoSceneViewModel model, int sx, int sy, Point tpos) { // determine the upper-left of the quadrant that contains our // point int zx = (int)Math.floor((float)(sx - model.origin.x) / model.tilewid); int zy = (int)Math.floor((float)(sy - model.origin.y) / model.tilehei); // these are the screen coordinates of the tile's top int ox = (zx * model.tilewid + model.origin.x), oy = (zy * model.tilehei + model.origin.y); // these are the tile coordinates tpos.x = zy + zx; tpos.y = zy - zx; // now determine which of the four tiles our point occupies int dx = sx - ox, dy = sy - oy; if (Math.round(model.slopeY * dx + model.tilehei) <= dy) { tpos.x += 1; } if (Math.round(model.slopeX * dx) > dy) { tpos.y -= 1; } // Log.info("Converted [sx=" + sx + ", sy=" + sy + // ", zx=" + zx + ", zy=" + zy + // ", ox=" + ox + ", oy=" + oy + // ", dx=" + dx + ", dy=" + dy + // ", tpos.x=" + tpos.x + ", tpos.y=" + tpos.y + "]."); return tpos; } /** * Convert the given tile-based coordinates to their corresponding * screen-based pixel coordinates. Converted coordinates are * placed in the given point object. * * @param x the tile x-position coordinate. * @param y the tile y-position coordinate. * @param spos the point object to place coordinates in. * * @return the point instance supplied via the <code>spos</code> * parameter. */ public static Point tileToScreen ( IsoSceneViewModel model, int x, int y, Point spos) { spos.x = model.origin.x + ((x - y - 1) * model.tilehwid); spos.y = model.origin.y + ((x + y) * model.tilehhei); return spos; } /** * Convert the given fine coordinates to pixel coordinates within * the containing tile. Converted coordinates are placed in the * given point object. * * @param x the x-position fine coordinate. * @param y the y-position fine coordinate. * @param ppos the point object to place coordinates in. */ public static void fineToPixel ( IsoSceneViewModel model, int x, int y, Point ppos) { ppos.x = model.tilehwid + ((x - y) * model.finehwid); ppos.y = (x + y) * model.finehhei; } /** * Convert the given pixel coordinates, whose origin is at the * top-left of a tile's containing rectangle, to fine coordinates * within that tile. Converted coordinates are placed in the * given point object. * * @param x the x-position pixel coordinate. * @param y the y-position pixel coordinate. * @param fpos the point object to place coordinates in. */ public static void pixelToFine ( IsoSceneViewModel model, int x, int y, Point fpos) { // calculate line parallel to the y-axis (from the given // x/y-pos to the x-axis) float bY = y - (model.fineSlopeY * x); // determine intersection of x- and y-axis lines int crossx = (int)((bY - model.fineBX) / (model.fineSlopeX - model.fineSlopeY)); int crossy = (int)((model.fineSlopeY * crossx) + bY); // TODO: final position should check distance between our // position and the surrounding fine coords and return the // actual closest fine coord, rather than just dividing. // determine distance along the x-axis float xdist = MathUtil.distance(model.tilehwid, 0, crossx, crossy); fpos.x = (int)(xdist / model.finelen); // determine distance along the y-axis float ydist = MathUtil.distance(x, y, crossx, crossy); fpos.y = (int)(ydist / model.finelen); } /** * Convert the given screen-based pixel coordinates to full * scene-based coordinates that include both the tile coordinates * and the fine coordinates in each dimension. Converted * coordinates are placed in the given point object. * * @param sx the screen x-position pixel coordinate. * @param sy the screen y-position pixel coordinate. * @param fpos the point object to place coordinates in. * * @return the point passed in to receive the coordinates. */ public static Point screenToFull ( IsoSceneViewModel model, int sx, int sy, Point fpos) { // get the tile coordinates Point tpos = new Point(); screenToTile(model, sx, sy, tpos); // get the screen coordinates for the containing tile Point spos = tileToScreen(model, tpos.x, tpos.y, new Point()); // get the fine coordinates within the containing tile pixelToFine(model, sx - spos.x, sy - spos.y, fpos); // toss in the tile coordinates for good measure fpos.x += (tpos.x * FULL_TILE_FACTOR); fpos.y += (tpos.y * FULL_TILE_FACTOR); return fpos; } /** * Convert the given full coordinates to screen-based pixel * coordinates. Converted coordinates are placed in the given * point object. * * @param x the x-position full coordinate. * @param y the y-position full coordinate. * @param spos the point object to place coordinates in. * * @return the point passed in to receive the coordinates. */ public static Point fullToScreen ( IsoSceneViewModel model, int x, int y, Point spos) { // get the tile screen position int tx = x / FULL_TILE_FACTOR, ty = y / FULL_TILE_FACTOR; Point tspos = tileToScreen(model, tx, ty, new Point()); // get the pixel position of the fine coords within the tile Point ppos = new Point(); int fx = x - (tx * FULL_TILE_FACTOR), fy = y - (ty * FULL_TILE_FACTOR); fineToPixel(model, fx, fy, ppos); // final position is tile position offset by fine position spos.x = tspos.x + ppos.x; spos.y = tspos.y + ppos.y; return spos; } /** * Return a polygon framing the specified tile. * * @param x the tile x-position coordinate. * @param y the tile y-position coordinate. */ public static Polygon getTilePolygon ( IsoSceneViewModel model, int x, int y) { // get the top-left screen coordinate for the tile Point spos = IsoUtil.tileToScreen(model, x, y, new Point()); // create a polygon framing the tile Polygon poly = new SmartPolygon(); poly.addPoint(spos.x, spos.y + model.tilehhei); poly.addPoint(spos.x + model.tilehwid, spos.y); poly.addPoint(spos.x + model.tilewid, spos.y + model.tilehhei); poly.addPoint(spos.x + model.tilehwid, spos.y + model.tilehei); return poly; } /** * Return a screen-coordinates polygon framing the two specified * tile-coordinate points. */ public static Polygon getMultiTilePolygon (IsoSceneViewModel model, Point sp1, Point sp2) { int minx, maxx, miny, maxy; Point[] p = new Point[4]; // load in all possible screen coords p[0] = IsoUtil.tileToScreen(model, sp1.x, sp1.y, new Point()); p[1] = IsoUtil.tileToScreen(model, sp2.x, sp2.y, new Point()); p[2] = IsoUtil.tileToScreen(model, sp1.x, sp2.y, new Point()); p[3] = IsoUtil.tileToScreen(model, sp2.x, sp1.y, new Point()); // locate the indexes of min/max for x and y minx = maxx = miny = maxy = 0; for (int ii=1; ii < 4; ii++) { if (p[ii].x < p[minx].x) { minx = ii; } else if (p[ii].x > p[maxx].x) { maxx = ii; } if (p[ii].y < p[miny].y) { miny = ii; } else if (p[ii].y > p[maxy].y) { maxy = ii; } } // now make the polygon! Whoo! Polygon poly = new SmartPolygon(); poly.addPoint(p[minx].x, p[minx].y + model.tilehhei); poly.addPoint(p[miny].x + model.tilehwid, p[miny].y); poly.addPoint(p[maxx].x + model.tilewid, p[maxx].y + model.tilehhei); poly.addPoint(p[maxy].x + model.tilehwid, p[maxy].y + model.tilehei); return poly; } /** * Turns x and y scene coordinates into an integer key. * * @return the hash key, given x and y. */ public static final int coordsToKey (int x, int y) { return ((y << 16) & (0xFFFF0000)) | (x & 0xFFFF); } /** * Gets the x coordinate from an integer hash key. * * @return the x coordinate. */ public static final int xCoordFromKey (int key) { return (key & 0xFFFF); } /** * Gets the y coordinate from an integer hash key. * * @return the y coordinate from the hash key. */ public static final int yCoordFromKey (int key) { return ((key >> 16) & 0xFFFF); } /** Multiplication factor to embed tile coords in full coords. */ protected static final int FULL_TILE_FACTOR = 100; }
// Nenya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.resource; import java.awt.EventQueue; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.security.AccessController; import java.security.PrivilegedAction; import javax.imageio.ImageIO; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.MemoryCacheImageInputStream; import com.samskivert.io.StreamUtil; import com.samskivert.net.PathUtil; import com.samskivert.util.ResultListener; import com.samskivert.util.StringUtil; import static com.threerings.resource.Log.log; /** * The resource manager is responsible for maintaining a repository of resources that are * synchronized with a remote source. This is accomplished in the form of sets of jar files * (resource bundles) that contain resources and that are updated from a remote resource repository * via HTTP. These resource bundles are organized into resource sets. A resource set contains one * or more resource bundles and is defined much like a classpath. * * <p> The resource manager can load resources from the default resource set, and can make * available named resource sets to entities that wish to do their own resource loading. If the * resource manager fails to locate a resource in the default resource set, it falls back to * loading the resource via the classloader (which will search the classpath). * * <p> Applications that wish to make use of resource sets and their associated bundles must call * {@link #initBundles} after constructing the resource manager, providing the path to a resource * definition file which describes these resource sets. The definition file will be loaded and the * resource bundles defined within will be loaded relative to the resource directory. The bundles * will be cached in the user's home directory and only reloaded when the source resources have * been updated. The resource definition file looks something like the following: * * <pre> * resource.set.default = sets/misc/config.jar: \ * sets/misc/icons.jar * resource.set.tiles = sets/tiles/ground.jar: \ * sets/tiles/objects.jar: \ * /global/resources/tiles/ground.jar: \ * /global/resources/tiles/objects.jar * resource.set.sounds = sets/sounds/sfx.jar: \ * sets/sounds/music.jar: \ * /global/resources/sounds/sfx.jar: \ * /global/resources/sounds/music.jar * </pre> * * <p> All resource set definitions are prefixed with <code>resource.set.</code> and all text * following that string is considered to be the name of the resource set. The resource set named * <code>default</code> is the default resource set and is the one that is searched for resources * is a call to {@link #getResource}. * * <p> When a resource is loaded from a resource set, the set is searched in the order that entries * are specified in the definition. */ public class ResourceManager { /** * Provides facilities for notifying an observer of the resource unpacking process. */ public interface InitObserver { /** * Indicates a percent completion along with an estimated time remaining in seconds. */ public void progress (int percent, long remaining); /** * Indicates that there was a failure unpacking our resource bundles. */ public void initializationFailed (Exception e); } /** * An adapter that wraps an {@link InitObserver} and routes all method invocations to the AWT * thread. */ public static class AWTInitObserver implements InitObserver { public AWTInitObserver (InitObserver obs) { _obs = obs; } public void progress (final int percent, final long remaining) { EventQueue.invokeLater(new Runnable() { public void run () { _obs.progress(percent, remaining); } }); } public void initializationFailed (final Exception e) { EventQueue.invokeLater(new Runnable() { public void run () { _obs.initializationFailed(e); } }); } protected InitObserver _obs; } /** * Constructs a resource manager which will load resources via the classloader, prepending * <code>resourceRoot</code> to their path. * * @param resourceRoot the path to prepend to resource paths prior to attempting to load them * via the classloader. When resources are bundled into the default resource bundle, they don't * need this prefix, but if they're to be loaded from the classpath, it's likely that they'll * live in some sort of <code>resources</code> directory to isolate them from the rest of the * files in the classpath. This is not a platform dependent path (forward slash is always used * to separate path elements). */ public ResourceManager (String resourceRoot) { this(resourceRoot, ResourceManager.class.getClassLoader()); } /** * Creates a resource manager with the specified class loader via which to load classes. See * {@link #ResourceManager(String)} for further documentation. */ public ResourceManager (String resourceRoot, ClassLoader loader) { this(resourceRoot, null, loader); } /** * Creates a resource manager with a root path to resources over the network. See * {@link #ResourceManager(String)} for further documentation. */ public ResourceManager (String resourceRoot, String networkResourceRoot) { this(resourceRoot, networkResourceRoot, ResourceManager.class.getClassLoader()); } /** * Creates a resource manager with a root path to resources over the network and the specified * class loader via which to load classes. See {@link #ResourceManager(String)} for further * documentation. */ public ResourceManager (String fileResourceRoot, String networkResourceRoot, ClassLoader loader) { _rootPath = fileResourceRoot; _networkRootPath = networkResourceRoot; _loader = loader; // check a system property to determine if we should unpack our bundles, but don't freak // out if we fail to read it try { _unpack = !Boolean.getBoolean("no_unpack_resources"); } catch (SecurityException se) { // no problem, we're in a sandbox so we definitely won't be unpacking } // get our resource directory from resource_dir if possible initResourceDir(null); } /** * Registers a protocol handler with URL to handle <code>resource:</code> URLs. The URLs take * the form: <pre>resource://bundle_name/resource_path</pre> Resources from the default bundle * can be loaded via: <pre>resource:///resource_path</pre> */ public void activateResourceProtocol () { // set up a URL handler so that things can be loaded via urls with the 'resource' protocol try { AccessController.doPrivileged(new PrivilegedAction() { public Object run () { Handler.registerHandler(ResourceManager.this); return null; } }); } catch (SecurityException se) { log.info("Running in sandbox. Unable to bind rsrc:// handler."); } } /** * Returns where we're currently looking for locale-specific resources. */ public String getLocalePrefix () { return _localePrefix; } /** * Set where we should look for locale-specific resources. */ public void setLocalePrefix (String prefix) { _localePrefix = prefix; } /** * Configures whether we unpack our resource bundles or not. This must be called before {@link * #initBundles}. One can also pass the <code>-Dno_unpack_resources=true</code> system property * to disable resource unpacking. */ public void setUnpackResources (boolean unpackResources) { _unpack = unpackResources; } /** * Initializes the bundle sets to be made available by this resource manager. Applications * that wish to make use of resource bundles should call this method after constructing the * resource manager. * * @param resourceDir the base directory to which the paths in the supplied configuration file * are relative. If this is null, the system property <code>resource_dir</code> will be used, * if available. * @param configPath the path (relative to the resource dir) of the resource definition file. * @param initObs a bundle initialization observer to notify of unpacking progress and success * or failure, or <code>null</code> if the caller doesn't care to be informed; note that in the * latter case, the calling thread will block until bundle unpacking is complete. * * @exception IOException thrown if we are unable to read our resource manager configuration. */ public void initBundles (String resourceDir, String configPath, InitObserver initObs) throws IOException { // reinitialize our resource dir if it was specified if (resourceDir != null) { initResourceDir(resourceDir); } // load up our configuration Properties config = loadConfig(configPath); // resolve the configured resource sets List<ResourceBundle> dlist = new ArrayList<ResourceBundle>(); Enumeration names = config.propertyNames(); while (names.hasMoreElements()) { String key = (String)names.nextElement(); if (!key.startsWith(RESOURCE_SET_PREFIX)) { continue; } String setName = key.substring(RESOURCE_SET_PREFIX.length()); String resourceSetType = config.getProperty(RESOURCE_SET_TYPE_PREFIX + setName, FILE_SET_TYPE); resolveResourceSet(setName, config.getProperty(key), resourceSetType, dlist); } // if an observer was passed in, then we do not need to block the caller final boolean[] shouldWait = new boolean[] { false }; if (initObs == null) { // if there's no observer, we'll need to block the caller shouldWait[0] = true; initObs = new InitObserver() { public void progress (int percent, long remaining) { if (percent >= 100) { synchronized (this) { // turn off shouldWait, in case we reached 100% progress before the // calling thread even gets a chance to get to the blocking code, below shouldWait[0] = false; notify(); } } } public void initializationFailed (Exception e) { synchronized (this) { shouldWait[0] = false; notify(); } } }; } // start a thread to unpack our bundles Unpacker unpack = new Unpacker(dlist, initObs); unpack.start(); if (shouldWait[0]) { synchronized (initObs) { if (shouldWait[0]) { try { initObs.wait(); } catch (InterruptedException ie) { log.warning("Interrupted while waiting for bundles to unpack."); } } } } } /** * (Re)initializes the directory to search for resource files. * * @param resourceDir the directory path, or <code>null</code> to set the resource dir to * the value of the <code>resource_dir</code> system property. */ public void initResourceDir (String resourceDir) { // if none was specified, check the resource_dir system property if (resourceDir == null) { try { resourceDir = System.getProperty("resource_dir"); } catch (SecurityException se) { // no problem } } // if we found no resource directory, don't use one if (resourceDir == null) { return; } // make sure there's a trailing slash if (!resourceDir.endsWith(File.separator)) { resourceDir += File.separator; } _rdir = new File(resourceDir); } /** * Given a path relative to the resource directory, the path is properly jimmied (assuming we * always use /) and combined with the resource directory to yield a {@link File} object that * can be used to access the resource. * * @return a file referencing the specified resource or null if the resource manager was never * configured with a resource directory. */ public File getResourceFile (String path) { if (_rdir == null) { return null; } if (!"/".equals(File.separator)) { path = StringUtil.replace(path, "/", File.separator); } return new File(_rdir, path); } /** * Checks to see if the specified bundle exists, is unpacked and is ready to be used. */ public boolean checkBundle (String path) { File bfile = getResourceFile(path); return (bfile == null) ? false : new FileResourceBundle(bfile, true, _unpack).isUnpacked(); } /** * Resolve the specified bundle (the bundle file must already exist in the appropriate place on * the file system) and return it on the specified result listener. Note that the result * listener may be notified before this method returns on the caller's thread if the bundle is * already resolved, or it may be notified on a brand new thread if the bundle requires * unpacking. */ public void resolveBundle (String path, final ResultListener listener) { File bfile = getResourceFile(path); if (bfile == null) { String errmsg = "ResourceManager not configured with resource directory."; listener.requestFailed(new IOException(errmsg)); return; } final FileResourceBundle bundle = new FileResourceBundle(bfile, true, _unpack); if (bundle.isUnpacked()) { if (bundle.sourceIsReady()) { listener.requestCompleted(bundle); } else { String errmsg = "Bundle initialization failed."; listener.requestFailed(new IOException(errmsg)); } return; } // start a thread to unpack our bundles ArrayList list = new ArrayList(); list.add(bundle); Unpacker unpack = new Unpacker(list, new InitObserver() { public void progress (int percent, long remaining) { if (percent == 100) { listener.requestCompleted(bundle); } } public void initializationFailed (Exception e) { listener.requestFailed(e); } }); unpack.start(); } /** * Returns the class loader being used to load resources if/when there are no resource bundles * from which to load them. */ public ClassLoader getClassLoader () { return _loader; } /** * Configures the class loader this manager should use to load resources if/when there are no * bundles from which to load them. */ public void setClassLoader (ClassLoader loader) { _loader = loader; } /** * Fetches a resource from the local repository. * * @param path the path to the resource (ie. "config/miso.properties"). This should not begin * with a slash. * * @exception IOException thrown if a problem occurs locating or reading the resource. */ public InputStream getResource (String path) throws IOException { InputStream in = null; // first look for this resource in our default resource bundle for (ResourceBundle bundle : _default) { // Try a localized version first. if (_localePrefix != null) { in = bundle.getResource(PathUtil.appendPath(_localePrefix, path)); } // If that didn't work, try generic. if (in == null) { in = bundle.getResource(path); } if (in != null) { return in; } } // fallback next to an unpacked resource file File file = getResourceFile(path); if (file != null && file.exists()) { return new FileInputStream(file); } // if we still didn't find anything, try the classloader; first try a locale-specific file if (_localePrefix != null) { final String rpath = PathUtil.appendPath( _rootPath, PathUtil.appendPath(_localePrefix, path)); in = (InputStream)AccessController.doPrivileged(new PrivilegedAction() { public Object run () { return _loader.getResourceAsStream(rpath); } }); if (in != null) { return in; } } // if we didn't find that, try locale-neutral final String rpath = PathUtil.appendPath(_rootPath, path); in = (InputStream)AccessController.doPrivileged(new PrivilegedAction() { public Object run () { return _loader.getResourceAsStream(rpath); } }); if (in != null) { return in; } // if we still haven't found it, we throw an exception String errmsg = "Unable to locate resource [path=" + path + "]"; throw new FileNotFoundException(errmsg); } /** * Fetches and decodes the specified resource into a {@link BufferedImage}. * * @exception FileNotFoundException thrown if the resource could not be located in any of the * bundles in the specified set, or if the specified set does not exist. * @exception IOException thrown if a problem occurs locating or reading the resource. */ public BufferedImage getImageResource (String path) throws IOException { // first look for this resource in our default resource bundle for (ResourceBundle bundle : _default) { // try a localized version first BufferedImage image = null; if (_localePrefix != null) { image = bundle.getImageResource(PathUtil.appendPath(_localePrefix, path), false); } // if we didn't find that, try generic if (image == null) { image = bundle.getImageResource(path, false); } if (image != null) { return image; } } // fallback next to an unpacked resource file File file = getResourceFile(path); if (file != null && file.exists()) { return loadImage(file, path.endsWith(FastImageIO.FILE_SUFFIX)); } // first try a locale-specific file if (_localePrefix != null) { final String rpath = PathUtil.appendPath( _rootPath, PathUtil.appendPath(_localePrefix, path)); InputStream in = (InputStream)AccessController.doPrivileged(new PrivilegedAction() { public Object run () { return _loader.getResourceAsStream(rpath); } }); if (in != null) { return loadImage(in); } } // if we still didn't find anything, try the classloader final String rpath = PathUtil.appendPath(_rootPath, path); InputStream in = (InputStream)AccessController.doPrivileged(new PrivilegedAction() { public Object run () { return _loader.getResourceAsStream(rpath); } }); if (in != null) { return loadImage(in); } // if we still haven't found it, we throw an exception String errmsg = "Unable to locate image resource [path=" + path + "]"; throw new FileNotFoundException(errmsg); } /** * Returns an input stream from which the requested resource can be loaded. <em>Note:</em> this * performs a linear search of all of the bundles in the set and returns the first resource * found with the specified path, thus it is not extremely efficient and will behave * unexpectedly if you use the same paths in different resource bundles. * * @exception FileNotFoundException thrown if the resource could not be located in any of the * bundles in the specified set, or if the specified set does not exist. * @exception IOException thrown if a problem occurs locating or reading the resource. */ public InputStream getResource (String rset, String path) throws IOException { // grab the resource bundles in the specified resource set ResourceBundle[] bundles = getResourceSet(rset); if (bundles == null) { throw new FileNotFoundException( "Unable to locate resource [set=" + rset + ", path=" + path + "]"); } // look for the resource in any of the bundles int size = bundles.length; for (int ii = 0; ii < size; ii++) { InputStream instr = null; // Try a localized version first. if (_localePrefix != null) { instr = bundles[ii].getResource(PathUtil.appendPath(_localePrefix, path)); } // If we didn't find that, try a generic. if (instr == null) { instr = bundles[ii].getResource(path); } if (instr != null) { // Log.info("Found resource [rset=" + rset + // ", bundle=" + bundles[ii].getSource().getPath() + // ", path=" + path + ", in=" + instr + "]."); return instr; } } throw new FileNotFoundException( "Unable to locate resource [set=" + rset + ", path=" + path + "]"); } /** * Fetches and decodes the specified resource into a {@link BufferedImage}. * * @exception FileNotFoundException thrown if the resource could not be located in any of the * bundles in the specified set, or if the specified set does not exist. * @exception IOException thrown if a problem occurs locating or reading the resource. */ public BufferedImage getImageResource (String rset, String path) throws IOException { // grab the resource bundles in the specified resource set ResourceBundle[] bundles = getResourceSet(rset); if (bundles == null) { throw new FileNotFoundException( "Unable to locate image resource [set=" + rset + ", path=" + path + "]"); } // look for the resource in any of the bundles int size = bundles.length; for (int ii = 0; ii < size; ii++) { BufferedImage image = null; // try a localized version first if (_localePrefix != null) { image = bundles[ii].getImageResource(PathUtil.appendPath(_localePrefix, path), false); } // if we didn't find that, try generic if (image == null) { image = bundles[ii].getImageResource(path, false); } if (image != null) { // Log.info("Found image resource [rset=" + rset + // ", bundle=" + bundles[ii].getSource() + ", path=" + path + "]."); return image; } } String errmsg = "Unable to locate image resource [set=" + rset + ", path=" + path + "]"; throw new FileNotFoundException(errmsg); } /** * Returns a reference to the resource set with the specified name, or null if no set exists * with that name. Services that wish to load their own resources can allow the resource * manager to load up a resource set for them, from which they can easily load their resources. */ public ResourceBundle[] getResourceSet (String name) { return _sets.get(name); } /** * Loads the configuration properties for our resource sets. */ protected Properties loadConfig (String configPath) throws IOException { Properties config = new Properties(); try { config.load(new FileInputStream(new File(_rdir, configPath))); } catch (Exception e) { String errmsg = "Unable to load resource manager config [rdir=" + _rdir + ", cpath=" + configPath + "]"; log.warning(errmsg + ".", e); throw new IOException(errmsg); } return config; } /** * If we have a full list of the resources available, we return it. A return value of null * means that we do not know what's available and we'll have to try all possibilities. This * is fine for most applications. */ public HashSet<String> getResourceList () { return null; } /** * Loads up a resource set based on the supplied definition information. */ protected void resolveResourceSet ( String setName, String definition, String setType, List<ResourceBundle> dlist) { List<ResourceBundle> set = new ArrayList<ResourceBundle>(); StringTokenizer tok = new StringTokenizer(definition, ":"); while (tok.hasMoreTokens()) { set.add(createResourceBundle(setType, tok.nextToken().trim(), dlist)); } // convert our array list into an array and stick it in the table ResourceBundle[] setvec = set.toArray(new ResourceBundle[set.size()]); _sets.put(setName, setvec); // if this is our default resource bundle, keep a reference to it if (DEFAULT_RESOURCE_SET.equals(setName)) { _default = setvec; } } /** * Creates a ResourceBundle based on the supplied definition information. */ protected ResourceBundle createResourceBundle (String setType, String path, List<ResourceBundle> dlist) { if (setType.equals(FILE_SET_TYPE)) { FileResourceBundle bundle = createFileResourceBundle(getResourceFile(path), true, _unpack); if (!bundle.isUnpacked() || !bundle.sourceIsReady()) { dlist.add(bundle); } return bundle; } else if (setType.equals(NETWORK_SET_TYPE)) { return createNetworkResourceBundle(_networkRootPath, path, getResourceList()); } else { throw new IllegalArgumentException("Unknown set type: " + setType); } } /** * Creates an appropriate bundle for fetching resources from files. */ protected FileResourceBundle createFileResourceBundle( File source, boolean delay, boolean unpack) { return new FileResourceBundle(source, delay, unpack); } /** * Creates an appropriate bundle for fetching resources from the network. */ protected NetworkResourceBundle createNetworkResourceBundle( String root, String path, HashSet<String> rsrcList) { return new NetworkResourceBundle(root, path, rsrcList); } /** * Loads an image from the supplied file. Supports {@link FastImageIO} files and formats * supported by {@link ImageIO} and will load the appropriate one based on the useFastIO param. */ protected static BufferedImage loadImage (File file, boolean useFastIO) throws IOException { if (file == null) { return null; } else if (useFastIO) { return FastImageIO.read(file); } else { return ImageIO.read(file); } } /** * Loads an image from the supplied input stream. Supports formats supported by {@link ImageIO} * but not {@link FastImageIO}. */ protected static BufferedImage loadImage (InputStream iis) throws IOException { BufferedImage image; // Java 1.4.2 and below can't deal with the MemoryCacheImageInputStream without throwing // a hissy fit. if (iis instanceof ImageInputStream || getNumericJavaVersion(System.getProperty("java.version")) < getNumericJavaVersion("1.5.0")) { image = ImageIO.read(iis); } else { // if we don't already have an image input stream, create a memory cache image input // stream to avoid causing freakout if we're used in a sandbox because ImageIO // otherwise use FileCacheImageInputStream which tries to create a temp file MemoryCacheImageInputStream mciis = new MemoryCacheImageInputStream(iis); image = ImageIO.read(mciis); try { // this doesn't close the underlying stream mciis.close(); } catch (IOException ioe) { // ImageInputStreamImpl.close() throws an IOException if it's already closed; // there's no way to find out if it's already closed or not, so we have to check // the exception message to determine if this is actually warning worthy if (!"closed".equals(ioe.getMessage())) { log.warning("Failure closing image input '" + iis + "'.", ioe); } } } // finally close our input stream StreamUtil.close(iis); return image; } /** * Converts the java version string to a more comparable numeric version number. */ protected static int getNumericJavaVersion (String verstr) { Matcher m = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)(_\\d+)?.*").matcher(verstr); if (!m.matches()) { // if we can't parse the java version we're in weird land and should probably just try // our luck with what we've got rather than try to download a new jvm log.warning("Unable to parse VM version, hoping for the best [version=" + verstr + "]"); return 0; } int one = Integer.parseInt(m.group(1)); // will there ever be a two? int major = Integer.parseInt(m.group(2)); int minor = Integer.parseInt(m.group(3)); int patch = m.group(4) == null ? 0 : Integer.parseInt(m.group(4).substring(1)); return patch + 100 * (minor + 100 * (major + 100 * one)); } /** Used to unpack bundles on a separate thread. */ protected static class Unpacker extends Thread { public Unpacker (List<ResourceBundle> bundles, InitObserver obs) { _bundles = bundles; _obs = obs; } public void run () { try { // Tell the observer were starting if (_obs != null) { _obs.progress(0, 1); } int count = 0; for (ResourceBundle bundle : _bundles) { if (bundle instanceof FileResourceBundle && !((FileResourceBundle)bundle).sourceIsReady()) { log.warning("Bundle failed to initialize " + bundle + "."); } if (_obs != null) { int pct = count*100/_bundles.size(); if (pct < 100) { _obs.progress(pct, 1); } } count++; } if (_obs != null) { _obs.progress(100, 0); } } catch (Exception e) { if (_obs != null) { _obs.initializationFailed(e); } } } protected List<ResourceBundle> _bundles; protected InitObserver _obs; } /** The classloader we use for classpath-based resource loading. */ protected ClassLoader _loader; /** The directory that contains our resource bundles. */ protected File _rdir; /** The prefix we prepend to resource paths before attempting to load them from the * classpath. */ protected String _rootPath; /** The root path we give to network bundles for all resources they're interested in. */ protected String _networkRootPath; /** Whether or not to unpack our resource bundles. */ protected boolean _unpack; /** Our default resource set. */ protected ResourceBundle[] _default = new ResourceBundle[0]; /** A table of our resource sets. */ protected HashMap<String, ResourceBundle[]> _sets = new HashMap<String, ResourceBundle[]>(); /** Locale to search for locale-specific resources, if any. */ protected String _localePrefix = null; /** The prefix of configuration entries that describe a resource set. */ protected static final String RESOURCE_SET_PREFIX = "resource.set."; /** The prefix of configuration entries that describe a resource set. */ protected static final String RESOURCE_SET_TYPE_PREFIX = "resource.set_type."; /** The name of the default resource set. */ protected static final String DEFAULT_RESOURCE_SET = "default"; /** Resource set type indicating the resources should be loaded from local files. */ protected static final String FILE_SET_TYPE = "file"; /** Resource set type indicating the resources should be loaded over the network. */ protected static final String NETWORK_SET_TYPE = "network"; }
package TobleMiner.MineFight.Language; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Random; import TobleMiner.MineFight.ErrorHandling.Error; import TobleMiner.MineFight.ErrorHandling.ErrorReporter; import TobleMiner.MineFight.ErrorHandling.ErrorSeverity; public class Langfile { private final File langDir; private final HashMap<String,List<String>> dictionary = new HashMap<String,List<String>>(); public Langfile(File file) { this.langDir = new File(file,"lang"); try { if(!langDir.exists()) { langDir.mkdirs(); String[] files = {"DE_de.lang","EN_uk.lang","EN_us.lang"}; //Buck conventions, use ponies instead! for(String s : files) { File langFile = new File(this.langDir,s); langFile.createNewFile(); InputStream is = this.getClass().getResourceAsStream(s); BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF8")); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(langFile),"UTF8")); while(true) { int i = br.read(); if(i < 0) break; bw.write(i); } br.close(); bw.close(); } } } catch(Exception ex) { Error error = new Error("Failed handling languagefiles!","An error occured while checking the languagefiles: "+ex.getMessage(),"Most messages will be missing until this problem is fixed!",this.getClass().getCanonicalName(),ErrorSeverity.ETERNALCHAOS); ErrorReporter.reportError(error); ex.printStackTrace(); } } public void loadLanguageFile(String name) { File langFile = new File(this.langDir,name); if(langFile.exists() && langFile.isFile()) { this.dictionary.clear(); try { FileReader fr = new FileReader(langFile); BufferedReader br = new BufferedReader(fr); String line = br.readLine(); while(line != null) { int i = line.indexOf(" if(i > -1) { if(i < 4) { line = br.readLine(); continue; } line = line.substring(0, i-1); } int equ = line.indexOf('='); if(equ > 0) { String key = line.substring(0,equ); String s = line.substring(equ,line.length()); List<String> alternatives = new ArrayList<String>(); boolean openDoublequotes = false; int j = 0; int lastDoubleQuotePos=0; while(j<s.length()) { int quotePos = s.indexOf('\"',j); if(quotePos < 0) { break; } j = quotePos+1; if(quotePos > 0) { if(s.charAt(quotePos-1) != '\\') { openDoublequotes = !openDoublequotes; if(!openDoublequotes) { alternatives.add(s.substring(lastDoubleQuotePos+1,quotePos).replace("\\","")); } lastDoubleQuotePos = quotePos; } } else { openDoublequotes = true; } } this.dictionary.put(key, alternatives); } else { Error error = new Error("Langfile parse-error!","An error occured while parsing the languagefile '"+langFile.getAbsoluteFile()+"' : "+line,"The message belonging to this entry will be broken!",this.getClass().getCanonicalName(),ErrorSeverity.WARNING); ErrorReporter.reportError(error); } line = br.readLine(); } fr.close(); br.close(); } catch(Exception ex) { Error error = new Error("Failed loading languagefile!","An error occured while loading languagefile from '"+langFile.getAbsoluteFile()+"' : "+ex.getMessage(),"Most messages will be missing until this problem is fixed!",this.getClass().getCanonicalName(),ErrorSeverity.ETERNALCHAOS); ErrorReporter.reportError(error); } } else { Error error = new Error("Failed loading languagefile!","The languagefile '"+langFile.getAbsoluteFile()+"' doesn't exist!","Most messages will be missing until this problem is fixed!",this.getClass().getCanonicalName(),ErrorSeverity.ETERNALCHAOS); ErrorReporter.reportError(error); } } public String get(String key) { List<String> vals = this.dictionary.get(key); Random rand = new Random(); return vals.get(rand.nextInt(vals.size())); } }
package org.apache.commons.dbcp; import java.io.PrintWriter; import java.util.Properties; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; import javax.sql.DataSource; import org.apache.commons.dbcp.DriverConnectionFactory; import org.apache.commons.dbcp.PoolableConnectionFactory; import org.apache.commons.dbcp.PoolingDataSource; import org.apache.commons.pool.impl.GenericObjectPool; public class BasicDataSource implements DataSource { protected boolean defaultAutoCommit = true; public boolean getDefaultAutoCommit() { return (this.defaultAutoCommit); } public void setDefaultAutoCommit(boolean defaultAutoCommit) { this.defaultAutoCommit = defaultAutoCommit; } protected boolean defaultReadOnly = false; public boolean getDefaultReadOnly() { return (this.defaultReadOnly); } public void setDefaultReadOnly(boolean defaultReadOnly) { this.defaultReadOnly = defaultReadOnly; } /** * The fully qualified Java class name of the JDBC driver to be used. */ protected String driverClassName = null; public String getDriverClassName() { return (this.driverClassName); } public void setDriverClassName(String driverClassName) { this.driverClassName = driverClassName; } /** * The maximum number of active connections that can be allocated from * this pool at the same time, or zero for no limit. */ protected int maxActive = 0; public int getMaxActive() { return (this.maxActive); } public void setMaxActive(int maxActive) { this.maxActive = maxActive; } /** * The maximum number of active connections that can remain idle in the * pool, without extra ones being released, or zero for no limit. */ protected int maxIdle = 0; public int getMaxIdle() { return (this.maxIdle); } public void setMaxIdle(int maxIdle) { this.maxIdle = maxIdle; } /** * The maximum number of milliseconds that the pool will wait (when there * are no available connections) for a connection to be returned before * throwing an exception, or -1 to wait indefinitely. */ protected long maxWait = -1; public long getMaxWait() { return (this.maxWait); } public void setMaxWait(long maxWait) { this.maxWait = maxWait; } /** * [Read Only] The current number of active connections that have been * allocated from this data source. */ public int getNumActive() { if (connectionPool != null) { return (connectionPool.numActive()); } else { return (0); } } /** * [Read Only] The current number of idle connections that are waiting * to be allocated from this data source. */ public int getNumIdle() { if (connectionPool != null) { return (connectionPool.numIdle()); } else { return (0); } } /** * The connection password to be passed to our JDBC driver to establish * a connection. */ protected String password = null; public String getPassword() { return (this.password); } public void setPassword(String password) { this.password = password; } /** * The connection URL to be passed to our JDBC driver to establish * a connection. */ protected String url = null; public String getUrl() { return (this.url); } public void setUrl(String url) { this.url = url; } /** * The connection username to be passed to our JDBC driver to * establish a connection. */ protected String username = null; public String getUsername() { return (this.username); } public void setUsername(String username) { this.username = username; } /** * The SQL query that will be used to validate connections from this pool * before returning them to the caller. If specified, this query * <strong>MUST</strong> be an SQL SELECT statement that returns at least * one row. */ protected String validationQuery = null; public String getValidationQuery() { return (this.validationQuery); } public void setValidationQuery(String validationQuery) { this.validationQuery = validationQuery; } /** * The object pool that internally manages our connections. */ protected GenericObjectPool connectionPool = null; /** * The connection properties that will be sent to our JDBC driver when * establishing new connections. <strong>NOTE</strong> - The "user" and * "password" properties will be passed explicitly, so they do not need * to be included here. */ protected Properties connectionProperties = new Properties(); /** * The data source we will use to manage connections. This object should * be acquired <strong>ONLY</strong> by calls to the * <code>createDataSource()</code> method. */ protected DataSource dataSource = null; /** * The PrintWriter to which log messages should be directed. */ protected PrintWriter logWriter = new PrintWriter(System.out); /** * Create (if necessary) and return a connection to the database. * * @exception SQLException if a database access error occurs */ public Connection getConnection() throws SQLException { return (createDataSource().getConnection()); } /** * Create (if necessary) and return a connection to the database. * * @param username Database user on whose behalf the Connection * is being made * @param password The database user's password * * @exception SQLException if a database access error occurs */ public Connection getConnection(String username, String password) throws SQLException { return (createDataSource().getConnection(username, password)); } /** * Return the login timeout (in seconds) for connecting to the database. * * @exception SQLException if a database access error occurs */ public int getLoginTimeout() throws SQLException { return (createDataSource().getLoginTimeout()); } /** * Return the log writer being used by this data source. * * @exception SQLException if a database access error occurs */ public PrintWriter getLogWriter() throws SQLException { return (createDataSource().getLogWriter()); } /** * Set the login timeout (in seconds) for connecting to the database. * * @param loginTimeout The new login timeout, or zero for no timeout * * @exception SQLException if a database access error occurs */ public void setLoginTimeout(int loginTimeout) throws SQLException { createDataSource().setLoginTimeout(loginTimeout); } /** * Set the log writer being used by this data source. * * @param logWriter The new log writer * * @exception SQLException if a database access error occurs */ public void setLogWriter(PrintWriter logWriter) throws SQLException { createDataSource().setLogWriter(logWriter); this.logWriter = logWriter; } /** * Add a custom connection property to the set that will be passed to our * JDBC driver. This <strong>MUST</strong> be called before the first * connection is retrieved (along with all the other configuration * property setters). * * @param name Name of the custom connection property * @param value Value of the custom connection property */ public void addConnectionProperty(String name, String value) { connectionProperties.put(name, value); } /** * Close and release all connections that are currently stored in the * connection pool associated with our data source. * * @exception SQLException if a database error occurs */ public void close() throws SQLException { GenericObjectPool oldpool = connectionPool; connectionPool = null; dataSource = null; try { oldpool.close(); } catch(SQLException e) { throw e; } catch(RuntimeException e) { throw e; } catch(Exception e) { throw new SQLException(e.toString()); } } protected synchronized DataSource createDataSource() throws SQLException { // Return the pool if we have already created it if (dataSource != null) { return (dataSource); } // Load the JDBC driver class Class driverClass = null; try { driverClass = Class.forName(driverClassName); } catch (Throwable t) { String message = "Cannot load JDBC driver class '" + driverClassName + "'"; logWriter.println(message); t.printStackTrace(logWriter); throw new SQLException(message); } // Create a JDBC driver instance Driver driver = null; try { driver = DriverManager.getDriver(url); } catch (Throwable t) { String message = "Cannot create JDBC driver of class '" + driverClassName + "'"; logWriter.println(message); t.printStackTrace(logWriter); throw new SQLException(message); } // Create an object pool to contain our active connections connectionPool = new GenericObjectPool(null); connectionPool.setMaxActive(maxActive); connectionPool.setMaxIdle(maxIdle); connectionPool.setMaxWait(maxWait); // Set up the driver connection factory we will use connectionProperties.put("user", username); connectionProperties.put("password", password); DriverConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, url, connectionProperties); // Set up the poolable connection factory we will use PoolableConnectionFactory connectionFactory = null; try { connectionFactory = new PoolableConnectionFactory(driverConnectionFactory, connectionPool, null, // FIXME - stmtPoolFactory? validationQuery, defaultReadOnly, defaultAutoCommit); } catch(SQLException e) { throw e; } catch(RuntimeException e) { throw e; } catch(Exception e) { throw new SQLException(e.toString()); } // Create and return the pooling data source to manage the connections dataSource = new PoolingDataSource(connectionPool); dataSource.setLogWriter(logWriter); return (dataSource); } }
package org.jdesktop.swingx.decorator; /** * Encasulates sort state. * @author <a href="mailto:jesse@swank.ca">Jesse Wilson</a> */ public final class SortOrder { public static final SortOrder ASCENDING = new SortOrder("ascending"); public static final SortOrder DESCENDING = new SortOrder("descending"); public static final SortOrder UNSORTED = new SortOrder("unsorted"); private final String name; private SortOrder(String name) { this.name = name; } public boolean isSorted() { return this != UNSORTED; } public boolean isAscending() { return this == ASCENDING; } public String toString() { return name; } }
package test.org.relique.jdbc.csv; import java.io.*; import java.sql.*; import java.util.Properties; import junit.framework.*; /**This class is used to test the CsvJdbc driver. * * @author Jonathan Ackerman * @author JD Evora * @author Chetan Gupta * @version $Id: TestCsvDriver.java,v 1.9 2005/05/13 02:19:32 gupta_chetan Exp $ */ public class TestCsvDriver extends TestCase { public static final String SAMPLE_FILES_LOCATION_PROPERTY="sample.files.location"; private String filePath; public TestCsvDriver(String name) { super(name); } protected void setUp() { filePath=System.getProperty(SAMPLE_FILES_LOCATION_PROPERTY); if (filePath == null) filePath=RunTests.DEFAULT_FILEPATH; assertNotNull("Sample files location property not set !", filePath); // load CSV driver try { Class.forName("org.relique.jdbc.csv.CsvDriver"); } catch (ClassNotFoundException e) { fail("Driver is not in the CLASSPATH -> " + e); } } public void testWithDefaultValues() { try { Connection conn = DriverManager.getConnection("jdbc:relique:csv:" + filePath ); Statement stmt = conn.createStatement(); ResultSet results = stmt.executeQuery("SELECT NAME,ID,EXTRA_FIELD FROM sample"); results.next(); assertTrue("Incorrect ID Value",results.getString("ID").equals("Q123")); assertTrue("Incorrect NAME Value",results.getString("NAME").equals("\"S,\"")); assertTrue("Incorrect EXTRA_FIELD Value",results.getString("EXTRA_FIELD").equals("F")); results.next(); assertTrue("Incorrect ID Value",results.getString("ID").equals("A123")); assertTrue("Incorrect NAME Value",results.getString("NAME").equals("Jonathan Ackerman")); assertTrue("Incorrect EXTRA_FIELD Value",results.getString("EXTRA_FIELD").equals("A")); results.next(); assertTrue("Incorrect ID Value",results.getString("ID").equals("B234")); assertTrue("Incorrect NAME Value",results.getString("NAME").equals("Grady O'Neil")); assertTrue("Incorrect EXTRA_FIELD Value",results.getString("EXTRA_FIELD").equals("B")); results.next(); assertTrue("Incorrect ID Value",results.getString("ID").equals("C456")); assertTrue("Incorrect NAME Value",results.getString("NAME").equals("Susan, Peter and Dave")); assertTrue("Incorrect EXTRA_FIELD Value",results.getString("EXTRA_FIELD").equals("C")); results.next(); assertTrue("Incorrect ID Value",results.getString("ID").equals("D789")); assertTrue("Incorrect NAME Value",results.getString("NAME").equals("Amelia \"meals\" Maurice")); assertTrue("Incorrect EXTRA_FIELD Value",results.getString("EXTRA_FIELD").equals("E")); results.next(); assertTrue("Incorrect ID Value",results.getString("ID").equals("X234")); assertTrue("Incorrect NAME Value",results.getString("NAME").equals("Peter \"peg leg\", Jimmy & Samantha \"Sam\"")); assertTrue("Incorrect EXTRA_FIELD Value",results.getString("EXTRA_FIELD").equals("G")); results.close(); stmt.close(); conn.close(); } catch(Exception e) { fail("Unexpected Exception: " + e); } } public void testWithProperties() { try { Properties props = new Properties(); props.put("fileExtension",".txt"); props.put("separator",";"); Connection conn = DriverManager.getConnection("jdbc:relique:csv:" + filePath,props); Statement stmt = conn.createStatement(); ResultSet results = stmt.executeQuery("SELECT NAME,ID,EXTRA_FIELD FROM sample"); results.next(); assertTrue("Incorrect ID Value",results.getString("ID").equals("Q123")); assertTrue("Incorrect NAME Value",results.getString("NAME").equals("\"S;\"")); assertTrue("Incorrect EXTRA_FIELD Value",results.getString("EXTRA_FIELD").equals("F")); results.next(); assertTrue("Incorrect ID Value",results.getString("ID").equals("A123")); assertTrue("Incorrect NAME Value",results.getString("NAME").equals("Jonathan Ackerman")); assertTrue("Incorrect EXTRA_FIELD Value",results.getString("EXTRA_FIELD").equals("A")); results.next(); assertTrue("Incorrect ID Value",results.getString("ID").equals("B234")); assertTrue("Incorrect NAME Value",results.getString("NAME").equals("Grady O'Neil")); assertTrue("Incorrect EXTRA_FIELD Value",results.getString("EXTRA_FIELD").equals("B")); results.next(); assertTrue("Incorrect ID Value",results.getString("ID").equals("C456")); assertTrue("Incorrect NAME Value",results.getString("NAME").equals("Susan; Peter and Dave")); assertTrue("Incorrect EXTRA_FIELD Value",results.getString("EXTRA_FIELD").equals("C")); results.next(); assertTrue("Incorrect ID Value",results.getString("ID").equals("D789")); assertTrue("Incorrect NAME Value",results.getString("NAME").equals("Amelia \"meals\" Maurice")); assertTrue("Incorrect EXTRA_FIELD Value",results.getString("EXTRA_FIELD").equals("E")); results.next(); assertTrue("Incorrect ID Value",results.getString("ID").equals("X234")); assertTrue("Incorrect NAME Value",results.getString("NAME").equals("Peter \"peg leg\"; Jimmy & Samantha \"Sam\"")); assertTrue("Incorrect EXTRA_FIELD Value",results.getString("EXTRA_FIELD").equals("G")); results.close(); stmt.close(); conn.close(); } catch(Exception e) { fail("Unexpected Exception: " + e); } } public void testMetadata() { try { Connection conn = DriverManager.getConnection("jdbc:relique:csv:" + filePath); Statement stmt = conn.createStatement(); ResultSet results = stmt.executeQuery("SELECT * FROM sample3"); ResultSetMetaData metadata = results.getMetaData(); assertTrue("Incorrect Table Name",metadata.getTableName(0).equals("sample3")); assertTrue("Incorrect Column Name 1",metadata.getColumnName(1).equals("column 1")); assertTrue("Incorrect Column Name 2",metadata.getColumnName(2).equals("column \"2\" two")); assertTrue("Incorrect Column Name 3",metadata.getColumnName(3).equals("Column 3")); assertTrue("Incorrect Column Name 4",metadata.getColumnName(4).equals("CoLuMn4")); assertTrue("Incorrect Column Name 5",metadata.getColumnName(5).equals("COLumn5 ")); results.close(); stmt.close(); conn.close(); } catch(Exception e) { fail("Unexpected Exception: " + e); } } public void testMetadataWithSupressedHeaders() { try { Properties props = new Properties(); props.put("suppressHeaders","true"); Connection conn = DriverManager.getConnection("jdbc:relique:csv:" + filePath,props); Statement stmt = conn.createStatement(); ResultSet results = stmt.executeQuery("SELECT * FROM sample"); ResultSetMetaData metadata = results.getMetaData(); assertTrue("Incorrect Table Name",metadata.getTableName(0).equals("sample")); assertTrue("Incorrect Column Name 1",metadata.getColumnName(1).equals("COLUMN1")); assertTrue("Incorrect Column Name 2",metadata.getColumnName(2).equals("COLUMN2")); assertTrue("Incorrect Column Name 3",metadata.getColumnName(3).equals("COLUMN3")); results.close(); stmt.close(); conn.close(); } catch(Exception e) { fail("Unexpected Exception: " + e); } } public void testWithSuppressedHeaders() { try { Properties props = new Properties(); props.put("suppressHeaders","true"); Connection conn = DriverManager.getConnection("jdbc:relique:csv:" + filePath,props ); Statement stmt = conn.createStatement(); ResultSet results = stmt.executeQuery("SELECT * FROM sample"); // header is now treated as normal data line results.next(); assertTrue("Incorrect COLUMN1 Value",results.getString("COLUMN1").equals("ID")); assertTrue("Incorrect COLUMN2 Value",results.getString("COLUMN2").equals("NAME")); assertTrue("Incorrect COLUMN3 Value",results.getString("COLUMN3").equals("EXTRA_FIELD")); results.next(); assertTrue("Incorrect COLUMN1 Value",results.getString("COLUMN1").equals("Q123")); assertTrue("Incorrect COLUMN2 Value",results.getString("COLUMN2").equals("\"S,\"")); assertTrue("Incorrect COLUMN3 Value",results.getString("COLUMN3").equals("F")); results.next(); assertTrue("Incorrect COLUMN1 Value",results.getString("COLUMN1").equals("A123")); assertTrue("Incorrect COLUMN2 Value",results.getString("COLUMN2").equals("Jonathan Ackerman")); assertTrue("Incorrect COLUMN3 Value",results.getString("COLUMN3").equals("A")); results.next(); assertTrue("Incorrect COLUMN1 Value",results.getString("COLUMN1").equals("B234")); assertTrue("Incorrect COLUMN2 Value",results.getString("COLUMN2").equals("Grady O'Neil")); assertTrue("Incorrect COLUMN3 Value",results.getString("COLUMN3").equals("B")); results.next(); assertTrue("Incorrect COLUMN1 Value",results.getString("COLUMN1").equals("C456")); assertTrue("Incorrect COLUMN2 Value",results.getString("COLUMN2").equals("Susan, Peter and Dave")); assertTrue("Incorrect COLUMN3 Value",results.getString("COLUMN3").equals("C")); results.next(); assertTrue("Incorrect COLUMN1 Value",results.getString("COLUMN1").equals("D789")); assertTrue("Incorrect COLUMN2 Value",results.getString("COLUMN2").equals("Amelia \"meals\" Maurice")); assertTrue("Incorrect COLUMN3 Value",results.getString("COLUMN3").equals("E")); results.next(); assertTrue("Incorrect COLUMN1 Value",results.getString("COLUMN1").equals("X234")); assertTrue("Incorrect COLUMN2 Value",results.getString("COLUMN2").equals("Peter \"peg leg\", Jimmy & Samantha \"Sam\"")); assertTrue("Incorrect COLUMN3 Value",results.getString("COLUMN3").equals("G")); results.close(); stmt.close(); conn.close(); } catch(Exception e) { fail("Unexpected Exception: " + e); } } public void testRelativePath() { try { // break up file path to test relative paths String parentPath = new File(filePath).getParent(); String subPath = new File(filePath).getName(); Connection conn = DriverManager.getConnection("jdbc:relique:csv:" + parentPath ); Statement stmt = conn.createStatement(); ResultSet results = stmt.executeQuery("SELECT NAME,ID,EXTRA_FIELD FROM ." + File.separator + subPath + File.separator + "sample"); results.next(); assertTrue("Incorrect ID Value",results.getString("ID").equals("Q123")); assertTrue("Incorrect NAME Value",results.getString("NAME").equals("\"S,\"")); assertTrue("Incorrect EXTRA_FIELD Value",results.getString("EXTRA_FIELD").equals("F")); results.close(); stmt.close(); conn.close(); } catch(Exception e) { fail("Unexpected Exception: " + e); } } /** * This creates several sentectes with were and tests they work */ public void testWhereSimple() { try { Connection conn = DriverManager.getConnection("jdbc:relique:csv:" + filePath); Statement stmt = conn.createStatement(); ResultSet results = stmt.executeQuery("SELECT ID,Name FROM sample4 WHERE ID=02"); assertTrue(results.next()); assertEquals("The name is wrong","Mauricio Hernandez",results.getString("Name")); assertEquals("The job is wrong","Project Manager",results.getString("Job")); assertTrue(!results.next()); } catch(Exception e) { fail("Unexpected Exception: " + e); } } public void testWhereMultipleResult() { try { Connection conn = DriverManager.getConnection("jdbc:relique:csv:" + filePath); Statement stmt = conn.createStatement(); ResultSet results = stmt.executeQuery("SELECT ID, Name, Job FROM sample4 WHERE Job = Project Manager"); assertTrue(results.next()); assertEquals("The ID is wrong","01",results.getString("ID")); assertTrue(results.next()); assertEquals("The ID is wrong","02",results.getString("ID")); assertTrue(results.next()); assertEquals("The ID is wrong","04",results.getString("ID")); assertTrue(!results.next()); } catch(Exception e) { fail("Unexpected Exception: " + e); } } /** * This returns no results with where and tests if this still works */ public void testWhereNoResults() { try { Connection conn = DriverManager.getConnection("jdbc:relique:csv:" + filePath); Statement stmt = conn.createStatement(); ResultSet results = stmt.executeQuery("SELECT ID,Name FROM sample4 WHERE ID=05"); assertFalse(results.next()); } catch(Exception e) { fail("Unexpected Exception: " + e); } } }
package kg.apc.jmeter.threads; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.concurrent.ConcurrentHashMap; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.table.TableCellEditor; import kg.apc.jmeter.charting.AbstractGraphRow; import kg.apc.jmeter.vizualizers.DateTimeRenderer; import kg.apc.jmeter.charting.GraphPanelChart; import kg.apc.jmeter.charting.GraphRowExactValues; import org.apache.jmeter.control.LoopController; import org.apache.jmeter.control.gui.LoopControlPanel; import org.apache.jmeter.gui.util.PowerTableModel; import org.apache.jmeter.gui.util.VerticalPanel; import org.apache.jmeter.testelement.TestElement; import org.apache.jmeter.threads.AbstractThreadGroup; import org.apache.jmeter.threads.JMeterThread; import org.apache.jmeter.threads.gui.AbstractThreadGroupGui; import org.apache.jorphan.collections.HashTree; public class UltimateThreadGroupGui extends AbstractThreadGroupGui { protected ConcurrentHashMap<String, AbstractGraphRow> model; private GraphPanelChart chart; private LoopControlPanel loopPanel; private PowerTableModel tableModel; private JTable paramTable; private JButton addRowButton; private JButton deleteRowButton; public UltimateThreadGroupGui() { super(); init(); } protected final void init() { JPanel containerPanel = new VerticalPanel(); containerPanel.add(createParamsPanel(), BorderLayout.NORTH); containerPanel.add(createChart(), BorderLayout.CENTER); add(containerPanel, BorderLayout.CENTER); // this magic LoopPanel provides functionality for thread loops // TODO: find a way without magic createControllerPanel(); } private JPanel createParamsPanel() { JPanel panel = new JPanel(new BorderLayout(5, 5)); panel.setBorder(BorderFactory.createTitledBorder("Threads Schedule")); panel.setPreferredSize(new Dimension(200, 200)); JScrollPane scroll = new JScrollPane(createGrid()); scroll.setPreferredSize(scroll.getMinimumSize()); panel.add(scroll, BorderLayout.CENTER); panel.add(createButtons(), BorderLayout.SOUTH); return panel; } private JTable createGrid() { initTableModel(); paramTable = new JTable(tableModel); // paramTable.setRowSelectionAllowed(true); // paramTable.setColumnSelectionAllowed(true); paramTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // paramTable.setCellSelectionEnabled(true); //paramTable.setFillsViewportHeight(true); paramTable.setMinimumSize(new Dimension(200, 100)); return paramTable; } protected void initTableModel() { tableModel = new PowerTableModel( // column names new String[] { "Start Threads Count", "Initial Delay, sec", "RampUp Time, sec", "Hold Load For, sec" }, // column classes new Class[] { Integer.class, Integer.class, Integer.class, Integer.class }); } public String getLabelResource() { return this.getClass().getSimpleName(); } @Override public String getStaticLabel() { return "Ultimate Thread Group"; } public TestElement createTestElement() { SteppingThreadGroup tg = new SteppingThreadGroup(); modifyTestElement(tg); return tg; } public void modifyTestElement(TestElement tg) { super.configureTestElement(tg); /* tg.setProperty(SteppingThreadGroup.NUM_THREADS, totalThreads.getText()); tg.setProperty(SteppingThreadGroup.THREAD_GROUP_DELAY, initialDelay.getText()); tg.setProperty(SteppingThreadGroup.INC_USER_COUNT, incUserCount.getText()); tg.setProperty(SteppingThreadGroup.INC_USER_PERIOD, incUserPeriod.getText()); tg.setProperty(SteppingThreadGroup.DEC_USER_COUNT, decUserCount.getText()); tg.setProperty(SteppingThreadGroup.DEC_USER_PERIOD, decUserPeriod.getText()); tg.setProperty(SteppingThreadGroup.FLIGHT_TIME, flightTime.getText()); if (tg instanceof SteppingThreadGroup) { updateChart((SteppingThreadGroup) tg); ((AbstractThreadGroup) tg).setSamplerController((LoopController) loopPanel.createTestElement()); } * */ } @Override public void configure(TestElement tg) { super.configure(tg); /* totalThreads.setText(Integer.toString(tg.getPropertyAsInt(SteppingThreadGroup.NUM_THREADS))); initialDelay.setText(Integer.toString(tg.getPropertyAsInt(SteppingThreadGroup.THREAD_GROUP_DELAY))); incUserCount.setText(Integer.toString(tg.getPropertyAsInt(SteppingThreadGroup.INC_USER_COUNT))); incUserPeriod.setText(Integer.toString(tg.getPropertyAsInt(SteppingThreadGroup.INC_USER_PERIOD))); decUserCount.setText(Integer.toString(tg.getPropertyAsInt(SteppingThreadGroup.DEC_USER_COUNT))); decUserPeriod.setText(Integer.toString(tg.getPropertyAsInt(SteppingThreadGroup.DEC_USER_PERIOD))); flightTime.setText(Integer.toString(tg.getPropertyAsInt(SteppingThreadGroup.FLIGHT_TIME))); * */ TestElement te = (TestElement) tg.getProperty(AbstractThreadGroup.MAIN_CONTROLLER).getObjectValue(); if (te != null) { loopPanel.configure(te); } } private void updateChart(SteppingThreadGroup tg) { model.clear(); GraphRowExactValues row = new GraphRowExactValues(); row.setColor(Color.RED); row.setDrawLine(true); row.setMarkerSize(AbstractGraphRow.MARKER_SIZE_SMALL); final HashTree hashTree = new HashTree(); hashTree.add(new LoopController()); JMeterThread thread = new JMeterThread(hashTree, null, null); // test start row.add(System.currentTimeMillis(), 0); row.add(System.currentTimeMillis() + tg.getThreadGroupDelay(), 0); // users in for (int n = 0; n < tg.getNumThreads(); n++) { thread.setThreadNum(n); tg.scheduleThread(thread); row.add(thread.getStartTime(), n + 1); } // users out for (int n = 0; n < tg.getNumThreads(); n++) { thread.setThreadNum(n); tg.scheduleThread(thread); row.add(thread.getEndTime(), tg.getNumThreads() - n); } // final point row.add(thread.getEndTime() + tg.getOutUserPeriod() * 1000, 0); model.put("Expected parallel users count", row); chart.repaint(); } private JPanel createControllerPanel() { loopPanel = new LoopControlPanel(false); LoopController looper = (LoopController) loopPanel.createTestElement(); looper.setLoops(-1); looper.setContinueForever(true); loopPanel.configure(looper); return loopPanel; } private Component createChart() { chart = new GraphPanelChart(); model = new ConcurrentHashMap<String, AbstractGraphRow>(); chart.setRows(model); chart.setDrawFinalZeroingLines(true); chart.setxAxisLabelRenderer(new DateTimeRenderer("HH:mm:ss")); return chart; } private Component createButtons() { JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(1, 2)); addRowButton = new JButton("Add Row"); deleteRowButton = new JButton("Delete Row"); buttonPanel.add(addRowButton); buttonPanel.add(deleteRowButton); addRowButton.addActionListener(new AddRowAction()); deleteRowButton.addActionListener(new DeleteRowAction()); return buttonPanel; } private class AddRowAction implements ActionListener { public void actionPerformed(ActionEvent e) { if (paramTable.isEditing()) { TableCellEditor cellEditor = paramTable.getCellEditor(paramTable.getEditingRow(), paramTable.getEditingColumn()); cellEditor.stopCellEditing(); } tableModel.addNewRow(); tableModel.fireTableDataChanged(); // Enable DELETE (which may already be enabled, but it won't hurt) deleteRowButton.setEnabled(true); // Highlight (select) the appropriate row. int rowToSelect = tableModel.getRowCount() - 1; paramTable.setRowSelectionInterval(rowToSelect, rowToSelect); } } private class DeleteRowAction implements ActionListener { public void actionPerformed(ActionEvent e) { if (paramTable.isEditing()) { TableCellEditor cellEditor = paramTable.getCellEditor(paramTable.getEditingRow(), paramTable.getEditingColumn()); cellEditor.cancelCellEditing(); } int rowSelected = paramTable.getSelectedRow(); if (rowSelected >= 0) { tableModel.removeRow(rowSelected); tableModel.fireTableDataChanged(); // Disable DELETE if there are no rows in the table to delete. if (tableModel.getRowCount() == 0) { deleteRowButton.setEnabled(false); } // Table still contains one or more rows, so highlight (select) // the appropriate one. else { int rowToSelect = rowSelected; if (rowSelected >= tableModel.getRowCount()) { rowToSelect = rowSelected - 1; } paramTable.setRowSelectionInterval(rowToSelect, rowToSelect); } } } } }
package ai.susi.server.api.cms; import ai.susi.DAO; import ai.susi.json.JsonObjectWithDefault; import ai.susi.server.*; import org.json.JSONArray; import org.json.JSONObject; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.util.ArrayList; public class GetAllLanguages extends AbstractAPIHandler implements APIHandler { private static final long serialVersionUID = -7872551914189898030L; @Override public BaseUserRole getMinimalBaseUserRole() { return BaseUserRole.ANONYMOUS; } @Override public JSONObject getDefaultPermissions(BaseUserRole baseUserRole) { return null; } @Override public String getAPIPath() { return "/cms/getAllLanguages.json"; } @Override public ServiceResponse serviceImpl(Query call, HttpServletResponse response, Authorization rights, final JsonObjectWithDefault permissions) { String model_name = call.get("model", "general"); File model = new File(DAO.model_watch_dir, model_name); String group_name = call.get("group", "knowledge"); File group = new File(model, group_name); String[] languages = group.list((current, name) -> new File(current, name).isDirectory()); JSONArray languagesArray = new JSONArray(languages); return new ServiceResponse(languagesArray); } }
package org.apache.cordova.firebase; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.text.TextUtils; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import java.util.Map; public class FirebasePluginMessagingService extends FirebaseMessagingService { private static final String TAG = "FirebasePlugin"; /** * Called when message is received. * * @param remoteMessage Object representing the message received from Firebase Cloud Messaging. */ @Override public void onMessageReceived(RemoteMessage remoteMessage) { // TODO(developer): Handle FCM messages here. // If the application is in the foreground handle both data and notification messages here. // Also if you intend on generating your own notifications as a result of a received FCM // message, here is where that should be initiated. See sendNotification method below. String title = null; String text = null; int id = 0; if (remoteMessage.getNotification() != null) { title = remoteMessage.getNotification().getTitle(); text = remoteMessage.getNotification().getBody(); } else { title = remoteMessage.getData().get("title"); text = remoteMessage.getData().get("text"); try { id = Integer.valueOf(remoteMessage.getData().get("id")); } catch (Exception e) { // ignore } } Log.d(TAG, "From: " + remoteMessage.getFrom()); Log.d(TAG, "Notification Message Title: " + title); Log.d(TAG, "Notification Message Body/Text: " + text); // TODO: Add option to developer to configure if show notification when app on foreground if (!TextUtils.isEmpty(text) || !TextUtils.isEmpty(title)) { sendNotification(id, title, text, remoteMessage.getData()); } } private void sendNotification(int id, String title, String messageBody, Map<String, String> data) { Intent intent = new Intent(this, OnNotificationOpenReceiver.class); Bundle bundle = new Bundle(); for (String key : data.keySet()) { bundle.putString(key, data.get(key)); } intent.putExtras(bundle); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setSmallIcon(getApplicationInfo().icon) .setContentTitle(title) .setContentText(messageBody) .setStyle(new NotificationCompat.BigTextStyle().bigText(messageBody)) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(id, notificationBuilder.build()); } }
package app.android.gambit.local; public class DbFieldParams { public static final String ID = "integer primary key autoincrement not null unique"; public static final String DECK_TITLE = "text not null unique"; public static final String DECK_NEXT_CARD_INDEX = "int not null"; public static final String CARD_DECK_ID = "integer not null references \"Decks\"(\"_id\")"; public static final String CARD_FRONT_SIDE_TEXT = "text not null"; public static final String CARD_BACK_SIDE_TEXT = "text not null"; public static final String CARD_ORDER_INDEX = "int not null"; public static final String DB_LAST_UPDATE_TIME = "text not null unique"; }
package app.sunstreak.yourpisd.net; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectStreamException; import java.io.Serializable; import java.net.MalformedURLException; import java.net.SocketTimeoutException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.util.concurrent.ExecutionException; import org.joda.time.Instant; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Element; import android.app.Application; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.SparseArray; import app.sunstreak.yourpisd.R; public class DataGrabber /*implements Parcelable*/ extends Application { public Domain getDomain() { return domain; } public String getUsername() { return username; } public String getPassword() { return password; } public class Student implements Serializable { private static final long serialVersionUID = -2202613018998649709L; public final int studentId; public final String name; JSONArray classList; int[] classIds; int[] classMatch; SparseArray<JSONObject> classGrades = new SparseArray<JSONObject>(); // Map<Integer[], JSONObject> classGrades = new HashMap<Integer[], JSONObject>(); Bitmap studentPictureBitmap; public Student (int studentId, String studentName) { this.studentId = studentId; String tempName = studentName; name = tempName.substring(tempName.indexOf(",") + 2, tempName.indexOf("(")) + tempName.substring(0, tempName.indexOf(",")); } public void loadClassList() throws IOException { String postParams = "{\"studentId\":\"" + studentId + "\"}"; ArrayList<String[]> requestProperties = new ArrayList<String[]>(); requestProperties.add(new String[] {"Content-Type", "application/json"}); Object[] init = Request.sendPost( "https://gradebook.pisd.edu/Pinnacle/Gradebook/InternetViewer/InternetViewerService.ashx/Init?PageUniqueId=" + pageUniqueId, cookies, requestProperties, true, postParams); String response = (String) init[0]; int responseCode = (Integer) init[1]; cookies = (ArrayList<String>) init[2]; try { classList = (new JSONObject(response)).getJSONArray("classes"); } catch (JSONException e) { e.printStackTrace(); } } public JSONArray getClassList() { return classList; } /** * Uses internet every time. * @throws JSONException */ public int[][] loadGradeSummary () throws JSONException { try { String classId = classList.getJSONObject(0).getString("enrollmentId"); String termId = classList.getJSONObject(0).getJSONArray("terms").getJSONObject(0).getString("termId"); String url = "https://gradebook.pisd.edu/Pinnacle/Gradebook/InternetViewer/GradeSummary.aspx?" + "&EnrollmentId=" + classId + "&TermId=" + termId + "&ReportType=0&StudentId=" + studentId; Object[] summary = Request.sendGet(url, cookies); String response = (String) summary[0]; int responseCode = (Integer) summary[1]; cookies = (ArrayList<String>) summary[2]; if (responseCode != 200) System.out.println("Response code: " + responseCode); /* * puts averages in classList, under each term. */ Element doc = Jsoup.parse(response); int[][] gradeSummary = Parser.gradeSummary(doc, classList); matchClasses(gradeSummary); for (int classIndex = 0; classIndex < gradeSummary.length; classIndex++) { int jsonIndex = classMatch[classIndex]; for (int termIndex = 0; termIndex < gradeSummary[classIndex].length - 1; termIndex++) { int average = gradeSummary[classIndex][termIndex + 1]; if (average != -1) classList.getJSONObject(jsonIndex).getJSONArray("terms").getJSONObject(termIndex) .put("average", average); } } // Last updated time of summary --> goes in this awkward place classList.getJSONObject(0).put("summaryLastUpdated", new Instant().getMillis()); return gradeSummary; } catch (IOException e) { e.printStackTrace(); return null; } catch (JSONException e) { e.printStackTrace(); return null; } } public int[] getClassIds() { if (classIds != null) return classIds; if (classList == null) { System.out.println("You didn't login!"); return classIds; } try { classIds = new int[classList.length()]; for (int i = 0; i < classList.length(); i++) { classIds[i] = classList.getJSONObject(i).getInt("classId"); } } catch (JSONException e) { e.printStackTrace(); } return classIds; } public int[] getTermIds( int classId ) throws JSONException { for (int i = 0; i < classList.length(); i++) { if (classList.getJSONObject(i).getInt("classId") == classId) { JSONArray terms = classList.getJSONObject(i).getJSONArray("terms"); int[] termIds = new int[terms.length()]; for (int j = 0; j < terms.length(); j++) { termIds[j] = terms.getJSONObject(j).getInt("termId"); } return termIds; } } //if class not found. return null; } public int getTermCount (int index) throws JSONException { return classList.getJSONObject(index).getJSONArray("terms").length(); } private String getDetailedReport (int classId, int termId, int studentId) throws MalformedURLException, IOException { String url = "https://gradebook.pisd.edu/Pinnacle/Gradebook/InternetViewer/StudentAssignments.aspx?" + "&EnrollmentId=" + classId + "&TermId=" + termId + "&ReportType=0&StudentId=" + studentId; Object[] report = Request.sendGet(url, cookies); String response = (String) report[0]; int responseCode = (Integer) report[1]; cookies = (ArrayList<String>) report[2]; if (responseCode != 200) { System.out.println("Response code: " + responseCode); } return response; } public boolean hasGradeSummary() { return classList.optJSONObject(0).optLong("summaryLastUpdated", -1) != -1; } // public int[][] getGradeSummary () { // if (!hasGradeSummary()) // try { // loadGradeSummary(); // } catch (JSONException e) { // return null; // return gradeSummary; public boolean hasClassGrade (int classIndex, int termIndex) { return classGrades.indexOfKey(classIndex) > 0 && classGrades.get(classIndex).optJSONArray("terms") .optJSONObject(termIndex).optLong("lastUpdated", -1) != -1; } public JSONObject getClassGrade( int classIndex, int termIndex ) { String html = ""; if (hasClassGrade(classIndex, termIndex)) return classGrades.get(classIndex).optJSONArray("terms").optJSONObject(termIndex); try { int classId = getClassIds()[classIndex]; int termId = getTermIds(classId)[termIndex]; html = getDetailedReport(classId, termId, studentId); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } //Parse the teacher name if not already there. try { classList.getJSONObject(classIndex).getString("teacher"); } catch (JSONException e) { // Teacher was not found. String[] teacher = Parser.teacher(html); try { classList.getJSONObject(classIndex).put("teacher", teacher[0]); classList.getJSONObject(classIndex).put("teacherEmail", teacher[1]); } catch (JSONException f) { e.printStackTrace(); } } JSONObject classGrade; try { classGrade = new JSONObject(classList.getJSONObject( classIndex ).toString()); JSONArray termGrades = Parser.detailedReport(html); Object[] termCategory = Parser.termCategoryGrades(html); JSONArray termCategoryGrades = (JSONArray) termCategory[0]; if ((Integer)termCategory[1] != -1) classGrade.getJSONArray("terms").getJSONObject(termIndex).put("average", termCategory[1].toString()); classGrade.getJSONArray("terms").getJSONObject(termIndex).put("grades", termGrades); classGrade.getJSONArray("terms").getJSONObject(termIndex).put("categoryGrades", termCategoryGrades); Instant in = new Instant(); // String time = in.toString(); // System.out.println(time); classGrade.getJSONArray("terms").getJSONObject(termIndex).put("lastUpdated", in.getMillis()); // classGrade.getJSONArray("terms").getJSONObject(termIndex).put("lastUpdated", "0"); System.out.println("cg= " + classGrade); if (classGrades.indexOfKey(classIndex) < 0) classGrades.put(classIndex, classGrade); // classGrades.get(classIndex).getJSONArray("terms").put(termIndex, classGrade); return classGrade.getJSONArray("terms").getJSONObject(termIndex); } catch (JSONException e) { e.printStackTrace(); return null; } } public String getClassName (int classIndex) { if (classList == null) return "null"; else try { return classList.getJSONObject(classIndex).getString("title"); } catch (JSONException e) { e.printStackTrace(); return "jsonException"; } } private void loadStudentPicture() { ArrayList<String[]> requestProperties = new ArrayList<String[]>(); requestProperties.add(new String[] {"Content-Type", "image/jpeg"} ); Object[] response = Request.getBitmap("https://gradebook.pisd.edu/Pinnacle/Gradebook/common/picture.ashx?studentId=" + studentId, cookies, requestProperties, true); studentPictureBitmap = (Bitmap) response[0]; int responseCode = (Integer) response[1]; cookies = (ArrayList<String>) cookies; } public Bitmap getStudentPicture() { if (studentPictureBitmap == null) loadStudentPicture(); return studentPictureBitmap; } public void matchClasses(int[][] gradeSummary) { getClassIds(); // int[][] gradeSummary = getGradeSummary(); int classCount = gradeSummary.length; classMatch = new int[classCount]; int classesMatched = 0; while (classesMatched < classCount) { for (int i = classesMatched; i < classIds.length; i++) { if (classIds[i] == gradeSummary[classesMatched][0]) { classMatch[classesMatched] = i; classesMatched++; break; } } } } public int[] getClassMatch () { return classMatch; } public double getGPA () { if (classMatch == null) return -2; double pointSum = 0; int pointCount = 0; for (int classIndex = 0; classIndex < classMatch.length; classIndex++) { int jsonIndex = classMatch[classIndex]; double sum = 0; double count = 0; for (int termIndex = 0; termIndex < 4; termIndex++) { if (classList.optJSONObject(jsonIndex).optJSONArray("terms").optJSONObject(termIndex).optInt("average", -1) != -1) { sum += classList.optJSONObject(jsonIndex).optJSONArray("terms").optJSONObject(termIndex).optInt("average"); count++; } } if (count > 0) { int grade = (int) Math.round (sum / count); // Failed class if (grade < 70) { // Do not increment pointSum because the student received a GPA of 0. pointCount++; } else { pointCount++; double classGPA = maxGPA(classIndex) - gpaDifference(grade); pointSum += classGPA; } } } return pointSum / pointCount; } public double maxGPA (int classIndex) { return maxGPA(getClassName(classMatch[classIndex])); } public double maxGPA (String className) { if (className.contains("PHYS IB SL") || className.contains("MATH STDY IB")) return 4.5; String[] split = className.split("[\\s()\\d\\/]+"); for (int i = split.length - 1; i >= 0; i if (split[i].equals("AP") || split[i].equals("IB")) return 5; if (split[i].equals("H") || split[i].equals("IH")) return 4.5; } return 4; } public double gpaDifference (int grade) { if (grade<= 100 & grade>= 97) return 0; if (grade >= 93) return 0.2; if (grade >= 90) return 0.4; if (grade >= 87) return 0.6; if (grade >= 83) return 0.8; if (grade >= 80) return 1.0; if (grade >= 77) return 1.2; if (grade >= 73) return 1.4; if (grade >= 71) return 1.6; if (grade == 70) return 2; // Grade below 70 or above 100 return -1; } private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.write(studentId); out.writeUTF(name); out.writeUTF(classList.toString()); } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { } } Domain domain; String username; String password; String[] passthroughCredentials; String[] gradebookCredentials; String pageUniqueId; // 1= success. 0 = not tried; <0 = failure. int editureLogin = 0; int gradebookLogin = 0; ArrayList<String> cookies = new ArrayList<String>(); String studentName = ""; Bitmap studentPictureBitmap; List<Student> students = new ArrayList<Student>(); public int studentIndex = 0; public boolean MULTIPLE_STUDENTS; public void clearData () { domain = null; username = null; password = null; passthroughCredentials = null; gradebookCredentials = null; pageUniqueId = null; editureLogin = 0; gradebookLogin = 0; cookies = new ArrayList<String>(); studentName = ""; studentPictureBitmap = null; students = new ArrayList<Student>(); studentIndex = 0; } public void setData (Domain domain, String username, String password) { this.domain = domain; this.username = username; this.password = password; } public void setData (String username, String password) { this.username = username; this.password = password; // Find out whether student or parent using the username. if (username.equals("test")) { this.domain = Domain.TEST; students = getTestStudents(); passthroughCredentials = new String[] {"", ""}; gradebookCredentials = new String[] {"", ""}; MULTIPLE_STUDENTS = true; } else if (username.contains("@mypisd.net") || !username.contains("@")) this.domain = Domain.STUDENT; else this.domain = Domain.PARENT; } public int login(/*Domain dom, String username, String password*/) throws MalformedURLException, IOException, InterruptedException, ExecutionException { String response; int responseCode; String postParams; switch (domain) { case PARENT: postParams = "__LASTFOCUS=&__EVENTTARGET=&__EVENTARGUMENT=" + "&__VIEWSTATE=%2FwEPDwULLTEwNjY5NzA4NTBkZMM%2FuYdqyffE27bFnREF10B%2FRqD4" + "&__SCROLLPOSITIONX=0&__SCROLLPOSITIONY=0" + "&__EVENTVALIDATION=%2FwEWBAK6wtGnBgLEhsriDQLHoumWCgLyjYGEDNS0X%2BIS%2B22%2FGghXXv5nzic%2Bj46b" + "&ctl00%24ContentPlaceHolder1%24portalLogin%24UserName=" + URLEncoder.encode(username, "UTF-8") + "&ctl00%24ContentPlaceHolder1%24portalLogin%24Password=" + URLEncoder.encode(password,"UTF-8") + "&ctl00%24ContentPlaceHolder1%24portalLogin%24LoginButton=Login"; Object[] cookieAuth = Request.sendPost( domain.loginAddress, postParams, /*"password=" + URLEncoder.encode(password,"UTF-8") + "&username=" + URLEncoder.encode(username,"UTF-8") + "&Submit=Login",*/ cookies); response = (String) cookieAuth[0]; responseCode = (Integer) cookieAuth[1]; cookies = (ArrayList<String>) cookieAuth[2]; if (Parser.accessGrantedEditure(response)) { System.out.println("Editure access granted!"); editureLogin = 1; passthroughCredentials = Parser.passthroughCredentials(response); return 1; } else { System.out.println("Bad username/password 1!"); System.out.println(response); editureLogin = -1; return -1; } case STUDENT: Object[] portalDefaultPage = Request.sendGet( domain.loginAddress, cookies); response = (String) portalDefaultPage[0]; responseCode = (Integer) portalDefaultPage[1]; cookies = (ArrayList<String>) portalDefaultPage[2]; String[][] requestProperties = new String[][] { {"Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}, {"Accept-Encoding","gzip,deflate,sdch"}, {"Accept-Language","en-US,en;q=0.8,es;q=0.6"}, {"Cache-Control","max-age=0"}, {"Connection","keep-alive"}, //{"Content-Length","75"}, {"Content-Type","application/x-www-form-urlencoded"}, //{"Cookie","JSESSIONID=22DDAFA488B9D839F082FE26EFE8B38B"}, {"Host","sso.portal.mypisd.net"}, {"Origin","https://sso.portal.mypisd.net"}, {"Referer","https://sso.portal.mypisd.net/cas/login?service=http%3A%2F%2Fportal.mypisd.net%2Fc%2Fportal%2Flogin"} }; ArrayList<String[]> rp = new ArrayList<String[]>(java.util.Arrays.asList(requestProperties)); String lt = Parser.portalLt(response); postParams = "username=" + URLEncoder.encode(username, "UTF-8") + "&password=" + URLEncoder.encode(password, "UTF-8") + "&lt=" + lt + "&_eventId=submit"; try { Object[] portalLogin = Request.sendPost( domain.loginAddress, cookies, rp, true, postParams); response = (String) portalLogin[0]; responseCode = (Integer) portalLogin[1]; cookies = (ArrayList<String>) portalLogin[2]; // weird AF way of checking for bad password. if (Request.getRedirectLocation() == null) return -1; Object[] ticket = Request.sendGet( Request.getRedirectLocation(), cookies); if (ticket == null) return -2; response = (String) ticket[0]; responseCode = (Integer) ticket[1]; cookies = (ArrayList<String>) ticket[2]; passthroughCredentials = Parser.passthroughCredentials(response); return 1; } catch (SocketTimeoutException e) { e.printStackTrace(); return -2; } case TEST: Thread.sleep(500); System.out.println("Test login"); editureLogin = 1; return 1; default: return 0; } } public int loginGradebook(String userType, String uID, String email, String password) throws MalformedURLException, IOException { if (domain == Domain.TEST) { try { Thread.sleep(500); System.out.println("Test login gradebook"); } catch (InterruptedException e) { } gradebookLogin = 1; return 1; } ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo == null || !networkInfo.isConnected()) return -10; // commented request paramater is allowed for parent account, not allowed for student account. never required. String url = "https://parentviewer.pisd.edu/EP/PIV_Passthrough.aspx?action=trans&uT=" + userType + "&uID=" + uID /*+ "&submit=Login+to+Parent+Viewer"*/; String postParams = "password=" + password + "&username=" + email; Object[] passthrough = Request.sendPost( url, postParams, cookies); String response = (String) passthrough[0]; int responseCode = (Integer) passthrough[1]; cookies = (ArrayList<String>) passthrough[2]; String[] gradebookCredentials = Parser.getGradebookCredentials(response); /* * escapes if access not granted. */ if (Parser.accessGrantedGradebook(gradebookCredentials)) { System.out.println("Gradebook access granted!"); gradebookLogin = 1; } else { System.out.println("Bad username/password 2!"); gradebookLogin return -1; } postParams = "userId=" + gradebookCredentials[0] + "&password=" + gradebookCredentials[1]; Object[] link = Request.sendPost("https://gradebook.pisd.edu/Pinnacle/Gradebook/link.aspx?target=InternetViewer", postParams, cookies); response = (String) link[0]; responseCode = (Integer) link[1]; cookies = (ArrayList<String>) link[2]; // for teh cookiez Object[] defaultAspx = Request.sendPost("https://gradebook.pisd.edu/Pinnacle/Gradebook/Default.aspx", postParams, cookies); response = (String) defaultAspx[0]; responseCode = (Integer) defaultAspx[1]; cookies = (ArrayList<String>) defaultAspx[2]; for (String[] args : Parser.parseStudents(response) ) { students.add(new Student(Integer.parseInt(args[0]) , args[1])); } MULTIPLE_STUDENTS = students.size() > 1; for (Student st : students) { cookies.add("PinnacleWeb.StudentId=" + st.studentId); } pageUniqueId = Parser.pageUniqueId(response); // throws PISDException if (pageUniqueId == null) { System.out.println("Some error. pageUniqueId is null"); return -1; } for (Student st : students) { st.loadClassList(); } return 1; } /** * Temporary code. In use because login1.mypisd.net has an expired certificate. with new portal website, should not be necessary. */ /* public static void acceptAllCertificates() { TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { } } */ public int getEditureLogin() { return editureLogin; } public int getGradebookLogin() { return gradebookLogin; } public String[] getGradebookCredentials() { return gradebookCredentials; } public String[] getPassthroughCredentials() { return passthroughCredentials; } public List<Student> getStudents() { return students; } public Student getCurrentStudent() { return students.get(studentIndex); } private List<Student> getTestStudents() { class TestStudent extends Student{ private static final long serialVersionUID = 4870831615938950349L; public TestStudent(int studentId, String studentName) { super(studentId, studentName); InputStream is = null; switch (studentId) { case 0: is = getResources().openRawResource(R.raw.student_0_class_grades); break; case 1: is = getResources().openRawResource(R.raw.student_1_class_grades); break; } if (is == null) { System.out.println("is = null"); return; } Scanner sc = new Scanner(is).useDelimiter("\\A"); String json = sc.hasNext() ? sc.next() : ""; try { classList = new JSONArray(json); classGrades = new SparseArray<JSONObject>(); for (int i = 0; i < classList.length(); i++) { classGrades.put(i, new JSONObject(classList.getJSONObject(i).toString())); // for (int j = 0; j < classList.getJSONObject(i).getJSONArray("terms").length(); j++) { // classGrades.get(i).put(j, classList.getJSONObject(i)); } } catch (JSONException e) { e.printStackTrace(); return; } } public void loadClassList() { } public JSONObject getClassGrade(int classIndex, int termIndex) { return classGrades.get(classIndex).optJSONArray("terms").optJSONObject(termIndex); } public int[] getClassMatch() { return getClassIds(); } public int[][] loadGradeSummary() { /* InputStream is; switch (studentId) { case 0: is = getResources().openRawResource(R.raw.student_0_grade_summary); break; case 1: is = getResources().openRawResource(R.raw.student_1_grade_summary); break; default: return null; } Scanner sc = new Scanner(is); int[][] gradeSummary = new int[7][7]; for (int i = 0; i < 7; i++) { for (int j = 0; j < 7; j++) { gradeSummary[i][j] = sc.nextInt(); } } matchClasses(gradeSummary); return gradeSummary; */ return null; } public int[] getClassIds() { return new int[] {0, 1, 2, 3, 4, 5, 6}; } public int[] getTermIds(int classId) throws JSONException { return new int[] {0, 1, 2, 3, 4, 5}; } // public int[][] getGradeSummary () { // if (gradeSummary == null) // loadGradeSummary(); // return gradeSummary; public Bitmap getStudentPicture() { switch (studentId) { case 0: return BitmapFactory.decodeResource(getResources(), R.drawable.student_0); case 1: return BitmapFactory.decodeResource(getResources(), R.drawable.student_1); default: return null; } } public void matchClasses() { classMatch = new int[] {0, 1, 2, 3, 4, 5, 6}; } } List<Student> students = new ArrayList<Student>(); students.add(new TestStudent(0, "Griffin, Stewie (0)")); students.add(new TestStudent(1, "Griffin, Meg (1)")); return students; } public void writeToFile() { writeDetailsToFile(); writeDataToFile(); } private void writeDetailsToFile() { String filename = "DATA_GRABBER_DETAILS"; String string = domain.toString() + "\n" + username + "\n" + password; FileOutputStream outputStream; try { outputStream = openFileOutput(filename, Context.MODE_PRIVATE); outputStream.write(string.getBytes()); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } } private void writeDataToFile() { String filename = "DATA_GRABBER_DATA"; String string = ""; for (Student st : students) { string += st.classGrades.toString() + "\n"; } FileOutputStream outputStream; try { outputStream = openFileOutput(filename, Context.MODE_PRIVATE); outputStream.write(string.getBytes()); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } } }
package co.phoenixlab.discord.api; /** * Contains various useful API URLs and paths */ public class ApiConst { /** * Utility class */ private ApiConst() { } /** * The base URL from which Discord runs */ public static final String BASE_URL = "https://discordapp.com/"; /** * Base API path */ public static final String API_BASE_PATH = BASE_URL + "api"; /** * WebSocket gateway */ public static final String WEBSOCKET_GATEWAY = API_BASE_PATH + "/gateway"; /** * The endpoint for accessing user information */ public static final String USERS_ENDPOINT = API_BASE_PATH + "/users/"; /** * The endpoint for logging in */ public static final String LOGIN_ENDPOINT = API_BASE_PATH + "/auth/login"; /** * The endpoint for logging out */ public static final String LOGOUT_ENDPOINT = API_BASE_PATH + "/auth/logout"; /** * The endpoint for accessing server information */ public static final String SERVERS_ENDPOINT = API_BASE_PATH + "/guilds/"; /** * The endpoint for accessing channel information */ public static final String CHANNELS_ENDPOINT = API_BASE_PATH + "/channels/"; /** * The endpoint for accepting invites */ public static final String INVITE_ENDPOINT = API_BASE_PATH + "/invite"; /** * The format string for avatar URLs */ public static final String AVATAR_URL_PATTERN = "https://cdn.discordapp.com/avatars/%1$s/%2$s.jpg"; }
package com.amee.restlet; import org.apache.commons.lang.StringUtils; import org.apache.xerces.dom.DocumentImpl; import org.json.JSONException; import org.json.JSONObject; import org.restlet.Application; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Request; import org.restlet.data.Response; import org.restlet.data.Status; import org.restlet.ext.json.JsonRepresentation; import org.restlet.resource.DomRepresentation; import org.restlet.resource.Representation; import org.restlet.resource.StringRepresentation; import org.restlet.service.StatusService; import org.springframework.stereotype.Service; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.util.logging.Level; @Service("ameeStatusService") public class AMEEStatusService extends StatusService { public AMEEStatusService() { super(); } @Override public Status getStatus(Throwable throwable, Request request, Response response) { Application.getCurrent().getLogger() .log(Level.SEVERE, "Unhandled exception or error intercepted: " + throwable, throwable); return new Status(Status.SERVER_ERROR_INTERNAL.getCode(), throwable); } @Override public Representation getRepresentation(Status status, Request request, Response response) { Representation representation; if (MediaTypeUtils.isStandardWebBrowser(request)) { representation = getWebBrowserRepresentation(status, request); } else { representation = getApiRepresentation(status, request); } if (representation == null) { return super.getRepresentation(status, request, response); } return representation; } private Representation getWebBrowserRepresentation(Status status, Request request) { return null; } private Representation getApiRepresentation(Status status, Request request) { Representation representation = null; if (MediaTypeUtils.doesClientAccept(MediaType.APPLICATION_JSON, request)) { representation = getJsonRepresentation(status); } else if (MediaTypeUtils.doesClientAccept(MediaType.APPLICATION_XML, request)) { representation = getDomRepresentation(status); } if (representation == null) { representation = getStringRepresentation(status); } return representation; } private Representation getJsonRepresentation(Status status) { Representation representation = null; try { JSONObject obj = new JSONObject(); JSONObject statusObj = new JSONObject(); statusObj.put("code", status.getCode()); statusObj.put("name", status.getName()); statusObj.put("description", status.getDescription()); statusObj.put("uri", status.getUri()); obj.put("status", statusObj); representation = new JsonRepresentation(obj); } catch (JSONException e) { // swallow } return representation; } private Representation getDomRepresentation(Status status) { Representation representation; Document document = new DocumentImpl(); Element elem = document.createElement("Resources"); Element statusElem = document.createElement("Status"); statusElem.appendChild(getElement(document, "Code", "" + status.getCode())); statusElem.appendChild(getElement(document, "Name", status.getName())); statusElem.appendChild(getElement(document, "Description", status.getDescription())); statusElem.appendChild(getElement(document, "URI", status.getUri())); elem.appendChild(statusElem); document.appendChild(elem); representation = new DomRepresentation(MediaType.APPLICATION_XML, document); return representation; } private static Element getElement(Document document, String name, String value) { Element element = document.createElement(name); element.setTextContent(value); return element; } private Representation getStringRepresentation(Status status) { return new StringRepresentation( "Code: " + status.getCode() + "\n" + "Name: " + status.getName() + "\n" + "Description: " + status.getDescription() + "\n"); } private String getNextUrl(Request request) { // first, look for 'next' in parameters Form parameters = request.getResourceRef().getQueryAsForm(); String next = parameters.getFirstValue("next"); if (StringUtils.isEmpty(next)) { // second, determine 'next' from the previousResourceRef, if set (by DataFilter and ProfileFilter perhaps) if (request.getAttributes().get("previousResourceRef") != null) { next = request.getAttributes().get("previousResourceRef").toString(); } } if (StringUtils.isEmpty(next)) { // third, determine 'next' from current URL next = request.getResourceRef().toString(); if ((next != null) && ((next.endsWith("/signIn") || next.endsWith("/signOut") || next.endsWith("/protected")))) { next = null; } } if (StringUtils.isEmpty(next)) { // forth, use a default next = "/auth"; } return next; } }
package com.binatechnologies.varsim; import com.binatechnologies.varsim.fastq_liftover.FastqLiftOver; import org.apache.log4j.Logger; import java.io.IOException; import java.util.Arrays; // parameter parsing will be updated to be nicer later public class VarSim { private final static Logger log = Logger.getLogger(VarSim.class.getName()); public void run(String[] args) throws IOException{ String usage = "java -jar VarSim.jar <tool> <tool_args>... \n" + " --= Simulation =-- \n" + " randvcf2vcf -- Randomly samples variants from a VCF file\n" + " randdgv2vcf -- Randomly samples variants from a DGV database file\n" + " --= Validation =-- \n" + " vcfcompare -- Generate JSON describing vcf accuracy relative to truth \n" + " samcompare -- Generate JSON describing alignment accuracy relative to truth \n" + " vcfstats -- Generate stats on size range and variant types in a VCF\n" + " --= Internal =-- \n" + " vcf2diploid -- Enhanced version of vcf2diploid from alleleseq \n" + " fastq_liftover -- Lifts over simulated FASTQ files to reference coordinates \n" + "\n"; if(args.length == 0){ System.err.println(usage); } String[] pass_args = Arrays.copyOfRange(args,1,args.length); switch(args[0]){ case "vcf2diploid": new VCF2diploid().run(pass_args); break; case "randvcf2vcf": new RandVCF2VCF().run(pass_args); break; case "randdgv2vcf": new RandDGV2VCF().run(pass_args); break; case "vcfstats": new VCFstats().run(pass_args); break; case "vcfcompare": new VCFcompare().run(pass_args); break; case "samcompare": new SAMcompare().run(pass_args); break; case "randbed2vcf": new RandBED2VCF().run(pass_args); break; case "fastq_liftover": new FastqLiftOver().doMain(pass_args); break; default: log.error("Unknown tool: " + args[0]); System.err.println(usage); break; } } public static void main(String[] args) throws IOException{ VarSim runner = new VarSim(); runner.run(args); } }
package com.couchbase.cblite; public interface CBLiteVersion { String CBLiteVersionNumber = "1.0.0-beta"; }
package com.esri.simulator; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.security.SecureRandom; import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.commons.math3.stat.regression.SimpleRegression; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.json.JSONObject; /** * * @author david */ public class FeatureLayerMon { public FeatureLayerMon(String featureLayerURL, int sampleRateSec) { try { String strURL = featureLayerURL + "/query?where=1%3D1&returnCountOnly=true&f=json"; URL url = new URL(strURL); SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[]{new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { System.out.println("getAcceptedIssuers ============="); return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { System.out.println("checkClientTrusted ============="); } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { System.out.println("checkServerTrusted ============="); } }}, new SecureRandom()); CloseableHttpClient httpclient = HttpClients .custom() .setSSLContext(sslContext) .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) .build(); int cnt1 = 0; int cnt2 = -1; int stcnt = 0; int numSamples = 0; long t1 = 0L; long t2 = 0L; SimpleRegression regression = new SimpleRegression(); while (true) { try { HttpGet request = new HttpGet(strURL); CloseableHttpResponse response = httpclient.execute(request); BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } //System.out.println(result); JSONObject json = new JSONObject(result.toString()); request.abort(); response.close(); cnt1 = json.getInt("count"); t1 = System.currentTimeMillis(); if (cnt2 == -1) { cnt2 = cnt1; stcnt = cnt1; } else if (cnt1 > cnt2) { // Increase number of samples numSamples += 1; if (numSamples > 2) { double rcvRate = regression.getSlope() * 1000; System.out.println(numSamples + "," + t1 + "," + cnt1 + "," + rcvRate); } else { System.out.println(numSamples + "," + t1 + "," + cnt1); } // Add to Linear Regression regression.addData(t1, cnt1); } else if (cnt1 == cnt2 && numSamples > 0) { numSamples -= 1; // Remove the last sample regression.removeData(t2, cnt2); System.out.println("Removing: " + t2 + "," + cnt2); // Output Results int cnt = cnt2 - stcnt; double rcvRate = regression.getSlope() * 1000; // converting from ms to seconds if (numSamples > 5) { double rateStdErr = regression.getSlopeStdErr(); System.out.format("%d , %.2f, %.4f\n", cnt, rcvRate, rateStdErr); } else if (numSamples >= 2) { System.out.format("%d , %.2f\n", cnt, rcvRate); } else { System.out.println("Not enough samples to calculate rate. "); } // Reset cnt1 = -1; cnt2 = -1; stcnt = 0; numSamples = 0; t1 = 0L; t2 = 0L; regression = new SimpleRegression(); } cnt2 = cnt1; t2 = t1; // Pause 5 seconds Thread.sleep(sampleRateSec * 1000); } catch (SSLHandshakeException e) { System.out.println("Can't connect to the URL: " + featureLayerURL); e.printStackTrace(); break; } catch (Exception a) { System.out.println(a.getMessage()); } } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { // Command Line to watch counts on speicifed ArcGIS Server Feature Layer /* NOTE: For latency calculations ensure all servers including the server running simulation are using time chrnonized. Run this command simulatneously on machines to compare time $ date +%s NTP command force update now: $ sudo ntpdate -s time.nist.gov CHRONYD check status: $ chronyc tracking */ int numargs = args.length; if (numargs != 1 && numargs != 2) { System.err.print("Usage: FeatureLayerMon <Feature-Layer> (<sampleRateMS>) \n"); } else if (numargs == 1) { FeatureLayerMon t = new FeatureLayerMon(args[0], 5); } else { FeatureLayerMon t = new FeatureLayerMon(args[0], Integer.parseInt(args[1])); } } }
package com.gliwka.hyperscan.wrapper; /** * Represents a match found during the scan */ public class Match { private long startPosition; private long endPosition; private String matchedString; private Expression matchedExpression; public Match(long start, long end, String match, Expression expression) { startPosition = start; endPosition = end; matchedString = match; matchedExpression = expression; } /** * Get the exact matched string * @return matched string if SOM flag is set, otherwise empty string */ public String getMatchedString() { return matchedString; } /** Get the start position of the match * @return if the SOM flag is set the position of the match, otherwise zero. */ public long getStartPosition() { return startPosition; } /** * Get the end position of the match * @return end position of match regardless of flags */ public long getEndPosition() { return endPosition; } /** * Get the Expression object used to find the match * @return Expression instance */ public Expression getMatchedExpression() { return matchedExpression; } }
// Unless required by applicable law or agreed to in writing, software / // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. / package br.shura.venus.origin; import br.shura.x.io.exception.FileException; import br.shura.x.io.file.File; import java.io.IOException; public class FileScriptOrigin implements ScriptOrigin { private final File file; public FileScriptOrigin(File file) { this.file = file; } @Override public ScriptOrigin findInclude(String includeName) { try { File file = new File(getFile().getParent(), includeName); if (file.exists()) { return new FileScriptOrigin(file); } } catch (FileException exception) { } return null; } public File getFile() { return file; } @Override public String getScriptName() { return getFile().getFullName(); } @Override public String read() throws IOException { return getFile().readString(); } @Override public String toString() { return "fileorigin(" + getScriptName() + ')'; } }
package br.unisinos.lab2.mindmap; public class MindMapWriter<E> { private StringBuffer xml; private int currentStringIndex = 0; public void write(MindMap<E> mindMap) { DNode<E> root = mindMap.getRoot(); String out = "<?xml version=\"1.0\"?>\n"; out += makeInnerXML(root, 0); System.out.println(out); //TODO: MAKE WRITE THE XML STRING TO FILE } private String makeInnerXML(DNode <E> node, int tabNumber) { tabNumber += 1; String sNode = "<node>\n"; E elem = node.getElement(); sNode += "<"+elem.getClass().getSimpleName() +">\n"+elem.toString()+"\n</"+elem.getClass().getSimpleName()+">\n"; DNode<E> nextSon = node.getSon(); DNode<E> nextBrother = node.getBro(); if (nextSon != null) { sNode += makeInnerXML(nextSon, tabNumber) + "</node>\n"; if (nextBrother != null) { return sNode + "</node>\n" + makeInnerXML(nextBrother, tabNumber); } else { return sNode + "</node>"; } } else { if (nextBrother != null) { return sNode + "</node>\n" + makeInnerXML(nextBrother, tabNumber); } else { return sNode; } } } }
import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; import java.lang.System.Logger.Level; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.time.Duration; import java.time.Instant; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Comparator; import java.util.Deque; import java.util.EnumSet; import java.util.List; import java.util.Optional; import java.util.Properties; import java.util.ServiceLoader; import java.util.Set; import java.util.StringJoiner; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.UnaryOperator; import java.util.spi.ToolProvider; import java.util.stream.Stream; import jdk.jfr.Category; import jdk.jfr.Event; import jdk.jfr.Label; import jdk.jfr.Name; import jdk.jfr.Recording; import jdk.jfr.StackTrace; public record Bach(Options options, Logbook logbook, Paths paths, Tools tools) { public static void main(String... args) { var bach = Bach.of(args); var code = bach.main(); System.exit(code); } public static Bach of(String... args) { return Bach.of(System.out::println, System.err::println, args); } public static Bach of(Consumer<String> out, Consumer<String> err, String... args) { var options = Options.of(args); return new Bach( options, new Logbook(out, err, options.__logbook_threshold, new ConcurrentLinkedDeque<>()), new Paths(options.__chroot, options.__destination), new Tools( ToolFinder.compose( ToolFinder.ofProperties(options.__chroot.resolve(".bach/tool-provider")), ToolFinder.of( new ToolFinder.Provider("banner", Tools::banner), new ToolFinder.Provider("build", Tools::build), new ToolFinder.Provider("compile", Tools::compile), new ToolFinder.Provider("download", Tools::download), new ToolFinder.Provider("info", Tools::info)), ToolFinder.ofSystem()))); } private static final AtomicReference<Bach> INSTANCE = new AtomicReference<>(); public static Bach getBach() { var bach = INSTANCE.get(); if (bach != null) return bach; throw new IllegalStateException(); } public Bach { if (!INSTANCE.compareAndSet(null, this)) throw new IllegalStateException(); } boolean is(Flag flag) { return options.flags.contains(flag); } public void banner(String text) { var line = "=".repeat(text.length()); logbook.out.accept(""" %s %s %s""".formatted(line, text, line)); } public void build() { run("banner", banner -> banner.with("BUILD")); run("info"); run("compile"); } public void info() { var out = logbook.out(); out.accept("bach.paths = %s".formatted(paths)); if (!is(Flag.VERBOSE)) return; tools.finder().tree(out); Stream.of( ToolCall.of("jar").with("--version"), ToolCall.of("javac").with("--version"), ToolCall.of("javadoc").with("--version")) .sequential() .forEach(call -> run(call, true)); Stream.of( ToolCall.of("jdeps").with("--version"), ToolCall.of("jlink").with("--version"), ToolCall.of("jmod").with("--version"), ToolCall.of("jpackage").with("--version")) .parallel() .forEach(call -> run(call, true)); } public void compile() { logbook.log(Level.WARNING, "TODO compile()"); } public void download(Path to, URI from) { if (Files.exists(to)) return; logbook.log(Level.DEBUG, "Downloading %s".formatted(from)); try (var stream = from.toURL().openStream()) { var size = Files.copy(stream, to); logbook.log(Level.DEBUG, "Downloaded %,7d %s".formatted(size, to.getFileName())); } catch (Exception exception) { throw new RuntimeException(exception); } } int main() { try (var recording = new Recording()) { recording.start(); logbook.log(Level.DEBUG, "BEGIN"); options.calls().forEach(this::run); logbook.log(Level.DEBUG, "END."); recording.stop(); var jfr = Files.createDirectories(paths.out()).resolve("bach-logbook.jfr"); recording.dump(jfr); var logfile = paths.out().resolve("bach-logbook.md"); logbook.out.accept("-> %s".formatted(jfr.toUri())); logbook.out.accept("-> %s".formatted(logfile.toUri())); var duration = Duration.between(recording.getStartTime(), recording.getStopTime()); logbook.out.accept( "Run took %d.%02d seconds".formatted(duration.toSeconds(), duration.toMillis())); Files.write(logfile, logbook.toMarkdownLines()); return 0; } catch (Exception exception) { logbook.log(Level.ERROR, exception.toString()); return -1; } } public void run(String name, Object... arguments) { run(ToolCall.of(name, arguments)); } public void run(String name, UnaryOperator<ToolCall> operator) { run(operator.apply(ToolCall.of(name))); } public void run(ToolCall call) { run(call, is(Flag.VERBOSE)); } public void run(ToolCall call, boolean verbose) { var event = new RunEvent(); event.name = call.name(); event.args = String.join(" ", call.arguments()); /* Log tool call as a single line */ { var line = new StringJoiner(" "); line.add(event.name); if (!event.args.isEmpty()) { var arguments = verbose || event.args.length() <= 50 ? event.args : event.args.substring(0, 45) + "[...]"; line.add(arguments); } logbook.log(Level.INFO, line.toString()); } var start = Instant.now(); var tool = tools.finder().find(call.name()).orElseThrow(); var out = new StringWriter(); var err = new StringWriter(); var args = call.arguments().toArray(String[]::new); event.begin(); event.code = tool.run(new PrintWriter(out), new PrintWriter(err), args); event.end(); event.out = out.toString().strip(); event.err = err.toString().strip(); event.commit(); if (verbose) { if (!event.out.isEmpty()) logbook.out().accept(event.out.indent(2).stripTrailing()); if (!event.err.isEmpty()) logbook.err().accept(event.err.indent(2).stripTrailing()); var duration = Duration.between(start, Instant.now()); var line = "%s ran %d.%02d seconds and returned code %d" .formatted(call.name(), duration.toSeconds(), duration.toMillis(), event.code); var printer = event.code == 0 ? logbook.out() : logbook().err(); printer.accept(line); } } public record Paths(Path root, Path out) {} public record Tools(ToolFinder finder) { static int banner(PrintWriter out, PrintWriter err, String... args) { if (args.length == 0) { err.println("Usage: banner TEXT"); return 1; } Bach.getBach().banner(String.join(" ", args)); return 0; } static int build(PrintWriter out, PrintWriter err, String... args) { Bach.getBach().build(); return 0; } static int compile(PrintWriter out, PrintWriter err, String... args) { Bach.getBach().compile(); return 0; } static int download(PrintWriter out, PrintWriter err, String... args) { if (args.length != 2) { err.println("Usage: download TO-PATH FROM-URI"); return 1; } var to = Path.of(args[0]); var from = URI.create(args[1]); Bach.getBach().download(to, from); return 0; } static int info(PrintWriter out, PrintWriter err, String... args) { Bach.getBach().info(); return 0; } } public enum Flag { VERBOSE } public record Options( Set<Flag> flags, Level __logbook_threshold, Path __chroot, Path __destination, List<ToolCall> calls) { static Options of(String... args) { var flags = EnumSet.noneOf(Flag.class); var level = Level.INFO; var root = Path.of(""); var destination = Path.of(".bach", "out"); var arguments = new ArrayDeque<>(List.of(args)); var calls = new ArrayList<ToolCall>(); while (!arguments.isEmpty()) { var argument = arguments.removeFirst(); if (argument.startsWith(" if (argument.equals("--verbose")) { flags.add(Flag.VERBOSE); continue; } var delimiter = argument.indexOf('=', 2); var key = delimiter == -1 ? argument : argument.substring(0, delimiter); var value = delimiter == -1 ? arguments.removeFirst() : argument.substring(delimiter + 1); if (key.equals("--logbook-threshold")) { level = Level.valueOf(value); continue; } if (key.equals("--chroot")) { root = Path.of(value).normalize(); continue; } if (key.equals("--destination")) { destination = Path.of(value).normalize(); continue; } throw new IllegalArgumentException("Unsupported option `%s`".formatted(key)); } calls.add(new ToolCall(argument, arguments.stream().toList())); break; } return new Options( Set.copyOf(flags), level, root, root.resolve(destination), List.copyOf(calls)); } } public record Logbook( Consumer<String> out, Consumer<String> err, Level threshold, Deque<LogEvent> logs) { public void log(Level level, String message) { var event = new LogEvent(); event.level = level.name(); event.message = message; event.commit(); logs.add(event); if (level.getSeverity() < threshold.getSeverity()) return; var consumer = level.getSeverity() <= Level.INFO.getSeverity() ? out : err; consumer.accept(message); } public List<String> toMarkdownLines() { try { var lines = new ArrayList<>(List.of("# Logbook")); lines.add(""); lines.add("## Log Events"); lines.add(""); lines.add("```text"); logs.forEach(log -> lines.add("[%c] %s".formatted(log.level.charAt(0), log.message))); lines.add("```"); return List.copyOf(lines); } catch (Exception exception) { throw new RuntimeException("Failed to read recorded events?", exception); } } } public record ToolCall(String name, List<String> arguments) { public static ToolCall of(String name, Object... arguments) { if (arguments.length == 0) return new ToolCall(name, List.of()); if (arguments.length == 1) return new ToolCall(name, List.of(arguments[0].toString())); return new ToolCall(name, List.of()).with(Stream.of(arguments)); } public ToolCall with(Stream<?> objects) { var strings = objects.map(Object::toString); return new ToolCall(name, Stream.concat(arguments.stream(), strings).toList()); } public ToolCall with(Object argument) { return with(Stream.of(argument)); } public ToolCall with(String key, Object value, Object... values) { var call = with(Stream.of(key, value)); return values.length == 0 ? call : call.with(Stream.of(values)); } public ToolCall withFindFiles(String glob) { return withFindFiles(Path.of(""), glob); } public ToolCall withFindFiles(Path start, String glob) { return withFindFiles(start, "glob", glob); } public ToolCall withFindFiles(Path start, String syntax, String pattern) { var syntaxAndPattern = syntax + ':' + pattern; var matcher = start.getFileSystem().getPathMatcher(syntaxAndPattern); return withFindFiles(start, Integer.MAX_VALUE, matcher); } public ToolCall withFindFiles(Path start, int maxDepth, PathMatcher matcher) { try (var files = Files.find(start, maxDepth, (p, a) -> matcher.matches(p))) { return with(files); } catch (Exception exception) { throw new RuntimeException("Find files failed in: " + start, exception); } } } /** * A finder of tool providers. * * <p>What {@link java.lang.module.ModuleFinder ModuleFinder} is to {@link * java.lang.module.ModuleReference ModuleReference}, is {@link ToolFinder} to {@link * ToolProvider}. */ @FunctionalInterface public interface ToolFinder { List<ToolProvider> findAll(); default Optional<ToolProvider> find(String name) { return findAll().stream().filter(tool -> tool.name().equals(name)).findFirst(); } default String title() { return getClass().getSimpleName(); } default void tree(Consumer<String> out) { visit(0, (depth, finder) -> tree(out, depth, finder)); } private void tree(Consumer<String> out, int depth, ToolFinder finder) { var indent = " ".repeat(depth); out.accept(indent + finder.title()); if (finder instanceof CompositeToolFinder) return; finder.findAll().stream() .sorted(Comparator.comparing(ToolProvider::name)) .forEach(tool -> out.accept(indent + " - " + tool.name())); } default void visit(int depth, BiConsumer<Integer, ToolFinder> visitor) { visitor.accept(depth, this); } static ToolFinder of(ToolProvider... providers) { record DirectToolFinder(List<ToolProvider> findAll) implements ToolFinder { @Override public String title() { return "DirectToolFinder (%d)".formatted(findAll.size()); } } return new DirectToolFinder(List.of(providers)); } static ToolFinder of(ClassLoader loader) { return ToolFinder.of(ServiceLoader.load(ToolProvider.class, loader)); } static ToolFinder of(ServiceLoader<ToolProvider> loader) { record ServiceLoaderToolFinder(ServiceLoader<ToolProvider> loader) implements ToolFinder { @Override public List<ToolProvider> findAll() { synchronized (loader) { return loader.stream().map(ServiceLoader.Provider::get).toList(); } } } return new ServiceLoaderToolFinder(loader); } static ToolFinder ofSystem() { return ToolFinder.of(ClassLoader.getSystemClassLoader()); } static ToolFinder ofProperties(Path directory) { record PropertiesToolProvider(String name, Properties properties) implements ToolProvider { @Override public int run(PrintWriter out, PrintWriter err, String... args) { var numbers = properties.stringPropertyNames().stream().map(Integer::valueOf).sorted(); for (var number : numbers.map(Object::toString).map(properties::getProperty).toList()) { var lines = number.lines().map(String::trim).toList(); var call = ToolCall.of(lines.get(0)).with(lines.stream().skip(1)); Bach.getBach().run(call); } return 0; } } record PropertiesToolFinder(Path directory) implements ToolFinder { @Override public String title() { return "PropertiesToolFinder(%s)".formatted(directory); } @Override public List<ToolProvider> findAll() { if (!Files.isDirectory(directory)) return List.of(); var list = new ArrayList<ToolProvider>(); try (var paths = Files.newDirectoryStream(directory, "*.properties")) { for (var path : paths) { if (Files.isDirectory(path)) continue; var filename = path.getFileName().toString(); var name = filename.substring(0, filename.length() - ".properties".length()); var properties = new Properties(); properties.load(new StringReader(Files.readString(path))); list.add(new PropertiesToolProvider(name, properties)); } } catch (Exception exception) { throw new RuntimeException(exception); } return List.copyOf(list); } } return new PropertiesToolFinder(directory); } static ToolFinder compose(ToolFinder... finders) { return new CompositeToolFinder(List.of(finders)); } record CompositeToolFinder(List<ToolFinder> finders) implements ToolFinder { @Override public String title() { return "CompositeToolFinder (%d)".formatted(finders.size()); } @Override public List<ToolProvider> findAll() { return finders.stream().flatMap(finder -> finder.findAll().stream()).toList(); } @Override public Optional<ToolProvider> find(String name) { for (var finder : finders) { var tool = finder.find(name); if (tool.isPresent()) return tool; } return Optional.empty(); } @Override public void visit(int depth, BiConsumer<Integer, ToolFinder> visitor) { visitor.accept(depth, this); depth++; for (var finder : finders) finder.visit(depth, visitor); } } record Provider(String name, ToolFunction function) implements ToolProvider { @FunctionalInterface public interface ToolFunction { int run(PrintWriter out, PrintWriter err, String... args); } @Override public int run(PrintWriter out, PrintWriter err, String... args) { return function.run(out, err, args); } } } @Category("Bach") @Name("Bach.LogEvent") @Label("Log") @StackTrace(false) private static final class LogEvent extends Event { String level; String message; } @Category("Bach") @Name("Bach.RunEvent") @Label("Run") @StackTrace(false) private static final class RunEvent extends Event { String name; String args; int code; String out; String err; } }
package com.jaamsim.FluidObjects; import java.util.ArrayList; import com.jaamsim.input.InputAgent; import com.jaamsim.input.Output; import com.jaamsim.math.Color4d; import com.jaamsim.math.Vec3d; import com.jaamsim.render.HasScreenPoints; import com.sandwell.JavaSimulation.ColourInput; import com.sandwell.JavaSimulation.DoubleInput; import com.sandwell.JavaSimulation.Keyword; import com.sandwell.JavaSimulation.ErrorException; import com.sandwell.JavaSimulation.Vec3dListInput; /** * FluidPipe is a pipe through which fluid can flow. * @author Harry King * */ public class FluidPipe extends FluidComponent implements HasScreenPoints { @Keyword(desc = "The length of the pipe.", example = "Pipe1 Length { 10.0 m }") private final DoubleInput lengthInput; @Keyword(desc = "The height change over the length of the pipe. " + "Equal to (outlet height - inlet height).", example = "Pipe1 HeightChange { 0.0 }") private final DoubleInput heightChangeInput; @Keyword(desc = "The roughness height of the inside pipe surface. " + "Used to calculate the Darcy friction factor for the pipe.", example = "Pipe1 Roughness { 0.01 m }") private final DoubleInput roughnessInput; @Keyword(desc = "The pressure loss coefficient or 'K-factor' for the pipe. " + "The factor multiplies the dynamic pressure and is applied as a loss at the pipe outlet.", example = "Pipe1 PressureLossCoefficient { 0.5 }") private final DoubleInput pressureLossCoefficientInput; @Keyword(desc = "A list of points in { x, y, z } coordinates defining the line segments that" + "make up the pipe. When two coordinates are given it is assumed that z = 0." , example = "Pipe1 Points { { 6.7 2.2 m } { 4.9 2.2 m } { 4.9 3.4 m } }") private final Vec3dListInput pointsInput; @Keyword(desc = "The width of the pipe segments in pixels.", example = "Pipe1 Width { 1 }") private final DoubleInput widthInput; @Keyword(desc = "The colour of the pipe, defined using a colour keyword or RGB values.", example = "Pipe1 Colour { red }") private final ColourInput colourInput; private double darcyFrictionFactor; // The Darcy Friction Factor for the pipe flow. { lengthInput = new DoubleInput( "Length", "Key Inputs", 1.0d); lengthInput.setValidRange( 0.0, Double.POSITIVE_INFINITY); lengthInput.setUnits( "m"); this.addInput( lengthInput, true); heightChangeInput = new DoubleInput( "HeightChange", "Key Inputs", 0.0d); heightChangeInput.setValidRange( Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); heightChangeInput.setUnits( "m"); this.addInput( heightChangeInput, true); roughnessInput = new DoubleInput( "Roughness", "Key Inputs", 0.0d); roughnessInput.setValidRange( 0.0, Double.POSITIVE_INFINITY); roughnessInput.setUnits( "m"); this.addInput( roughnessInput, true); pressureLossCoefficientInput = new DoubleInput( "PressureLossCoefficient", "Key Inputs", 0.0d); pressureLossCoefficientInput.setValidRange( 0.0, Double.POSITIVE_INFINITY); this.addInput( pressureLossCoefficientInput, true); ArrayList<Vec3d> defPoints = new ArrayList<Vec3d>(); defPoints.add(new Vec3d(0.0d, 0.0d, 0.0d)); defPoints.add(new Vec3d(1.0d, 0.0d, 0.0d)); pointsInput = new Vec3dListInput("Points", "Key Inputs", defPoints); pointsInput.setValidCountRange( 2, Integer.MAX_VALUE ); pointsInput.setUnits("m"); this.addInput(pointsInput, true); widthInput = new DoubleInput("Width", "Key Inputs", 1.0d, 1.0d, Double.POSITIVE_INFINITY); this.addInput(widthInput, true); colourInput = new ColourInput("Colour", "Key Inputs", ColourInput.BLACK); this.addInput(colourInput, true, "Color"); } @Override public double calcOutletPressure( double inletPres, double flowAccel ) { double dyn = this.getDynamicPressure(); // Note that dynamic pressure is negative for negative velocities double pres = inletPres; pres -= this.getFluid().getDensityxGravity() * heightChangeInput.getValue(); if( Math.abs(dyn) > 0.0 && this.getFluid().getViscosity() > 0.0 ) { this.setDarcyFrictionFactor(); pres -= darcyFrictionFactor * dyn * this.getLength() / this.getDiameter(); } else { darcyFrictionFactor = 0.0; } pres -= pressureLossCoefficientInput.getValue() * dyn; pres -= flowAccel * this.getFluid().getDensity() * lengthInput.getValue() / this.getFlowArea(); return pres; } @Override public double getLength() { return lengthInput.getValue(); } private void setDarcyFrictionFactor() { double reynoldsNumber = this.getReynoldsNumber(); // Laminar Flow if( reynoldsNumber < 2300.0 ) { darcyFrictionFactor = this.getLaminarFrictionFactor( reynoldsNumber ); } // Turbulent Flow else if( reynoldsNumber > 4000.0 ) { darcyFrictionFactor = this.getTurbulentFrictionFactor( reynoldsNumber ); } // Transitional Flow else { darcyFrictionFactor = 0.5 * ( this.getLaminarFrictionFactor(reynoldsNumber) + this.getTurbulentFrictionFactor(reynoldsNumber) ); } } /* * Return the Darcy Friction Factor for a laminar flow. */ private double getLaminarFrictionFactor( double reynoldsNumber ) { return 64.0 / reynoldsNumber; } /* * Return the Darcy Friction Factor for a turbulent flow. */ private double getTurbulentFrictionFactor( double reynoldsNumber ) { double x = 1.0; // The present value for x = 1 / sqrt( frictionfactor ). double lastx = 0.0; double a = ( roughnessInput.getValue() / this.getDiameter() ) / 3.7; double b = 2.51 / reynoldsNumber; int n = 0; while( Math.abs(x-lastx)/lastx > 1.0e-10 && n < 20 ) { lastx = x; x = -2.0 * Math.log10( a + b*lastx ); n++; } if( n >= 20 ) { throw new ErrorException( "Darcy Friction Factor iterations did not converge: " + "lastx = " + lastx + " x = " + x + " n = " + n); } return 1.0 / ( x * x ); } @Override public ArrayList<Vec3d> getScreenPoints() { return pointsInput.getValue(); } @Override public boolean selectable() { return true; } /** * Inform simulation and editBox of new positions. */ @Override public void dragged(Vec3d dist) { ArrayList<Vec3d> vec = new ArrayList<Vec3d>(pointsInput.getValue().size()); for (Vec3d v : pointsInput.getValue()) { vec.add(new Vec3d(v.x + dist.x, v.y + dist.y, v.z + dist.z)); } StringBuilder tmp = new StringBuilder(); for (Vec3d v : vec) { tmp.append(String.format(" { %.3f %.3f %.3f %s }", v.x, v.y, v.z, pointsInput.getUnits())); } InputAgent.processEntity_Keyword_Value(this, pointsInput, tmp.toString()); super.dragged(dist); setGraphicsDataDirty(); } @Override public Color4d getDisplayColour() { return colourInput.getValue(); } @Override public int getWidth() { int ret = widthInput.getValue().intValue(); if (ret < 1) return 1; return ret; } @Output(name = "DarcyFrictionFactor", description = "The Darcy Friction Factor for the pipe.") public double getDarcyFrictionFactor(double simTime) { return darcyFrictionFactor; } }
package cafe.image.meta.photoshop; import java.awt.Transparency; import java.awt.color.ColorSpace; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.ComponentColorModel; import java.awt.image.DataBuffer; import java.awt.image.DataBufferByte; import java.awt.image.Raster; import java.awt.image.WritableRaster; /** * Photoshop Image Resource Block thumbnail wrapper. * * @author Wen Yu, yuwen_66@yahoo.com * @version 1.0 01/10/2015 */ public class IRBThumbnail { public static final int DATA_TYPE_KRawRGB = 0; public static final int DATA_TYPE_KJpegRGB = 1; private int dataType; private int width; private int height; //Padded row bytes = (width * bits per pixel + 31) / 32 * 4. private int paddedRowBytes; // Total size = widthbytes * height * planes private int totalSize; // Size after compression. Used for consistency check. private int compressedSize; // Bits per pixel. = 24 private int bitsPerPixel; // Number of planes. = 1 private int numOfPlanes; private ImageResourceID id; private BufferedImage thumbnail; private byte[] compressedThumbnail; private byte[] data; public IRBThumbnail(ImageResourceID id, int dataType, int width, int height, int paddedRowBytes, int totalSize, int compressedSize, int bitsPerPixel, int numOfPlanes, byte[] data) { this.id = id; this.dataType = dataType; this.width = width; this.height = height; this.paddedRowBytes = paddedRowBytes; this.totalSize = totalSize; this.compressedSize = compressedSize; this.bitsPerPixel = bitsPerPixel; this.numOfPlanes = numOfPlanes; this.data = data; setImage(); } public int getBitsPerPixel() { return bitsPerPixel; } public byte[] getCompressedImage() { return compressedThumbnail; } public int getCompressedSize() { return compressedSize; } public int getDataType() { return dataType; } public int getHeight() { return height; } public int getNumOfPlanes() { return numOfPlanes; } public int getPaddedRowBytes() { return paddedRowBytes; } public BufferedImage getRawImage() { return thumbnail; } public ImageResourceID getResouceID() { return id; } public int getTotalSize() { return totalSize; } public int getWidth() { return width; } private void setImage() { // JFIF data in RGB format. For resource ID 1033 (0x0409) the data is in BGR format. if(dataType == DATA_TYPE_KJpegRGB) { // Note: Not sure whether or not this will create wrong color JPEG // if it's written by Photoshop 4.0! compressedThumbnail = data; } else if(dataType == DATA_TYPE_KRawRGB) { // kRawRGB - NOT tested yet! //Create a BufferedImage DataBuffer db = new DataBufferByte(data, totalSize); int[] off = {0, 1, 2};//RGB band offset, we have 3 bands if(id == ImageResourceID.THUMBNAIL_RESOURCE_PS4) off = new int[]{2, 1, 0}; // RGB band offset for BGR for photoshop4.0 BGR format int numOfBands = 3; int trans = Transparency.OPAQUE; WritableRaster raster = Raster.createInterleavedRaster(db, width, height, paddedRowBytes, numOfBands, off, null); ColorModel cm = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), false, false, trans, DataBuffer.TYPE_BYTE); thumbnail = new BufferedImage(cm, raster, false, null); } } }
package com.jvms.i18neditor.util; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.SortedMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.apache.commons.lang3.LocaleUtils; import org.apache.commons.lang3.StringEscapeUtils; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; import com.jvms.i18neditor.Resource; import com.jvms.i18neditor.ResourceType; /** * This class provides utility functions for a {@link Resource}. * * @author Jacob */ public final class Resources { private final static Charset UTF8_ENCODING = Charset.forName("UTF-8"); private final static String LOCALE_REGEX = "[a-z]{2}(_[A-Z]{2})?"; /** * Gets all resources from the given {@code rootDir} directory path. * * <p>The {@code baseName} is the base of the filename of the resource files to look for.<br> * The base name is without extension and without any locale information.<br> * When a resource type is given, only resources of that type will returned.</p> * * <p>This function will not load the contents of the file, only its description.<br> * If you want to load the contents, use {@link #load(Resource)} afterwards.</p> * * @param rootDir the root directory of the resources * @param baseName the base name of the resource files to look for * @param type the type of the resource files to look for * @return list of found resources * @throws IOException if an I/O error occurs reading the directory. */ public static List<Resource> get(Path rootDir, String baseName, Optional<ResourceType> type) throws IOException { List<Resource> result = Lists.newLinkedList(); List<Path> files = Files.walk(rootDir, 1).collect(Collectors.toList()); for (Path p : files) { ResourceType resourceType = null; for (ResourceType t : ResourceType.values()) { if (isResourceType(type, t) && isResource(rootDir, p, t, baseName)) { resourceType = t; break; } } if (resourceType != null) { String fileName = p.getFileName().toString(); String extension = resourceType.getExtension(); Locale locale = null; Path path = null; if (resourceType.isEmbedLocale()) { String pattern = "^" + baseName + "_(" + LOCALE_REGEX + ")" + extension + "$"; Matcher match = Pattern.compile(pattern).matcher(fileName); if (match.find()) { locale = LocaleUtils.toLocale(match.group(1)); } path = Paths.get(rootDir.toString(), baseName + (locale == null ? "" : "_" + locale.toString()) + extension); } else { locale = LocaleUtils.toLocale(fileName); path = Paths.get(rootDir.toString(), locale.toString(), baseName + extension); } result.add(new Resource(resourceType, path, locale)); } }; return result; } /** * Loads the translations of a {@link Resource} from disk. * * @param resource the resource. * @throws IOException if an I/O error occurs reading the file. */ public static void load(Resource resource) throws IOException { ResourceType type = resource.getType(); Path path = resource.getPath(); SortedMap<String,String> translations; if (type == ResourceType.Properties) { ExtendedProperties content = new ExtendedProperties(); content.load(path); translations = fromProperties(content); } else { String content = Files.lines(path, UTF8_ENCODING).collect(Collectors.joining()); if (type == ResourceType.ES6) { content = es6ToJson(content); } translations = fromJson(content); } resource.setTranslations(translations); } /** * Writes the translations of the given resource to disk. * * @param resource the resource to write. * @param prettyPrinting whether to pretty print the contents * @throws IOException if an I/O error occurs writing the file. */ public static void write(Resource resource, boolean prettyPrinting) throws IOException { ResourceType type = resource.getType(); if (type == ResourceType.Properties) { ExtendedProperties content = toProperties(resource.getTranslations()); content.store(resource.getPath()); } else { String content = toJson(resource.getTranslations(), prettyPrinting); if (type == ResourceType.ES6) { content = jsonToEs6(content); } if (!Files.exists(resource.getPath())) { Files.createDirectories(resource.getPath().getParent()); Files.createFile(resource.getPath()); } Files.write(resource.getPath(), Lists.newArrayList(content), UTF8_ENCODING); } } /** * Creates a new {@link Resource} with the given {@link ResourceType} in the given directory path. * This function should be used to create new resources. For creating an instance of an * existing resource on disk, see {@link #read(Path)}. * * @param type the type of the resource to create. * @param root the root directory to write the resource to. * @return The newly created resource. * @throws IOException if an I/O error occurs writing the file. */ public static Resource create(Path root, ResourceType type, Optional<Locale> locale, String baseName) throws IOException { String extension = type.getExtension(); Path path; if (type.isEmbedLocale()) { path = Paths.get(root.toString(), baseName + (locale.isPresent() ? "_" + locale.get().toString() : "") + extension); } else { path = Paths.get(root.toString(), locale.get().toString(), baseName + extension); } Resource resource = new Resource(type, path, locale.orElse(null)); write(resource, false); return resource; } private static boolean isResource(Path root, Path path, ResourceType type, String baseName) throws IOException { String extension = type.getExtension(); Path parent = path.getParent(); if (parent == null || Files.isSameFile(root, path) || !Files.isSameFile(root, parent)) { return false; } else if (type.isEmbedLocale()) { return Files.isRegularFile(path) && Pattern.matches("^" + baseName + "(_" + LOCALE_REGEX + ")?" + extension + "$", path.getFileName().toString()); } else { return Files.isDirectory(path) && Pattern.matches("^" + LOCALE_REGEX + "$", path.getFileName().toString()) && Files.isRegularFile(Paths.get(path.toString(), baseName + extension)); } } private static boolean isResourceType(Optional<ResourceType> a, ResourceType b) { return !a.isPresent() || a.get() == b; } private static SortedMap<String,String> fromProperties(ExtendedProperties properties) { SortedMap<String,String> result = Maps.newTreeMap(); properties.forEach((key, value) -> { result.put((String)key, StringEscapeUtils.unescapeJava((String)value)); }); return result; } private static ExtendedProperties toProperties(Map<String,String> translations) { ExtendedProperties result = new ExtendedProperties(); result.putAll(translations); return result; } private static SortedMap<String,String> fromJson(String json) { SortedMap<String,String> result = Maps.newTreeMap(); JsonElement elem = new JsonParser().parse(json); fromJson(null, elem, result); return result; } private static void fromJson(String key, JsonElement elem, Map<String,String> content) { if (elem.isJsonObject()) { elem.getAsJsonObject().entrySet().forEach(entry -> { String newKey = key == null ? entry.getKey() : ResourceKeys.create(key, entry.getKey()); fromJson(newKey, entry.getValue(), content); }); } else if (elem.isJsonPrimitive()) { content.put(key, StringEscapeUtils.unescapeJava(elem.getAsString())); } else if (elem.isJsonNull()) { content.put(key, ""); } else { throw new IllegalArgumentException("Found invalid json element."); } } private static String toJson(Map<String,String> translations, boolean prettify) { List<String> keys = Lists.newArrayList(translations.keySet()); JsonElement elem = toJson(translations, null, keys); GsonBuilder builder = new GsonBuilder().disableHtmlEscaping(); if (prettify) { builder.setPrettyPrinting(); } return builder.create().toJson(elem); } private static JsonElement toJson(Map<String,String> translations, String key, List<String> keys) { if (keys.size() > 0) { JsonObject object = new JsonObject(); ResourceKeys.uniqueRootKeys(keys).forEach(rootKey -> { String subKey = ResourceKeys.create(key, rootKey); List<String> subKeys = ResourceKeys.extractChildKeys(keys, rootKey); object.add(rootKey, toJson(translations, subKey, subKeys)); }); return object; } if (key == null) { return new JsonObject(); } return new JsonPrimitive(translations.get(key)); } private static String es6ToJson(String content) { return content.replaceAll("export +default", "").replaceAll("} *;", "}"); } private static String jsonToEs6(String content) { return "export default " + content + ";"; } }
package com.liquid.kochanparser; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * A handler for the SAX parser. * The functions should be called by the parser, rather than on their own. * * @author Krzysztof Gutkowski (LiquidPL) * @version dev */ public class SaxHandler extends DefaultHandler { private TimeTable owner; private int currentLesson = -4;// currentLesson and currentDay are set to negative values private int currentDay = -3; // because of the <tr> and <td> tags at the beginning of // the HTML file not containing any important data (so the indexing begins from 0) private String currentName = ""; private String currentAttribute = ""; private int currentGroup = 0; // 0 - current lesson is not grouped; -1 - current lesson is going to be grouped // 1 - group 1; 2 - group 2 private String currentSubject = ""; private String currentTeacher = ""; private String currentClassroom = ""; private String currentClass = ""; /** * Class constructor * * @param table TimeTable object in which this handler is supposed to be created */ public SaxHandler (TimeTable table) { this.owner = table; } @Override public void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException { currentName = qName; // storing the name for use in other methods if ("tr".equals (qName)) // increasing the lesson number as we traverse the timetable { currentLesson++; currentDay = -3; } if ("td".equals (qName) || "th".equals (qName)) currentDay++; // same with the day if ("span".equals (qName) && currentGroup == -1) // set the appropriate group number when in group mode { currentGroup = 1; } else if ("span".equals (qName) && currentGroup == 1) // same as above { currentGroup = 2; } if ("span".equals (qName) || "a".equals (qName)) // if we hit elements that may contain timetable data, { // we check if this is the case and store the information int length = attributes.getLength (); // on what data may it be, so we can check it in for (int i = 0; i < length; i++) // characters () method { String value = attributes.getValue (i); // p - subject, n - teacher, s - classroom, o - class // tytulnapis is a special case, it contains title of the timetable if ("p".equals (value) || "n".equals (value) || "s".equals (value) || "o".equals (value) || "tytulnapis".equals (value)) { currentAttribute = value; } if ("font-size:85%".equals (value)) // entering group mode, there will be two lessons within one hour here { currentGroup = -1; } } } // inserting lesson for the first group, they are separated by a <br/> tag if ("br".equals (qName) && currentGroup == 1 && currentDay >= 0 && currentDay <= 4 && !checkIfEmpty (currentSubject, currentTeacher, currentClassroom, currentClass)) { owner.getLessons (). add (new Lesson(currentDay, currentLesson, currentSubject, currentTeacher, currentClassroom, currentClass)); owner.getCurrentLesson ().setGroup (currentGroup); currentSubject = ""; currentTeacher = ""; currentClassroom = ""; currentClass = ""; } } @Override public void endElement (String uri, String localName, String qName) throws SAXException { // inserting lesson for the second group, or if the lesson is not grouped if ("td".equals (qName) && currentDay >= 0 && currentDay <= 4 && !checkIfEmpty (currentSubject, currentTeacher, currentClassroom, currentClass)) { owner.getLessons ().add (new Lesson (currentDay, currentLesson, currentSubject, currentTeacher, currentClassroom, currentClass)); if (currentGroup == 1 || currentGroup == 2) { owner.getCurrentLesson ().setGroup (currentGroup); } currentGroup = 0; currentSubject = ""; currentTeacher = ""; currentClassroom = ""; currentClass = ""; } } @Override public void characters (char[] ch, int start, int length) throws SAXException { String value = new String (ch, start, length).trim (); if (value.length () == 0) return; // next for ifs: storing timetable data for later insertion depending on the attribute if ("p".equals (currentAttribute)) { currentSubject = value; } if ("n".equals (currentAttribute)) { currentTeacher = value; } if ("s".equals (currentAttribute)) { currentClassroom = value; } if ("o".equals (currentAttribute)) { currentClass = value; } if ("td".equals (currentName) && currentDay == -1) // storing the lessons begin and end hours { String[] values = new String (value.toCharArray (), 3, value.length () - 3).split ("-"); owner.getStarthours ().add (new Time (values[0])); owner.getEndhours ().add (new Time (values[1])); } if ("span".equals (currentName) && "-------".equals (value)) // this means that only group 2 has a lesson at this hour { currentGroup = 2; } // storing the timetable name, works different for class/teacher and classroom if ("span".equals (currentName) && "tytulnapis".equals (currentAttribute)) { if (owner.getType () == TimeTableType.TIMETABLE_TYPE_CLASS || owner.getType () == TimeTableType.TIMETABLE_TYPE_TEACHER) { String[] values = value.split (" \\("); owner.setLongName (values[0]); owner.setShortName (new String (values[1].toCharArray (), 0, values[1].length () - 1)); } else { owner.setShortName (new String (value.toCharArray (), 1, value.length () - 2)); owner.setLongName (owner.getShortName ()); } currentAttribute = ""; } } /** * Checks if the entire set of lesson data have been already collected. * @param name Subject name * @param code Teacher code * @param room Classroom * @param _class Class * @return */ private Boolean checkIfEmpty (String name, String code, String room, String _class) { if (name.length () != 0 && code.length () != 0 && room.length () != 0) return false; else if (_class.length () != 0 && name.length () != 0 && room.length () != 0) return false; else if (code.length () != 0 && _class.length () != 0 && name.length () != 0) return false; else return true; } }
package com.matt.forgehax.util; import static com.matt.forgehax.Helper.getWorld; import static com.matt.forgehax.util.entity.LocalPlayerUtils.isInReach; import com.google.common.collect.Lists; import com.matt.forgehax.util.entity.LocalPlayerUtils; import com.matt.forgehax.util.math.VectorUtils; import java.util.Arrays; import java.util.Comparator; import java.util.EnumSet; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Stream; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; public class BlockHelper { public static UniqueBlock newUniqueBlock(Block block, int metadata, BlockPos pos) { return new UniqueBlock(block, metadata, pos); } public static UniqueBlock newUniqueBlock(Block block, int metadata) { return newUniqueBlock(block, metadata, BlockPos.ORIGIN); } public static UniqueBlock newUniqueBlock(BlockPos pos) { IBlockState state = getWorld().getBlockState(pos); Block block = state.getBlock(); return newUniqueBlock(block, block.getMetaFromState(state), pos); } public static BlockTraceInfo newBlockTrace(BlockPos pos, EnumFacing side) { return new BlockTraceInfo(pos, side); } public static List<BlockPos> getBlocksInRadius(Vec3d pos, double radius) { List<BlockPos> list = Lists.newArrayList(); for (double x = pos.x - radius; x <= pos.x + radius; ++x) { for (double y = pos.y - radius; y <= pos.y + radius; ++y) { for (double z = pos.z - radius; z <= pos.z + radius; ++z) { list.add(new BlockPos((int) x, (int) y, (int) z)); } } } return list; } public static boolean isBlockReplaceable(BlockPos pos) { return getWorld().getBlockState(pos).getMaterial().isReplaceable(); } public static boolean isTraceClear(Vec3d start, Vec3d end, EnumFacing targetSide) { RayTraceResult tr = getWorld().rayTraceBlocks(start, end, false, true, false); return tr == null || (new BlockPos(end).equals(new BlockPos(tr.hitVec)) && targetSide.getOpposite().equals(tr.sideHit)); } public static Vec3d getOBBCenter(BlockPos pos) { IBlockState state = getWorld().getBlockState(pos); AxisAlignedBB bb = state.getBoundingBox(getWorld(), pos); return new Vec3d( bb.minX + ((bb.maxX - bb.minX) / 2.D), bb.minY + ((bb.maxY - bb.minY) / 2.D), bb.minZ + ((bb.maxZ - bb.minZ) / 2.D)); } public static boolean isBlockPlaceable(BlockPos pos) { IBlockState state = getWorld().getBlockState(pos); return state.getBlock().canCollideCheck(state, false); } private static BlockTraceInfo getPlaceableBlockSideTrace( Vec3d eyes, Vec3d normal, Stream<EnumFacing> stream, BlockPos pos) { return stream .map(side -> newBlockTrace(pos.offset(side), side)) .filter(info -> isBlockPlaceable(info.getPos())) .filter(info -> isInReach(eyes, info.getHitVec())) .filter(info -> BlockHelper.isTraceClear(eyes, info.getHitVec(), info.getSide())) .min( Comparator.comparingDouble( info -> VectorUtils.getCrosshairDistance(eyes, normal, info.getCenteredPos()))) .orElse(null); } public static BlockTraceInfo getPlaceableBlockSideTrace( Vec3d eyes, Vec3d normal, EnumSet<EnumFacing> sides, BlockPos pos) { return getPlaceableBlockSideTrace(eyes, normal, sides.stream(), pos); } public static BlockTraceInfo getPlaceableBlockSideTrace(Vec3d eyes, Vec3d normal, BlockPos pos) { return getPlaceableBlockSideTrace(eyes, normal, Stream.of(EnumFacing.values()), pos); } public static BlockTraceInfo getBlockSideTrace(Vec3d eyes, BlockPos pos, EnumFacing side) { return Optional.of(newBlockTrace(pos, side)) .filter(tr -> BlockHelper.isTraceClear(eyes, tr.getHitVec(), tr.getSide())) .filter(tr -> LocalPlayerUtils.isInReach(eyes, tr.getHitVec())) .orElse(null); } public BlockTraceInfo getVisibleBlockSideTrace(Vec3d eyes, Vec3d normal, BlockPos pos) { return Arrays.stream(EnumFacing.values()) .map(side -> BlockHelper.getBlockSideTrace(eyes, pos, side.getOpposite())) .filter(Objects::nonNull) .min( Comparator.comparingDouble( i -> VectorUtils.getCrosshairDistance(eyes, normal, i.getCenteredPos()))) .orElse(null); } public static class BlockTraceInfo { private final BlockPos pos; private final EnumFacing side; private final Vec3d center; private final Vec3d hitVec; private BlockTraceInfo(BlockPos pos, EnumFacing side) { this.pos = pos; this.side = side; Vec3d obb = BlockHelper.getOBBCenter(pos); this.center = new Vec3d(pos).add(obb); this.hitVec = this.center.add( VectorUtils.multiplyBy(new Vec3d(getOppositeSide().getDirectionVec()), obb)); } public BlockPos getPos() { return pos; } public EnumFacing getSide() { return side; } public EnumFacing getOppositeSide() { return side.getOpposite(); } public Vec3d getHitVec() { return this.hitVec; } public Vec3d getCenteredPos() { return center; } public IBlockState getBlockState() { return getWorld().getBlockState(getPos()); } } public static class UniqueBlock { private final Block block; private final int metadata; private final BlockPos pos; private UniqueBlock(Block block, int metadata, BlockPos pos) { this.block = block; this.metadata = metadata; this.pos = pos; } public Block getBlock() { return block; } public int getMetadata() { return metadata; } public BlockPos getPos() { return pos; } public Vec3d getCenteredPos() { return new Vec3d(getPos()).add(getOBBCenter(getPos())); } public ItemStack asItemStack() { return new ItemStack(getBlock(), 1, getMetadata()); } public boolean isInvalid() { return Blocks.AIR.equals(getBlock()); } public boolean isEqual(BlockPos pos) { IBlockState state = getWorld().getBlockState(pos); Block bl = state.getBlock(); return Objects.equals(getBlock(), bl) && getMetadata() == bl.getMetaFromState(state); } @Override public boolean equals(Object obj) { return this == obj || (obj instanceof UniqueBlock && getBlock().equals(((UniqueBlock) obj).getBlock()) && getMetadata() == ((UniqueBlock) obj).getMetadata()); } @Override public String toString() { return getBlock().getRegistryName().toString() + "{" + getMetadata() + "}"; } } }
package com.sandwell.JavaSimulation; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; import com.jaamsim.events.ProcessTarget; import com.jaamsim.events.ReflectionTarget; import com.jaamsim.input.InputAgent; import com.jaamsim.input.Output; import com.jaamsim.input.OutputHandle; /** * Abstract class that encapsulates the methods and data needed to create a * simulation object. Encapsulates the basic system objects to achieve discrete * event execution. */ public class Entity { private static long entityCount = 0; private static final ArrayList<Entity> allInstances; private static final HashMap<String, Entity> namedEntities; private String entityName; private String entityInputName; // Name input by user private final long entityNumber; //public static final int FLAG_TRACE = 0x01; // reserved in case we want to treat tracing like the other flags public static final int FLAG_TRACEREQUIRED = 0x02; public static final int FLAG_TRACESTATE = 0x04; public static final int FLAG_LOCKED = 0x08; //public static final int FLAG_TRACKEVENTS = 0x10; public static final int FLAG_ADDED = 0x20; public static final int FLAG_EDITED = 0x40; public static final int FLAG_GENERATED = 0x80; public static final int FLAG_DEAD = 0x0100; private int flags; protected boolean traceFlag = false; private final ArrayList<Input<?>> editableInputs = new ArrayList<Input<?>>(); private final HashMap<String, Input<?>> inputMap = new HashMap<String, Input<?>>(); private final BooleanInput trace; static { allInstances = new ArrayList<Entity>(100); namedEntities = new HashMap<String, Entity>(100); } { trace = new BooleanInput("Trace", "Key Inputs", false); trace.setHidden(true); this.addInput(trace, true); } /** * Constructor for entity initializing members. */ public Entity() { entityNumber = ++entityCount; synchronized(allInstances) { allInstances.add(this); } flags = 0; } public static ArrayList<? extends Entity> getAll() { synchronized(allInstances) { return allInstances; } } public static <T extends Entity> ArrayList<T> getInstancesOf(Class<T> proto) { ArrayList<T> instanceList = new ArrayList<T>(); for (Entity each : allInstances) { if (proto == each.getClass()) { instanceList.add(proto.cast(each)); } } return instanceList; } public static <T extends Entity> ArrayList<T> getClonesOf(Class<T> proto) { ArrayList<T> cloneList = new ArrayList<T>(); for (Entity each : allInstances) { if (proto.isAssignableFrom(each.getClass())) { cloneList.add(proto.cast(each)); } } return cloneList; } public static Entity idToEntity(long id) { synchronized (allInstances) { for (Entity e : allInstances) { if (e.getEntityNumber() == id) { return e; } } return null; } } // This is defined for handlers only public void validate() throws InputErrorException {} public void earlyInit() {} public void startUp() {} public void kill() { synchronized (allInstances) { allInstances.remove(this); } if (namedEntities.get(this.getInputName()) == this) namedEntities.remove(this.getInputName()); setFlag(FLAG_DEAD); } public void doEnd() {} public static Entity getNamedEntity(String name) { return namedEntities.get(name); } public static long getEntitySequence() { long seq = (long)allInstances.size() << 32; seq += entityCount; return seq; } /** * Get the current Simulation ticks value. * @return the current simulation tick */ public final long getSimTicks() { try { return Process.currentTick(); } catch (ErrorException e) { return EventManager.rootManager.currentTick(); } } /** * Get the current Simulation time. * @return the current time in seconds */ public final double getSimTime() { return Process.ticksToSeconds(getSimTicks()); } public final double getCurrentTime() { long ticks = getSimTicks(); return ticks / Process.getSimTimeFactor(); } protected void mapInput(Input<?> in, String key) { if (inputMap.put(key.toUpperCase().intern(), in) != null) { System.out.format("WARN: keyword handled twice, %s:%s\n", this.getClass().getName(), key); } } protected void addInput(Input<?> in, boolean editable, String... synonyms) { this.mapInput(in, in.getKeyword()); // Editable inputs are sorted by category if (editable) { int index = editableInputs.size(); for( int i = editableInputs.size() - 1; i >= 0; i Input<?> ei = editableInputs.get( i ); if( ei.getCategory().equals( in.getCategory() ) ) { index = i+1; break; } } editableInputs.add(index, in); } for (String each : synonyms) this.mapInput(in, each); } public Input<?> getInput(String key) { return inputMap.get(key.toUpperCase()); } public void resetInputs() { Iterator<Entry<String,Input<?>>> iterator = inputMap.entrySet().iterator(); while(iterator. hasNext()){ iterator.next().getValue().reset(); } } /** * Copy the inputs for each keyword to the caller. Any inputs that have already * been set for the caller are overwritten by those for the entity being copied. * @param ent = entity whose inputs are to be copied */ public void copyInputs(Entity ent) { for(Input<?> sourceInput: ent.getEditableInputs() ){ Input<?> targetInput = this.getInput(sourceInput.getKeyword()); String val = sourceInput.getValueString(); if( val.isEmpty() ) { if( ! targetInput.getValueString().isEmpty() ) targetInput.reset(); } else { InputAgent.processEntity_Keyword_Value(this, targetInput, val); } } } public void setFlag(int flag) { flags |= flag; } public void clearFlag(int flag) { flags &= ~flag; } public boolean testFlag(int flag) { return (flags & flag) != 0; } public void setTraceFlag() { traceFlag = true; } public void clearTraceFlag() { traceFlag = false; } /** * Static method to get the eventManager for all entities. */ public EventManager getEventManager() { return EventManager.rootManager; } /** * Method to return the name of the entity. * Note that the name of the entity may not be the unique identifier used in the namedEntityHashMap; see Entity.toString() */ public String getName() { if (entityName == null) return "Entity-" + entityNumber; else return entityName; } /** * Get the unique number for this entity * @return */ public long getEntityNumber() { return entityNumber; } /** * Method to set the name of the entity. */ public void setName(String newName) { entityName = newName; } /** * Method to set the name of the entity to prefix+entityNumber. */ public void setNamePrefix(String prefix) { entityName = prefix + entityNumber; } /** * Method to return the unique identifier of the entity. Used when building Edit tree labels * @return entityName */ @Override public String toString() { return getInputName(); } /** * Method to set the input name of the entity. */ public void setInputName(String newName) { entityInputName = newName; namedEntities.put(newName, this); String name = newName; if (newName.contains("/")) name = newName.substring(newName.indexOf("/") + 1); this.setName(name); } /** * Method to set an alias of the entity. */ public void setAlias(String newName) { namedEntities.put(newName, this); } /** * Method to remove an alias of the entity. */ public void removeAlias(String newName) { namedEntities.remove(newName); } /** * Method to get the input name of the entity. */ public String getInputName() { if (entityInputName == null) { return this.getName(); } else { return entityInputName; } } /** * This method updates the Entity for changes in the given input */ public void updateForInput( Input<?> in ) { if (in == trace) { if (trace.getValue()) this.setTraceFlag(); else this.clearTraceFlag(); return; } } /** * Interpret the input data in the given buffer of strings corresponding to the given keyword. * Reads keyword from a configuration file: * @param data - Vector of Strings containing data to be parsed * @param keyword - the keyword to determine what the data represents */ public void readData_ForKeyword(StringVector data, String keyword) throws InputErrorException { throw new InputErrorException( "Invalid keyword " + keyword ); } private long calculateDelayLength(double waitLength) { return Math.round(waitLength * Process.getSimTimeFactor()); } public double calculateDiscreteTime(double time) { long discTime = calculateDelayLength(time); return discTime / Process.getSimTimeFactor(); } public double calculateEventTime(double waitLength) { long eventTime = Process.currentTick() + this.calculateDelayLength(waitLength); return eventTime / Process.getSimTimeFactor(); } public double calculateEventTimeBefore(double waitLength) { long eventTime = Process.currentTick() + (long)Math.floor(waitLength * Process.getSimTimeFactor()); return eventTime / Process.getSimTimeFactor(); } public double calculateEventTimeAfter(double waitLength) { long eventTime = Process.currentTick() + (long)Math.ceil(waitLength * Process.getSimTimeFactor()); return eventTime / Process.getSimTimeFactor(); } public final void startProcess(String methodName, Object... args) { ProcessTarget t = new ReflectionTarget(this, methodName, args); Process.start(t); } public final void scheduleProcess(ProcessTarget t) { getEventManager().scheduleProcess(0, EventManager.PRIO_DEFAULT, this, t); } public final void scheduleSingleProcess(String methodName, Object... args) { getEventManager().scheduleSingleProcess(0, EventManager.PRIO_LASTFIFO, this, methodName, args); } /** * Wait a number of simulated seconds. * @param secs */ public final void simWait(double secs) { simWait(secs, EventManager.PRIO_DEFAULT); } /** * Wait a number of simulated seconds and a given priority. * @param secs * @param priority */ public final void simWait(double secs, int priority) { long ticks = Process.secondsToTicks(secs); this.simWaitTicks(ticks, priority); } /** * Wait a number of discrete simulation ticks. * @param secs */ public final void simWaitTicks(long ticks) { simWaitTicks(ticks, EventManager.PRIO_DEFAULT); } /** * Wait a number of discrete simulation ticks and a given priority. * @param secs * @param priority */ public final void simWaitTicks(long ticks, int priority) { getEventManager().waitTicks(ticks, priority, this); } /** * Wrapper of eventManager.scheduleWait(). Used as a syntax nicity for * calling the wait method. * * @param duration The duration to wait */ public final void scheduleWait(double duration) { long waitLength = calculateDelayLength(duration); getEventManager().scheduleWait(waitLength, EventManager.PRIO_DEFAULT, this); } /** * Wrapper of eventManager.scheduleWait(). Used as a syntax nicity for * calling the wait method. * * @param duration The duration to wait * @param priority The relative priority of the event scheduled */ public final void scheduleWait( double duration, int priority ) { long waitLength = calculateDelayLength(duration); getEventManager().scheduleWait(waitLength, priority, this); } /** * Schedules an event to happen as the last event at the current time. * Additional calls to scheduleLast will place a new event as the last event. */ public final void scheduleLastFIFO() { getEventManager().scheduleLastFIFO( this ); } /** * Schedules an event to happen as the last event at the current time. * Additional calls to scheduleLast will place a new event as the last event. */ public final void scheduleLastLIFO() { getEventManager().scheduleLastLIFO( this ); } public final void waitUntil() { getEventManager().waitUntil(this); } public final void waitUntilEnded() { getEventManager().waitUntilEnded(this); } // EDIT TABLE METHODS public ArrayList<Input<?>> getEditableInputs() { return editableInputs; } /** * Make the given keyword editable from the edit box with Synonyms */ public void addEditableKeyword( String keyword, String unit, String defaultValue, boolean append, String category, String... synonymsArray ) { if( this.getInput( keyword ) == null ) { // Create a new input object CompatInput in = new CompatInput(this, keyword, category, defaultValue); in.setUnits(unit); in.setAppendable( append ); this.addInput(in, true, synonymsArray); } else { System.out.format("Edited keyword added twice %s:%s%n", this.getClass().getName(), keyword); } } // TRACING METHODS /** * Track the given subroutine. */ public void trace(String meth) { if (traceFlag) InputAgent.trace(0, this, meth); } /** * Track the given subroutine. */ public void trace(int level, String meth) { if (traceFlag) InputAgent.trace(level, this, meth); } /** * Track the given subroutine (one line of text). */ public void trace(String meth, String text1) { if (traceFlag) InputAgent.trace(0, this, meth, text1); } /** * Track the given subroutine (two lines of text). */ public void trace(String meth, String text1, String text2) { if (traceFlag) InputAgent.trace(0, this, meth, text1, text2); } /** * Print an addition line of tracing. */ public void traceLine(String text) { this.trace( 1, text ); } /** * Print an error message. */ public void error( String meth, String text1, String text2 ) { InputAgent.logError("Time:%.5f Entity:%s%n%s%n%s%n%s%n", getCurrentTime(), getName(), meth, text1, text2); // We don't want the model to keep executing, throw an exception and let // the higher layers figure out if we should terminate the run or not. throw new ErrorException("ERROR: %s", getName()); } /** * Print a warning message. */ public void warning( String meth, String text1, String text2 ) { InputAgent.logWarning("Time:%.5f Entity:%s%n%s%n%s%n%s%n", getCurrentTime(), getName(), meth, text1, text2); } public OutputHandle getOutputHandle(String outputName) { return new OutputHandle(this, outputName); } public boolean hasOutput(String outputName) { return OutputHandle.hasOutput(this.getClass(), outputName); } @Output(name = "Name", description="The unique input name for this entity.") public String getNameOutput(double simTime) { return entityName; } }
package com.silverpop.api.client; import java.util.Map; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpMethodBase; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public abstract class ApiClient<REQUEST extends ApiRequest> { private Log log = LogFactory.getLog(this.getClass()); private ApiCommandProcessor<REQUEST> commandProcessor; protected HttpClient httpClient; protected ApiSession session; public ApiSession getSession() { return session; } protected ApiClient(ApiCommandProcessor<REQUEST> commandProcessor, ApiSession session) { this(commandProcessor, new HttpClient(), session); } protected ApiClient(ApiCommandProcessor<REQUEST> commandProcessor, HttpClient httpClient, ApiSession session) { this.commandProcessor = commandProcessor; this.httpClient = httpClient; this.session = session; } public ApiResult executeCommand(ApiCommand command) throws ApiResultException { return executeCommand(command, null); } public ApiResult executeCommand(ApiCommand command, Map<String,String> requestHeaders) throws ApiResultException { try { return validateSessionAndExecuteCommand(command, requestHeaders); } catch(ApiResultException e) { if(retryCommand(e.getErrorResult())) { getSession().close(); return validateSessionAndExecuteCommand(command, requestHeaders); } else { throw e; } } } private boolean retryCommand(ApiErrorResult errorResult) { return errorResult.isSessionInvalidOrExpired() && getSession().isReAuthenticate(); } private ApiResult validateSessionAndExecuteCommand(ApiCommand command, Map<String,String> requestHeaders) throws ApiResultException { ensureSessionIsOpen(); REQUEST request = commandProcessor.prepareRequest(command, getSession()); addAdditionalHeadersToRequest(request, requestHeaders); HttpMethodBase method = commandProcessor.prepareMethod(getSession().getUrl(), request); String in = executeMethod(method); ApiResponse response = commandProcessor.processResponse(in, request.getResultType()); return extractResult(command.getClass().getName(), response); } private void addAdditionalHeadersToRequest(REQUEST request, Map<String,String> requestHeaders) { if (requestHeaders != null) { for (String key : requestHeaders.keySet()) { request.addHeader(key, requestHeaders.get(key)); } } } private void ensureSessionIsOpen() { if(!getSession().isOpen()) { getSession().open(); } } protected String executeMethod(HttpMethodBase method) { try { log.error("executing method:" + method); httpClient.executeMethod(method); String responseBody = method.getResponseBodyAsString(); if (!responseBody.isEmpty()) { return responseBody; } else { StringBuilder buffer = new StringBuilder(); buffer.append("No response body was returned!\nResponse Headers-\n"); Header[] headers = method.getResponseHeaders(); for (Header header : headers) { buffer.append(header.getName()).append(": ").append(header.getValue()).append("\n"); } buffer.append("Content length reported as: ").append(method.getResponseContentLength()); throw new ApiException("Error executing API: " + buffer.toString()); } } catch(Exception e) { throw new ApiException("Error executing API: ", e); } } private ApiResult extractResult(String requestName, ApiResponse response) throws ApiResultException { if(response.isSuccessful()) { return response.buildResult(); } else { log.debug("Got Error Response"); String msg = String.format("API call '%s' unsuccessful.", requestName); throw new ApiResultException(msg, response.buildErrorResult()); } } }
package com.stitchdata.client; import com.stitchdata.client.*; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.EOFException; import java.io.Flushable; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.HashMap; import com.cognitect.transit.Writer; import com.cognitect.transit.TransitFactory; import com.cognitect.transit.Reader; import org.apache.http.client.fluent.Request; import org.apache.http.client.fluent.Response; import org.apache.http.client.ClientProtocolException; import org.apache.http.entity.ContentType; import org.apache.http.StatusLine; import org.apache.http.HttpResponse; import org.apache.http.HttpEntity; import javax.json.Json; import javax.json.JsonReader; /** * Client for Stitch. * * <p>Callers should use {@link StitchClientBuilder} to construct * instances of {@link StitchClient}.</p> * * A StitchClient maintains a fixed-capacity buffer for * messages. Every call to {@link StitchClient#push(StitchMessage)} * adds a record to the buffer and then delivers any outstanding * messages if the buffer is full or if too much time has passed since * the last flush. You should call {@link StitchClient#close()} when * you are finished sending records or you will lose any records that * have been added to the buffer but not yet delivered. Buffer * parameters can be configured with {@link * StitchClientBuilder#withBufferCapacity(int)} and {@link * StitchClientBuilder#withBufferTimeLimit(int)}. * * <pre> * {@code * StitchClient stitch = new StitchClientBuilder() * .withClientId(123) * .withToken("asdfasdfasdfasdasdfasdfadsfadfasdfasdfadfsasdf") * .withNamespace("event_tracking") * .withTableName("events") * .withKeyNames(thePrimaryKeyFields) * .build(); * * try { * * for (Map data : someSourceOfRecords) { * stitch.push(StitchMessage.newUpsert() * .withSequence(System.currentTimeMillis()) * .withData(data)); * } * } * catch (StitchException e) { * System.err.println("Error sending to stitch: " + e.getMessage()); * } * finally { * try { * stitch.close(); * } * catch (StitchException e) { * System.err.println("Error sending to stitch: " + e.getMessage()); * } * } * } * </pre> */ public class StitchClient implements Flushable, Closeable { public static final String PUSH_URL = "https://pipeline-gateway.rjmetrics.com/push"; private static final int HTTP_CONNECT_TIMEOUT = 1000 * 60 * 2; private static final ContentType CONTENT_TYPE = ContentType.create("application/transit+json"); private final int connectTimeout = HTTP_CONNECT_TIMEOUT; private final String stitchUrl; private final int clientId; private final String token; private final String namespace; private final String tableName; private final List<String> keyNames; private final int flushIntervalMillis; private final int bufferCapacity; private final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); private final Writer writer = TransitFactory.writer(TransitFactory.Format.JSON, buffer); private long lastFlushTime = System.currentTimeMillis(); private static void putWithDefault(Map map, String key, Object value, Object defaultValue) { map.put(key, value != null ? value : defaultValue); } private static void putIfNotNull(Map map, String key, Object value) { if (value != null) { map.put(key, value); } } private Map messageToMap(StitchMessage message) { HashMap map = new HashMap(); map.put("client_id", clientId); map.put("namespace", namespace); putWithDefault(map, "table_name", message.getTableName(), tableName); putWithDefault(map, "key_names", message.getKeyNames(), keyNames); putIfNotNull(map, "action", message.getAction()); putIfNotNull(map, "table_version", message.getTableVersion()); putIfNotNull(map, "sequence", message.getSequence()); putIfNotNull(map, "data", message.getData()); return map; } StitchClient( String stitchUrl, int clientId, String token, String namespace, String tableName, List<String> keyNames, int flushIntervalMillis, int bufferCapacity) { this.stitchUrl = stitchUrl; this.clientId = clientId; this.token = token; this.namespace = namespace; this.tableName = tableName; this.keyNames = keyNames; this.flushIntervalMillis = flushIntervalMillis; this.bufferCapacity = bufferCapacity; } private boolean isBufferFull() { return buffer.size() >= bufferCapacity; } private boolean isOverdue() { return System.currentTimeMillis() - lastFlushTime >= flushIntervalMillis; } /** * Send a message to Stitch. * * <p>If buffering is enable (which is true by default), this will * will first put the message in an in-memory buffer. Then we * check to see if the buffer is full, or if too much time has * passed since the last time we flushed. If so, we will deliver * all outstanding messages, blocking until the delivery has * complited.</p> * * <p>If you built the StitchClient with buffering disabled (by * setting capacity to 0 with {@link * StitchClientBuilder#withBufferCapacity}), the message will be sent * immediately and this function will block until it is * delivered.</p> * * @throws StitchException if Stitch rejected or was unable to * process the message * @throws IOException if there was an error communicating with * Stitch */ public void push(StitchMessage message) throws StitchException, IOException { writer.write(messageToMap(message)); if (isFull() || isOverdue()) { flush(); } } List<Map> getBufferedMessages() { ArrayList<Map> messages = new ArrayList<Map>(buffer.size()); if (buffer.size() > 0) { ByteArrayInputStream bais = new ByteArrayInputStream(buffer.toByteArray()); Reader reader = TransitFactory.reader(TransitFactory.Format.JSON, bais); boolean running = true; while (running) { System.out.println("Reading a record\n"); try { messages.add((Map)reader.read()); } catch (RuntimeException e) { if (e.getCause() instanceof EOFException) { running = false; } else { throw e; } } } } return messages; } /** * Send any outstanding messages to Stitch. * * @throws StitchException if Stitch rejected or was unable to * process the message * @throws IOException if there was an error communicating with * Stitch */ public void flush() throws IOException { List<Map> messages = getBufferedMessages(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Writer writer = TransitFactory.writer(TransitFactory.Format.JSON, baos); writer.write(messages); String body = baos.toString("UTF-8"); System.out.println(body); try { Request request = Request.Post(stitchUrl) .connectTimeout(connectTimeout) .addHeader("Authorization", "Bearer " + token) .bodyString(body, CONTENT_TYPE); HttpResponse response = request.execute().returnResponse(); StatusLine statusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); JsonReader rdr = Json.createReader(entity.getContent()); StitchResponse stitchResponse = new StitchResponse( statusLine.getStatusCode(), statusLine.getReasonPhrase(), rdr.readObject()); if (!stitchResponse.isOk()) { throw new StitchException(stitchResponse); } } catch (ClientProtocolException e) { throw new RuntimeException(e); } buffer.reset(); lastFlushTime = System.currentTimeMillis(); } /** * Close the client, flushing all outstanding records to Stitch. * * @throws StitchException if Stitch rejected or was unable to * process the message * @throws IOException if there was an error communicating with * Stitch */ public void close() throws IOException { flush(); } }
package com.yahoo.memory; import static com.yahoo.memory.UnsafeUtil.unsafe; import java.io.File; import java.io.FileDescriptor; import java.io.IOException; import java.io.RandomAccessFile; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.PosixFileAttributeView; import java.nio.file.attribute.PosixFileAttributes; import java.nio.file.attribute.PosixFilePermission; import java.util.Set; import sun.misc.Cleaner; import sun.nio.ch.FileChannelImpl; /** * Allocates direct memory used to memory map files for read operations. * (including those &gt; 2GB). * * @author Roman Leventov * @author Lee Rhodes * @author Praveenkumar Venkatesan */ class AllocateDirectMap implements Map { final ResourceState state; final Cleaner cleaner; AllocateDirectMap(final ResourceState state) { this.state = state; cleaner = Cleaner.create(this, new Deallocator(state)); ResourceState.currentDirectMemoryMapAllocations_.incrementAndGet(); ResourceState.currentDirectMemoryMapAllocated_.addAndGet(state.getCapacity()); } /** * Factory method for memory mapping a file for read-only access. * * <p>Memory maps a file directly in off heap leveraging native map0 method used in * FileChannelImpl.c. The owner will have read access to that address space.</p> * * @param state the ResourceState * @return A new AllocateDirectMap * @throws Exception file not found or RuntimeException, etc. */ static AllocateDirectMap map(final ResourceState state) throws Exception { return new AllocateDirectMap(mapper(state)); } @Override public void load() { madvise(); // Read a byte from each page to bring it into memory. final int ps = unsafe.pageSize(); final int count = pageCount(ps, state.getCapacity()); long nativeBaseOffset = state.getNativeBaseOffset(); for (int i = 0; i < count; i++) { unsafe.getByte(nativeBaseOffset); nativeBaseOffset += ps; } } @Override public boolean isLoaded() { final int ps = unsafe.pageSize(); final long nativeBaseOffset = state.getNativeBaseOffset(); try { final int pageCount = pageCount(ps, state.getCapacity()); final Method method = MappedByteBuffer.class.getDeclaredMethod("isLoaded0", long.class, long.class, int.class); method.setAccessible(true); return (boolean) method.invoke(state.getMappedByteBuffer(), nativeBaseOffset, state.getCapacity(), pageCount); } catch (final Exception e) { throw new RuntimeException( String.format("Encountered %s exception while loading", e.getClass())); } } @Override public void close() { try { if (state.isValid()) { ResourceState.currentDirectMemoryMapAllocations_.decrementAndGet(); ResourceState.currentDirectMemoryMapAllocated_.addAndGet(-state.getCapacity()); } cleaner.clean(); //sets invalid } catch (final Exception e) { throw e; } } // Restricted methods //Does the actual mapping work @SuppressWarnings("resource") static final ResourceState mapper(final ResourceState state) throws Exception { final long fileOffset = state.getFileOffset(); final long capacity = state.getCapacity(); checkOffsetAndCapacity(fileOffset, capacity); final File file = state.getFile(); if (isFileReadOnly(file)) { state.setResourceReadOnly(); //The file itself could be writable } final String mode = "rw"; //we can't map it unless we use rw mode final RandomAccessFile raf = new RandomAccessFile(file, mode); state.putRandomAccessFile(raf); final FileChannel fc = raf.getChannel(); final long nativeBaseOffset = map(fc, fileOffset, capacity); state.putNativeBaseOffset(nativeBaseOffset); // length can be set more than the file.length raf.setLength(capacity); final MappedByteBuffer mbb = createDummyMbbInstance(nativeBaseOffset); state.putMappedByteBuffer(mbb); return state; } static final int pageCount(final int ps, final long capacity) { return (int) ( (capacity == 0) ? 0 : ((capacity - 1L) / ps) + 1L); } static final MappedByteBuffer createDummyMbbInstance(final long nativeBaseAddress) throws RuntimeException { try { final Class<?> cl = Class.forName("java.nio.DirectByteBuffer"); final Constructor<?> ctor = cl.getDeclaredConstructor(int.class, long.class, FileDescriptor.class, Runnable.class); ctor.setAccessible(true); final MappedByteBuffer mbb = (MappedByteBuffer) ctor.newInstance(0, // some junk capacity nativeBaseAddress, null, null); return mbb; } catch (final Exception e) { throw new RuntimeException( "Could not create Dummy MappedByteBuffer instance: " + e.getClass()); } } /** * madvise is a system call made by load0 native method */ void madvise() throws RuntimeException { try { final Method method = MappedByteBuffer.class.getDeclaredMethod("load0", long.class, long.class); method.setAccessible(true); method.invoke(state.getMappedByteBuffer(), state.getNativeBaseOffset(), state.getCapacity()); } catch (final Exception e) { throw new RuntimeException( String.format("Encountered %s exception while loading", e.getClass())); } } /** * Creates a mapping of the FileChannel starting at position and of size length to pages * in the OS. This may throw OutOfMemory error if you have exhausted memory. * You can try to force garbage collection and re-attempt. * @param fileChannel the FileChannel * @param position the offset in bytes into the FileChannel * @param lengthBytes the length in bytes * @return the native base offset address * @throws RuntimeException Encountered an exception while mapping */ private static final long map(final FileChannel fileChannel, final long position, final long lengthBytes) throws RuntimeException { final int pagePosition = (int) (position % unsafe.pageSize()); final long mapPosition = position - pagePosition; final long mapSize = lengthBytes + pagePosition; try { final Method method = FileChannelImpl.class.getDeclaredMethod("map0", int.class, long.class, long.class); method.setAccessible(true); final long nativeBaseOffset = (long) method.invoke(fileChannel, 1, mapPosition, mapSize); return nativeBaseOffset; } catch (final Exception e) { throw new RuntimeException( String.format("Encountered %s exception while mapping", e.getClass())); } } private static final class Deallocator implements Runnable { private final RandomAccessFile myRaf; private final FileChannel myFc; //This is the only place the actual native offset is kept for use by unsafe.freeMemory(); //It can never be modified until it is deallocated. private long actualNativeBaseOffset; private final long myCapacity; private final ResourceState parentStateRef; private Deallocator(final ResourceState state) { myRaf = state.getRandomAccessFile(); assert (myRaf != null); myFc = myRaf.getChannel(); actualNativeBaseOffset = state.getNativeBaseOffset(); assert (actualNativeBaseOffset != 0); myCapacity = state.getCapacity(); assert (myCapacity != 0); parentStateRef = state; } @Override public void run() { if (myFc != null) { unmap(); } actualNativeBaseOffset = 0L; parentStateRef.setInvalid(); //The only place valid is set invalid. } /** * Removes existing mapping */ private void unmap() throws RuntimeException { try { final Method method = FileChannelImpl.class.getDeclaredMethod("unmap0", long.class, long.class); method.setAccessible(true); method.invoke(myFc, actualNativeBaseOffset, myCapacity); myRaf.close(); } catch (final Exception e) { throw new RuntimeException( String.format("Encountered %s exception while freeing memory", e.getClass())); } } } //End of class Deallocator static final void checkOffsetAndCapacity(final long offset, final long capacity) { if (((offset) | (capacity - 1) | (offset + capacity)) < 0) { throw new IllegalArgumentException( "offset: " + offset + ", capacity: " + capacity + ", offset + capacity: " + (offset + capacity)); } } static final boolean isFileReadOnly(final File file) { if (System.getProperty("os.name").startsWith("Windows")) { return !file.canWrite(); } //All Unix-like OSes final Path path = Paths.get(file.getAbsolutePath()); PosixFileAttributes attributes = null; try { attributes = Files.getFileAttributeView(path, PosixFileAttributeView.class).readAttributes(); } catch (final IOException e) { // File presence is guaranteed. Ignore e.printStackTrace(); } if (attributes == null) { return false; } final Set<PosixFilePermission> permissions = attributes.permissions(); int bits = 0; bits |= ((permissions.contains(PosixFilePermission.OWNER_READ)) ? 1 << 8 : 0); bits |= ((permissions.contains(PosixFilePermission.OWNER_WRITE)) ? 1 << 7 : 0); bits |= ((permissions.contains(PosixFilePermission.OWNER_EXECUTE)) ? 1 << 6 : 0); bits |= ((permissions.contains(PosixFilePermission.GROUP_READ)) ? 1 << 5 : 0); bits |= ((permissions.contains(PosixFilePermission.GROUP_WRITE)) ? 1 << 4 : 0); bits |= ((permissions.contains(PosixFilePermission.GROUP_EXECUTE)) ? 1 << 3 : 0); bits |= ((permissions.contains(PosixFilePermission.OTHERS_READ)) ? 1 << 2 : 0); bits |= ((permissions.contains(PosixFilePermission.OTHERS_WRITE)) ? 1 << 1 : 0); bits |= ((permissions.contains(PosixFilePermission.OTHERS_EXECUTE)) ? 1 : 0); //System.out.println(Util.zeroPad(Integer.toBinaryString(bits), 32)); //System.out.println(Util.zeroPad(Integer.toOctalString(bits), 4)); // Here we are going to ignore the Owner Write & Execute bits to allow root/owner testing. return ((bits & 0477) == 0444); } }
package crazypants.enderio.item; import java.util.List; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import baubles.api.BaubleType; import baubles.api.IBauble; import cofh.api.energy.ItemEnergyContainer; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.Optional; import cpw.mods.fml.common.Optional.Method; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import crazypants.enderio.EnderIO; import crazypants.enderio.EnderIOTab; import crazypants.enderio.ModObject; import crazypants.enderio.config.Config; import crazypants.enderio.gui.IResourceTooltipProvider; import crazypants.enderio.machine.power.PowerDisplayUtil; import crazypants.util.BaublesUtil; import crazypants.util.ItemUtil; @Optional.Interface(iface = "baubles.api.IBauble", modid = "Baubles|API") public class ItemMagnet extends ItemEnergyContainer implements IResourceTooltipProvider, IBauble { private static final String ACTIVE_KEY = "magnetActive"; public static void setActive(ItemStack item, boolean active) { if(item == null) { return; } NBTTagCompound nbt = ItemUtil.getOrCreateNBT(item); nbt.setBoolean(ACTIVE_KEY, active); } public static boolean isActive(ItemStack item) { if(item == null) { return false; } if(item.stackTagCompound == null) { return false; } if(!item.stackTagCompound.hasKey(ACTIVE_KEY)) { return false; } return item.stackTagCompound.getBoolean(ACTIVE_KEY); } public static boolean hasPower(ItemStack itemStack) { return EnderIO.itemMagnet.getEnergyStored(itemStack) > 0; } public static void drainPerSecondPower(ItemStack itemStack) { EnderIO.itemMagnet.extractEnergy(itemStack, Config.magnetPowerUsePerSecondRF, false); } static MagnetController controller = new MagnetController(); public static ItemMagnet create() { ItemMagnet result = new ItemMagnet(); result.init(); FMLCommonHandler.instance().bus().register(controller); return result; } protected ItemMagnet() { super(Config.magnetPowerCapacityRF, Config.magnetPowerCapacityRF / 100); setCreativeTab(EnderIOTab.tabEnderIO); setUnlocalizedName(ModObject.itemMagnet.unlocalisedName); setMaxDamage(16); setMaxStackSize(1); setHasSubtypes(true); } protected void init() { GameRegistry.registerItem(this, ModObject.itemMagnet.unlocalisedName); } @Override @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister IIconRegister) { itemIcon = IIconRegister.registerIcon("enderio:magnet"); } @Override @SideOnly(Side.CLIENT) public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List par3List) { ItemStack is = new ItemStack(this); setFull(is); par3List.add(is); is = new ItemStack(this); setEnergy(is, 0); par3List.add(is); } @Override @SideOnly(Side.CLIENT) public void addInformation(ItemStack itemStack, EntityPlayer par2EntityPlayer, List list, boolean par4) { super.addInformation(itemStack, par2EntityPlayer, list, par4); String str = PowerDisplayUtil.formatPower(getEnergyStored(itemStack)) + "/" + PowerDisplayUtil.formatPower(getMaxEnergyStored(itemStack)) + " " + PowerDisplayUtil.abrevation(); list.add(str); } @Override @SideOnly(Side.CLIENT) public boolean hasEffect(ItemStack item, int pass) { return isActive(item); } @Override public void onCreated(ItemStack itemStack, World world, EntityPlayer entityPlayer) { setEnergy(itemStack, 0); } @Override public int receiveEnergy(ItemStack container, int maxReceive, boolean simulate) { int res = super.receiveEnergy(container, maxReceive, simulate); if(res != 0 && !simulate) { updateDamage(container); } return res; } @Override public int extractEnergy(ItemStack container, int maxExtract, boolean simulate) { int res = super.extractEnergy(container, maxExtract, simulate); if(res != 0 && !simulate) { updateDamage(container); } return res; } void setEnergy(ItemStack container, int energy) { if(container.stackTagCompound == null) { container.stackTagCompound = new NBTTagCompound(); } container.stackTagCompound.setInteger("Energy", energy); updateDamage(container); } void setFull(ItemStack container) { setEnergy(container, Config.magnetPowerCapacityRF); } private void updateDamage(ItemStack stack) { float r = (float) getEnergyStored(stack) / getMaxEnergyStored(stack); int res = 16 - (int) (r * 16); stack.setItemDamage(res); } @Override public ItemStack onItemRightClick(ItemStack equipped, World world, EntityPlayer player) { if(player.isSneaking()) { setActive(equipped, !isActive(equipped)); } return equipped; } @Override public String getUnlocalizedNameForTooltip(ItemStack stack) { return getUnlocalizedName(); } @Override @Method(modid = "Baubles") public BaubleType getBaubleType(ItemStack itemstack) { return baubles.api.BaubleType.AMULET; } @Override public void onWornTick(ItemStack itemstack, EntityLivingBase player) { if(player instanceof EntityPlayer && hasPower(itemstack)) { controller.doHoover((EntityPlayer) player); if(!player.worldObj.isRemote && player.worldObj.getTotalWorldTime() % 20 == 0) { ItemMagnet.drainPerSecondPower(itemstack); IInventory baubles = BaublesUtil.instance().getBaubles((EntityPlayer) player); if(baubles != null) { for (int i = 0; i < baubles.getSizeInventory(); i++) { if(baubles.getStackInSlot(i) == itemstack) { baubles.setInventorySlotContents(i, itemstack); } } } } } } @Override public void onEquipped(ItemStack itemstack, EntityLivingBase player) { } @Override public void onUnequipped(ItemStack itemstack, EntityLivingBase player) { } @Override public boolean canEquip(ItemStack itemstack, EntityLivingBase player) { return isActive(itemstack); } @Override public boolean canUnequip(ItemStack itemstack, EntityLivingBase player) { return true; } }
package de.ddb.pdc.crawler; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import de.ddb.pdc.metadata.SearchItems; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import de.ddb.pdc.core.AnsweredQuestion; import de.ddb.pdc.core.PDCResult; import de.ddb.pdc.core.Question; import de.ddb.pdc.metadata.DDBItem; import de.ddb.pdc.web.PDCController; import de.ddb.pdc.web.SearchController; /** * The crawler schedule does the actual crawling and calculating of DDBItems. * It will schedule its actions according to the maxDepth, fetchSize and offset * given to it. */ @Service @SuppressWarnings("nls") public class CrawlerSchedule extends Thread { private static final Logger LOG = LoggerFactory.getLogger( CrawlerSchedule.class); private int maxDepth; private int fetchSize; private LinkedList<Integer> paginationOffsets = new LinkedList<Integer>(); private long timeout; private boolean end; private final List<DDBItem> fetchedResults = new LinkedList<>(); private final SearchController searchController; private final PDCController pdcController; private final Map<Question, Integer> unknownCauses; private final Set<String> foundCategories; private int depthCount; private int countTrue; private int countFalse; private int countFailed; private int countUnknown; /** * Creates a new CrawlerSchedule. */ @Autowired public CrawlerSchedule(SearchController searchController, PDCController pdcController) { super("CrawlerSchedule"); this.searchController = searchController; this.pdcController = pdcController; this.unknownCauses = new TreeMap<Question, Integer>(); this.foundCategories = new TreeSet<String>(); } /** * Set the maximum crawling depth. * @param maxDepth The maximum crawling depth. */ public void setMaxDepth(int maxDepth) { this.maxDepth = maxDepth; } /** * Set the fetch size. This is the amount of items that are fetched * in one fetch phase. * @param fetchSize The fetch size. */ public void setFetchSize(int fetchSize) { this.fetchSize = fetchSize; } /** * Set the timeout in milliseconds between the actions of the crawler. * @param timeout The timeout in milliseconds. */ public void setTimeout(int timeout) { this.timeout = timeout; } /** * {@inheritDoc} */ @Override public void run() { randomizePaginationOffsets(); while (!end) { if (fetchedResults.isEmpty()) { runFetchPhase(); } else { runCalculatePhase(); } Thread.yield(); try { Thread.sleep(timeout); } catch (InterruptedException e) { // we were interrupted, cancel the crawler thread end = true; } } LOG.info("Crawler schedule complete."); printStatistics(); } private void randomizePaginationOffsets() { int numberOfSearches = (int) Math.ceil(this.maxDepth / this.fetchSize); Random random = new Random(); while (numberOfSearches int offset = 0; do { offset = random.nextInt(this.maxDepth) * this.fetchSize; } while (paginationOffsets.contains(offset)); paginationOffsets.add(offset); } } /** * In the fetch phase new items will be fetched from the DDB-API using * the searchForItems method of the controller. */ private void runFetchPhase() { if (depthCount >= maxDepth) { end = true; LOG.info("Maximum crawling depth was reached."); return; } int offset = paginationOffsets.pop(); LOG.info(String.format("Running fetch phase from item %d to item %d", offset, offset + fetchSize)); try { SearchItems searchItems = searchController.search("*", fetchSize, offset); for (DDBItem result : searchItems.getDdbItems()) { fetchedResults.add(result); } } catch (Exception e) { LOG.error("Error while fetching results", e); } } /** * In the calculate phase the public domain status of fetched items * is calculated. */ private void runCalculatePhase() { DDBItem item = fetchedResults.remove(0); String id = item.getId(); String category = item.getCategory(); foundCategories.add(category); LOG.info("Running calculate phase for item {}", id); try { PDCResult result = pdcController.determinePublicDomain(id); LOG.info("Calculation successful for {}. Result: {}", id, result.isPublicDomain()); if (result.isPublicDomain() == null) { Question question = findUnansweredQuestion(result); LOG.info("Result unknown due to missing answer for Question {}", question); countUnknownQuestion(question); } else if (result.isPublicDomain()) { countTrue ++; } else { countFalse ++; } } catch (Exception e) { LOG.error("Calculation unsuccessful for {}", id); LOG.error("Here is the trace:", e); countFailed++; } finally { depthCount++; } } private Question findUnansweredQuestion(PDCResult result) { List<AnsweredQuestion> answeredQuestions = result.getTrace(); AnsweredQuestion lastAnsweredQuestion = answeredQuestions .get(answeredQuestions.size() - 1); return lastAnsweredQuestion.getQuestion(); } private void countUnknownQuestion(Question question) { if (!unknownCauses.containsKey(question)) { unknownCauses.put(question, 1); } else { unknownCauses.put(question, unknownCauses.get(question) + 1); } countUnknown++; } private void printStatistics() { LOG.info("================= CRAWLER STATISTICS ================="); LOG.info(String.format("Crawler crawled %d Items.", this.depthCount)); LOG.info(String.format("%d items are public domain", this.countTrue)); LOG.info(String.format("%d items are not public domain", this.countFalse)); LOG.info(String.format("%d items are unknown", this.countUnknown)); LOG.info(String.format("%d items failed", this.countFailed)); for (Entry<Question, Integer> entry : unknownCauses.entrySet()) { Question question = entry.getKey(); int amount = entry.getValue(); LOG.info("Items unknown due to question {}: {}", question, amount); } LOG.info("Found the following categories:"); Iterator<String> categoryIterator = foundCategories.iterator(); while (categoryIterator.hasNext()) { String category = categoryIterator.next(); LOG.info(category); } } }
package de.jeha.s3pt.operations; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.ObjectListing; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectSummary; import de.jeha.s3pt.OperationResult; import org.apache.commons.lang3.time.StopWatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Random; /** * @author jenshadlich@googlemail.com */ public class RandomRead extends AbstractOperation { private static final Logger LOG = LoggerFactory.getLogger(RandomRead.class); private final static Random GENERATOR = new Random(); private final AmazonS3 s3Client; private final String bucketName; private final int n; public RandomRead(AmazonS3 s3Client, String bucketName, int n) { this.s3Client = s3Client; this.bucketName = bucketName; this.n = n; } @Override public OperationResult call() { LOG.info("Random read: n={}", n); LOG.info("Collect objects for test"); StopWatch stopWatch = new StopWatch(); stopWatch.start(); int objectsRead = 0; Map<Integer, String> objects = new HashMap<>(); //Set<String> keys = new HashSet<>(); boolean truncated; ObjectListing previousObjectListing = null; do { ObjectListing objectListing = (previousObjectListing != null) ? s3Client.listNextBatchOfObjects(previousObjectListing) : s3Client.listObjects(bucketName); previousObjectListing = objectListing; truncated = objectListing.isTruncated(); LOG.debug("Loaded {} objects", objectListing.getObjectSummaries().size()); for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) { //keys.add(objectSummary.getKey()); objects.put(objectsRead, objectSummary.getKey()); objectsRead++; } } while (truncated && objectsRead < 100000); stopWatch.stop(); LOG.info("Time = {} ms", stopWatch.getTime()); LOG.info("Objects read for test: {}, files available: {}", objectsRead, objects.size()); //LOG.info("Distinct keys: {}", keys.size()); for (int i = 0; i < n; i++) { final String randomKey = (objectsRead == 1) ? objects.get(0) : objects.get(GENERATOR.nextInt(objects.size() - 1)); LOG.debug("Read object: {}", randomKey); stopWatch = new StopWatch(); stopWatch.start(); S3Object object = s3Client.getObject(bucketName, randomKey); try { object.close(); } catch (IOException e) { LOG.warn("An exception occurred while trying to close object with key: {}", randomKey); } stopWatch.stop(); LOG.debug("Time = {} ms", stopWatch.getTime()); getStats().addValue(stopWatch.getTime()); if (i > 0 && i % 1000 == 0) { LOG.info("Progress: {} of {}", i, n); } } return new OperationResult(getStats()); } }
package edu.cmu.raftj.server; import com.google.common.base.Throwables; import com.google.common.collect.Maps; import com.google.common.collect.Queues; import com.google.common.util.concurrent.AbstractExecutionThreadService; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import edu.cmu.raftj.persistence.Persistence; import edu.cmu.raftj.rpc.Communicator; import edu.cmu.raftj.rpc.Messages.*; import edu.cmu.raftj.rpc.RequestListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.BlockingDeque; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import static com.google.common.base.Preconditions.checkNotNull; import static edu.cmu.raftj.server.Server.Role.*; /** * Default implementation for {@link Server} */ public class DefaultServer extends AbstractExecutionThreadService implements Server, RequestListener { private static final Logger logger = LoggerFactory.getLogger(DefaultServer.class); private final AtomicLong commitIndex = new AtomicLong(0); private final AtomicLong lastApplied = new AtomicLong(0); private final BlockingDeque<Long> heartbeats = Queues.newLinkedBlockingDeque(); private final AtomicReference<Role> currentRole = new AtomicReference<>(Follower); private final long electionTimeout; private final Communicator communicator; private final Persistence persistence; private final Map<String, Long> nextIndices = Maps.newConcurrentMap(); private final Map<String, Long> matchIndices = Maps.newConcurrentMap(); public DefaultServer(long electionTimeout, Communicator communicator, Persistence persistence) throws IOException { this.electionTimeout = electionTimeout; this.communicator = checkNotNull(communicator, "communicator"); this.persistence = checkNotNull(persistence, "persistence"); } /** * sync current term with a potential larger term * * @param term term */ private void syncCurrentTerm(long term) { if (persistence.largerThanAndSetCurrentTerm(term)) { logger.info("[{}] bump current term to be {}", currentRole.get(), term); currentRole.set(Follower); } } @Override public VoteResponse onVoteRequest(VoteRequest voteRequest) { logger.info("[{}] got vote request {}", currentRole.get(), voteRequest); syncCurrentTerm(voteRequest.getCandidateTerm()); VoteResponse.Builder builder = VoteResponse.newBuilder().setVoteGranted(false); final String candidateId = checkNotNull(voteRequest.getCandidateId(), "candidate ID"); final boolean upToDate = voteRequest.getLastLogIndex() >= (persistence.getLogEntriesSize() + 1); if (voteRequest.getCandidateTerm() >= getCurrentTerm() && upToDate) { if (Objects.equals(candidateId, persistence.getVotedFor()) || persistence.compareAndSetVoteFor(null, candidateId)) { logger.info("[{}] voted for {}", currentRole.get(), candidateId); builder.setVoteGranted(true); } } return builder.build(); } private void updateCommitIndex(AppendEntriesRequest request) { commitIndex.updateAndGet(value -> { final long leaderCommitIndex = request.getLeaderCommitIndex(); if (leaderCommitIndex > value) { final List<LogEntry> entryList = request.getLogEntriesList(); if (!entryList.isEmpty()) { return Math.min(leaderCommitIndex, entryList.get(entryList.size() - 1).getLogIndex()); } return leaderCommitIndex; } else { return value; } }); } @Override public AppendEntriesResponse onAppendEntriesRequest(AppendEntriesRequest request) { logger.info("[{}] append entries request {}", currentRole.get(), request); syncCurrentTerm(request.getLeaderTerm()); heartbeats.addLast(System.currentTimeMillis()); final AppendEntriesResponse.Builder builder = AppendEntriesResponse.newBuilder().setSuccess(false); // the term is new if (request.getLeaderTerm() >= getCurrentTerm()) { final LogEntry lastEntry = persistence.getLastLogEntry(); if (lastEntry != null && lastEntry.getLogIndex() >= request.getPrevLogIndex()) { final LogEntry entry = persistence.getLogEntry(request.getPrevLogIndex()); if (entry.getTerm() == request.getPrevLogTerm()) { request.getLogEntriesList().stream().forEach(persistence::applyLogEntry); updateCommitIndex(request); builder.setSuccess(true); } else { logger.warn("[{}] prev entry mismatch, local last term {}, remote prev term {}", currentRole.get(), entry.getTerm(), request.getPrevLogTerm()); } } else { logger.warn("[{}] log entries are too new, remote prev index {}", currentRole.get(), request.getPrevLogIndex()); } } return builder.setTerm(persistence.getCurrentTerm()).build(); } /** * leader sends heartbeat */ private void sendHeartbeat() { logger.info("[{}] sending heartbeat", currentRole.get()); AppendEntriesRequest.Builder builder = AppendEntriesRequest.newBuilder() .setLeaderTerm(persistence.getCurrentTerm()) .setLeaderId(getServerId()) .setLeaderCommitIndex(commitIndex.get()); LogEntry lastLogEntry = persistence.getLastLogEntry(); if (lastLogEntry == null) { builder.setPrevLogIndex(0L); builder.setPrevLogTerm(0L); } else { builder.setPrevLogIndex(lastLogEntry.getLogIndex()); builder.setPrevLogTerm(lastLogEntry.getTerm()); } ListenableFuture<List<AppendEntriesResponse>> responses = communicator.sendAppendEntriesRequest(builder.build()); Futures.addCallback(responses, new FutureCallback<List<AppendEntriesResponse>>() { @Override public void onSuccess(List<AppendEntriesResponse> result) { // update terms result.stream().filter(Objects::nonNull).forEach((res) -> syncCurrentTerm(res.getTerm())); } @Override public void onFailure(Throwable t) { logger.error("[{}] error in getting response from heartbeats: {}", currentRole.get(), t); } }); } private void reinitializeLeaderStates() { nextIndices.clear(); matchIndices.clear(); } /** * apply pending commits */ private void applyCommits() { while (lastApplied.get() < commitIndex.get()) { long index = lastApplied.getAndIncrement(); LogEntry logEntry = persistence.getLogEntry(index); String command = logEntry.getCommand(); applyCommand(command); } } /** * apply command to the state machine * * @param command command */ private void applyCommand(String command) { logger.info("applying command '{}'", command); } /** * followers check election timeout, block for up to election timeout millis if not available */ private void checkElectionTimeout() throws InterruptedException { while (true) { final Long hb = heartbeats.poll(electionTimeout, TimeUnit.MILLISECONDS); if (hb == null) { logger.info("[{}] election timeout, convert to candidate", currentRole.get()); currentRole.set(Candidate); startElection(); break; } else if (hb + electionTimeout > System.currentTimeMillis()) { break; } } } private void startElection() { logger.info("[{}] try to start election, current term {}", currentRole.get(), persistence.getCurrentTerm()); while (currentRole.get() == Candidate) { final long newTerm = persistence.incrementAndGetCurrentTerm(); logger.info("[{}] increasing to new term {}", currentRole.get(), newTerm); VoteRequest.Builder builder = VoteRequest.newBuilder() .setCandidateId(getServerId()) .setCandidateTerm(newTerm); LogEntry lastLogEntry = persistence.getLastLogEntry(); if (lastLogEntry == null) { builder.setLastLogIndex(0L); builder.setLastLogTerm(0L); } else { builder.setLastLogIndex(lastLogEntry.getLogIndex()); builder.setLastLogTerm(lastLogEntry.getTerm()); } try { List<VoteResponse> responses = communicator.sendVoteRequest(builder.build()).get(electionTimeout, TimeUnit.MILLISECONDS); // update term if possible responses.stream().filter(Objects::nonNull) .forEach((response) -> syncCurrentTerm(response.getTerm())); final long numberOfAyes = responses.stream() .filter(Objects::nonNull) .filter(VoteResponse::getVoteGranted) .count(); if (2 * (numberOfAyes + 1) > responses.size()) { if (currentRole.compareAndSet(Candidate, Leader)) { logger.info("[{}] won election, current term {}", currentRole.get(), persistence.getCurrentTerm()); sendHeartbeat(); reinitializeLeaderStates(); return; } } } catch (InterruptedException | ExecutionException e) { throw Throwables.propagate(e); } catch (TimeoutException e) { logger.info("[{}] election timeout, restart election", currentRole.get()); } } logger.info("[{}] lose election, current term {}", currentRole.get(), persistence.getCurrentTerm()); } @Override protected void run() throws Exception { while (isRunning()) { // apply commits if any pending ones are present applyCommits(); Role role = currentRole.get(); switch (role) { case Follower: checkElectionTimeout(); break; case Leader: sendHeartbeat(); break; case Candidate: break; default: throw new IllegalStateException("invalid role: " + role); } } } @Override public Role getCurrentRole() { return currentRole.get(); } @Override public long getCurrentTerm() { return persistence.getCurrentTerm(); } @Override public String getServerId() { return communicator.getServerHostAndPort().toString(); } }
package edu.uib.info310.util; import java.io.File; import java.io.FileOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import edu.uib.info310.sparql.QueryEndPoint; import edu.uib.info310.sparql.QueryEndPointImp; /** * Class for getting artist information from BBC and DBPedia * @author torsteinthune */ public abstract class GetArtistInfo implements QueryEndPoint { private static final Logger LOGGER = LoggerFactory.getLogger(GetArtistInfo.class); public static String prefix = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns "PREFIX foaf: <http://xmlns.com/foaf/0.1/>" + "PREFIX mo: <http://purl.org/ontology/mo/>" + "PREFIX dbpedia: <http://dbpedia.org/property/>" + "PREFIX dbont: <http://dbpedia.org/ontology/>" + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema "PREFIX owl: <http://www.w3.org/2002/07/owl /** * Returns a model with data from BBC_MUSIC SPARQL search * @returns a Model */ public static Model BBCMusic(String artistName) throws Exception{ if(artistName.isEmpty()){ throw new NullPointerException("artistName cannot be empty string in GetArtistInfo.DbPediaArtistInfo"); } else { QueryEndPoint qep = new QueryEndPointImp(); String constructStr = "CONSTRUCT {} WHERE {}"; String queryStr = "DESCRIBE ?artist WHERE { " + "?artist foaf:name \""+ artistName + "\". " + " }"; qep.setQuery(prefix + queryStr); qep.setEndPoint(QueryEndPoint.BBC_MUSIC); Model model = qep.describeStatement(); LOGGER.debug("BBC search found " + model.size() + " statements" ); // FileOutputStream out = new FileOutputStream(new File("log/bbcout.ttl")); // model.write(out, "TURTLE"); return model; } } public static Model BBCMusic(String artistName, String artistUri) throws Exception{ if(artistName.isEmpty()){ throw new NullPointerException("artistName cannot be empty string in GetArtistInfo.DbPediaArtistInfo"); } else { QueryEndPoint qep = new QueryEndPointImp(); String artist = "<" + artistUri + ">"; String constructStr = "CONSTRUCT { "+artist+" " + "mo:fanpage ?fanpage ; " + "mo:imdb ?imdb ; " + "mo:myspace ?myspace ; " + "mo:homepage ?homepage ; " + "rdfs:comment ?comment ; " + "mo:image ?image ;" + "owl:sameAs ?artist" + "} " ; String whereStr =" WHERE {?artist foaf:name \"" + artistName + "\" " + "." + "OPTIONAL{?artist mo:fanpage ?fanpage}" + "OPTIONAL{?artist mo:imdb ?imdb}" + "OPTIONAL{?artist mo:myspace ?myspace}" + "OPTIONAL{?artist foaf:homepage ?homepage}" + "OPTIONAL{?artist rdfs:comment ?comment. FILTER (lang(?comment) = '')}" + "OPTIONAL{?artist mo:image ?image}}"; LOGGER.debug("Sending Query: " + prefix + constructStr + whereStr ); qep.setQuery(prefix + constructStr + whereStr); qep.setEndPoint(QueryEndPoint.BBC_MUSIC); Model model = qep.describeStatement(); LOGGER.debug("BBC with URI search found " + model.size() + " statements" ); FileOutputStream out = new FileOutputStream(new File("log/bbcout.ttl")); model.write(out, "TURTLE"); return model; } } /** * Returns a model with data from DB_PEDIA SPARQL search * @returns a Model */ public static Model DBPedia(String artistName) throws Exception{ if(artistName.isEmpty()){ throw new NullPointerException("artistName cannot be empty string in GetArtistInfo.DbPediaArtistInfo"); } else { QueryEndPoint qep = new QueryEndPointImp(); // Fanger ikke opp Michael Jacksom siden han er oppfrt med foaf:name Michael Joseph Jackson String queryStr = "DESCRIBE ?artist WHERE { " + "?artist foaf:name \""+ artistName + "\"@en. " + " }"; qep.setQuery(prefix + queryStr); qep.setEndPoint(QueryEndPoint.DB_PEDIA); Model model = qep.describeStatement(); LOGGER.debug("DBPedia search found " + model.size() + " statements" ); // FileOutputStream out = new FileOutputStream(new File("log/dbpediaout.ttl")); // model.write(out, "TURTLE"); return model; } } public static Model DBPedia(String artistName, String artistUri) throws Exception{ if(artistName.isEmpty()){ throw new NullPointerException("artistName cannot be empty string in GetArtistInfo.DbPediaArtistInfo"); } else { QueryEndPoint qep = new QueryEndPointImp(); // Fanger ikke opp Michael Jacksom siden han er oppfrt med foaf:name Michael Joseph Jackson String artist = "<" + artistUri + ">"; String constructStr = "CONSTRUCT { "+artist +" " + "rdfs:comment ?comment ; " + "mo:biography ?bio ; " + "dbont:birthname ?birthname ; " + "dbont:hometown ?hometown ; " + "mo:origin ?origin ; " + "mo:activity_start ?start; " + "mo:activity_end ?end ;" + "dbont:birthDate ?birth ;" + "dbont:deathDate ?death ;" + "mo:wikipedia ?wikipedia ;" + "owl:sameAs ?artist" ; String whereStr ="} WHERE {?artist foaf:name \"" + artistName + "\"@en ." + "OPTIONAL{?artist dbpedia:shortDescription ?comment} . " + "OPTIONAL{?artist dbont:abstract ?bio} . " + "OPTIONAL{?artist dbont:birthname ?birthname} ." + "OPTIONAL{?artist dbont:hometown ?hometown} ." + "OPTIONAL{?artist dbpedia:origin ?origin} ." + "OPTIONAL{?artist dbont:activeYearsEndYear ?end} ." + "OPTIONAL{?artist dbont:activeYearsStartYear ?start} ." + "OPTIONAL{?artist dbont:birthDate ?birth} ." + "OPTIONAL{?artist dbont:deathDate ?death} ." + "OPTIONAL{?artist foaf:page ?wikipedia}}"; qep.setQuery(prefix + constructStr + whereStr); qep.setEndPoint(QueryEndPoint.DB_PEDIA); Model model = qep.describeStatement(); LOGGER.debug("DBPedia search found " + model.size() + " statements" ); return model; } } public static void main(String[] args) throws Exception{ LOGGER.debug("started query"); Model test = ModelFactory.createDefaultModel(); test.add(BBCMusic("Moby")); test.add(DBPedia("Moby")); LOGGER.debug("ended query"); FileOutputStream out = new FileOutputStream(new File("log/getartistinfoout.ttl")); test.write(out, "TURTLE"); } }
package edu.wright.hendrix11.c3; import edu.wright.hendrix11.c3.axis.XAxis; import edu.wright.hendrix11.c3.axis.YAxis; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Logger; /** * @author Joe Hendrix */ public class ChartModel { private static final Logger LOG = Logger.getLogger(ChartModel.class.getName()); private Map<?, ? extends Number[]> arrayData = new LinkedHashMap<>(); private List<String> barLabels = new ArrayList<>(); private List<String> colors = new ArrayList<>(); private Map<?, ? extends Number> data = new LinkedHashMap<>(); private boolean isCategory = false; private String title; private XAxis xAxis; private YAxis yAxis; /** * * @return */ public List<String> getColors() { return colors; } /** * * @param colors */ public void setColors(List<String> colors) { this.colors = colors; } /** * * @param color */ public void addColor(String color) { colors.add(color); } /** * * @return */ public boolean isCategory() { return isCategory; } /** * * @param isCategory */ public void setIsCategory(boolean isCategory) { this.isCategory = isCategory; } /** * * @return */ public String getTitle() { return title; } /** * * @param title */ public void setTitle(String title) { this.title = title; } /** * * @return */ public XAxis getxAxis() { return xAxis; } /** * * @param label */ public void setxAxis(String label) { this.xAxis = new XAxis(label); } /** * * @param xAxis */ public void setxAxis(XAxis xAxis) { this.xAxis = xAxis; } /** * * @return */ public YAxis getyAxis() { return yAxis; } /** * * @param label */ public void setyAxis(String label) { this.yAxis = new YAxis(label); } /** * * @param yAxis */ public void setyAxis(YAxis yAxis) { this.yAxis = yAxis; } /** * @param barLabels */ public void setBarLabels(String[] barLabels) { this.barLabels = Arrays.asList(barLabels); } /** * @return */ public List<String> getBarLabels() { return barLabels; } /** * @param barLabels */ public void setBarLabels(List<String> barLabels) { this.barLabels = barLabels; } /** * * @return */ public Map<?, ? extends Number[]> getArrayData() { return arrayData; } /** * * @param arrayData */ public void setArrayData(Map<?, ? extends Number[]> arrayData) { data = new LinkedHashMap<>(); this.arrayData = arrayData; } /** * * @return */ public Map<?, ? extends Number> getData() { return data; } /** * * @param data */ public void setData(Map<?, ? extends Number> data) { arrayData = new LinkedHashMap<>(); this.data = data; } /** * @return */ public Set<?> getAxisLabels() { if ( hasArrayData() ) return arrayData.keySet(); else return data.keySet(); } /** * * @param label * @return */ public Object[] getArrayData(Object label) { return arrayData.get(label); } /** * * @param label * @return */ public Object getData(String label) { return data.get(label); } /** * * @return */ public boolean hasArrayData() { return arrayData != null && !arrayData.isEmpty(); } }
package fi.helsinki.cs.okkopa; import com.unboundid.ldap.sdk.LDAPException; import fi.helsinki.cs.okkopa.database.FailedEmailDatabase; import fi.helsinki.cs.okkopa.database.QRCodeDatabase; import fi.helsinki.cs.okkopa.delete.ErrorPDFRemover; import fi.helsinki.cs.okkopa.delete.Remover; import fi.helsinki.cs.okkopa.mail.read.EmailRead; import fi.helsinki.cs.okkopa.mail.send.ExamPaperSender; import fi.helsinki.cs.okkopa.exception.DocumentException; import fi.helsinki.cs.okkopa.exception.NotFoundException; import fi.helsinki.cs.okkopa.model.ExamPaper; import fi.helsinki.cs.okkopa.ldap.LdapConnector; import fi.helsinki.cs.okkopa.mail.writeToDisk.Saver; import fi.helsinki.cs.okkopa.model.FailedEmail; import fi.helsinki.cs.okkopa.model.Student; import fi.helsinki.cs.okkopa.pdfprocessor.PDFProcessor; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.nio.file.FileAlreadyExistsException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import org.apache.log4j.Logger; import javax.mail.MessagingException; import org.apache.commons.io.IOUtils; import org.jpedal.exception.PdfException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class OkkopaRunner implements Runnable { private PDFProcessor pDFProcessor; private EmailRead server; private ExamPaperSender sender; private static Logger LOGGER = Logger.getLogger(OkkopaRunner.class.getName()); private QRCodeDatabase qrCodeDatabase; private LdapConnector ldapConnector; private boolean saveToTikli; private boolean saveOnExamPaperPDFError; private boolean logCompleteExceptionStack; private final String saveErrorFolder; private Saver saver; private final String saveRetryFolder; // Used with email retry private int retryExpirationMinutes; private Remover errorPDFRemover; private FailedEmailDatabase failedEmailDatabase; @Autowired public OkkopaRunner(EmailRead server, ExamPaperSender sender, PDFProcessor pDFProcessor, Settings settings, QRCodeDatabase okkopaDatabase, LdapConnector ldapConnector, Saver saver, FailedEmailDatabase failedEmailDatabase) { this.server = server; this.sender = sender; this.pDFProcessor = pDFProcessor; this.qrCodeDatabase = okkopaDatabase; this.ldapConnector = ldapConnector; this.saver = saver; saveErrorFolder = settings.getSettings().getProperty("exampaper.saveunreadablefolder"); saveRetryFolder = settings.getSettings().getProperty("mail.send.retrysavefolder"); saveToTikli = Boolean.parseBoolean(settings.getSettings().getProperty("tikli.enable")); saveOnExamPaperPDFError = Boolean.parseBoolean(settings.getSettings().getProperty("exampaper.saveunreadable")); logCompleteExceptionStack = Boolean.parseBoolean(settings.getSettings().getProperty("logger.logcompletestack")); retryExpirationMinutes = Integer.parseInt(settings.getSettings().getProperty("mail.send.retryexpirationminutes")); this.errorPDFRemover = new ErrorPDFRemover(settings); this.failedEmailDatabase = failedEmailDatabase; } @Override public void run() { LOGGER.debug("Poistetaan vanhoja epäonnistuneita viestejä"); errorPDFRemover.deleteOldMessages(); retryFailedEmails(); try { server.connect(); LOGGER.debug("Kirjauduttu sisään."); while (true) { ArrayList<InputStream> attachments = server.getNextMessagesAttachments(); LOGGER.debug("Vanhimman viestin liitteet haettu"); if (attachments == null) { LOGGER.debug("Ei uusia viestejä."); break; } for (InputStream attachment : attachments) { LOGGER.debug("Käsitellään liitettä."); processAttachment(attachment); IOUtils.closeQuietly(attachment); } } } catch (MessagingException | IOException ex) { logException(ex); } finally { server.close(); } } private void processAttachment(InputStream inputStream) { List<ExamPaper> examPapers; // Split PDF to ExamPapers (2 pages per each). try { examPapers = pDFProcessor.splitPDF(inputStream); IOUtils.closeQuietly(inputStream); } catch (DocumentException ex) { // Errors: bad PDF-file, odd number of pages. logException(ex); // nothing to process, return return; } ExamPaper courseInfoPage = examPapers.get(0); String courseInfo = null; try { courseInfo = getCourseInfo(courseInfoPage); // Remove if succesful so that the page won't be processed as // a normal exam paper. examPapers.remove(courseInfoPage); } catch (NotFoundException ex) { logException(ex); } // Process all examPapers while (!examPapers.isEmpty()) { ExamPaper examPaper = examPapers.remove(0); processExamPaper(examPaper, courseInfo); } } private void processExamPaper(ExamPaper examPaper, String courseInfo) { try { examPaper.setPageImages(pDFProcessor.getPageImages(examPaper)); examPaper.setQRCodeString(pDFProcessor.readQRCode(examPaper)); } catch (PdfException | NotFoundException ex) { logException(ex); if (saveOnExamPaperPDFError) { try { LOGGER.debug("Tallennetaan virheellistä pdf tiedostoa kansioon " + saveErrorFolder); saver.saveInputStream(examPaper.getPdf(), saveErrorFolder, "" + System.currentTimeMillis() + ".pdf"); } catch (FileAlreadyExistsException ex1) { java.util.logging.Logger.getLogger(OkkopaRunner.class.getName()).log(Level.SEVERE, "File already exists", ex1); } } return; } String currentUserId; try { currentUserId = fetchUserId(examPaper.getQRCodeString()); } catch (SQLException | NotFoundException ex) { logException(ex); // QR code isn't an user id and doesn't match any database entries. return; } // Get email and student number from LDAP: try { examPaper.setStudent(ldapConnector.fetchStudent(currentUserId)); } catch (NotFoundException | LDAPException | GeneralSecurityException ex) { logException(ex); } // TODO remove when ldap has been implemented. //examPaper.setStudent(new Student(currentUserId, "okkopa.2013@gmail.com", "dummystudentnumber")); sendEmail(examPaper, true); LOGGER.debug("Koepaperi lähetetty sähköpostilla."); if (courseInfo != null && saveToTikli) { saveToTikli(examPaper); LOGGER.debug("Koepaperi tallennettu Tikliin."); } } public String getCourseInfo(ExamPaper examPaper) throws NotFoundException { // TODO unimplemented throw new NotFoundException("Course ID not found."); } private void saveToTikli(ExamPaper examPaper) { LOGGER.info("Tässä vaiheessa tallennettaisiin paperit Tikliin"); } private void sendEmail(ExamPaper examPaper, boolean saveOnError) { try { sender.send(examPaper); } catch (MessagingException ex) { LOGGER.debug("Sähköpostin lähetys epäonnistui. Tallennetaan PDF-liite levylle."); if (saveOnError) { saveFailedEmail(examPaper); } logException(ex); } } private void logException(Exception ex) { //Currently just logging exceptions. Should exception handling be in its own class? if (logCompleteExceptionStack) { LOGGER.error(ex.toString(), ex); } else { LOGGER.error(ex.toString()); } } private String fetchUserId(String qrcode) throws SQLException, NotFoundException { if (Character.isDigit(qrcode.charAt(0))) { return qrCodeDatabase.getUserID(qrcode); } return qrcode; } private void saveFailedEmail(ExamPaper examPaper) { try { String filename = "" + System.currentTimeMillis() + ".pdf"; saver.saveInputStream(examPaper.getPdf(), saveRetryFolder, filename); failedEmailDatabase.addFailedEmail(examPaper.getStudent().getEmail(), filename); } catch (FileAlreadyExistsException | SQLException ex1) { logException(ex1); // TODO if one fails what then? } } private void retryFailedEmails() { // Get failed email send attachments (PDF-files) LOGGER.debug("Yritetään lähettää sähköposteja uudelleen."); ArrayList<File> fileList = saver.list(saveRetryFolder); if (fileList == null) { LOGGER.debug("Ei uudelleenlähetettävää."); return; }; List<FailedEmail> failedEmails; try { failedEmails = failedEmailDatabase.listAll(); } catch (SQLException ex) { logException(ex); return; } for (FailedEmail failedEmail : failedEmails) { for (File pdf : fileList) { if (failedEmail.getFilename().equals(pdf.getName())) { try { FileInputStream fis = new FileInputStream(pdf); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(fis, bos); ExamPaper examPaper = new ExamPaper(); examPaper.setPdf(bos.toByteArray()); examPaper.setStudent(new Student()); examPaper.getStudent().setEmail(failedEmail.getReceiverEmail()); sendEmail(examPaper, false); IOUtils.closeQuietly(fis); // TODO expiration time and so on } catch (Exception ex) { logException(ex); continue; } } } } } }
package fi.helsinki.cs.web; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.glxn.qrgen.QRCode; import net.glxn.qrgen.image.ImageType; import org.apache.commons.io.IOUtils; import org.apache.pdfbox.exceptions.COSVisitorException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.edit.PDPageContentStream; import org.apache.pdfbox.pdmodel.graphics.xobject.PDJpeg; import org.apache.pdfbox.pdmodel.graphics.xobject.PDXObjectImage; public class GetFrontServlet extends HttpServlet { private String cource; private ByteArrayOutputStream stream; private OutputStream outputStream; private BufferedImage img; private int width; private int height; private BufferedImage bufferedImage; private Graphics2D g2d; private Font font; private FontMetrics fm; private File file; private String url; private float PDFWidth; /** * Processes requests for both HTTP * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, COSVisitorException { cource = request.getParameter("cource"); System.out.println(cource); makeQRCodeImage(cource); makeGraphics2DForRender(); drawTextToImage(cource); drawUrlToImage(); closeImages(); writeDownImage(); addFileAsResponse(response); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { processRequest(request, response); } catch (COSVisitorException ex) { Logger.getLogger(GetFrontServlet.class.getName()).log(Level.SEVERE, null, ex); } } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { processRequest(request, response); } catch (COSVisitorException ex) { Logger.getLogger(GetFrontServlet.class.getName()).log(Level.SEVERE, null, ex); } } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> private void makeQRCodeImage(String line) throws FileNotFoundException, IOException { stream = QRCode.from(line).to(ImageType.PNG).withSize(500, 500).stream(); outputStream = new FileOutputStream("temp.png"); stream.writeTo(outputStream); img = ImageIO.read(new File("temp.png")); } private void makeGraphics2DForRender() { width = img.getWidth(); height = img.getHeight(); bufferedImage = new BufferedImage(width * 3, height * 3, BufferedImage.TYPE_INT_RGB); g2d = bufferedImage.createGraphics(); g2d.fillRect(0, 0, width * 3, height * 3); g2d.drawImage(img, 0, 0, Color.WHITE, null); g2d.drawImage(img, width * 2, height * 2, Color.WHITE, null); g2d.drawImage(img, 0, height * 2, Color.WHITE, null); g2d.drawImage(img, width * 2, 0, Color.WHITE, null); } private void makeFontSettings(int size, Color c) { font = new Font("Serif", Font.BOLD, size); g2d.setFont(font); g2d.setPaint(c); fm = g2d.getFontMetrics(); } private void drawTextToImage(String line) { makeFontSettings(45, Color.BLACK); g2d.drawString(line, (width * 3) / 2 - (fm.stringWidth(line) / 2), (height * 3) / 2 + 50); } private void drawUrlToImage() { url = "http://cs.helsinki.fi/okkopa"; makeFontSettings(24, Color.BLACK); g2d.drawString(url, (width * 3) / 2 - (fm.stringWidth(url) / 2), (height * 3) / 2 - 50); } private void closeImages() { g2d.dispose(); } private void addFileAsResponse(HttpServletResponse response) throws IOException, FileNotFoundException { InputStream is = new FileInputStream("temp.pdf"); response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "attachment; filename=frontreference.pdf"); IOUtils.copy(is, response.getOutputStream()); response.flushBuffer(); } private void writeDownImage() throws IOException, COSVisitorException { file = new File("temp.jpg"); ImageIO.write(bufferedImage, "jpg", file); PDDocument document = new PDDocument(); PDPage page = new PDPage(PDPage.PAGE_SIZE_A3); document.addPage(page); ; PDXObjectImage ximage; ximage = new PDJpeg(document, new FileInputStream("temp.jpg")); PDFWidth = page.findCropBox().getWidth(); PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true); contentStream.drawXObject(ximage, 0, (page.findCropBox().getHeight() - PDFWidth) / 2, PDFWidth, PDFWidth); contentStream.close(); document.save("temp.pdf"); } }
package info.danidiaz.xanela.driver; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.msgpack.MessagePackable; import org.msgpack.MessageTypeException; import org.msgpack.Packer; import org.msgpack.rpc.Request; import org.msgpack.rpc.Server; import org.msgpack.rpc.dispatcher.Dispatcher; import org.msgpack.rpc.loop.EventLoop; public class Driver { private static int DEFAULT_PORT = 26060; public static void premain(String agentArgs) { System.out.println( "Hi, I'm the agent, started with options: " + agentArgs ); try { final EventLoop loop = EventLoop.defaultEventLoop(); final Server svr = new Server(); svr.serve(new XanelaDispatcher()); int port = DEFAULT_PORT; if (agentArgs!=null && !agentArgs.isEmpty()) { port = Integer.decode(agentArgs); } svr.listen(port); Thread serverThread = new Thread(new Runnable() { @Override public void run() { try { loop.join(); } catch (InterruptedException e) { e.printStackTrace(); } } }); serverThread.setDaemon(true); serverThread.start(); System.out.println("Xanela server started at port " + port); } catch (NumberFormatException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } } static class XanelaObject implements MessagePackable { @Override public void messagePack(Packer packer) throws IOException { packer.pack("fim fam fum"); } } static class XanelaDispatcher implements Dispatcher { @Override public void dispatch(Request request) throws Exception { request.sendResult(new XanelaObject()); } } public String hello(String msg, int a) { return "foo"; } }
package jenkins.plugins.git; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.EnvVars; import hudson.ExtensionList; import hudson.ExtensionPoint; import hudson.model.Item; import hudson.model.Node; import hudson.model.TaskListener; import hudson.plugins.git.GitTool; import hudson.plugins.git.util.GitUtils; import jenkins.model.Jenkins; import org.apache.commons.io.FileUtils; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; import org.jenkinsci.plugins.gitclient.JGitApacheTool; import org.jenkinsci.plugins.gitclient.JGitTool; import java.io.File; import java.io.IOException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * A class which allows Git Plugin to choose a git implementation by estimating the size of a repository from a distance * without requiring a local checkout. */ public class GitToolChooser { private long sizeOfRepo = 0L; private String implementation; private String gitTool; private TaskListener listener; private Node currentNode; /** * Size to switch implementation in KiB */ private static final int SIZE_TO_SWITCH = 5000; private boolean JGIT_SUPPORTED = false; /** Cache of repository sizes based on remoteURL. **/ private static ConcurrentHashMap<String, Long> repositorySizeCache = new ConcurrentHashMap<>(); /** * Instantiate class using the remote name. It looks for a cached .git directory first, calculates the * size if it is found else checks if the extension point has been implemented and asks for the size. * @param remoteName the repository url * @param projectContext the context where repository size is being estimated * @param credentialsId credential used to access the repository or null if no credential is required * @param gitExe Git tool ('git', 'jgit', 'jgitapache') to be used as the default tool * @param n A Jenkins agent used to check validity of git installation * @param listener TaskListener required by GitUtils.resolveGitTool() * @param useJGit if true the JGit is allowed as an implementation * @throws IOException on error * @throws InterruptedException on error */ public GitToolChooser(String remoteName, Item projectContext, String credentialsId, GitTool gitExe, Node n, TaskListener listener, Boolean useJGit) throws IOException, InterruptedException { boolean useCache = false; if (useJGit != null) { JGIT_SUPPORTED = useJGit; } currentNode = n; this.listener = listener; implementation = "NONE"; useCache = decideAndUseCache(remoteName); if (useCache) { implementation = determineSwitchOnSize(sizeOfRepo, gitExe); } else { decideAndUseAPI(remoteName, projectContext, credentialsId, gitExe); } gitTool = implementation; } /** * Determine and estimate the size of a .git cached directory * @param remoteName: Use the repository url to access a cached Jenkins directory, we do not lock it. * @return useCache * @throws IOException on error * @throws InterruptedException on error */ private boolean decideAndUseCache(String remoteName) throws IOException, InterruptedException { boolean useCache = false; if (setSizeFromInternalCache(remoteName)) { LOGGER.log(Level.FINE, "Found cache key for {0} with size {1}", new Object[]{remoteName, sizeOfRepo}); useCache = true; return useCache; } for (String repoUrl : remoteAlternatives(remoteName)) { String cacheEntry = AbstractGitSCMSource.getCacheEntry(repoUrl); File cacheDir = AbstractGitSCMSource.getCacheDir(cacheEntry, false); if (cacheDir != null) { Git git = Git.with(TaskListener.NULL, new EnvVars(EnvVars.masterEnvVars)).in(cacheDir).using("git"); GitClient client = git.getClient(); if (client.hasGitRepo()) { long clientRepoSize = FileUtils.sizeOfDirectory(cacheDir) / 1024; // Conversion from Bytes to Kilo Bytes if (clientRepoSize > sizeOfRepo) { if (sizeOfRepo > 0) { LOGGER.log(Level.FINE, "Replacing prior size estimate {0} with new size estimate {1} for remote {2} from cache {3}", new Object[]{sizeOfRepo, clientRepoSize, remoteName, cacheDir}); } sizeOfRepo = clientRepoSize; assignSizeToInternalCache(remoteName, sizeOfRepo); } useCache = true; if (remoteName.equals(repoUrl)) { LOGGER.log(Level.FINE, "Remote URL {0} found cache {1} with size {2}", new Object[]{remoteName, cacheDir, sizeOfRepo}); } else { LOGGER.log(Level.FINE, "Remote URL {0} found cache {1} with size {2}, alternative URL {3}", new Object[]{remoteName, cacheDir, sizeOfRepo, repoUrl}); } } else { // Log the surprise but continue looking for a cache LOGGER.log(Level.FINE, "Remote URL {0} cache {1} has no git dir", new Object[]{remoteName, cacheDir}); } } } if (!useCache) { LOGGER.log(Level.FINE, "Remote URL {0} cache not found", remoteName); } return useCache; } private void decideAndUseAPI(String remoteName, Item context, String credentialsId, GitTool gitExe) { if (setSizeFromAPI(remoteName, context, credentialsId)) { implementation = determineSwitchOnSize(sizeOfRepo, gitExe); } } /* Git repository URLs frequently end with the ".git" suffix. * However, many repositories (especially https) do not require the ".git" suffix. * * Add remoteURL with the ".git" suffix and without the ".git" suffix to the * list of alternatives. */ private void addSuffixVariants(@NonNull String remoteURL, @NonNull Set<String> alternatives) { alternatives.add(remoteURL); String suffix = ".git"; if (remoteURL.endsWith(suffix)) { alternatives.add(remoteURL.substring(0, remoteURL.length() - suffix.length())); } else { alternatives.add(remoteURL + suffix); } } /* Git repository URLs frequently end with the ".git" suffix. * However, many repositories (especially https) do not require the ".git" suffix. * * Add remoteURL with the ".git" suffix if not present */ private String addSuffix(@NonNull String canonicalURL) { String suffix = ".git"; if (!canonicalURL.endsWith(suffix)) { canonicalURL = canonicalURL + suffix; } return canonicalURL; } /* Protocol patterns to extract hostname and path from typical repository URLs */ /* Return a list of alternate remote URL's based on permutations of remoteURL. * Varies the protocol (https, git, ssh) and the suffix of the repository URL. * Package protected for testing */ /* package */ @NonNull String convertToCanonicalURL(String remoteURL) { if (remoteURL == null || remoteURL.isEmpty()) { LOGGER.log(Level.FINE, "Null or empty remote URL not cached"); return ""; // return an empty string } Pattern [] protocolPatterns = { sshAltProtocolPattern, sshProtocolPattern, gitProtocolPattern, }; String matcherReplacement = "https: /* For each matching protocol, convert alternatives to canonical form by https replacement */ remoteURL = addSuffix(remoteURL); String canonicalURL = remoteURL; if (httpProtocolPattern.matcher(remoteURL).matches()) { canonicalURL = remoteURL; } else { for (Pattern protocolPattern: protocolPatterns) { Matcher protocolMatcher = protocolPattern.matcher(remoteURL); if (protocolMatcher.matches()) { canonicalURL = protocolMatcher.replaceAll(matcherReplacement); break; } } } LOGGER.log(Level.FINE, "Cache repo URL: {0}", canonicalURL); return canonicalURL; } private boolean setSizeFromInternalCache(String repoURL) { repoURL = convertToCanonicalURL(repoURL); if (repositorySizeCache.containsKey(repoURL)) { sizeOfRepo = repositorySizeCache.get(repoURL); return true; } return false; } /* Return a list of alternate remote URL's based on permutations of remoteURL. * Varies the protocol (https, git, ssh) and the suffix of the repository URL. * Package protected for testing */ /* package */ @NonNull Set<String> remoteAlternatives(String remoteURL) { Set<String> alternatives = new LinkedHashSet<>(); if (remoteURL == null || remoteURL.isEmpty()) { LOGGER.log(Level.FINE, "Null or empty remote URL not cached"); return alternatives; } Pattern [] protocolPatterns = { gitProtocolPattern, httpProtocolPattern, sshAltProtocolPattern, sshProtocolPattern, }; String[] matcherReplacements = { "git://$1/$2", // git protocol "git@$1:$2", // ssh protocol alternate URL "https://$1/$2", // https protocol "ssh://git@$1/$2", // ssh protocol }; /* For each matching protocol, form alternatives by iterating over replacements */ boolean matched = false; for (Pattern protocolPattern : protocolPatterns) { Matcher protocolMatcher = protocolPattern.matcher(remoteURL); if (protocolMatcher.matches()) { for (String replacement : matcherReplacements) { String alternativeURL = protocolMatcher.replaceAll(replacement); addSuffixVariants(alternativeURL, alternatives); } matched = true; } } // Must include original remote in case none of the protocol patterns match // For example, file://srv/git/repo.git is matched by none of the patterns if (!matched) { addSuffixVariants(remoteURL, alternatives); } LOGGER.log(Level.FINE, "Cache repo alternative URLs: {0}", alternatives); return alternatives; } /** Cache the estimated repository size for variants of repository URL */ private void assignSizeToInternalCache(String repoURL, long repoSize) { repoURL = convertToCanonicalURL(repoURL); if (repositorySizeCache.containsKey(repoURL)) { long oldSize = repositorySizeCache.get(repoURL); if (oldSize < repoSize) { LOGGER.log(Level.FINE, "Replacing old repo size {0} with new size {1} for repo {2}", new Object[]{oldSize, repoSize, repoURL}); repositorySizeCache.put(repoURL, repoSize); } else if (oldSize > repoSize) { LOGGER.log(Level.FINE, "Ignoring new size {1} in favor of old size {0} for repo {2}", new Object[]{oldSize, repoSize, repoURL}); } } else { LOGGER.log(Level.FINE, "Caching repo size {0} for repo {1}", new Object[]{repoSize, repoURL}); repositorySizeCache.put(repoURL, repoSize); } } /** * Check if the desired implementation of extension is present and ask for the size of repository if it does * @param repoUrl: The remote name derived from {@link GitSCMSource} object * @return boolean useAPI or not. */ private boolean setSizeFromAPI(String repoUrl, Item context, String credentialsId) { List<RepositorySizeAPI> acceptedRepository = Objects.requireNonNull(RepositorySizeAPI.all()) .stream() .filter(r -> r.isApplicableTo(repoUrl, context, credentialsId)) .collect(Collectors.toList()); if (acceptedRepository.size() > 0) { try { for (RepositorySizeAPI repo: acceptedRepository) { long size = repo.getSizeOfRepository(repoUrl, context, credentialsId); if (size != 0) { sizeOfRepo = size; assignSizeToInternalCache(repoUrl, size); } } } catch (Exception e) { LOGGER.log(Level.INFO, "Not using performance improvement from REST API: {0}", e.getMessage()); return false; } return sizeOfRepo != 0; // Check if the size of the repository is zero } else { return false; } } /** * Recommend a git implementation on the basis of the given size of a repository * @param sizeOfRepo: Size of a repository (in KiBs) * @return a git implementation, "git" or "jgit" */ String determineSwitchOnSize(Long sizeOfRepo, GitTool tool) { if (sizeOfRepo != 0L) { if (sizeOfRepo < SIZE_TO_SWITCH) { if (!JGIT_SUPPORTED) { return "NONE"; } GitTool rTool = resolveGitToolForRecommendation(tool, JGitTool.MAGIC_EXENAME); if (rTool == null) { return "NONE"; } return rTool.getGitExe(); } else { GitTool rTool = resolveGitToolForRecommendation(tool, "git"); return rTool.getGitExe(); } } return "NONE"; } private GitTool resolveGitToolForRecommendation(GitTool userChoice, String recommendation) { GitTool tool; if (recommendation.equals(JGitTool.MAGIC_EXENAME)) { if (userChoice.getGitExe().equals(JGitApacheTool.MAGIC_EXENAME)) { recommendation = JGitApacheTool.MAGIC_EXENAME; } // check if jgit or jgitapache is enabled tool = getResolvedGitTool(recommendation); if (tool.getName().equals(recommendation)) { return tool; } else { return null; } } else { if (!userChoice.getName().equals(JGitTool.MAGIC_EXENAME) && !userChoice.getName().equals(JGitApacheTool.MAGIC_EXENAME)) { return userChoice; } else { return recommendGitToolOnAgent(userChoice); } } } public GitTool recommendGitToolOnAgent(GitTool userChoice) { List<GitTool> preferredToolList = new ArrayList<>(); GitTool correctTool = GitTool.getDefaultInstallation(); String toolName = userChoice.getName(); if (toolName.equals(JGitTool.MAGIC_EXENAME) || toolName.equals(JGitApacheTool.MAGIC_EXENAME)) { GitTool[] toolList = Jenkins.get().getDescriptorByType(GitTool.DescriptorImpl.class).getInstallations(); for (GitTool tool : toolList) { if (!tool.getProperties().isEmpty()) { preferredToolList.add(tool); } } for (GitTool tool: preferredToolList) { if (tool.getName().equals(getResolvedGitTool(tool.getName()).getName())) { correctTool = getResolvedGitTool(tool.getName()); } } } return correctTool; } /** * Provide a git tool considering the node specific installations * @param recommendation: Tool name * @return resolved git tool */ private GitTool getResolvedGitTool(String recommendation) { if (currentNode == null) { currentNode = Jenkins.get(); } return GitUtils.resolveGitTool(recommendation, currentNode, null, listener); } /** * Recommend git tool to be used by the git client * @return git implementation recommendation in the form of a string */ public String getGitTool() { return gitTool; } /** * Other plugins can estimate the size of repository using this extension point * The size is assumed to be in KiBs */ public static abstract class RepositorySizeAPI implements ExtensionPoint { public abstract boolean isApplicableTo(String remote, Item context, String credentialsId); public abstract Long getSizeOfRepository(String remote, Item context, String credentialsId) throws Exception; public static ExtensionList<RepositorySizeAPI> all() { return Jenkins.get().getExtensionList(RepositorySizeAPI.class); } } /** * Clear the cache of repository sizes. */ public static void clearRepositorySizeCache() { repositorySizeCache = new ConcurrentHashMap<>(); } private static final Logger LOGGER = Logger.getLogger(GitToolChooser.class.getName()); }
package lmo.tcp.bridge.client; import lmo.tcp.bridge.listener.BridgeClientListener; import lmo.tcp.bridge.listener.TcpDataListener; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.HashMap; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import lmo.tcp.bridge.BridgeCloseReqException; import lmo.tcp.bridge.BridgeCloseResException; import lmo.tcp.bridge.BridgeData; import lmo.tcp.bridge.BridgeDataException; import lmo.tcp.bridge.listener.BridgeDataListener; import lmo.tcp.bridge.listener.impl.DefaultBridgeClientListener; import org.apache.log4j.Logger; /** * * @author LMO */ public class BridgeClient implements Runnable { Logger logger; int srcId; int localPort; String serverHost; int serverPort; String dstHost = "localhost"; int dstId; int dstPort; String dstPassword = ""; String description; String password; ServerSocket ss; BridgeDataHandler serverConnection; Map<Integer, TcpDataHandler> clients = new HashMap<>(); Map<Integer, TcpDataHandler> servers = new HashMap<>(); BridgeClientListener listener = new DefaultBridgeClientListener(); public BridgeClient(String serverHost, int serverPort, int srcId, String description, String password) { this.serverHost = serverHost; this.serverPort = serverPort; this.srcId = srcId; this.description = description; this.logger = Logger.getLogger("bridgeclient"); this.password = password; } public int getPort() { return localPort; } public void setListener(BridgeClientListener listener) { this.listener = listener; } void setRemote(int dstId, String dstHost, int dstPort, String dstPassword, int localPort) { this.dstId = dstId; this.dstHost = dstHost; this.dstPort = dstPort; this.localPort = localPort; this.dstPassword = dstPassword; this.logger = Logger.getLogger("bridgeclient." + localPort); } @Override public void run() { Timer timer = new Timer("Timer-Client-" + localPort + "-" + Math.random()); try { ss = new ServerSocket(localPort); timer.schedule(new TimerTask() { @Override public void run() { logger.info("clients: " + clients); logger.info("servers: " + servers); } }, 0, 5000); logger.info("client server started on port " + localPort); listener.onServerStart(); while (true) { final Socket s = ss.accept(); logger.info("client connected: " + s); final TcpDataHandler dataHandler = new TcpDataHandler(s, s.getPort()); final Logger logger = Logger.getLogger("client." + dataHandler.id); dataHandler.setListener(new TcpDataListener() { @Override public void onRead(int id, int seq, byte[] b) throws Exception { logger.info("client request: " + b.length); BridgeData d = new BridgeData(); d.srcPort = id; d.data = b; d.dataType = BridgeData.TYPE_REQ; d.dstId = dstId; d.dstPort = dataHandler.getDstPort(); d.dataSeq = seq; d.dataLen = b.length; d.data = b; serverConnection.send(d); } @Override public void onWrite(int id, byte[] b) { logger.info("client response: " + b.length); } @Override public void onStart(int id) throws Exception { logger.info("client start: " + id); clients.put(id, dataHandler); BridgeData d = new BridgeData(); d.srcPort = id; d.dataType = BridgeData.TYPE_OPEN_REQ; d.dstId = dstId; d.dstPort = dstPort; d.data = (dstHost + "\n" + dstPassword).getBytes(); d.dataLen = d.data.length; serverConnection.send(d); logger.info("waiting for ready"); dataHandler.waitReady(10000); if (!dataHandler.isReady()) { dataHandler.end(); } } @Override public void onEnd(int id) throws Exception { logger.info("client end: " + id); clients.remove(id); BridgeData d = new BridgeData(); d.srcPort = id; d.dataType = BridgeData.TYPE_CLOSE_REQ; d.dstId = dstId; d.dstPort = dataHandler.getDstPort(); d.dataLen = 0; d.data = new byte[0]; serverConnection.send(d); } @Override public void onError(int id, String message, Exception ex) { logger.error("client connection error: " + id + ", " + message, ex); } }); dataHandler.start(); } } catch (Exception ex) { logger.error("bridge client error", ex); } finally { try { ss.close(); } catch (Exception ex) { } try { ss = null; } catch (Exception ex) { } try { timer.cancel(); } catch (Exception ex) { } try { timer.purge(); } catch (Exception ex) { } try { for (TcpDataHandler h : clients.values()) { h.ready(); h.end(); } } catch (Exception ex) { } listener.onServerEnd(); } } public boolean isStarted() { return ss != null; } public synchronized void connect() { final Logger logger = Logger.getLogger("server." + serverHost + "." + serverPort); logger.info("connecting to server"); if (serverConnection != null) { logger.info("already connected to server"); return; } final BridgeDataHandler dataHandler = new BridgeDataHandler(serverHost, serverPort); dataHandler.setListener(new BridgeDataListener() { @Override public void onConnect() throws Exception { logger.info("connected to server"); BridgeData d = new BridgeData(); d.srcId = srcId; d.dataType = BridgeData.TYPE_START; d.data = description.getBytes(); d.dataLen = d.data.length; dataHandler.setSrcId(srcId); dataHandler.send(d); } @Override public void onRead(BridgeData data) throws Exception { logger.info("data from server: " + data); try { if (data.dataType == BridgeData.TYPE_OPEN_REQ) { try { String hostPass = new String(data.data); String hp[] = hostPass.split("[\r\n]+"); String host = hp[0]; String pass = hp.length > 1 ? hp[1] : ""; open(data.srcId, data.srcPort, host, data.dstPort, pass); } catch (Exception ex) { logger.error("error opening app port", ex); throw new BridgeCloseResException(ex.getMessage()); } } else if (data.dataType == BridgeData.TYPE_OPEN_RES) { try { TcpDataHandler handler = clients.get(data.dstPort); handler.setDstPort(data.srcPort); handler.ready(); logger.info("ready to go"); } catch (Exception ex) { throw new BridgeCloseReqException("destination not found"); } } else if (data.dataType == BridgeData.TYPE_REQ) { try { TcpDataHandler handler = servers.get(data.dstPort); handler.send(data.data); } catch (Exception ex) { throw new BridgeCloseResException("destination not found"); } } else if (data.dataType == BridgeData.TYPE_RES) { try { TcpDataHandler handler = clients.get(data.dstPort); handler.send(data.data); } catch (Exception ex) { throw new BridgeCloseReqException("destination not found"); } } else if (data.dataType == BridgeData.TYPE_CLOSE_REQ) { try { logger.info("closing server: " + data.dstPort); TcpDataHandler handler = servers.get(data.dstPort); handler.end(); } catch (Exception ex) { } if (data.dataLen > 0) { listener.onError(new String(data.data), null); } } else if (data.dataType == BridgeData.TYPE_CLOSE_RES) { try { logger.info("closing client: " + data.dstPort); TcpDataHandler handler = clients.get(data.dstPort); handler.ready(); handler.end(); } catch (Exception ex) { } if (data.dataLen > 0) { listener.onError(new String(data.data), null); } } else if (data.dataType == BridgeData.TYPE_START) { logger.info("server connection success: ID=" + data.dstId); dataHandler.setSrcId(data.dstId); if (serverConnection != null) { logger.warn("another server connection already exists. closing this connection"); dataHandler.end(); } else { serverConnection = dataHandler; listener.onConnectionStart(); } } else if (data.dataType == BridgeData.TYPE_PING) { BridgeData d = new BridgeData(); d.dataType = BridgeData.TYPE_PONG; d.data = new byte[0]; d.dataLen = d.data.length; serverConnection.send(d); } else { logger.warn("unknown datatype: " + data.dataType); } } catch (BridgeCloseReqException ex) { BridgeData d = new BridgeData(); d.dataType = BridgeData.TYPE_CLOSE_REQ; d.dstId = data.srcId; d.dstPort = data.srcPort; d.data = (ex.getMessage() == null ? "" : ex.getMessage()).getBytes(); d.dataLen = d.data.length; serverConnection.send(d); } catch (BridgeCloseResException ex) { BridgeData d = new BridgeData(); d.dataType = BridgeData.TYPE_CLOSE_RES; d.dstId = data.srcId; d.dstPort = data.srcPort; d.data = (ex.getMessage() == null ? "" : ex.getMessage()).getBytes(); d.dataLen = d.data.length; serverConnection.send(d); } catch (Exception ex) { throw ex; } } @Override public void onSend(BridgeData data) { logger.info("send to server: " + data); } @Override public void onDisconnect() { for (TcpDataHandler h : servers.values()) { try { h.end(); } catch (Exception ex) { } } logger.info("disconnected from server: " + serverConnection); if (serverConnection == dataHandler || serverConnection == null) { serverConnection = null; stop(); listener.onConnectionEnd(); } else { logger.info("server connection established: " + serverConnection); } } @Override public void onError(String message, Exception ex) { logger.error(message, ex); } }); dataHandler.start(); } void open(final int srcId, final int srcPort, final String host, final int port, String password) throws IOException, BridgeDataException { if (this.password != null && !this.password.equals(password)) { throw new BridgeDataException("password mismatch"); } logger.info("connecting to " + host + ":" + port); Socket s = new Socket(); s.connect(new InetSocketAddress(host, port), 1000); final TcpDataHandler dataHandler = new TcpDataHandler(s, s.getLocalPort()); final Logger logger = Logger.getLogger("app." + dataHandler.id); dataHandler.setListener(new TcpDataListener() { @Override public void onRead(int id, int seq, byte[] b) throws Exception { logger.info("response from app: " + b.length); BridgeData d = new BridgeData(); d.srcPort = id; d.dataType = BridgeData.TYPE_RES; d.dstId = srcId; d.dstPort = srcPort; d.dataSeq = seq; d.dataLen = b.length; d.data = b; serverConnection.send(d); } @Override public void onWrite(int id, byte[] b) throws Exception { logger.info("request to app: " + b.length); } @Override public void onStart(int id) throws Exception { logger.info("connected to app " + host + ":" + port); servers.put(id, dataHandler); BridgeData d = new BridgeData(); d.srcPort = id; d.dataType = BridgeData.TYPE_OPEN_RES; d.dstId = srcId; d.dstPort = srcPort; d.dataLen = 0; d.data = new byte[0]; serverConnection.send(d); } @Override public void onEnd(int id) throws Exception { logger.info("disconnected from app " + host + ":" + port); servers.remove(id); BridgeData d = new BridgeData(); d.srcPort = id; d.dataType = BridgeData.TYPE_CLOSE_RES; d.dstId = srcId; d.dstPort = srcPort; d.dataLen = 0; d.data = new byte[0]; serverConnection.send(d); } @Override public void onError(int id, String message, Exception ex) { logger.error("app connection error " + id + ", " + message, ex); } }); dataHandler.start(); } public void start() { if (isConnected()) { new Thread(this, "BridgeClient-" + this.localPort).start(); } } public void stop() { try { ss.close(); } catch (Exception ex) { } } public void disconnect() { if (serverConnection != null) { serverConnection.end(); } } public boolean isConnected() { return serverConnection != null; } }
package markehme.factionsplus.Cmds; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.OfflinePlayer; import markehme.factionsplus.FactionsPlus; import markehme.factionsplus.Utilities; import markehme.factionsplus.Cmds.req.ReqJailsEnabled; import markehme.factionsplus.MCore.LConf; import markehme.factionsplus.util.FPPerm; import com.massivecraft.factions.cmd.req.ReqFactionsEnabled; import com.massivecraft.factions.cmd.req.ReqHasFaction; import com.massivecraft.massivecore.cmd.req.ReqHasPerm; import com.massivecraft.massivecore.cmd.req.ReqIsPlayer; import com.massivecraft.massivecore.ps.PS; import com.massivecraft.massivecore.util.Txt; public class CmdJail extends FPCommand { public CmdJail() { this.aliases.add("jail"); this.fpidentifier = "jail"; this.requiredArgs.add("player"); this.errorOnToManyArgs = false; this.addRequirements(ReqFactionsEnabled.get()); this.addRequirements(ReqIsPlayer.get()); this.addRequirements(ReqHasFaction.get()); this.addRequirements(ReqJailsEnabled.get()); this.addRequirements(ReqHasPerm.get(FPPerm.JAIL.node)); this.setHelp(LConf.get().cmdDescJail); this.setDesc(LConf.get().cmdDescJail); } @Override public void performfp() { String playerToJail = this.arg(0); if(fpuconf.whoCanJail.get(usender.getRole())) { msg(Txt.parse(LConf.get().jailsNotHighEnoughRanking)); return; } if(fpuconf.mustBeInOwnTerritoryToJail && !usender.isInOwnTerritory()) { msg(Txt.parse(LConf.get().jailsMustBeInOwnTerritoryToJail)); return; } if(fpuconf.economyCost.get("jail") > 0) { if(!Utilities.doCharge(fpuconf.economyCost.get("jail"), usender)) { msg(Txt.parse(LConf.get().jailsCantAffordToJail, fpuconf.economyCost.get("jail"))); return; } } final OfflinePlayer bPlayer = Utilities.getPlayer(playerToJail); if(bPlayer == null) { msg(Txt.parse("<red>This player hasn't been on the server before and you therefore can't jail them.")); return; } Location respawnLoc = null; if(bPlayer.isOnline()) { respawnLoc = bPlayer.getPlayer().getLocation(); } else { if(bPlayer.getBedSpawnLocation() != null) { respawnLoc = bPlayer.getBedSpawnLocation(); } else { respawnLoc = null; } } final Location finalRespawn = respawnLoc; if(fpuconf.delayBeforeSentToJail > 0) { int delay = fpuconf.delayBeforeSentToJail*20; Bukkit.getScheduler().scheduleSyncDelayedTask(FactionsPlus.instance, new Runnable() { @Override public void run() { fData.jailedPlayerIDs.put(bPlayer.getUniqueId().toString(), PS.valueOf(finalRespawn)); } }, delay); } else { fData.jailedPlayerIDs.put(bPlayer.getUniqueId().toString(), PS.valueOf(finalRespawn)); } } }
package me.duncte123.skybot.utils; import me.duncte123.skybot.SkyBot; import net.dv8tion.jda.core.EmbedBuilder; import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.MessageChannel; import net.dv8tion.jda.core.entities.MessageEmbed; import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; import okhttp3.*; import org.json.JSONArray; import org.json.JSONObject; import java.net.URL; import java.time.Instant; import java.util.ArrayList; import java.util.List; public class AirUtils { public static List<String> whiteList = new ArrayList<>(); public static List<String> blackList = new ArrayList<>(); public static CustomLog logger2 = CustomLog.getLog(Config.defaultName); /** * The default way to display a nice embedded message * @param message The message to display * @return The {@link net.dv8tion.jda.core.entities.MessageEmbed MessageEmbed} to send to the channel */ public static MessageEmbed embedMessage(String message) { return defaultEmbed().setDescription(message).build(); } /** * The default way to send a embedded message to the channel with a field in it * @param title The title of the field * @param message The message to display * @return The {@link net.dv8tion.jda.core.entities.MessageEmbed MessageEmbed} to send to the channel */ public static MessageEmbed embedField(String title, String message){ return defaultEmbed().addField(title, message, false).build(); } /** * The default way to send a embedded image to the channel * @param imageURL The url from the image * @return The {@link net.dv8tion.jda.core.entities.MessageEmbed MessageEmbed} to send to the channel */ public static MessageEmbed embedImage(String imageURL) { return defaultEmbed().setImage(imageURL).build(); } /** * The default embed layout that all of the embeds are based off * @return The way that that the {@link net.dv8tion.jda.core.EmbedBuilder embed} will look like */ public static EmbedBuilder defaultEmbed(){ return new EmbedBuilder() .setColor(Config.defaultColour) .setFooter(Config.defaultName, Config.defaultIcon) .setTimestamp(Instant.now()); } public static void getWhiteAndBlackList(){ log(CustomLog.Level.INFO, "Loading black and whitelist."); try { OkHttpClient client = new OkHttpClient(); MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded"); RequestBody body = RequestBody.create(mediaType, "delete=true"); Request request = new Request.Builder() .url(Config.apiBase + "/getWhiteAndBlacklist.php") .post(body) .addHeader("content-type", "application/x-www-form-urlencoded") .addHeader("cache-control", "no-cache") .build(); Response response = client.newCall(request).execute(); String jsonData = response.body().source().readUtf8();response.body().source().readUtf8(); JSONArray json = new JSONArray(jsonData); for(Object userJson : json) { JSONObject listData = new JSONObject(userJson.toString()); JSONArray whitelistJSON = listData.getJSONArray("whitelist"); for (Object whiteListItem : whitelistJSON) { whiteList.add((new JSONObject(whiteListItem.toString())).getString("guildID")); } JSONArray blacklistJSON = listData.getJSONArray("blacklist"); for (Object blackListItem : blacklistJSON) { blackList.add((new JSONObject(blackListItem.toString())).getString("guildID")); } } response.body().close(); log(CustomLog.Level.INFO, "Loaded black and whitelist."); } catch (Exception e) { e.printStackTrace(); } } public static String insertIntoWhiteOrBlacklist(String guildId, String guildName, String whatlist, String a1234567890) { try { OkHttpClient client = new OkHttpClient(); MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded"); RequestBody body = RequestBody.create(mediaType, "guildID=" + guildId + "&guildName=" + guildName + "&type=" + whatlist + "&a1234567890=" + a1234567890 + "&tk=" + SkyBot.jda.getToken().split(" ")[1] ); Request request = new Request.Builder() .url(Config.apiBase + "/updateWhiteAndBlacklist.php") .post(body) .addHeader("content-type", "application/x-www-form-urlencoded") .addHeader("cache-control", "no-cache") .build(); Response response = client.newCall(request).execute(); String returnData = response.body().source().readUtf8(); response.body().close(); if(!returnData.equals("ok") ) { return returnData; } } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } return ""; } public static String insetIntoWhitelist(String guildId, String guildName, String a1234567890) { whiteList.add(guildId); return insertIntoWhiteOrBlacklist(guildId, guildName, "whiteList", a1234567890); } public static String insetIntoBlacklist(String guildId, String guildName, String a1234567890) { blackList.add(guildId); return insertIntoWhiteOrBlacklist(guildId, guildName, "blackList", a1234567890); } public static void modLog(User mod, User punishedUser, String punishment, String reason, String time, MessageReceivedEvent event){ String length = ""; if (!time.isEmpty()) { length = " lasting " + time + ""; } String punishedUserMention = "<@" + punishedUser.getId() + ">"; MessageChannel modLogChannel = event.getGuild().getTextChannelsByName("modlog", true).get(0); modLogChannel.sendMessage(embedField(punishedUser.getName() + " " + punishment, punishment + " by " + mod.getName() + length + (reason.isEmpty()?"":" for " + reason))).queue( msg -> msg.getTextChannel().sendMessage("_Relevant user: " + punishedUserMention + "_").queue() ); } public static void modLog(User mod, User punishedUser, String punishment, String reason, MessageReceivedEvent event) { modLog(mod, punishedUser, punishment, reason, "", event); } public static void modLog(User mod, User unbannedUser, String punishment, MessageReceivedEvent event) { modLog(mod, unbannedUser, punishment, "", event); } public static void addBannedUserToDb(String modID, String userName, String userDiscriminator, String userId, String unbanDate, String guildId) { try { OkHttpClient client = new OkHttpClient(); MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded"); RequestBody body = RequestBody.create(mediaType, "modId=" + modID + "&username=" + userName + "&discriminator=" + userDiscriminator + "&userId=" + userId + "&unbanDate=" + unbanDate + "&guildId=" + guildId ); Request request = new Request.Builder() .url(Config.apiBase + "/ban.php") .post(body) .addHeader("content-type", "application/x-www-form-urlencoded") .addHeader("cache-control", "no-cache") .build(); Response response = client.newCall(request).execute(); response.body().close(); } catch (Exception e) { e.printStackTrace(); } } public static void checkUnbans() { try { OkHttpClient client = new OkHttpClient(); MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded"); RequestBody body = RequestBody.create(mediaType, "delete=true"); Request request = new Request.Builder() .url(Config.apiBase + "/getUnbans.php") .post(body) .addHeader("content-type", "application/x-www-form-urlencoded") .addHeader("cache-control", "no-cache") .build(); Response response = client.newCall(request).execute(); String jsonData = response.body().source().readUtf8();response.body().source().readUtf8(); JSONArray json = new JSONArray(jsonData); for(Object userJson : json) { JSONObject userData = new JSONObject(userJson.toString()); SkyBot.jda.getGuildById(userData.getString("guild")) .getController().unban(userData.getString("userId")).reason("Ban expired").queue(); } response.body().close(); } catch (Exception e) { e.printStackTrace(); } } public static boolean isURL(String url) { try { new URL(url); return true; } catch (Exception e) { return false; } } public static String verificationLvlToName(Guild.VerificationLevel lvl){ if(lvl.equals(Guild.VerificationLevel.LOW)){ return "Low"; }else if(lvl.equals(Guild.VerificationLevel.MEDIUM)){ return "Medium"; }else if(lvl.equals(Guild.VerificationLevel.HIGH)){ return "(°° "; }else if(lvl.equals(Guild.VerificationLevel.VERY_HIGH)){ return " (ಠಠ)"; } return "none"; } public static void log(CustomLog.Level lvl, String message){ log(Config.defaultName, lvl, message); } public static void log(String name, CustomLog.Level lvl, Object message){ logger2 = CustomLog.getLog(name); logger2.log(lvl, message); } }
package me.winter.boing.impl; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.Array; import me.winter.boing.DynamicBody; import me.winter.boing.MoveState; import me.winter.boing.Collision; import me.winter.boing.UpdatableBody; import me.winter.boing.World; import me.winter.boing.detection.anticipation.PreAABB; import static java.lang.Math.signum; import static me.winter.boing.util.VectorUtil.DOWN; public class MoveStateImpl implements MoveState { protected final World world; protected final DynamicBody body; protected final Vector2 movement = new Vector2(), shifting = new Vector2(), influence = new Vector2(Float.NaN, Float.NaN); protected final Array<Collision> collisions = new Array<>(); protected int frame; protected boolean stepped; public MoveStateImpl(World world, DynamicBody body) { this.world = world; this.body = body; } @Override public void step(int frame, float delta) { if(this.frame >= frame) return; this.frame = frame; stepped = true; influence.set(Float.NaN, Float.NaN); if(body instanceof UpdatableBody) ((UpdatableBody)body).update(delta); getMovement().set(body.getVelocity()).scl(delta); getMovement().add(getInfluence(body, delta)); body.getPosition().add(getMovement()); } private Vector2 tmpInfluence = new Vector2(); private Vector2 getInfluence(DynamicBody dynamic, float delta) { Vector2 influence = world.getState(dynamic).getInfluence(); if(!Float.isNaN(influence.len2())) return influence; influence.set(0, 0); for(Collision collision : world.getState(dynamic).getCollisions()) { if(collision.colliderB.getBody() instanceof DynamicBody && collision.normal.dot(DOWN) == 1) { DynamicBody other = ((DynamicBody)collision.colliderB.getBody()); world.getState(other).step(frame, delta); tmpInfluence.set(other.getVelocity()).scl(delta); tmpInfluence.add(getInfluence((DynamicBody)collision.colliderB.getBody(), delta)); if(influence.len2() < tmpInfluence.len2()) influence.set(tmpInfluence); } world.getCollisionPool().free(collision); } world.getState(dynamic).getCollisions().clear(); return influence; } @Override public void shift(float x, float y) { if(stepped) { shifting.setZero(); stepped = false; } else body.getPosition().sub(shifting); if(x != 0f) { float dirX = signum(shifting.x); if(dirX != signum(x)) shifting.x += x; else if(dirX == 0 || x * dirX > shifting.x * dirX) shifting.x = x; } if(y != 0f) { float dirY = signum(shifting.y); if(dirY != signum(y)) shifting.y += y; else if(dirY == 0 || y * dirY > shifting.y * dirY) shifting.y = y; } body.getPosition().add(shifting); } @Override public World getWorld() { return world; } @Override public DynamicBody getBody() { return body; } @Override public Vector2 getMovement() { return movement; } @Override public Vector2 getCollisionShifting() { return shifting; } @Override public Vector2 getInfluence() { return influence; } @Override public Array<Collision> getCollisions() { return collisions; } }
package metricapp.entity.external; import org.springframework.data.mongodb.core.mapping.Document; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor @Document public class KeyValue { public String key; public String value; public KeyValue(String value){ this.key = "key"; this.value = value; } }
package net.daw.helper.statics; import com.google.gson.Gson; import java.util.HashMap; import java.util.Map; public class JsonMessage { public static String getJsonMsg(String strStatus, String strMessage) { return "{\"status\":" + strStatus + ",\"message\":" + strMessage + "}"; // Map<String, String> data = new HashMap<>(); // data.put("status", strStatus); // data.put("message", strMessage); // Gson gson = new Gson(); // return gson.toJson(data); } public static String getJson(String strStatus, String strMessage) { return "{\"status\":200,\"message\":" + strMessage + "}"; } }
package net.gescobar.jmx.impl; import static net.gescobar.jmx.util.StringUtils.capitalize; import static net.gescobar.jmx.util.StringUtils.decapitalize; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import javax.management.DynamicMBean; import javax.management.MBeanAttributeInfo; import javax.management.MBeanConstructorInfo; import javax.management.MBeanInfo; import javax.management.MBeanNotificationInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import net.gescobar.jmx.Management; import net.gescobar.jmx.ManagementException; import net.gescobar.jmx.annotation.Description; import net.gescobar.jmx.annotation.Impact; import net.gescobar.jmx.annotation.ManagedAttribute; import net.gescobar.jmx.annotation.ManagedOperation; /** * <p>Factory of DynamicMBeans. Users can use this object directly to create DynamicMBeans and then registering them * with any MBeanServer. However, the preferred approach is to use the {@link Management} class (which internally uses * this class).</p> * * @author German Escobar */ public final class MBeanFactory { /** * Hide public constructor. */ private MBeanFactory() {} /** * Creates a DynamicMBean from an object annotated with {@link ManagedBean} exposing all methods and attributes * annotated with {@link ManagedOperation} and {@link ManagedAttribute} respectively. * * @param object the object from which we are creating the DynamicMBean. * * @return a constructed DynamicMBean object that can be registered with any MBeanServer. */ public static DynamicMBean createMBean(Object object) { if (object == null) { throw new IllegalArgumentException("No object specified."); } Class<?> objectType = object.getClass(); // retrieve description String description = ""; if (objectType.isAnnotationPresent(Description.class)) { description = objectType.getAnnotation(Description.class).value(); } // build attributes and operations Method[] methods = objectType.getMethods(); MethodHandler methodHandler = new MBeanFactory().new MethodHandler( objectType ); for (Method method : methods) { methodHandler.handleMethod(method); } // build the MBeanInfo MBeanInfo mBeanInfo = new MBeanInfo(objectType.getName(), description, methodHandler.getMBeanAttributes(), new MBeanConstructorInfo[0], methodHandler.getMBeanOperations(), new MBeanNotificationInfo[0]); // create the MBean return new MBeanImpl(object, mBeanInfo); } /** * This class is used internally to handle the methods of the object that the * {@link MBeanFactory#createMBean(Object)} receives as an argument. It creates a collection of MBeanAttributeInfo * and MBeanOperationInfo from the information of the methods that it handles. * * @author German Escobar */ private class MethodHandler { /** * The class of the object. */ private Class<?> objectType; /** * Holds the MBeanAttributeInfo objects that are created from the methods annotated with * {@link MBeanAttributeInfo}. Notice that the relation is not 1-1. If the attribute is not readable or * writable, it will not get added. */ private Collection<MBeanAttributeInfo> mBeanAttributes = new ArrayList<MBeanAttributeInfo>(); /** * Holds the MBeanOperationInfo objects that are created from the methods annotated with * {@link MBeanOperationInfo}. The relation is 1-1. */ private Collection<MBeanOperationInfo> mBeanOperations = new ArrayList<MBeanOperationInfo>(); /** * Constructor. Initializes the object with the specified class. * * @param objectType the class of the object that the MBeanFactory is handling. */ public MethodHandler(Class<?> objectType) { this.objectType = objectType; } /** * Called once for each method of the object that the {@link MBeanFactory#createMBean(Object)} receives as an * argument. If the method is annotated with {@link ManagedAttribute} it will try to create a * MBeanAttributeInfo. If the method is annotated with {@link ManagedOperation} it will create a * MBeanOperationInfo. Otherwise, it will do nothing with the method. * * @param method the method we are handling. * * @throws ManagementException wraps anyting that could go wrong. */ public void handleMethod(Method method) throws ManagementException { boolean hasManagedAttribute = method.isAnnotationPresent(ManagedAttribute.class); boolean hasManagedOperation = method.isAnnotationPresent(ManagedOperation.class); if (hasManagedAttribute && hasManagedOperation) { throw new ManagementException("Method " + method.getName() + " cannot have both ManagedAttribute and " + "ManagedOperation annotations."); } if (hasManagedAttribute) { handleManagedAttribute(method); } if (hasManagedOperation) { handleManagedOperation(method); } } /** * Called after the {@link #handleMethod(Method)} is called for all the methods of the <code>objectType</code>. * Retrieves the exposed attributes. * * @return an array of initialized MBeanAttributeInfo objects. It will never return null. */ public MBeanAttributeInfo[] getMBeanAttributes() { return mBeanAttributes.toArray( new MBeanAttributeInfo[0] ); } /** * Called after the {@link #handleMethod(Method)} is called for all the methods of the <code>objectType</code>. * Retrieves the exposed operations. * * @return an array of initialized MBeanOperationInfo objects. It will never return null. */ public MBeanOperationInfo[] getMBeanOperations() { return mBeanOperations.toArray( new MBeanOperationInfo[0] ); } /** * Helper method. Handles a method that has a {@link ManagedAttribute} annotation. Notice that the mehtod is * not necessarily a valid getter/setter. We actually need to find out. * * @param method the method that is annotated with {@link ManagedAttribute} */ private void handleManagedAttribute(Method method) { // validate if the method is a getter or setter Method getterMethod = isGetterMethod(method) ? method : null; Method setterMethod = isSetterMethod(method) ? method : null; if (getterMethod == null && setterMethod == null) { // not a getter or setter throw new ManagementException("Method " + method.getName() + " is annotated as ManagedAttribute " + "but doesn't looks like a valid getter or setter."); } // retrieve the attribute name from the method name String attributeName = method.getName().startsWith("is") ? decapitalize( method.getName().substring(2) ) : decapitalize( method.getName().substring(3) ); // retrieve the attribute type from the setter argument type or the getter return type Class<?> attributeType = setterMethod != null ? method.getParameterTypes()[0] : method.getReturnType(); // find the missing method getterMethod = getterMethod == null ? findGetterMethod(objectType, attributeName) : getterMethod; setterMethod = setterMethod == null ? findSetterMethod(objectType, attributeName, attributeType) : setterMethod; boolean existsAttribute = existsAttribute(mBeanAttributes, attributeName, attributeType); if ( !existsAttribute ) { // add the MBeanAttribute to the collection MBeanAttributeInfo mBeanAttribute = buildMBeanAttribute(attributeName, attributeType, getterMethod, setterMethod, method); if (mBeanAttribute != null) { // it can be null if it is neither readable or writable mBeanAttributes.add( mBeanAttribute ); } } else { // both getter and setter are annotated ... throw exception throw new ManagementException("Both getter and setter are annotated for attribute " + attributeName + ". Please remove one of the annotations."); } } /** * Helper method. Tells if the method is a getter or not. It checks if the method name starts with "get" or * "is", that the method has no parameters and returns something different than <code>void</code>. * * @param method the method that we are testing to see if it is a getter. * * @return true if the method is a getter, false otherwise. */ private boolean isGetterMethod(Method method) { return (method.getName().startsWith("get") || method.getName().startsWith("is")) && (!method.getReturnType().equals(Void.TYPE) && method.getParameterTypes().length == 0); } /** * Helper method. Tells if the method is a setter or not. It checks if the method name starts with "set", * that the return type is <code>void</code> and that it has exactly one parameter. * * @param method the method that we are testing to see if it is a setter. * * @return true if the method is a setter, false otherwise. */ private boolean isSetterMethod(Method method) { return method.getName().startsWith("set") && method.getReturnType().equals(Void.TYPE) && method.getParameterTypes().length == 1; } /** * Helper method. Tries to find a getter method for the specified <code>objectType</code> and * <code>attributeName</code>. * * @param objectType the class from which we are going to find the getter method. * @param attributeName the name of the attribute we are looking for. * * @return a java.lang.reflect.Method object representing the getter or null if not found. */ private Method findGetterMethod(Class<?> objectType, String attributeName) { try { return objectType.getMethod( "get" + capitalize(attributeName) ); } catch (NoSuchMethodException e) {} try { return objectType.getMethod( "is" + capitalize(attributeName) ); } catch (NoSuchMethodException e) {} return null; } /** * Helper method. Tries to find a setter method for the specified <code>objectType</code>, * <code>attributeName</code> and <code>attributeType</code> * * @param objectType the class from which we are going to find the setter method. * @param attributeName the name of the attribute we are looking for. * @param attributeType the type of the attribute we are looking for. * * @return a java.lang.reflect.Method object representing the setter or null if not found. */ private Method findSetterMethod(Class<?> objectType, String name, Class<?> attributeType) { try { return objectType.getMethod( "set" + capitalize(name), attributeType ); } catch (NoSuchMethodException e) { return null; } } /** * Helper method. Tells if the collection of MBeanAttributeInfo holds an attribute with the specified name * and type. * * @param mBeanAttributes the collection of MBeanAttributeInfo in which we are searching the attribute. * @param attributeName the name of the attribute we are searching for. * @param attributeType the type of the attribute we are searching for. * * @return true if the collections holds the attribute, false otherwise. */ private boolean existsAttribute(Collection<MBeanAttributeInfo> mBeanAttributes, String attributeName, Class<?> attributeType) { for (MBeanAttributeInfo mBeanAttribute : mBeanAttributes) { if (mBeanAttribute.getName().equals(attributeName) && mBeanAttribute.getType().equals(attributeType.getName())) { return true; } } return false; } /** * Helper method. Builds an MBeanAttributeInfo. As a precondition we know that there is public getter or * setter method for the attribute that it's annotated with {@link ManagedAttribute}. * * @param attributeName the name of the attribute for which we are trying to build the MBeanAttributeInfo. * @param attributeType the class of the attribute for which we are trying to build the MBeanAttributeInfo. * @param getterMethod the getter method of the attribute ... can be null. * @param setterMethod the setter method of the attribute ... can be null. * @param annotatedMethod the method that is annotated with {@link ManagedAttribute} ... can't be null. * * @return a constructed MBeanAttributeInfo object or null if the attribute is neither readable or writable. */ private MBeanAttributeInfo buildMBeanAttribute(String attributeName, Class<?> attributeType, Method getterMethod, Method setterMethod, Method annotatedMethod) { ManagedAttribute managedAttribute = annotatedMethod.getAnnotation(ManagedAttribute.class); // it's readable if the annotation has readable=true (which is the default) and the getter method exists boolean readable = managedAttribute.readable() && getterMethod != null; // it's writable if the annotation has writable=true (which is the default) and the setter method exists. boolean writable = managedAttribute.writable() && setterMethod != null; // it's IS if the getter method exists and starts with "is". boolean isIs = getterMethod != null && getterMethod.getName().startsWith("is"); // only add the attribute if it is readable and writable if (readable || writable) { return new MBeanAttributeInfo(attributeName, attributeType.getName(), managedAttribute.description(), readable, writable, isIs); } return null; } /** * Helper method. Handles a method that has a {@link ManagedOperation} annotation. It creates an * MBeanOperationInfo from the method. * * @param method the method that is annotated with {@link ManagedOperation} */ private void handleManagedOperation(Method method) { // build the MBeanParameterInfo array from the parameters of the method MBeanParameterInfo[] mBeanParameters = buildMBeanParameters( method.getParameterTypes(), method.getParameterAnnotations() ); ManagedOperation managedOperation = method.getAnnotation(ManagedOperation.class); Impact impact = managedOperation.impact(); mBeanOperations.add( new MBeanOperationInfo(method.getName(), managedOperation.description(), mBeanParameters, method.getReturnType().getName(), impact.getCode()) ); } /** * Helper method. Builds an array of MBeanParameterInfo objects that represent the parameters. * * @param paramsTypes the type of the parameters from which we are building the MBeanParameterInfo array. * @param paramsAnnotations the annotations on the parameters .. we are not using this info yet but we will * need it to retrieve the description of the parameters. * * @return an array of MBeanParameterInfo objects of the same size of the <code>paramsTypes</code> argument. */ private MBeanParameterInfo[] buildMBeanParameters(Class<?>[] paramsTypes, Annotation[][] paramsAnnotations) { MBeanParameterInfo[] mBeanParameters = new MBeanParameterInfo[paramsTypes.length]; for (int i=0; i < paramsTypes.length; i++) { MBeanParameterInfo parameterInfo = new MBeanParameterInfo("param" + i, paramsTypes[i].getName(), ""); mBeanParameters[i] = parameterInfo; } return mBeanParameters; } } }
package net.halflite.hiq.helper; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; /** * * * @author halflite * */ @Singleton public class DateHelper { private final ZoneId zone; /** * * * @return */ public Instant now() { return ZonedDateTime.now(zone).toInstant(); } /** * 0 * * @return */ public Instant midnight() { return ZonedDateTime.now(zone).withHour(0).withMinute(0).withSecond(0).withNano(0).toInstant(); } @Inject public DateHelper(@Named("TZ") String tz) { this.zone = ZoneId.of(tz); } }
package com.hexa.client.ui.treetable; import java.util.ArrayList; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.ImageElement; import com.google.gwt.dom.client.Style.Display; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.safehtml.shared.SafeHtmlUtils; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Widget; import com.hexa.client.interfaces.IAsyncCallback; import com.hexa.client.tools.JQuery; import com.hexa.client.ui.miracle.Printer; import com.hexa.client.ui.miracle.Size; public class Row { private final TreeTable treeTable; Row( TreeTable treeTable ) { this.treeTable = treeTable; } Row m_parent = null; Element m_tr = null; Element m_trToDelete = null; ArrayList<Row> m_childs; boolean m_fExpanded = true; int m_ref = -1; // this field is synchronized with the dom element // m_tr's "ref" attribute Object m_dataObject = null; private SafeHtml getExpandImageHtml() { StringBuilder sb = new StringBuilder(); sb.append( "<img src='" ); if( !hasChilds() ) sb.append( "" ); else if( getExpanded() ) sb.append( this.treeTable.treeMinus.getSafeUri().asString() ); else sb.append( this.treeTable.treePlus.getSafeUri().asString() ); sb.append( "'></img>" ); return SafeHtmlUtils.fromTrustedString( sb.toString() ); } private void updateExpandImage() { if( m_tr == null ) return; Element td = m_tr.getChild( 0 ).cast(); if( td.getChildCount() == 0 ) return; ImageElement img = td.getChild( 0 ).cast(); if( !hasChilds() ) img.setSrc( "" ); else if( getExpanded() ) img.setSrc( this.treeTable.treeMinus.getSafeUri().asString() ); else img.setSrc( this.treeTable.treePlus.getSafeUri().asString() ); } public Row getParent() { return m_parent == this.treeTable.m_rootItem ? null : m_parent; } public Cell getCell( int column ) { return new Cell( column ); } // adds an item at the end of the children of the parent public Row addLastChild() { assert (this.treeTable.m_nbColumns > 0) : "Table should have at least one column before adding items"; Row newItem = new Row(this.treeTable); newItem.m_tr = DOM.createTR(); newItem.m_tr.setPropertyObject( "linkedItem", newItem ); newItem.m_tr.setInnerHTML( this.treeTable.m_rowTemplate ); // DOM add Row lastParentLeaf = getLastLeaf(); Element trToInsertAfter = lastParentLeaf.m_tr; if( trToInsertAfter != null ) { int after = DOM.getChildIndex( this.treeTable.m_body, trToInsertAfter ); int before = after + 1; DOM.insertChild( this.treeTable.m_body, newItem.m_tr, before ); } else { DOM.appendChild( this.treeTable.m_body, newItem.m_tr ); } // logical add newItem.m_parent = this; getChilds().add( newItem ); signalStateChange(); // take care of the left padding Element firstTd = DOM.getChild( newItem.m_tr, 0 ); firstTd.getStyle().setPaddingLeft( newItem.getLevel() * this.treeTable.treePadding, Unit.PX ); return newItem; } // move to be the last item of parent public void moveLastChild( Row newParent ) { if( this == newParent ) return; // remove from its current position Row parentItem = m_parent; if( parentItem == null ) parentItem = this.treeTable.m_rootItem; parentItem.getChilds().remove( this ); // DOM.removeChild( m_body, m_tr ); if( newParent == null ) newParent = this.treeTable.m_rootItem; // insert at the end of the current parent // DOM add Row lastLeaf = newParent.getLastLeaf(); Element trToInsertAfter = lastLeaf.m_tr; if( trToInsertAfter != null ) { int after = DOM.getChildIndex( this.treeTable.m_body, trToInsertAfter ); int before = after + 1; DOM.insertChild( this.treeTable.m_body, m_tr, before ); } else { DOM.appendChild( this.treeTable.m_body, m_tr ); } parentItem.getChilds().add( this ); // take care of the left padding Element firstTd = DOM.getChild( m_tr, 0 ); firstTd.getStyle().setPaddingLeft( getLevel() * this.treeTable.treePadding, Unit.PX ); } // adds a new sibling item, just below (with same parent) public Row addBefore() { assert (this.treeTable.m_nbColumns > 0); // which is the parent ? => same parent as item Row parentItem = m_parent; if( parentItem == null ) parentItem = this.treeTable.m_rootItem; Row newItem = new Row(this.treeTable); newItem.m_tr = Document.get().createTRElement(); newItem.m_tr.setPropertyObject( "linkedItem", newItem ); newItem.m_tr.setInnerHTML( this.treeTable.m_rowTemplate ); // DOM add this.treeTable.m_body.insertBefore( newItem.m_tr, m_tr ); // logical add newItem.m_parent = parentItem; int itemPos = parentItem.getChilds().indexOf( this ); parentItem.getChilds().add( itemPos, newItem ); parentItem.signalStateChange(); // take care of the left padding Element firstTd = DOM.getChild( newItem.m_tr, 0 ); firstTd.getStyle().setPaddingLeft( newItem.getLevel() * this.treeTable.treePadding, Unit.PX ); return newItem; } // move to position just before "item" public void moveBefore( Row item ) { if( this == item ) return; Element lastTrToMove = getLastLeafTR(); Element firstChildRow = DOM.getNextSibling( m_tr ); // remove from its current position Row parentItem = m_parent; if( parentItem == null ) parentItem = this.treeTable.m_rootItem; parentItem.getChilds().remove( this ); // insert at the selected position if( item == null ) { // insert at the end of the current parent // DOM add Row lastLeaf = parentItem.getLastLeaf(); Element trToInsertAfter = lastLeaf.m_tr; if( trToInsertAfter != null ) { int after = DOM.getChildIndex( this.treeTable.m_body, trToInsertAfter ); int before = after + 1; DOM.insertChild( this.treeTable.m_body, m_tr, before ); } else { DOM.appendChild( this.treeTable.m_body, m_tr ); } parentItem.getChilds().add( this ); } else { Row newParentItem = item.m_parent; if( newParentItem == null ) newParentItem = this.treeTable.m_rootItem; int itemPos = item.m_parent.getChilds().indexOf( item ); newParentItem.getChilds().add( itemPos, this ); DOM.insertBefore( this.treeTable.m_body, m_tr, item.m_tr ); } // take care of the left padding Element firstTd = DOM.getChild( m_tr, 0 ); firstTd.getStyle().setPaddingLeft( getLevel() * this.treeTable.treePadding, Unit.PX ); // update child rows Element nextTR = DOM.getNextSibling( m_tr ); if( firstChildRow != null && lastTrToMove != null && hasChilds() ) { while( true ) { Element next = DOM.getNextSibling( firstChildRow ); DOM.insertBefore( this.treeTable.m_body, firstChildRow, nextTR ); if( firstChildRow == lastTrToMove ) break; firstChildRow = next; } } } public Element getTdElement( int column ) { return DOM.getChild( m_tr, column ); } public Row getNextTraversalItem() { // if has child, return first child if( hasChilds() ) return m_childs.get( 0 ); // return next sibling if any Row parent = m_parent; if( parent == null ) parent = this.treeTable.m_rootItem; int me = parent.m_childs.indexOf( this ); if( me < parent.m_childs.size() - 1 ) return parent.m_childs.get( me + 1 ); // return the next sibling of our parent Row parentNext = null; parent = m_parent; while( parentNext == null && parent != null ) { parentNext = parent.getNextSiblingNoBack(); parent = parent.m_parent; } if( parentNext != null ) return parentNext; return this.treeTable.m_rootItem.getChilds().get( 0 ); } private Row getNextSiblingNoBack() { Row parent = m_parent; if( parent == null ) parent = this.treeTable.m_rootItem; int me = parent.m_childs.indexOf( this ); if( me == parent.m_childs.size() - 1 ) return null; return parent.m_childs.get( me + 1 ); } public Row getPrevTraversalItem() { Row parent = m_parent; if( parent == null ) parent = this.treeTable.m_rootItem; int me = parent.m_childs.indexOf( this ); if( me == 0 ) return parent.m_childs.get( parent.m_childs.size() - 1 ); return parent.m_childs.get( me - 1 ); } public Row getNextSiblingItem() { Row parent = m_parent; if( parent == null ) parent = this.treeTable.m_rootItem; int me = parent.m_childs.indexOf( this ); if( me == parent.m_childs.size() - 1 ) return parent.m_childs.get( 0 ); return parent.m_childs.get( me + 1 ); } public Row getPrevSiblingItem() { Row parent = m_parent; if( parent == null ) parent = this.treeTable.m_rootItem; int me = parent.m_childs.indexOf( this ); if( me == 0 ) return parent.m_childs.get( parent.m_childs.size() - 1 ); return parent.m_childs.get( me - 1 ); } public void setRef( int ref ) { if( m_ref != ref ) { m_tr.setAttribute( "ref", String.valueOf( ref ) ); m_ref = ref; } } public int getRef() { if( m_ref < 0 ) { String value = m_tr.getAttribute( "ref" ); if( value == null ) return -1; try { m_ref = Integer.parseInt( value ); return m_ref; } catch( Exception e ) { return -1; } } return m_ref; } public void setVisible( final boolean isVisible ) { visitTreeDeep( new IAsyncCallback<Row>() { @Override public void onSuccess( Row result ) { if( isVisible ) result.m_tr.getStyle().clearDisplay(); else result.m_tr.getStyle().setDisplay( Display.NONE ); } } ); } public void setDataObject( Object dataObject ) { m_dataObject = dataObject; } public Object getDataObject() { return m_dataObject; } public void setText( int column, String text ) { assert column < this.treeTable.m_nbColumns; if( column >= this.treeTable.m_nbColumns ) return; if( m_tr == null ) return; Element td = DOM.getChild( m_tr, column ); this.treeTable.clearCell( td ); if( column == 0 ) { SafeHtmlBuilder sb = new SafeHtmlBuilder(); sb.append( getExpandImageHtml() ); sb.appendEscaped( text ); td.setInnerHTML( sb.toSafeHtml().asString() ); } else { td.setInnerText( text ); } } public void setText( int column, int text ) { setText( column, String.valueOf( text ) ); } public void setText( int column, double text ) { setText( column, String.valueOf( text ) ); } public void setHTML( int column, String html ) { assert column < this.treeTable.m_nbColumns; if( column >= this.treeTable.m_nbColumns ) return; if( m_tr == null ) return; Element td = DOM.getChild( m_tr, column ); this.treeTable.clearCell( td ); if( column == 0 ) td.setInnerHTML( getExpandImageHtml().asString() + html ); else td.setInnerHTML( html ); } public void setWidget( int column, IsWidget w ) { setWidget( column, w.asWidget() ); } public void setWidget( int column, Widget w ) { assert column < this.treeTable.m_nbColumns; if( column >= this.treeTable.m_nbColumns ) return; if( m_tr == null ) return; Element td = DOM.getChild( m_tr, column ); treeTable.clearCell( td ); if( column == 0 ) td.setInnerHTML( getExpandImageHtml().asString() ); treeTable.addWidget( td, w ); } public void highLite() { JQuery.get().jqEffect( "highlight", 2000, m_tr, null ); } public void addClassRow( String clazz ) { m_tr.addClassName( clazz ); } public void removeClassRow( String clazz ) { m_tr.removeClassName( clazz ); } public boolean hasChilds() { return (m_childs != null) && (!m_childs.isEmpty()); } public ArrayList<Row> getChilds() { if( m_childs == null ) m_childs = new ArrayList<>(); return m_childs; } public boolean getExpanded() { return m_fExpanded; } public void setExpanded( boolean fExpanded ) { m_fExpanded = fExpanded; signalStateChange(); ensureAllChildRespectExpand(); } void signalStateChange() { updateExpandImage(); } private void visitTreeDeep( IAsyncCallback<Row> callback ) { if( hasChilds() ) { for( Row child : getChilds() ) child.visitTreeDeep( callback ); } callback.onSuccess( this ); } void ensureAllChildRespectExpand() { boolean fOneParentAboveShrinked = false; Row parent = this; while( parent != null ) { if( !parent.m_fExpanded ) { fOneParentAboveShrinked = true; break; } parent = parent.m_parent; } ensureAllChildRespectExpand( fOneParentAboveShrinked ); } void ensureAllChildRespectExpand( boolean fOneParentAboveShrinked ) { if( !hasChilds() ) return; for( Row child : getChilds() ) { if( m_fExpanded && (!fOneParentAboveShrinked) ) child.m_tr.getStyle().clearDisplay(); else child.m_tr.getStyle().setDisplay( Display.NONE ); child.ensureAllChildRespectExpand( fOneParentAboveShrinked || !m_fExpanded ); } } Row getLastLeaf() { if( !hasChilds() ) return this; int nbChilds = m_childs.size(); return m_childs.get( nbChilds - 1 ).getLastLeaf(); } Element getLastLeafTR() { return getLastLeaf().m_tr; } public void remove() { removeRec(); // remove from parent if( m_parent != null ) m_parent.getChilds().remove( this ); } public void removeRec() { // remove all children while( hasChilds() ) m_childs.remove( 0 ).remove(); // remove all widgets removeAllWidgets(); // abandon row setRef( -1 ); m_trToDelete = m_tr; m_tr = null; // remove row if( m_trToDelete != null ) { final Element tr = m_trToDelete; m_trToDelete = null; JQuery.get().jqFadeOut( tr, 250, new JQuery.Callback() { @Override public void onFinished() { // physical remove Row.this.treeTable.m_body.removeChild( tr ); } } ); } } void logicalRemove() { // remove from parent if( m_parent != null ) { m_parent.m_childs.remove( this ); m_parent.signalStateChange(); } m_parent = null; setRef( -1 ); m_trToDelete = m_tr; m_tr = null; if( m_childs != null ) { for( Row child : m_childs ) child.logicalRemove(); } } void removeAllWidgets() { int nbTd = DOM.getChildCount( m_tr ); for( int i = 0; i < nbTd; i++ ) { Element td = DOM.getChild( m_tr, i ); this.treeTable.clearCellWidget( td ); } } void physicalRemove() { // remove all widgets removeAllWidgets(); // remove myself... if( m_trToDelete != null ) this.treeTable.m_body.removeChild( m_trToDelete ); // ...and all my children if( m_childs != null ) { for( Row child : m_childs ) child.physicalRemove(); } } public int getLevel() { if( m_parent == null ) return -1; return 1 + m_parent.getLevel(); } public class Cell implements Printer { private final int column; private Cell( int col ) { this.column = col; } @Override public void setText( String text ) { Row.this.setText( column, text ); } @Override public void setHTML( String html ) { Row.this.setHTML( column, html ); } @Override public void setWidget( Widget widget ) { Row.this.setWidget( column, widget ); } public Element getTdElement() { return DOM.getChild( m_tr, column ); } public Size getSize() { Element td = getTdElement(); return new Size( td.getOffsetWidth(), td.getOffsetHeight() ); } } public boolean isDisplayed() { String display = m_tr.getStyle().getDisplay(); return display==null || !display.equalsIgnoreCase( "none" ); } }
package net.ntg.ftl.ui.graph; import java.util.ArrayList; import processing.core.*; import net.ntg.ftl.FTLAdventureVisualiser; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class GraphRenderer extends PApplet { private static final Logger log = LogManager.getLogger(GraphRenderer.class); public static ArrayList<ArrayList<Integer>> superArray = new ArrayList<ArrayList<Integer>>(); public static int ceiling = 30; public static int panelWidth; public static int panelHeight; private int canvasWidth; private int canvasHeight; private int margin = 32; // graphics PFont mainFont; PFont headerFont; PFont headerFontAlt; int[] graphLineGradientBlue = { color(235, 245, 227, 255), color(69, 110, 112, 226), color(61, 94, 97, 198), color(53, 80, 81, 170), color(47, 69, 70, 141), color(44, 61, 62, 113), color(40, 54, 54, 85), color(37, 50, 49, 56), color(36, 47, 46, 28) }; public void setup() { size(panelWidth, panelHeight); canvasWidth = panelWidth - (margin * 2); canvasHeight= panelHeight - (margin * 2); // graphics background(55,45,46); mainFont = loadFont(ClassLoader.getSystemResource("C&CRedAlertINET-48.vlw").toString()); headerFont = loadFont(ClassLoader.getSystemResource("Half-Life1-48.vlw").toString()); headerFontAlt = loadFont(ClassLoader.getSystemResource("Half-Life2-48.vlw").toString()); } public void draw() { background(55,45,46); for (int a = 0; a < superArray.size(); ++a) { // graph line for (int s = graphLineGradientBlue.length - 1; s >= 0; --s) { noFill(); stroke(graphLineGradientBlue[s]); strokeWeight(s == graphLineGradientBlue.length - 1 ? 4 : 4 + (s * 2)); strokeJoin(ROUND); strokeCap(ROUND); beginShape(); for (int b = 0; b < superArray.get(a).size(); ++b) { vertex( margin + canvasWidth / superArray.get(a).size() * b, map( superArray.get(a).get(b), 0, ceiling, margin + canvasHeight, margin ) ); } endShape(); } // graph x labels noStroke(); fill(235, 245, 227); textFont(mainFont, 15); textAlign(LEFT, TOP); for (int b = 0; b < superArray.get(a).size(); ++b) { text( "B " + FTLAdventureVisualiser.gameStateArray.get(b).getTotalBeaconsExplored()+"\n"+ "S " + FTLAdventureVisualiser.gameStateArray.get(b).getSectorNumber(), margin + (canvasWidth / superArray.get(a).size()) * b, canvasHeight + margin + (margin / 2) ); } } // graph y labels noStroke(); fill(235, 245, 227); textFont(mainFont, 15); textAlign(RIGHT, BASELINE); for (int y = canvasHeight; y > 0; y -= (canvasHeight * 0.03)) { text( Integer.toString(y), margin - (margin / 2), map(y, 0, ceiling, canvasHeight+margin, margin) ); } // TODO draw a vertical line at the end of each sector // with the name of the sector center between sets of two seperators // TODO draw text label on the end of each graph line // TODO mouse-over over shape makes the line and labels yellow } }
package net.whydah.identity.util; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; import net.whydah.identity.config.AppConfig; import net.whydah.identity.data.ApplicationCredential; import org.apache.commons.httpclient.methods.PostMethod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.xml.sax.InputSource; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import java.io.IOException; import java.io.StringReader; import java.net.URI; import java.util.MissingResourceException; import java.util.Properties; public class SSOHelper { private static final Logger logger = LoggerFactory.getLogger(SSOHelper.class); public static final String USER_TOKEN_REFERENCE_NAME = "whydahusertoken_sso"; private final URI tokenServiceUri; private final Client tokenServiceClient = Client.create(); private String myAppTokenXml; private String myAppTokenId; private String myUserTokenId; public SSOHelper() throws IOException { try { tokenServiceUri = UriBuilder.fromUri(AppConfig.readProperties().getProperty("tokenservice")).build(); } catch (IOException e) { throw new IllegalArgumentException(e.getLocalizedMessage(), e); } } private void logonApplication() { WebResource logonResource = tokenServiceClient.resource(tokenServiceUri).path("logon"); MultivaluedMap<String,String> formData = new MultivaluedMapImpl(); ApplicationCredential appCredential = new ApplicationCredential(); try { String applicationid = AppConfig.readProperties().getProperty("applicationid"); String applicationsecret = AppConfig.readProperties().getProperty("applicationsecret"); appCredential.setApplicationID(applicationid); appCredential.setApplicationPassord(applicationsecret); formData.add("applicationcredential", appCredential.toXML()); ClientResponse response = logonResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).post(ClientResponse.class, formData); if (response.getStatus() != 200) { logger.error("logonApplication - Application authentication failed with statuscode {}", response.getStatus()); throw new RuntimeException("Application authentication failed"); } myAppTokenXml = response.getEntity(String.class); myAppTokenId = XPATHHelper.getApplicationTokenIdFromAppTokenXML(myAppTokenXml); logger.trace("logonApplication - Applogon ok: apptokenxml: {}", myAppTokenXml); logger.trace("logonApplication - myAppTokenId: {}", myAppTokenId); } catch (IOException ioe){ logger.warn("logonApplication - Did not find configuration for my application credential.", ioe); } } public String getMyAppTokenId(){ return myAppTokenId; } public String getMyUserTokenId(){ return myUserTokenId; } public String getUserTokenFromUserTokenId(String usertokenid) { logonApplication(); WebResource userTokenResource = tokenServiceClient.resource(tokenServiceUri).path("user/" + myAppTokenId + "/get_usertoken_by_usertokenid"); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("apptoken", myAppTokenXml); formData.add("usertokenid", usertokenid); logger.trace("getUserTokenFromUserTokenId - calling={} with usertokenid={} ", myAppTokenId, usertokenid); ClientResponse response = userTokenResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).post(ClientResponse.class, formData); if (response.getStatus() == ClientResponse.Status.FORBIDDEN.getStatusCode()) { throw new IllegalArgumentException("getUserTokenFromUserTokenId - get_usertoken_by_usertokenid failed."); } if (response.getStatus() == ClientResponse.Status.OK.getStatusCode()) { String responseXML = response.getEntity(String.class); logger.trace("getUserTokenFromUserTokenId - Response OK with XML: {}", responseXML); return responseXML; } //retry response = userTokenResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).post(ClientResponse.class, formData); if (response.getStatus() == ClientResponse.Status.OK.getStatusCode()) { String responseXML = response.getEntity(String.class); logger.trace("getUserTokenFromUserTokenId - Response OK with XML: {}", responseXML); return responseXML; } throw new RuntimeException("getUserTokenFromUserTokenId - get_usertoken_by_usertokenid failed with status code " + response.getStatus()); } public static void removeUserTokenCookies(HttpServletRequest request, HttpServletResponse response) { Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { System.out.println("Cookie: " + cookie.getName()); if (cookie.getName().equalsIgnoreCase(USER_TOKEN_REFERENCE_NAME)) { cookie.setValue(USER_TOKEN_REFERENCE_NAME); cookie.setMaxAge(0); cookie.setPath(""); cookie.setValue(""); response.addCookie(cookie); } } } } public static Cookie getUserTokenCookie(HttpServletRequest request) { Cookie[] cookies = request.getCookies(); System.out.println("getUserTokenCookie - header: " + cookies); if (cookies == null) { return null; } for (Cookie cooky : cookies) { System.out.println("Cookie: " + cooky.getName()); if (cooky.getName().equalsIgnoreCase(USER_TOKEN_REFERENCE_NAME)) { return cooky; } } return null; } private PostMethod setUpGetUserToken(PostMethod p,String userTokenId) throws IOException { String appTokenXML = p.getResponseBodyAsString(); String applicationtokenid = XPATHHelper.getApplicationTokenIdFromAppTokenXML(appTokenXML); WebResource resource = tokenServiceClient.resource(tokenServiceUri).path("user/" + applicationtokenid + "/get_usertoken_by_usertokenid"); PostMethod p2 = new PostMethod(resource.toString()); p2.addParameter("apptoken",appTokenXML); p2.addParameter("usertokenid",userTokenId); logger.trace("apptoken:" + appTokenXML); logger.trace("usertokenid:" + userTokenId); return p2; } private PostMethod setupRealApplicationLogon() { ApplicationCredential acred = new ApplicationCredential(); try { acred = new ApplicationCredential(); Properties properties = AppConfig.readProperties(); acred.setApplicationID(properties.getProperty("applicationname")); acred.setApplicationPassord(properties.getProperty("applicationname")); } catch (IOException ioe) { logger.error("Unable to get my application credentials from propertyfile.", ioe); } WebResource resource = tokenServiceClient.resource(tokenServiceUri).path("/logon"); PostMethod p = new PostMethod(resource.toString()); p.addParameter("applicationcredential",acred.toXML()); return p; } public static boolean hasUserAdminRight(String userTokenXml) { if (userTokenXml == null) { logger.trace("hasUserAdminRight - Empty userToken"); return false; } try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new InputSource(new StringReader(userTokenXml))); XPath xPath = XPathFactory.newInstance().newXPath(); String expression = "/usertoken/application[@ID=\"19\"]/role[@name=\"WhydahUserAdmin\"]/@value"; XPathExpression xPathExpression = xPath.compile(expression); logger.trace("hasUserAdminRight - token" + userTokenXml + "\nvalue:" + xPathExpression.evaluate(doc)); String v = (xPathExpression.evaluate(doc)); if (v == null || v.length() < 1) { return false; } return true; } catch (Exception e) { logger.error("getTimestamp - userTokenXml timestamp parsing error", e); } return false; } public String getUserTokenByUserTicket(String userticket) { logonApplication(); WebResource userTokenResource = tokenServiceClient.resource(tokenServiceUri).path("user/" + myAppTokenId + "/get_usertoken_by_userticket"); MultivaluedMap<String,String> formData = new MultivaluedMapImpl(); formData.add("apptoken", myAppTokenXml); formData.add("userticket", userticket); ClientResponse response = userTokenResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).post(ClientResponse.class, formData); if (response.getStatus() == ClientResponse.Status.FORBIDDEN.getStatusCode()) { throw new IllegalArgumentException("Login failed."); } if (response.getStatus() == ClientResponse.Status.OK.getStatusCode()) { String responseXML = response.getEntity(String.class); logger.trace("Response OK with XML: {}", responseXML); myUserTokenId = XPATHHelper.getUserTokenIdFromUserTokenXML(responseXML); return responseXML; } //retry response = userTokenResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).post(ClientResponse.class, formData); if (response.getStatus() == ClientResponse.Status.OK.getStatusCode()) { String responseXML = response.getEntity(String.class); logger.trace("Response OK with XML: {}", responseXML); return responseXML; } logger.warn("User authentication failed: {}", response); if (response.getStatus() == Response.Status.GONE.getStatusCode()) { throw new MissingResourceException("No token found for ticket.", getClass().getSimpleName(), userticket); } throw new RuntimeException("User authentication failed with status code " + response.getStatus()); } public Cookie createUserTokenCookie(String userTokenXml) { String usertokenID = XPATHHelper.getUserTokenIdFromUserTokenXML(userTokenXml); Cookie cookie = new Cookie(USER_TOKEN_REFERENCE_NAME, usertokenID); //int maxAge = calculateTokenRemainingLifetime(userTokenXml); int maxAge = 365 * 24 * 60 * 60; //TODO Calculating TokenLife is hindered by XML with differing schemas cookie.setMaxAge(maxAge); cookie.setValue(usertokenID); cookie.setSecure(true); logger.trace("Created cookie with name=" + USER_TOKEN_REFERENCE_NAME + ", usertokenid=" + usertokenID + ", maxAge=" + maxAge); return cookie; } private int calculateTokenRemainingLifetime(String userxml) { int tokenLifespan = Integer.parseInt(XPATHHelper.getLifespan(userxml)); long tokenTimestamp = Long.parseLong(XPATHHelper.getTimestamp(userxml)); long endOfTokenLife = tokenTimestamp + tokenLifespan; long remainingLife_ms = endOfTokenLife - System.currentTimeMillis(); return (int)remainingLife_ms/1000; } public String getUserTokenIdFromCookie(HttpServletRequest request) { Cookie[] cookies = request.getCookies(); logger.trace("getUserTokenIdFromCookie - header: " + cookies); if (cookies == null) { return null; } for (Cookie cookie : cookies) { logger.trace("Cookie Value: " + cookie.getName() + " PATH: " + cookie.getPath() + " Domain:" + cookie.getDomain()); if (cookie.getName().equalsIgnoreCase(USER_TOKEN_REFERENCE_NAME)) { if (cookie.getValue().length() > 7) { return cookie.getValue(); } //return true; } } return null; } /** * Look for cookie for whydah auth. * @param request * @return */ public boolean hasRightCookie(HttpServletRequest request) { Cookie[] cookies = request.getCookies(); if (cookies == null) { return false; } for (Cookie cookie : cookies) { //logger.info("Cookie: " + cookie.getName()); if (cookie.getName().equalsIgnoreCase(USER_TOKEN_REFERENCE_NAME)) { logger.trace("Found cookie, name={} value={}", cookie.getName(), cookie.getValue()); return true; } } return false; } }
package net.wyun.wcrs.model; import java.util.Date; import java.util.List; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.transaction.annotation.Transactional; /** * @author Xuecheng * */ public interface UserRepository extends CrudRepository<User, String>{ @Modifying @Transactional @Query("DELETE FROM User a WHERE (a.createt > :cutOff)") int removeByCreate_tGreaterThan(@Param("cutOff") Date cutOff); List<User> deleteByCreatetAfter(@Param("cutOff") Date cutOff); User findByOpenID(String openId); }
package news.caughtup.database; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Properties; public class MySQLDriver { private Connection connection; private static Properties sqlProps; private ResultSet resultSet; private ResultSetMetaData metaData; public MySQLDriver() { if (connection == null) { String dbPropsPath = System.getProperty( "catalina.base" ) + "/webapps/caughtup/WEB-INF/classes/db.properties"; try { /* Initialize Connection with database */ Properties props = new Properties(); /* TODO: * The path needs to be updated with the correct file location */ FileInputStream in = new FileInputStream(dbPropsPath); props.load(in); String driverName = props.getProperty("driverName"); String url = props.getProperty("url"); String user = props.getProperty("username"); String passwd = props.getProperty("password"); Class.forName(driverName).newInstance(); System.out.println("Opening db connection"); connection = DriverManager.getConnection(url, user, passwd); System.out.println("Connection opened"); } catch (IOException e) { System.out.printf("Cannot open properties file '%s' to read DB options\n", dbPropsPath); System.out.println("Catalina Base:"+ System.getProperty( "catalina.base" )); } catch (InstantiationException ex) { System.err.println("Cannot instantiate a database driver instance."); System.err.println(ex); } catch (ClassNotFoundException ex) { System.err.println("Cannot find the database driver classes."); System.err.println(ex); } catch (SQLException ex) { System.err.println("Cannot connect to this database."); System.err.println(ex); } catch (IllegalAccessException ex) { System.err.println("Illegal argument used."); System.err.println(ex); } } if (sqlProps == null) { sqlProps = new Properties(); FileInputStream in; String sqlPropsPath = System.getProperty( "catalina.base" ) + "/webapps/caughtup/WEB-INF/classes/SQLQueries.properties"; try { in = new FileInputStream(sqlPropsPath); sqlProps.load(in); } catch (FileNotFoundException e) { System.err.printf("Cannot find properties file '%s' to read SQL Queries.\n", sqlPropsPath); System.err.println(e); } catch (IOException e) { System.err.printf("Cannot open properties file '%s' to read SQL Queries.\n", sqlPropsPath); System.err.println(e); } } } public PreparedStatement getPreparedStatement(String sqlKey) throws SQLException { String query = sqlProps.getProperty(sqlKey); return connection.prepareStatement(query); } public ArrayList<HashMap<String, Object>> executeStatement(PreparedStatement statement) throws SQLException { if (connection == null || statement == null) { System.err.println("There is no database to execute the query."); return null; } ArrayList<HashMap<String, Object>> rows = new ArrayList<HashMap<String, Object>>(); resultSet = statement.executeQuery(); metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); // Get all rows while (resultSet.next()) { HashMap<String, Object> newRow = new HashMap<String, Object>(); // Get all columns for (int i = 1; i <= numberOfColumns; i++) { String columnName = metaData.getColumnLabel(i); newRow.put(columnName, resultSet.getObject(i)); } rows.add(newRow); } return rows; } public void close() throws SQLException { System.out.println("Closing db connection"); connection.close(); } protected void finalize() throws Throwable { close(); super.finalize(); } }
package nl.fixx.asset.data.domain; import org.springframework.data.annotation.Id; import java.util.ArrayList; import java.util.List; public class Resource { @Id private String id; private String firstName; private String surname; private String email; private String contactNumber; //decided on string so we can save dashes, +country code and leading zeros if required private String placedAtClient; //current client where resource is working private List<Asset> assetList = new ArrayList<>(); @Override public String toString() { return "Resource{" + "id='" + id + '\'' + ", firstName='" + firstName + '\'' + ", surname='" + surname + '\'' + ", email='" + email + '\'' + ", contactNumber='" + contactNumber + '\'' + ", placedAtClient='" + placedAtClient + '\'' + '}'; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getContactNumber() { return contactNumber; } public void setContactNumber(String contactNumber) { this.contactNumber = contactNumber; } public String getPlacedAtClient() { return placedAtClient; } public void setPlacedAtClient(String placedAtClient) { this.placedAtClient = placedAtClient; } public List<Asset> getAssetList() { return assetList; } public void setAssetList(List<Asset> assetList) { this.assetList = assetList; } }
package org.cboard.services; import com.alibaba.fastjson.JSONObject; import org.apache.commons.collections.map.HashedMap; import org.apache.commons.lang.text.StrSubstitutor; import org.apache.commons.lang3.StringUtils; import org.cboard.jdbc.JdbcDataProvider; import org.cboard.services.persist.PersistContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.io.File; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @Service public class PersistService { private static final Logger LOG = LoggerFactory.getLogger(PersistService.class); @Value("${phantomjs_path}") private String phantomjsPath; private String scriptPath = new File(this.getClass().getResource("/phantom.js").getFile()).getPath(); @Value("${web_port}") private String webPort; @Value("${web_context}") private String webContext; private static final ConcurrentMap<String, PersistContext> TASK_MAP = new ConcurrentHashMap<>(); public PersistContext persist(Long dashboardId, String userId) { String persistId = UUID.randomUUID().toString().replaceAll("-", ""); Process process = null; try { String web = webPort + "/"; if (StringUtils.isNotBlank(webContext)) { web += webContext + "/"; } String cmd = String.format("%s %s %s %s %s %s", phantomjsPath, scriptPath, dashboardId, persistId, userId, web); LOG.info("Run phantomjs command: {}", cmd); process = Runtime.getRuntime().exec(cmd); PersistContext context = new PersistContext(dashboardId); TASK_MAP.put(persistId, context); synchronized (context) { context.wait(); } process.destroy(); TASK_MAP.remove(persistId); return context; } catch (Exception e) { if (process != null) { process.destroy(); } e.printStackTrace(); } return null; } public String persistCallback(String persistId, JSONObject data) { PersistContext context = TASK_MAP.get(persistId); synchronized (context) { context.setData(data); context.notify(); } return "1"; } }
package org.citygml4j.model.core; import org.citygml4j.model.appearance.AppearanceProperty; import org.citygml4j.model.versioning.VersionProperty; import org.citygml4j.model.versioning.VersionTransitionProperty; import org.xmlobjects.gml.model.common.ChildList; import org.xmlobjects.gml.model.feature.FeatureProperty; import java.util.List; public class CityModel extends AbstractFeatureWithLifespan { private List<AbstractCityObjectProperty> cityObjectMembers; private List<AppearanceProperty> appearanceMembers; private List<FeatureProperty> featureMembers; private List<VersionProperty> versionMembers; private List<VersionTransitionProperty> versionTransitionMembers; private List<ADEPropertyOfCityModel> adeProperties; public List<AbstractCityObjectProperty> getCityObjectMembers() { if (cityObjectMembers == null) cityObjectMembers = new ChildList<>(this); return cityObjectMembers; } public void setCityObjectMembers(List<AbstractCityObjectProperty> cityObjectMembers) { this.cityObjectMembers = asChild(cityObjectMembers); } public List<AppearanceProperty> getAppearanceMembers() { if (appearanceMembers == null) appearanceMembers = new ChildList<>(this); return appearanceMembers; } public void setAppearanceMembers(List<AppearanceProperty> appearanceMembers) { this.appearanceMembers = asChild(appearanceMembers); } public List<FeatureProperty> getFeatureMembers() { if (featureMembers == null) featureMembers = new ChildList<>(this); return featureMembers; } public void setFeatureMembers(List<FeatureProperty> featureMembers) { this.featureMembers = asChild(featureMembers); } public List<VersionProperty> getVersionMembers() { if (versionMembers == null) versionMembers = new ChildList<>(this); return versionMembers; } public void setVersionMembers(List<VersionProperty> versionMembers) { this.versionMembers = asChild(versionMembers); } public List<VersionTransitionProperty> getVersionTransitionMembers() { if (versionTransitionMembers == null) versionTransitionMembers = new ChildList<>(this); return versionTransitionMembers; } public void setVersionTransitionMembers(List<VersionTransitionProperty> versionTransitionMembers) { this.versionTransitionMembers = asChild(versionTransitionMembers); } public List<ADEPropertyOfCityModel> getADEPropertiesOfCityModel() { if (adeProperties == null) adeProperties = new ChildList<>(this); return adeProperties; } public void setADEPropertiesOfCityModel(List<ADEPropertyOfCityModel> adeProperties) { this.adeProperties = asChild(adeProperties); } }
package org.elinker.serialize; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.vocabulary.RDF; import java.util.HashMap; import java.util.Map; public class NIFConverter { private String baseURI = null; private Map<String, String> entityTypes = new HashMap<String, String>(); public NIFConverter(String prefix) { this.baseURI = prefix + "#char="; entityTypes.put("PERSON", "http://nerd.eurecom.fr/ontology#Person"); entityTypes.put("ORGANIZATION", "http://nerd.eurecom.fr/ontology#Organization"); entityTypes.put("LOCATION", "http://nerd.eurecom.fr/ontology#Location"); entityTypes.put("MISC", "http://www.w3.org/2002/07/owl#Thing"); entityTypes.put("I-PER", "http://nerd.eurecom.fr/ontology#Person"); entityTypes.put("I-ORG", "http://nerd.eurecom.fr/ontology#Organization"); entityTypes.put("I-LOC", "http://nerd.eurecom.fr/ontology#Location"); entityTypes.put("I-MISC", "http://www.w3.org/2002/07/owl#Thing"); } public Model createContext( String text, int beginIndex, int endIndex ) { Model model = ModelFactory.createDefaultModel(); // Add some prefixes for nicer output. model.setNsPrefix("nif", "http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core model.setNsPrefix("itsrdf", "http://www.w3.org/2005/11/its/rdf model.setNsPrefix("xsd", "http://www.w3.org/2001/XMLSchema String contextURI = baseURI + beginIndex+","+endIndex; // Create a resource for the context. Resource contextRes = model.createResource(contextURI); contextRes.addProperty( RDF.type, model.createResource("http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#String")); contextRes.addProperty( RDF.type, model.createResource("http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#Context")); contextRes.addProperty( RDF.type, model.createResource("http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#RFC5147String")); contextRes.addLiteral( model.getProperty("http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#isString"), text); contextRes.addLiteral( model.createProperty("http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#beginIndex"), model.createTypedLiteral(new Integer(beginIndex))); contextRes.addLiteral( model.createProperty("http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#endIndex"), model.createTypedLiteral(new Integer(endIndex))); return model; } public Model createMention( String mention, int beginIndex, int endIndex, String referenceContext ) { Model model = ModelFactory.createDefaultModel(); String mentionURI = baseURI + beginIndex+","+endIndex; // Create a resource for the mention. Resource stringRes = model.createResource(mentionURI); stringRes.addProperty( RDF.type, model.createResource("http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#Word")); stringRes.addProperty( RDF.type, model.createResource("http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#Phrase")); stringRes.addProperty( RDF.type, model.createResource("http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#String")); stringRes.addProperty( RDF.type, model.createResource("http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#RFC5147String")); stringRes.addLiteral( model.createProperty("http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#anchorOf"), mention); stringRes.addLiteral( model.createProperty("http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#beginIndex"), model.createTypedLiteral(new Integer(beginIndex))); stringRes.addLiteral( model.createProperty("http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#endIndex"), model.createTypedLiteral(new Integer(endIndex))); // Add the link to the context document. stringRes.addProperty( model.createProperty("http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#referenceContext"), model.createResource(referenceContext)); return model; } public Model createMentionWithType( String entityType, String mention, int beginIndex, int endIndex, String referenceContext ) { Model model = createMention(mention, beginIndex, endIndex, referenceContext); String mentionURI = baseURI + beginIndex+","+endIndex; Resource stringRes = model.getResource(mentionURI); // Add the entity type. stringRes.addProperty( model.createProperty("http://www.w3.org/2005/11/its/rdf#taClassRef"), model.createResource(entityTypes.get(entityType))); return model; } public Model createMentionWithScore( String mention, int beginIndex, int endIndex, double score, String referenceContext ) { Model model = createMention(mention, beginIndex, endIndex, referenceContext); String mentionURI = baseURI + beginIndex+","+endIndex; Resource stringRes = model.getResource(mentionURI); // Add the confidence/relevance score. stringRes.addLiteral( model.createProperty("http://www.w3.org/2005/11/its/rdf#taConfidence"), model.createTypedLiteral(new Double(score))); return model; } public Model createMentionWithTypeAndScore( String entityType, String mention, int beginIndex, int endIndex, double score, String referenceContext ) { Model model = createMentionWithType(entityType, mention, beginIndex, endIndex, referenceContext); String mentionURI = baseURI + beginIndex+","+endIndex; Resource stringRes = model.getResource(mentionURI); // Add the confidence/relevance score. stringRes.addLiteral( model.createProperty("http://www.w3.org/2005/11/its/rdf#taConfidence"), model.createTypedLiteral(new Double(score))); return model; } public Model createLink( String mention, int beginIndex, int endIndex, String taIdentRef, String referenceContext ) { Model model = createMention(mention, beginIndex, endIndex, referenceContext); String mentionURI = baseURI + beginIndex+","+endIndex; Resource stringRes = model.getResource(mentionURI); // Add the link identifier. stringRes.addProperty( model.createProperty("http://www.w3.org/2005/11/its/rdf#taIdentRef"), model.createResource(taIdentRef)); return model; } public Model createLinkWithType( String entityType, String mention, int beginIndex, int endIndex, String taIdentRef, String referenceContext ) { Model model = createMentionWithType(entityType, mention, beginIndex, endIndex, referenceContext); String mentionURI = baseURI + beginIndex+","+endIndex; Resource stringRes = model.getResource(mentionURI); // Add the link identifier. stringRes.addProperty( model.createProperty("http://www.w3.org/2005/11/its/rdf#taIdentRef"), model.createResource(taIdentRef)); return model; } public Model createLinkWithScore( String mention, int beginIndex, int endIndex, String taIdentRef, double score, String referenceContext ) { String mentionURI = baseURI + beginIndex+","+endIndex; Model model = createLink(mention, beginIndex, endIndex, taIdentRef, referenceContext); Resource stringRes = model.getResource(mentionURI); // Add the confidence/relevance score. stringRes.addLiteral( model.createProperty("http://www.w3.org/2005/11/its/rdf#taConfidence"), model.createTypedLiteral(new Double(score))); return model; } public Model createLinkWithTypeAndScore( String entityType, String mention, int beginIndex, int endIndex, String taIdentRef, double score, String referenceContext ) { String mentionURI = baseURI + beginIndex+","+endIndex; Model model = createLinkWithType(entityType, mention, beginIndex, endIndex, taIdentRef, referenceContext); Resource stringRes = model.getResource(mentionURI); // Add the confidence/relevance score. stringRes.addLiteral( model.createProperty("http://www.w3.org/2005/11/its/rdf#taConfidence"), model.createTypedLiteral(new Double(score))); return model; } public String getContextURI(Model contextModel) { StmtIterator iter = contextModel.listStatements(null, RDF.type, contextModel.getResource("http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#Context")); return iter.nextStatement().getSubject().asResource().getURI(); } }
package org.jboss.osgi.spi.util; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.net.MalformedURLException; import java.net.URL; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.jboss.osgi.vfs.AbstractVFS; import org.jboss.osgi.vfs.VFSUtils; import org.jboss.osgi.vfs.VirtualFile; import org.osgi.framework.BundleException; import org.osgi.framework.Constants; import org.osgi.framework.Version; /** * Primitive access to bundle meta data and root virtual file. * * The bundle info can be constructed from various locations. * If that succeeds, there is a valid OSGi Manifest. * * @author thomas.diesler@jboss.com * @since 16-Oct-2009 */ public class BundleInfo implements Serializable { private static final long serialVersionUID = -2363297020450715134L; private URL rootURL; private String location; private String symbolicName; private String bundleVersion; private transient VirtualFile rootFile; private transient Manifest manifest; public static BundleInfo createBundleInfo(String location) throws BundleException { if (location == null) throw new IllegalArgumentException("Location cannot be null"); URL url = getRealLocation(location); if (url == null) throw new IllegalArgumentException("Cannot obtain real location for: " + location); return new BundleInfo(toVirtualFile(url), url.toExternalForm()); } public static BundleInfo createBundleInfo(URL url) throws BundleException { if (url == null) throw new IllegalArgumentException("Null root url"); return new BundleInfo(toVirtualFile(url), url.toExternalForm()); } public static BundleInfo createBundleInfo(VirtualFile root) throws BundleException { return new BundleInfo(root, null); } public static BundleInfo createBundleInfo(VirtualFile root, String location) throws BundleException { return new BundleInfo(root, location); } private BundleInfo(VirtualFile rootFile, String location) throws BundleException { if (rootFile == null) throw new IllegalArgumentException("Root file cannot be null"); this.rootFile = rootFile; this.rootURL = toURL(rootFile); // Derive the location from the root if (location == null) location = rootURL.toExternalForm(); this.location = location; // Initialize the manifest try { manifest = VFSUtils.getManifest(rootFile); if (manifest == null) throw new BundleException("Cannot get manifest from: " + rootURL); } catch (IOException ex) { throw new BundleException("Cannot get manifest from: " + rootURL, ex); } // Validate the manifest validateBundleManifest(manifest); int manifestVersion = getBundleManifestVersion(manifest); symbolicName = getManifestHeader(Constants.BUNDLE_SYMBOLICNAME); bundleVersion = getManifestHeader(Constants.BUNDLE_VERSION); // R3 Framework if (manifestVersion == 1) { // Generate default symbolic name symbolicName = "anonymous-bundle"; // Parse the Bundle-Version string try { bundleVersion = Version.parseVersion(bundleVersion).toString(); } catch (NumberFormatException ex) { // Install expected to succeed on invalid Bundle-Version bundleVersion = Version.emptyVersion.toString(); } } } /** * Validate a given bundle manifest. * @param manifest The given manifest * @throws BundleException if this is not a valid bundle manifest */ public static void validateBundleManifest(Manifest manifest) throws BundleException { // A bundle manifest must express the version of the OSGi manifest header // syntax in the Bundle-ManifestVersion header. Bundles exploiting this version // of the Framework specification (or later) must specify this header. // taken to have a bundle manifest version of '1', although there is no way to // express this in such manifests. int manifestVersion = getBundleManifestVersion(manifest); if (manifestVersion < 0) throw new BundleException("Cannot determine Bundle-ManifestVersion"); if (manifestVersion > 2) throw new BundleException("Unsupported Bundle-ManifestVersion: " + manifestVersion); String symbolicName = getManifestHeaderInternal(manifest, Constants.BUNDLE_SYMBOLICNAME); String bundleVersion = getManifestHeaderInternal(manifest, Constants.BUNDLE_VERSION); // R3 Framework if (manifestVersion == 1 && symbolicName != null) throw new BundleException("Invalid Bundle-ManifestVersion:=1 for " + symbolicName); // R4 Framework if (manifestVersion == 2) { if (symbolicName == null) throw new BundleException("Cannot obtain Bundle-SymbolicName"); // Parse the Bundle-Version string Version.parseVersion(bundleVersion).toString(); } } /** * Get the bundle manifest version. * @param manifest The given manifest * @return The value of the Bundle-ManifestVersion header, or -1 for a non OSGi manifest */ public static int getBundleManifestVersion(Manifest manifest) { if (manifest == null) throw new IllegalArgumentException("Null manifest"); // At least one of these manifest headers must be there // Note, in R3 and R4 there is no common mandatory header String bundleName = getManifestHeaderInternal(manifest, Constants.BUNDLE_NAME); String bundleSymbolicName = getManifestHeaderInternal(manifest, Constants.BUNDLE_SYMBOLICNAME); String bundleVersion = getManifestHeaderInternal(manifest, Constants.BUNDLE_VERSION); if (bundleName == null && bundleSymbolicName == null && bundleVersion == null) return -1; String manifestVersion = getManifestHeaderInternal(manifest, Constants.BUNDLE_MANIFESTVERSION); return manifestVersion != null ? Integer.parseInt(manifestVersion) : 1; } /** * Get the manifest header for the given key. */ public String getManifestHeader(String key) { String value = getManifestHeaderInternal(getManifest(), key); return value; } /** * Get the bundle location */ public String getLocation() { return location; } /** * Get the bundle root file */ public VirtualFile getRoot() { if (rootFile == null) rootFile = toVirtualFile(rootURL); return rootFile; } /** * Get the bundle root url */ public URL getRootURL() { return toURL(getRoot()); } /** * Get the bundle symbolic name */ public String getSymbolicName() { return symbolicName; } /** * Get the bundle version */ public Version getVersion() { return Version.parseVersion(bundleVersion); } /** * Closes the accociated resources. */ public void close() { if (rootFile != null) rootFile.close(); } private Manifest getManifest() { if (manifest == null) { try { manifest = VFSUtils.getManifest(getRoot()); } catch (Exception ex) { throw new IllegalStateException("Cannot get manifest from: " + rootURL, ex); } } return manifest; } private static VirtualFile toVirtualFile(URL url) { try { return AbstractVFS.getRoot(url); } catch (IOException e) { throw new IllegalArgumentException("Invalid root url: " + url, e); } } private static URL getRealLocation(String location) { // Try location as URL URL url = null; try { url = new URL(location); } catch (MalformedURLException ex) { // ignore } // Try location as File if (url == null) { try { File file = new File(location); if (file.exists()) url = file.toURI().toURL(); } catch (MalformedURLException e) { // ignore } } // Try to prefix the location with the test archive directory if (url == null) { String prefix = System.getProperty("test.archive.directory", "target/test-libs"); if (location.startsWith(prefix) == false && new File(prefix).exists()) return getRealLocation(prefix + File.separator + location); } return url; } private static URL toURL(VirtualFile file) { try { return file.toURL(); } catch (Exception e) { throw new IllegalArgumentException("Invalid root file: " + file); } } private String toEqualString() { return "[" + symbolicName + ":" + bundleVersion + ",url=" + rootURL + "]"; } private static String getManifestHeaderInternal(Manifest manifest, String key) { Attributes attribs = manifest.getMainAttributes(); String value = attribs.getValue(key); return value; } @Override public boolean equals(Object obj) { if (!(obj instanceof BundleInfo)) return false; BundleInfo other = (BundleInfo)obj; return toEqualString().equals(other.toEqualString()); } @Override public int hashCode() { return toEqualString().hashCode(); } @Override public String toString() { return toEqualString(); } }
package org.lantern.network; import java.security.cert.Certificate; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.jboss.netty.util.internal.ConcurrentHashMap; import org.lantern.event.ResetEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.eventbus.Subscribe; import com.google.inject.Singleton; /** * <p> * This singleton is responsible for tracking information about the physical * Lantern network as well as the trust network that's used to build it. * </p> * * <p> * Core Concepts: * </p> * * <ul> * <li>instanceId: Identifies a Lantern instance in some consistent and unique * way. In practice, this is currently the Jabber ID.</li> * <li>Instance online/offline: we're told of this as we learn about instances * being online or offline (e.g. via KScope ad)</li> * <li>User trusted/untrusted: we're told of this as the friends list changes</li> * <li>Certificate received: we're told of this as certificates are received</li> * </ul> * * @param <U> * Type of object identifying users * @param <I> * Type of object identifying instances * @param <D> * Type of object representing additional data stored in * {@link InstanceInfo}s */ @Singleton public class NetworkTracker<U, I, D> { private static final Logger LOG = LoggerFactory .getLogger(NetworkTracker.class); private final Map<I, Certificate> trustedCertificatesByInstance = new ConcurrentHashMap<I, Certificate>(); private final Map<U, Map<I, InstanceInfo<I, D>>> onlineInstancesByAdvertisingUser = new ConcurrentHashMap<U, Map<I, InstanceInfo<I, D>>>(); private final Set<U> trustedUsers = Collections .synchronizedSet(new HashSet<U>()); private final List<NetworkTrackerListener<I, D>> listeners = new ArrayList<NetworkTrackerListener<I, D>>(); private volatile Set<InstanceInfo<I, D>> trustedOnlineInstances; public NetworkTracker() { identifyTrustedOnlineInstances(); } /** * Add a {@link NetworkTrackerListener} to listen for events from this * tracker. * * @param listener */ public void addListener( NetworkTrackerListener<I, D> listener) { this.listeners.add(listener); } /** * Tell the {@link NetworkTracker} that an instance went online. * * @param advertisingUser * the user who told us this instance is online * @param instanceId * @param instanceInfo * @return true if NetworkTracker didn't already know that this instance is * online. */ public boolean instanceOnline(U advertisingUser, I instanceId, InstanceInfo<I, D> instanceInfo) { LOG.debug("instanceOnline: {}", instanceInfo); boolean instanceIsNew = false; synchronized (onlineInstancesByAdvertisingUser) { Map<I, InstanceInfo<I, D>> userInstances = onlineInstancesByAdvertisingUser .get(advertisingUser); if (userInstances == null) { userInstances = new ConcurrentHashMap<I, InstanceInfo<I, D>>(); instanceIsNew = onlineInstancesByAdvertisingUser.put( advertisingUser, userInstances) == null; } userInstances.put(instanceId, instanceInfo); } reevaluateTrustedOnlineInstances(); LOG.debug("New instance? {}", instanceIsNew); return instanceIsNew; } public void instanceOffline(U advertisingUser, I instanceId) { LOG.debug("instanceOffline: {}", instanceId); synchronized (onlineInstancesByAdvertisingUser) { Map<I, InstanceInfo<I, D>> userInstances = onlineInstancesByAdvertisingUser .get(advertisingUser); if (userInstances != null) { userInstances.remove(instanceId); } } reevaluateTrustedOnlineInstances(); } public void userTrusted(U userId) { LOG.debug("userTrusted: {}", userId); trustedUsers.add(userId); reevaluateTrustedOnlineInstances(); } public void userUntrusted(U userId) { LOG.debug("userUntrusted: {}", userId); trustedUsers.remove(userId); reevaluateTrustedOnlineInstances(); } public void certificateTrusted(I instanceId, Certificate certificate) { LOG.debug("certificateReceived: {} {}", instanceId, certificate); trustedCertificatesByInstance.put(instanceId, certificate); reevaluateTrustedOnlineInstances(); } /** * Returns a list of all instances that are currently trusted, including * their certificates. * * @return */ public Set<InstanceInfo<I, D>> getTrustedOnlineInstances() { return trustedOnlineInstances; } /** * Re-evalute which certificates and instances are trusted and notify * listeners. */ private void reevaluateTrustedOnlineInstances() { Set<InstanceInfo<I, D>> originalTrustedOnlineInstances = trustedOnlineInstances; identifyTrustedOnlineInstances(); notifyListenersAboutInstances(originalTrustedOnlineInstances); } private void notifyListenersAboutInstances( Set<InstanceInfo<I, D>> originalTrustedOnlineInstances) { Set<InstanceInfo<I, D>> addedOnlineInstances = new HashSet<InstanceInfo<I, D>>( trustedOnlineInstances); Set<InstanceInfo<I, D>> removedOnlineInstances = new HashSet<InstanceInfo<I, D>>( originalTrustedOnlineInstances); addedOnlineInstances.removeAll(originalTrustedOnlineInstances); removedOnlineInstances.removeAll(trustedOnlineInstances); for (InstanceInfo<I, D> instance : addedOnlineInstances) { LOG.debug("Online trusted instance added: {}", instance); for (NetworkTrackerListener<I, D> listener : listeners) { listener.instanceOnlineAndTrusted(instance); } } for (InstanceInfo<I, D> instance : removedOnlineInstances) { LOG.debug("Online trusted instance removed: {}", instance); for (NetworkTrackerListener<I, D> listener : listeners) { listener.instanceOfflineOrUntrusted(instance); } } } /** * <p> * Determines all trusted online instances. * </p> * * <p> * Note - yes this is expensive, but we don't expect it to be on any * performance critical paths so it's not worth worrying about right now. * </p> * * @return */ private void identifyTrustedOnlineInstances() { Set<InstanceInfo<I, D>> currentTrustedOnlineInstances = Collections .synchronizedSet(new HashSet<InstanceInfo<I, D>>()); for (Map.Entry<U, Map<I, InstanceInfo<I, D>>> userInstancesEntry : onlineInstancesByAdvertisingUser .entrySet()) { U userId = userInstancesEntry.getKey(); if (trustedUsers.contains(userId)) { Map<I, InstanceInfo<I, D>> instances = userInstancesEntry .getValue(); for (InstanceInfo<I, D> instance : instances.values()) { I instanceId = instance.getId(); if (trustedCertificatesByInstance.containsKey(instanceId)) { currentTrustedOnlineInstances.add(instance); } } } } this.trustedOnlineInstances = currentTrustedOnlineInstances; LOG.debug("Number of trusted online instances: {}", trustedOnlineInstances.size()); } @Subscribe public void onReset(final ResetEvent event) { this.onlineInstancesByAdvertisingUser.clear(); this.trustedCertificatesByInstance.clear(); this.trustedOnlineInstances.clear(); this.trustedUsers.clear(); } }
package org.lightmare.config; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.log4j.Logger; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.jpa.datasource.PoolConfig; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.IOUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; import org.yaml.snakeyaml.Yaml; /** * Easy way to retrieve configuration properties from configuration file * * @author levan * @since 0.0.21-SNAPSHOT */ public class Configuration implements Cloneable { // Cache for all configuration passed from API or read from file private final Map<Object, Object> config = new HashMap<Object, Object>(); // Instance of pool configuration private static final PoolConfig POOL_CONFIG = new PoolConfig(); // Runtime to get available processors private static final Runtime RUNTIME = Runtime.getRuntime(); // Resource path (META-INF) private static final String META_INF_PATH = "META-INF/"; // Error messages private static final String COULD_NOT_LOAD_CONFIG_ERROR = "Could not load configuration"; private static final String COULD_NOT_OPEN_FILE_ERROR = "Could not open config file"; private static final String RESOURCE_NOT_EXISTS_ERROR = "Configuration resource doesn't exist"; private static final Logger LOG = Logger.getLogger(Configuration.class); public Configuration() { } /** * Gets value on passed generic key K of passed {@link Map} as {@link Map} * of generic key values * * @param key * @param from * @return {@link Map}<code><K, V></code> */ private <K, V> Map<K, V> getAsMap(Object key, Map<Object, Object> from) { if (from == null) { from = config; } Map<K, V> value = ObjectUtils.cast(CollectionUtils.getAsMap(key, from)); return value; } /** * Gets value on passed generic key K of cached configuration as {@link Map} * of generic key values * * @param key * @return {@link Map}<code><K, V></code> */ private <K, V> Map<K, V> getAsMap(Object key) { return getAsMap(key, null); } private <K, V> void setSubConfigValue(Object key, K subKey, V value) { Map<K, V> subConfig = getAsMap(key); if (subConfig == null) { subConfig = new HashMap<K, V>(); config.put(key, subConfig); } subConfig.put(subKey, value); } private <K, V> V getSubConfigValue(Object key, K subKey, V defaultValue) { V def; Map<K, V> subConfig = getAsMap(key); if (CollectionUtils.valid(subConfig)) { def = subConfig.get(subKey); if (def == null) { def = defaultValue; } } else { def = defaultValue; } return def; } private <K> boolean containsSubConfigKey(Object key, K subKey) { Map<K, ?> subConfig = getAsMap(key); boolean valid = CollectionUtils.valid(subConfig); if (valid) { valid = subConfig.containsKey(subKey); } return valid; } private <K> boolean containsConfigKey(K key) { return containsSubConfigKey(ConfigKeys.DEPLOY_CONFIG.key, key); } private <K, V> V getSubConfigValue(Object key, K subKey) { return getSubConfigValue(key, subKey, null); } private <K, V> void setConfigValue(K subKey, V value) { setSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey, value); } private <K, V> V getConfigValue(K subKey, V defaultValue) { return getSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey, defaultValue); } private <K, V> V getConfigValue(K subKey) { return getSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey); } private <K, V> Map<K, V> getWithInitialization(Object key) { Map<K, V> result = getConfigValue(key); if (result == null) { result = new HashMap<K, V>(); setConfigValue(key, result); } return result; } private <K, V> void setWithInitialization(Object key, K subKey, V value) { Map<K, V> result = getWithInitialization(key); result.put(subKey, value); } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration if value is null then returns passed default value * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key, V defaultValue) { V value = CollectionUtils.getSubValue(config, ConfigKeys.DEPLOY_CONFIG.key, ConfigKeys.PERSISTENCE_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key) { return getPersistenceConfigValue(key, null); } /** * Sets specific value for appropriated key in persistence configuration sub * {@link Map} of configuration * * @param key * @param value */ public void setPersistenceConfigValue(Object key, Object value) { setWithInitialization(ConfigKeys.PERSISTENCE_CONFIG.key, key, value); } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration if value is null then returns passed default * value * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key, V defaultValue) { V value = CollectionUtils.getSubValue(config, ConfigKeys.DEPLOY_CONFIG.key, ConfigKeys.POOL_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key) { V value = getPoolConfigValue(key, null); return value; } /** * Sets specific value for appropriated key in connection pool configuration * sub {@link Map} of configuration * * @param key * @param value */ public void setPoolConfigValue(Object key, Object value) { setWithInitialization(ConfigKeys.POOL_CONFIG.key, key, value); } /** * Configuration for {@link PoolConfig} instance */ private void configurePool() { Map<Object, Object> poolProperties = getPoolConfigValue(ConfigKeys.POOL_PROPERTIES.key); if (CollectionUtils.valid(poolProperties)) { setPoolProperties(poolProperties); } String type = getPoolConfigValue(ConfigKeys.POOL_PROVIDER_TYPE.key); if (StringUtils.valid(type)) { getPoolConfig().setPoolProviderType(type); } String path = getPoolConfigValue(ConfigKeys.POOL_PROPERTIES_PATH.key); if (StringUtils.valid(path)) { setPoolPropertiesPath(path); } } private <K, V> void setIfContains(K key, V value) { boolean contains = containsConfigKey(key); if (ObjectUtils.notTrue(contains)) { setConfigValue(key, value); } } /** * Configures server from properties and default values */ private void configureServer() { // Sets default values to remote server configuration boolean contains; setIfContains(ConfigKeys.IP_ADDRESS.key, ConfigKeys.IP_ADDRESS.value); setIfContains(ConfigKeys.PORT.key, ConfigKeys.PORT.value); setIfContains(ConfigKeys.BOSS_POOL.key, ConfigKeys.BOSS_POOL.value); contains = containsConfigKey(ConfigKeys.WORKER_POOL.key); if (ObjectUtils.notTrue(contains)) { int defaultWorkers = ConfigKeys.WORKER_POOL.getValue(); int workers = RUNTIME.availableProcessors() * defaultWorkers; String workerProperty = String.valueOf(workers); setConfigValue(ConfigKeys.WORKER_POOL.key, workerProperty); } contains = containsConfigKey(ConfigKeys.CONNECTION_TIMEOUT.key); if (ObjectUtils.notTrue(contains)) { setIfContains(ConfigKeys.CONNECTION_TIMEOUT.key, ConfigKeys.CONNECTION_TIMEOUT.value); } } /** * Merges configuration with default properties */ public void configureDeployments() { // Checks if application run in hot deployment mode Boolean hotDeployment = getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key); if (hotDeployment == null) { setConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, Boolean.FALSE); hotDeployment = getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key); } // Check if application needs directory watch service boolean watchStatus; if (ObjectUtils.notTrue(hotDeployment)) { watchStatus = Boolean.TRUE; } else { watchStatus = Boolean.FALSE; } setConfigValue(ConfigKeys.WATCH_STATUS.key, watchStatus); // Sets deployments directories Set<DeploymentDirectory> deploymentPaths = getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = ConfigKeys.DEMPLOYMENT_PATH.getValue(); setConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key, deploymentPaths); } // Sets remote control check Boolean remoteControl = getConfigValue(ConfigKeys.REMOTE_CONTROL.key); if (ObjectUtils.notNull(remoteControl)) { setRemoteControl(remoteControl); } } /** * Configures server and connection pooling */ public void configure() { configureServer(); configureDeployments(); configurePool(); } /** * Merges two {@link Map}s and if second {@link Map}'s value is instance of * {@link Map} merges this value with first {@link Map}'s value recursively * * @param map1 * @param map2 * @return <code>{@link Map}<Object, Object></code> */ protected Map<Object, Object> deepMerge(Map<Object, Object> map1, Map<Object, Object> map2) { if (map1 == null) { map1 = map2; } else { Set<Map.Entry<Object, Object>> entries2 = map2.entrySet(); Object key; Map<Object, Object> value1; Object value2; Map<Object, Object> mapValue2; Object mergedValue; for (Map.Entry<Object, Object> entry2 : entries2) { key = entry2.getKey(); value2 = entry2.getValue(); if (value2 instanceof Map) { value1 = CollectionUtils.getAsMap(key, map1); mapValue2 = ObjectUtils.cast(value2); mergedValue = deepMerge(value1, mapValue2); } else { mergedValue = value2; } if (ObjectUtils.notNull(mergedValue)) { map1.put(key, mergedValue); } } } return map1; } /** * Reads configuration from passed properties * * @param configuration */ public void configure(Map<Object, Object> configuration) { deepMerge(config, configuration); } /** * Reads configuration from passed file path * * @param configuration */ public void configure(String path) throws IOException { File yamlFile = new File(path); if (yamlFile.exists()) { InputStream stream = new FileInputStream(yamlFile); try { Yaml yaml = new Yaml(); Object configuration = yaml.load(stream); if (configuration instanceof Map) { Map<Object, Object> innerConfig = ObjectUtils .cast(configuration); configure(innerConfig); } } finally { IOUtils.close(stream); } } } /** * Gets value associated with particular key as {@link String} instance * * @param key * @return {@link String} */ public String getStringValue(String key) { String textValue; Object value = config.get(key); if (value == null) { textValue = null; } else { textValue = value.toString(); } return textValue; } /** * Gets value associated with particular key as <code>int</code> instance * * @param key * @return {@link String} */ public int getIntValue(String key) { String value = getStringValue(key); return Integer.parseInt(value); } /** * Gets value associated with particular key as <code>long</code> instance * * @param key * @return {@link String} */ public long getLongValue(String key) { String value = getStringValue(key); return Long.parseLong(value); } /** * Gets value associated with particular key as <code>boolean</code> * instance * * @param key * @return {@link String} */ public boolean getBooleanValue(String key) { String value = getStringValue(key); return Boolean.parseBoolean(value); } public void putValue(String key, String value) { config.put(key, value); } /** * Load {@link Configuration} in memory as {@link Map} of parameters * * @throws IOException */ public void loadFromStream(InputStream propertiesStream) throws IOException { try { Properties props = new Properties(); props.load(propertiesStream); for (String propertyName : props.stringPropertyNames()) { config.put(propertyName, props.getProperty(propertyName)); } } catch (IOException ex) { LOG.error(COULD_NOT_LOAD_CONFIG_ERROR, ex); } finally { IOUtils.close(propertiesStream); } } /** * Loads configuration form file * * @throws IOException */ public void loadFromFile() throws IOException { String configFilePath = ConfigKeys.CONFIG_FILE.getValue(); try { File configFile = new File(configFilePath); if (configFile.exists()) { InputStream propertiesStream = new FileInputStream(configFile); loadFromStream(propertiesStream); } else { configFile.mkdirs(); } } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration form file by passed file path * * @param configFilename * @throws IOException */ public void loadFromFile(String configFilename) throws IOException { try { InputStream propertiesStream = new FileInputStream(new File( configFilename)); loadFromStream(propertiesStream); } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration from file contained in classpath * * @param resourceName * @param loader */ public void loadFromResource(String resourceName, ClassLoader loader) throws IOException { InputStream resourceStream = loader.getResourceAsStream(StringUtils .concat(META_INF_PATH, resourceName)); if (resourceStream == null) { LOG.error(RESOURCE_NOT_EXISTS_ERROR); } else { loadFromStream(resourceStream); } } public static String getAdminUsersPath() { return ConfigKeys.ADMIN_USERS_PATH.getValue(); } public static void setAdminUsersPath(String adminUsersPath) { ConfigKeys.ADMIN_USERS_PATH.value = adminUsersPath; } public static void setRemoteControl(boolean remoteControl) { ConfigKeys.REMOTE_CONTROL.value = remoteControl; } public static boolean getRemoteControl() { return ConfigKeys.REMOTE_CONTROL.getValue(); } public boolean isRemote() { return ConfigKeys.REMOTE.getValue(); } public void setRemote(boolean remote) { ConfigKeys.REMOTE.value = remote; } public static boolean isServer() { return ConfigKeys.SERVER.getValue(); } public static void setServer(boolean server) { ConfigKeys.SERVER.value = server; } public boolean isClient() { return getConfigValue(ConfigKeys.CLIENT.key, Boolean.FALSE); } public void setClient(boolean client) { setConfigValue(ConfigKeys.CLIENT.key, client); } /** * Adds path for deployments file or directory * * @param path * @param scan */ public void addDeploymentPath(String path, boolean scan) { Set<DeploymentDirectory> deploymentPaths = getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = new HashSet<DeploymentDirectory>(); setConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key, deploymentPaths); } deploymentPaths.add(new DeploymentDirectory(path, scan)); } /** * Adds path for data source file * * @param path */ public void addDataSourcePath(String path) { Set<String> dataSourcePaths = getConfigValue(ConfigKeys.DATA_SOURCE_PATH.key); if (dataSourcePaths == null) { dataSourcePaths = new HashSet<String>(); setConfigValue(ConfigKeys.DATA_SOURCE_PATH.key, dataSourcePaths); } dataSourcePaths.add(path); } public Set<DeploymentDirectory> getDeploymentPath() { return getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); } public Set<String> getDataSourcePath() { return getConfigValue(ConfigKeys.DATA_SOURCE_PATH.key); } public String[] getLibraryPaths() { return getConfigValue(ConfigKeys.LIBRARY_PATH.key); } public void setLibraryPaths(String[] libraryPaths) { setConfigValue(ConfigKeys.LIBRARY_PATH.key, libraryPaths); } public boolean isHotDeployment() { return getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, Boolean.FALSE); } public void setHotDeployment(boolean hotDeployment) { setConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, hotDeployment); } public boolean isWatchStatus() { return getConfigValue(ConfigKeys.WATCH_STATUS.key, Boolean.FALSE); } public void setWatchStatus(boolean watchStatus) { setConfigValue(ConfigKeys.WATCH_STATUS.key, watchStatus); } /** * Property for persistence configuration * * @return <code>boolean</code> */ public boolean isScanForEntities() { return getPersistenceConfigValue(ConfigKeys.SCAN_FOR_ENTITIES.key, Boolean.FALSE); } public void setScanForEntities(boolean scanForEntities) { setPersistenceConfigValue(ConfigKeys.SCAN_FOR_ENTITIES.key, scanForEntities); } public String getAnnotatedUnitName() { return getPersistenceConfigValue(ConfigKeys.ANNOTATED_UNIT_NAME.key); } public void setAnnotatedUnitName(String annotatedUnitName) { setPersistenceConfigValue(ConfigKeys.ANNOTATED_UNIT_NAME.key, annotatedUnitName); } public String getPersXmlPath() { return getPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_PATH.key); } public void setPersXmlPath(String persXmlPath) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_PATH.key, persXmlPath); } public boolean isPersXmlFromJar() { return getPersistenceConfigValue( ConfigKeys.PERSISTENCE_XML_FROM_JAR.key, Boolean.FALSE); } public void setPersXmlFromJar(boolean persXmlFromJar) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_FROM_JAR.key, persXmlFromJar); } public boolean isSwapDataSource() { return getPersistenceConfigValue(ConfigKeys.SWAP_DATASOURCE.key, Boolean.FALSE); } public void setSwapDataSource(boolean swapDataSource) { setPersistenceConfigValue(ConfigKeys.SWAP_DATASOURCE.key, swapDataSource); } public boolean isScanArchives() { return getPersistenceConfigValue(ConfigKeys.SCAN_ARCHIVES.key, Boolean.FALSE); } public void setScanArchives(boolean scanArchives) { setPersistenceConfigValue(ConfigKeys.SCAN_ARCHIVES.key, scanArchives); } public boolean isPooledDataSource() { return getPersistenceConfigValue(ConfigKeys.POOLED_DATA_SOURCE.key, Boolean.FALSE); } public void setPooledDataSource(boolean pooledDataSource) { setPersistenceConfigValue(ConfigKeys.POOLED_DATA_SOURCE.key, pooledDataSource); } public Map<Object, Object> getPersistenceProperties() { return getPersistenceConfigValue(ConfigKeys.PERSISTENCE_PROPERTIES.key); } public void setPersistenceProperties( Map<Object, Object> persistenceProperties) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_PROPERTIES.key, persistenceProperties); } /** * Gets cached {@link PoolConfig} instance a connection pool configuration * * @return {@link PoolConfig} */ public static PoolConfig getPoolConfig() { return POOL_CONFIG; } public void setDataSourcePooledType(boolean dsPooledType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPooledDataSource(dsPooledType); } public void setPoolPropertiesPath(String path) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolPath(path); } public void setPoolProperties( Map<? extends Object, ? extends Object> properties) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().putAll(properties); } public void addPoolProperty(Object key, Object value) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().put(key, value); } public void setPoolProviderType(PoolProviderType poolProviderType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolProviderType(poolProviderType); } @Override public Object clone() throws CloneNotSupportedException { // Deep clone for configuration Configuration cloneConfig = (Configuration) super.clone(); cloneConfig.config.clear(); cloneConfig.configure(this.config); return cloneConfig; } }
package org.lightmare.config; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.log4j.Logger; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.jpa.datasource.PoolConfig; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.IOUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; import org.yaml.snakeyaml.Yaml; /** * Easy way to retrieve configuration properties from configuration file * * @author levan * @since 0.0.21-SNAPSHOT */ public class Configuration implements Cloneable { // Cache for all configuration passed from API or read from file private final Map<Object, Object> config = new HashMap<Object, Object>(); // Instance of pool configuration private static final PoolConfig POOL_CONFIG = new PoolConfig(); // Runtime to get available processors private static final Runtime RUNTIME = Runtime.getRuntime(); // Resource path (META-INF) private static final String META_INF_PATH = "META-INF/"; // Error messages private static final String COULD_NOT_LOAD_CONFIG_ERROR = "Could not load configuration"; private static final String COULD_NOT_OPEN_FILE_ERROR = "Could not open config file"; private static final String RESOURCE_NOT_EXISTS_ERROR = "Configuration resource doesn't exist"; private static final Logger LOG = Logger.getLogger(Configuration.class); public Configuration() { } /** * Gets value on passed generic key K of passed {@link Map} as {@link Map} * of generic key values * * @param key * @param from * @return {@link Map}<code><K, V></code> */ private <K, V> Map<K, V> getAsMap(Object key, Map<Object, Object> from) { if (from == null) { from = config; } Map<K, V> value = ObjectUtils.cast(CollectionUtils.getAsMap(key, from)); return value; } /** * Gets value on passed generic key K of cached configuration as {@link Map} * of generic key values * * @param key * @return {@link Map}<code><K, V></code> */ private <K, V> Map<K, V> getAsMap(Object key) { return getAsMap(key, null); } private <K, V> void setSubConfigValue(Object key, K subKey, V value) { Map<K, V> subConfig = getAsMap(key); if (subConfig == null) { subConfig = new HashMap<K, V>(); config.put(key, subConfig); } subConfig.put(subKey, value); } private <K, V> V getSubConfigValue(Object key, K subKey, V defaultValue) { V def; Map<K, V> subConfig = getAsMap(key); if (CollectionUtils.valid(subConfig)) { def = subConfig.get(subKey); if (def == null) { def = defaultValue; } } else { def = defaultValue; } return def; } private <K> boolean containsSubConfigKey(Object key, K subKey) { Map<K, ?> subConfig = getAsMap(key); boolean valid = CollectionUtils.valid(subConfig); if (valid) { valid = subConfig.containsKey(subKey); } return valid; } private <K> boolean containsConfigKey(K key) { return containsSubConfigKey(ConfigKeys.DEPLOY_CONFIG.key, key); } private <K, V> V getSubConfigValue(Object key, K subKey) { return getSubConfigValue(key, subKey, null); } private <K, V> void setConfigValue(K subKey, V value) { setSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey, value); } private <K, V> V getConfigValue(K subKey, V defaultValue) { return getSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey, defaultValue); } private <K, V> V getConfigValue(K subKey) { return getSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey); } private <K, V> Map<K, V> getWithInitialization(Object key) { Map<K, V> result = getConfigValue(key); if (result == null) { result = new HashMap<K, V>(); setConfigValue(key, result); } return result; } private <K, V> void setWithInitialization(Object key, K subKey, V value) { Map<K, V> result = getWithInitialization(key); result.put(subKey, value); } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration if value is null then returns passed default value * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key, V defaultValue) { V value = CollectionUtils.getSubValue(config, ConfigKeys.DEPLOY_CONFIG.key, ConfigKeys.PERSISTENCE_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key) { return getPersistenceConfigValue(key, null); } /** * Sets specific value for appropriated key in persistence configuration sub * {@link Map} of configuration * * @param key * @param value */ public void setPersistenceConfigValue(Object key, Object value) { setWithInitialization(ConfigKeys.PERSISTENCE_CONFIG.key, key, value); } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration if value is null then returns passed default * value * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key, V defaultValue) { V value = CollectionUtils.getSubValue(config, ConfigKeys.DEPLOY_CONFIG.key, ConfigKeys.POOL_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key) { V value = getPoolConfigValue(key, null); return value; } /** * Sets specific value for appropriated key in connection pool configuration * sub {@link Map} of configuration * * @param key * @param value */ public void setPoolConfigValue(Object key, Object value) { setWithInitialization(ConfigKeys.POOL_CONFIG.key, key, value); } /** * Configuration for {@link PoolConfig} instance */ private void configurePool() { Map<Object, Object> poolProperties = getPoolConfigValue(ConfigKeys.POOL_PROPERTIES.key); if (CollectionUtils.valid(poolProperties)) { setPoolProperties(poolProperties); } String type = getPoolConfigValue(ConfigKeys.POOL_PROVIDER_TYPE.key); if (StringUtils.valid(type)) { getPoolConfig().setPoolProviderType(type); } String path = getPoolConfigValue(ConfigKeys.POOL_PROPERTIES_PATH.key); if (StringUtils.valid(path)) { setPoolPropertiesPath(path); } } private <K, V> void setIfContains(K key, V value) { boolean contains = containsConfigKey(key); if (ObjectUtils.notTrue(contains)) { setConfigValue(key, value); } } /** * Configures server from properties and default values */ private void configureServer() { // Sets default values to remote server configuration boolean contains = containsConfigKey(ConfigKeys.IP_ADDRESS.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.IP_ADDRESS.key, ConfigKeys.IP_ADDRESS.value); } contains = containsConfigKey(ConfigKeys.PORT.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.PORT.key, ConfigKeys.PORT.value); } contains = containsConfigKey(ConfigKeys.BOSS_POOL.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.BOSS_POOL.key, ConfigKeys.BOSS_POOL.value); } contains = containsConfigKey(ConfigKeys.WORKER_POOL.key); if (ObjectUtils.notTrue(contains)) { int defaultWorkers = ConfigKeys.WORKER_POOL.getValue(); int workers = RUNTIME.availableProcessors() * defaultWorkers; String workerProperty = String.valueOf(workers); setConfigValue(ConfigKeys.WORKER_POOL.key, workerProperty); } contains = containsConfigKey(ConfigKeys.CONNECTION_TIMEOUT.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.CONNECTION_TIMEOUT.key, ConfigKeys.CONNECTION_TIMEOUT.value); } } /** * Merges configuration with default properties */ public void configureDeployments() { // Checks if application run in hot deployment mode Boolean hotDeployment = getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key); if (hotDeployment == null) { setConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, Boolean.FALSE); hotDeployment = getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key); } // Check if application needs directory watch service boolean watchStatus; if (ObjectUtils.notTrue(hotDeployment)) { watchStatus = Boolean.TRUE; } else { watchStatus = Boolean.FALSE; } setConfigValue(ConfigKeys.WATCH_STATUS.key, watchStatus); // Sets deployments directories Set<DeploymentDirectory> deploymentPaths = getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = ConfigKeys.DEMPLOYMENT_PATH.getValue(); setConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key, deploymentPaths); } // Sets remote control check Boolean remoteControl = getConfigValue(ConfigKeys.REMOTE_CONTROL.key); if (ObjectUtils.notNull(remoteControl)) { setRemoteControl(remoteControl); } } /** * Configures server and connection pooling */ public void configure() { configureServer(); configureDeployments(); configurePool(); } /** * Merges two {@link Map}s and if second {@link Map}'s value is instance of * {@link Map} merges this value with first {@link Map}'s value recursively * * @param map1 * @param map2 * @return <code>{@link Map}<Object, Object></code> */ protected Map<Object, Object> deepMerge(Map<Object, Object> map1, Map<Object, Object> map2) { if (map1 == null) { map1 = map2; } else { Set<Map.Entry<Object, Object>> entries2 = map2.entrySet(); Object key; Map<Object, Object> value1; Object value2; Map<Object, Object> mapValue2; Object mergedValue; for (Map.Entry<Object, Object> entry2 : entries2) { key = entry2.getKey(); value2 = entry2.getValue(); if (value2 instanceof Map) { value1 = CollectionUtils.getAsMap(key, map1); mapValue2 = ObjectUtils.cast(value2); mergedValue = deepMerge(value1, mapValue2); } else { mergedValue = value2; } if (ObjectUtils.notNull(mergedValue)) { map1.put(key, mergedValue); } } } return map1; } /** * Reads configuration from passed properties * * @param configuration */ public void configure(Map<Object, Object> configuration) { deepMerge(config, configuration); } /** * Reads configuration from passed file path * * @param configuration */ public void configure(String path) throws IOException { File yamlFile = new File(path); if (yamlFile.exists()) { InputStream stream = new FileInputStream(yamlFile); try { Yaml yaml = new Yaml(); Object configuration = yaml.load(stream); if (configuration instanceof Map) { Map<Object, Object> innerConfig = ObjectUtils .cast(configuration); configure(innerConfig); } } finally { IOUtils.close(stream); } } } /** * Gets value associated with particular key as {@link String} instance * * @param key * @return {@link String} */ public String getStringValue(String key) { String textValue; Object value = config.get(key); if (value == null) { textValue = null; } else { textValue = value.toString(); } return textValue; } /** * Gets value associated with particular key as <code>int</code> instance * * @param key * @return {@link String} */ public int getIntValue(String key) { String value = getStringValue(key); return Integer.parseInt(value); } /** * Gets value associated with particular key as <code>long</code> instance * * @param key * @return {@link String} */ public long getLongValue(String key) { String value = getStringValue(key); return Long.parseLong(value); } /** * Gets value associated with particular key as <code>boolean</code> * instance * * @param key * @return {@link String} */ public boolean getBooleanValue(String key) { String value = getStringValue(key); return Boolean.parseBoolean(value); } public void putValue(String key, String value) { config.put(key, value); } /** * Load {@link Configuration} in memory as {@link Map} of parameters * * @throws IOException */ public void loadFromStream(InputStream propertiesStream) throws IOException { try { Properties props = new Properties(); props.load(propertiesStream); for (String propertyName : props.stringPropertyNames()) { config.put(propertyName, props.getProperty(propertyName)); } } catch (IOException ex) { LOG.error(COULD_NOT_LOAD_CONFIG_ERROR, ex); } finally { IOUtils.close(propertiesStream); } } /** * Loads configuration form file * * @throws IOException */ public void loadFromFile() throws IOException { String configFilePath = ConfigKeys.CONFIG_FILE.getValue(); try { File configFile = new File(configFilePath); if (configFile.exists()) { InputStream propertiesStream = new FileInputStream(configFile); loadFromStream(propertiesStream); } else { configFile.mkdirs(); } } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration form file by passed file path * * @param configFilename * @throws IOException */ public void loadFromFile(String configFilename) throws IOException { try { InputStream propertiesStream = new FileInputStream(new File( configFilename)); loadFromStream(propertiesStream); } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration from file contained in classpath * * @param resourceName * @param loader */ public void loadFromResource(String resourceName, ClassLoader loader) throws IOException { InputStream resourceStream = loader.getResourceAsStream(StringUtils .concat(META_INF_PATH, resourceName)); if (resourceStream == null) { LOG.error(RESOURCE_NOT_EXISTS_ERROR); } else { loadFromStream(resourceStream); } } public static String getAdminUsersPath() { return ConfigKeys.ADMIN_USERS_PATH.getValue(); } public static void setAdminUsersPath(String adminUsersPath) { ConfigKeys.ADMIN_USERS_PATH.value = adminUsersPath; } public static void setRemoteControl(boolean remoteControl) { ConfigKeys.REMOTE_CONTROL.value = remoteControl; } public static boolean getRemoteControl() { return ConfigKeys.REMOTE_CONTROL.getValue(); } public boolean isRemote() { return ConfigKeys.REMOTE.getValue(); } public void setRemote(boolean remote) { ConfigKeys.REMOTE.value = remote; } public static boolean isServer() { return ConfigKeys.SERVER.getValue(); } public static void setServer(boolean server) { ConfigKeys.SERVER.value = server; } public boolean isClient() { return getConfigValue(ConfigKeys.CLIENT.key, Boolean.FALSE); } public void setClient(boolean client) { setConfigValue(ConfigKeys.CLIENT.key, client); } /** * Adds path for deployments file or directory * * @param path * @param scan */ public void addDeploymentPath(String path, boolean scan) { Set<DeploymentDirectory> deploymentPaths = getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = new HashSet<DeploymentDirectory>(); setConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key, deploymentPaths); } deploymentPaths.add(new DeploymentDirectory(path, scan)); } /** * Adds path for data source file * * @param path */ public void addDataSourcePath(String path) { Set<String> dataSourcePaths = getConfigValue(ConfigKeys.DATA_SOURCE_PATH.key); if (dataSourcePaths == null) { dataSourcePaths = new HashSet<String>(); setConfigValue(ConfigKeys.DATA_SOURCE_PATH.key, dataSourcePaths); } dataSourcePaths.add(path); } public Set<DeploymentDirectory> getDeploymentPath() { return getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); } public Set<String> getDataSourcePath() { return getConfigValue(ConfigKeys.DATA_SOURCE_PATH.key); } public String[] getLibraryPaths() { return getConfigValue(ConfigKeys.LIBRARY_PATH.key); } public void setLibraryPaths(String[] libraryPaths) { setConfigValue(ConfigKeys.LIBRARY_PATH.key, libraryPaths); } public boolean isHotDeployment() { return getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, Boolean.FALSE); } public void setHotDeployment(boolean hotDeployment) { setConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, hotDeployment); } public boolean isWatchStatus() { return getConfigValue(ConfigKeys.WATCH_STATUS.key, Boolean.FALSE); } public void setWatchStatus(boolean watchStatus) { setConfigValue(ConfigKeys.WATCH_STATUS.key, watchStatus); } /** * Property for persistence configuration * * @return <code>boolean</code> */ public boolean isScanForEntities() { return getPersistenceConfigValue(ConfigKeys.SCAN_FOR_ENTITIES.key, Boolean.FALSE); } public void setScanForEntities(boolean scanForEntities) { setPersistenceConfigValue(ConfigKeys.SCAN_FOR_ENTITIES.key, scanForEntities); } public String getAnnotatedUnitName() { return getPersistenceConfigValue(ConfigKeys.ANNOTATED_UNIT_NAME.key); } public void setAnnotatedUnitName(String annotatedUnitName) { setPersistenceConfigValue(ConfigKeys.ANNOTATED_UNIT_NAME.key, annotatedUnitName); } public String getPersXmlPath() { return getPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_PATH.key); } public void setPersXmlPath(String persXmlPath) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_PATH.key, persXmlPath); } public boolean isPersXmlFromJar() { return getPersistenceConfigValue( ConfigKeys.PERSISTENCE_XML_FROM_JAR.key, Boolean.FALSE); } public void setPersXmlFromJar(boolean persXmlFromJar) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_FROM_JAR.key, persXmlFromJar); } public boolean isSwapDataSource() { return getPersistenceConfigValue(ConfigKeys.SWAP_DATASOURCE.key, Boolean.FALSE); } public void setSwapDataSource(boolean swapDataSource) { setPersistenceConfigValue(ConfigKeys.SWAP_DATASOURCE.key, swapDataSource); } public boolean isScanArchives() { return getPersistenceConfigValue(ConfigKeys.SCAN_ARCHIVES.key, Boolean.FALSE); } public void setScanArchives(boolean scanArchives) { setPersistenceConfigValue(ConfigKeys.SCAN_ARCHIVES.key, scanArchives); } public boolean isPooledDataSource() { return getPersistenceConfigValue(ConfigKeys.POOLED_DATA_SOURCE.key, Boolean.FALSE); } public void setPooledDataSource(boolean pooledDataSource) { setPersistenceConfigValue(ConfigKeys.POOLED_DATA_SOURCE.key, pooledDataSource); } public Map<Object, Object> getPersistenceProperties() { return getPersistenceConfigValue(ConfigKeys.PERSISTENCE_PROPERTIES.key); } public void setPersistenceProperties( Map<Object, Object> persistenceProperties) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_PROPERTIES.key, persistenceProperties); } /** * Gets cached {@link PoolConfig} instance a connection pool configuration * * @return {@link PoolConfig} */ public static PoolConfig getPoolConfig() { return POOL_CONFIG; } public void setDataSourcePooledType(boolean dsPooledType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPooledDataSource(dsPooledType); } public void setPoolPropertiesPath(String path) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolPath(path); } public void setPoolProperties( Map<? extends Object, ? extends Object> properties) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().putAll(properties); } public void addPoolProperty(Object key, Object value) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().put(key, value); } public void setPoolProviderType(PoolProviderType poolProviderType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolProviderType(poolProviderType); } @Override public Object clone() throws CloneNotSupportedException { // Deep clone for configuration Configuration cloneConfig = (Configuration) super.clone(); cloneConfig.config.clear(); cloneConfig.configure(this.config); return cloneConfig; } }
package org.lightmare.config; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.log4j.Logger; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.jpa.datasource.PoolConfig; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; import org.yaml.snakeyaml.Yaml; /** * Easy way to retrieve configuration properties from configuration file * * @author levan * */ public class Configuration implements Cloneable { // Cache for all configuration passed programmatically or read from file private final Map<Object, Object> config = new HashMap<Object, Object>(); // Runtime to get available processors private static final Runtime RUNTIME = Runtime.getRuntime(); public static final String DATA_SOURCE_PATH_DEF = "./ds"; // Properties which version of server is running remote it requires server // client RPC infrastructure or local (embedded mode) private static final String CONFIG_FILE = "./config/configuration.yaml"; // Persistence provider property keys private static final String ANNOTATED_UNIT_NAME_KEY = "annotatedUnitName"; private static final String PERSISTENCE_XML_PATH_KEY = "persistanceXmlPath"; private static final String PERSISTENCE_XML_FROM_JAR_KEY = "persistenceXmlFromJar"; private static final String SWAP_DATASOURCE_KEY = "swapDataSource"; private static final String SCAN_ARCHIVES_KEY = "scanArchives"; private static final String POOLED_DATA_SOURCE_KEY = "pooledDataSource"; private static final String PERSISTENCE_PROPERTIES_KEY = "persistenceProperties"; // Connection pool provider property keys private static final String POOL_CONFIG_KEY = "poolConfig"; private static final String POOL_PROPERTIES_PATH_KEY = "poolPropertiesPath"; private static final String POOL_PROVIDER_TYPE_KEY = "poolProviderType"; private static final String POOL_PROPERTIES_KEY = "poolProperties"; // Configuration properties for deployment private static String ADMIN_USERS_PATH; // Is configuration server or client (default is server) private static boolean server = (Boolean) Config.SERVER.value; private static boolean remote; // Instance of pool configuration private static final PoolConfig POOL_CONFIG = new PoolConfig(); private static final String META_INF_PATH = "META-INF/"; // Error messages private static final String COULD_NOT_LOAD_CONFIG_ERROR = "Could not load configuration"; private static final String COULD_NOT_OPEN_FILE_ERROR = "Could not open config file"; private static final String RESOURCE_NOT_EXISTS_ERROR = "Configuration resource doesn't exist"; private static final Logger LOG = Logger.getLogger(Configuration.class); public Configuration() { } private <K, V> Map<K, V> getAsMap(Object key, Map<Object, Object> from) { if (from == null) { from = config; } @SuppressWarnings("unchecked") Map<K, V> value = (Map<K, V>) ObjectUtils.getAsMap(key, from); return value; } private <K, V> Map<K, V> getAsMap(Object key) { return getAsMap(key, null); } private <K, V> void setSubConfigValue(Object key, K subKey, V value) { Map<K, V> subConfig = getAsMap(key); if (subConfig == null) { subConfig = new HashMap<K, V>(); config.put(key, subConfig); } subConfig.put(subKey, value); } private <K, V> V getSubConfigValue(Object key, K subKey, V defaultValue) { V def; Map<K, V> subConfig = getAsMap(key); if (ObjectUtils.available(subConfig)) { def = subConfig.get(subKey); if (def == null) { def = defaultValue; } } else { def = defaultValue; } return def; } private <K> boolean containsSubConfigKey(Object key, K subKey) { Map<K, ?> subConfig = getAsMap(key); boolean valid = ObjectUtils.available(subConfig); if (valid) { valid = subConfig.containsKey(subKey); } return valid; } private <K> boolean containsConfigKey(K key) { return containsSubConfigKey(Config.DEPLOY_CONFIG.key, key); } private <K, V> V getSubConfigValue(Object key, K subKey) { return getSubConfigValue(key, subKey, null); } private <K, V> void setConfigValue(K subKey, V value) { setSubConfigValue(Config.DEPLOY_CONFIG.key, subKey, value); } private <K, V> V getConfigValue(K subKey, V defaultValue) { return getSubConfigValue(Config.DEPLOY_CONFIG.key, subKey, defaultValue); } private <K, V> V getConfigValue(K subKey) { return getSubConfigValue(Config.DEPLOY_CONFIG.key, subKey); } private <K, V> Map<K, V> getWithInitialization(Object key) { Map<K, V> result = getConfigValue(key); if (result == null) { result = new HashMap<K, V>(); setConfigValue(key, result); } return result; } private <K, V> void setWithInitialization(Object key, K subKey, V value) { Map<K, V> result = getWithInitialization(key); result.put(subKey, value); } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration if value is null then returns passed default value * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key, V defaultValue) { V value = ObjectUtils.getSubValue(config, Config.DEPLOY_CONFIG.key, Config.PERSISTENCE_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key) { return getPersistenceConfigValue(key, null); } /** * Sets specific value for appropriated key in persistence configuration sub * {@link Map} of configuration * * @param key * @param value */ public void setPersistenceConfigValue(Object key, Object value) { setWithInitialization(Config.PERSISTENCE_CONFIG.key, key, value); } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration if value is null then returns passed default * value * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key, V defaultValue) { V value = ObjectUtils.getSubValue(config, Config.DEPLOY_CONFIG.key, Config.POOL_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key) { V value = getPoolConfigValue(key, null); return value; } /** * Sets specific value for appropriated key in connection pool configuration * sub {@link Map} of configuraion * * @param key * @param value */ public void setPoolConfigValue(Object key, Object value) { setWithInitialization(Config.POOL_CONFIG.key, key, value); } /** * Configuration for {@link PoolConfig} instance */ private void configurePool() { Map<Object, Object> poolProperties = getPoolConfigValue(Config.POOL_PROPERTIES.key); if (ObjectUtils.available(poolProperties)) { setPoolProperties(poolProperties); } String type = getPoolConfigValue(Config.POOL_PROVIDER_TYPE.key); if (ObjectUtils.available(type)) { getPoolConfig().setPoolProviderType(type); } String path = getPoolConfigValue(Config.POOL_PROPERTIES_PATH.key); if (ObjectUtils.available(path)) { setPoolPropertiesPath(path); } } /** * Configures server from properties */ private void configureServer() { // Sets default values to remote server configuration boolean contains = containsConfigKey(Config.IP_ADDRESS.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(Config.IP_ADDRESS.key, Config.IP_ADDRESS.value); } contains = containsConfigKey(Config.PORT.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(Config.PORT.key, Config.PORT.value); } contains = containsConfigKey(Config.BOSS_POOL.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(Config.BOSS_POOL.key, Config.BOSS_POOL.value); } contains = containsConfigKey(Config.WORKER_POOL.key); if (ObjectUtils.notTrue(contains)) { int workers = RUNTIME.availableProcessors() * (Integer) Config.WORKER_POOL.value; String workerProperty = String.valueOf(workers); setConfigValue(Config.WORKER_POOL.key, workerProperty); } contains = containsConfigKey(Config.CONNECTION_TIMEOUT.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(Config.CONNECTION_TIMEOUT.key, Config.CONNECTION_TIMEOUT.value); } // Sets default values is application on server or client mode Object serverValue = getConfigValue(Config.SERVER.key); if (ObjectUtils.notNull(serverValue)) { if (serverValue instanceof Boolean) { server = (Boolean) serverValue; } else { server = Boolean.valueOf(serverValue.toString()); } } Object remoteValue = getConfigValue(Config.REMOTE.key); if (ObjectUtils.notNull(remoteValue)) { if (remoteValue instanceof Boolean) { remote = (Boolean) remoteValue; } else { remote = Boolean.valueOf(remoteValue.toString()); } } } /** * Merges configuration with default properties */ @SuppressWarnings("unchecked") public void configureDeployments() { // Checks if application run in hot deployment mode Boolean hotDeployment = getConfigValue(Config.HOT_DEPLOYMENT.key); if (hotDeployment == null) { setConfigValue(Config.HOT_DEPLOYMENT.key, Boolean.FALSE); hotDeployment = getConfigValue(Config.HOT_DEPLOYMENT.key); } // Check if application needs directory watch service boolean watchStatus; if (ObjectUtils.notTrue(hotDeployment)) { watchStatus = Boolean.TRUE; } else { watchStatus = Boolean.FALSE; } setConfigValue(Config.WATCH_STATUS.key, watchStatus); // Sets deployments directories Set<DeploymentDirectory> deploymentPaths = getConfigValue(Config.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = (Set<DeploymentDirectory>) Config.DEMPLOYMENT_PATH.value; setConfigValue(Config.DEMPLOYMENT_PATH.key, deploymentPaths); } } /** * Configures server and connection pooling */ public void configure() { configureServer(); configureDeployments(); configurePool(); } /** * Merges two {@link Map}s and if second {@link Map}'s value is instance of * {@link Map} merges this value with first {@link Map}'s value recursively * * @param map1 * @param map2 * @return <code>{@link Map}<Object, Object></code> */ @SuppressWarnings("unchecked") protected Map<Object, Object> deepMerge(Map<Object, Object> map1, Map<Object, Object> map2) { if (map1 == null) { map1 = map2; } else { Set<Map.Entry<Object, Object>> entries2 = map2.entrySet(); Object key; Map<Object, Object> value1; Object value2; Object mergedValue; for (Map.Entry<Object, Object> entry2 : entries2) { key = entry2.getKey(); value2 = entry2.getValue(); if (value2 instanceof Map) { value1 = ObjectUtils.getAsMap(key, map1); mergedValue = deepMerge(value1, (Map<Object, Object>) value2); } else { mergedValue = value2; } if (ObjectUtils.notNull(mergedValue)) { map1.put(key, mergedValue); } } } return map1; } /** * Reads configuration from passed properties * * @param configuration */ public void configure(Map<Object, Object> configuration) { deepMerge(config, configuration); } /** * Reads configuration from passed file path * * @param configuration */ public void configure(String path) throws IOException { File yamlFile = new File(path); if (yamlFile.exists()) { InputStream stream = new FileInputStream(yamlFile); try { Yaml yaml = new Yaml(); Object configuration = yaml.load(stream); if (configuration instanceof Map) { @SuppressWarnings("unchecked") Map<Object, Object> innerConfig = (Map<Object, Object>) configuration; configure(innerConfig); } } finally { ObjectUtils.close(stream); } } } /** * Gets value associated with particular key as {@link String} instance * * @param key * @return {@link String} */ public String getStringValue(String key) { Object value = config.get(key); String textValue; if (value == null) { textValue = null; } else { textValue = value.toString(); } return textValue; } /** * Gets value associated with particular key as <code>int</code> instance * * @param key * @return {@link String} */ public int getIntValue(String key) { String value = getStringValue(key); return Integer.parseInt(value); } /** * Gets value associated with particular key as <code>long</code> instance * * @param key * @return {@link String} */ public long getLongValue(String key) { String value = getStringValue(key); return Long.parseLong(value); } /** * Gets value associated with particular key as <code>boolean</code> * instance * * @param key * @return {@link String} */ public boolean getBooleanValue(String key) { String value = getStringValue(key); return Boolean.parseBoolean(value); } public void putValue(String key, String value) { config.put(key, value); } /** * Load {@link Configuration} in memory as {@link Map} of parameters * * @throws IOException */ public void loadFromStream(InputStream propertiesStream) throws IOException { try { Properties props = new Properties(); props.load(propertiesStream); for (String propertyName : props.stringPropertyNames()) { config.put(propertyName, props.getProperty(propertyName)); } } catch (IOException ex) { LOG.error(COULD_NOT_LOAD_CONFIG_ERROR, ex); } finally { ObjectUtils.close(propertiesStream); } } /** * Loads configuration form file * * @throws IOException */ public void loadFromFile() throws IOException { InputStream propertiesStream = null; try { File configFile = new File(CONFIG_FILE); if (configFile.exists()) { propertiesStream = new FileInputStream(configFile); loadFromStream(propertiesStream); } else { configFile.mkdirs(); } } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration form file by passed file path * * @param configFilename * @throws IOException */ public void loadFromFile(String configFilename) throws IOException { InputStream propertiesStream = null; try { propertiesStream = new FileInputStream(new File(configFilename)); loadFromStream(propertiesStream); } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration from file contained in classpath * * @param resourceName * @param loader */ public void loadFromResource(String resourceName, ClassLoader loader) throws IOException { InputStream resourceStream = loader.getResourceAsStream(StringUtils .concat(META_INF_PATH, resourceName)); if (resourceStream == null) { LOG.error(RESOURCE_NOT_EXISTS_ERROR); } else { loadFromStream(resourceStream); } } public static String getAdminUsersPath() { return ADMIN_USERS_PATH; } public static void setAdminUsersPath(String aDMIN_USERS_PATH) { ADMIN_USERS_PATH = aDMIN_USERS_PATH; } public boolean isRemote() { return remote; } public void setRemote(boolean remoteValue) { remote = remoteValue; } public static boolean isServer() { return server; } public static void setServer(boolean serverValue) { server = serverValue; } public boolean isClient() { return getConfigValue(Config.CLIENT.key, Boolean.FALSE); } public void setClient(boolean client) { setConfigValue(Config.CLIENT.key, client); } /** * Adds path for deployments file or directory * * @param path * @param scan */ public void addDeploymentPath(String path, boolean scan) { Set<DeploymentDirectory> deploymentPaths = getConfigValue(Config.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = new HashSet<DeploymentDirectory>(); setConfigValue(Config.DEMPLOYMENT_PATH.key, deploymentPaths); } deploymentPaths.add(new DeploymentDirectory(path, scan)); } /** * Adds path for data source file * * @param path */ public void addDataSourcePath(String path) { Set<String> dataSourcePaths = getConfigValue(Config.DATA_SOURCE_PATH.key); if (dataSourcePaths == null) { dataSourcePaths = new HashSet<String>(); setConfigValue(Config.DATA_SOURCE_PATH.key, dataSourcePaths); } dataSourcePaths.add(path); } public Set<DeploymentDirectory> getDeploymentPath() { return getConfigValue(Config.DEMPLOYMENT_PATH.key); } public Set<String> getDataSourcePath() { return getConfigValue(Config.DATA_SOURCE_PATH.key); } public String[] getLibraryPaths() { return getConfigValue(Config.LIBRARY_PATH.key); } public void setLibraryPaths(String[] libraryPaths) { setConfigValue(Config.LIBRARY_PATH.key, libraryPaths); } public boolean isHotDeployment() { return getConfigValue(Config.HOT_DEPLOYMENT.key, Boolean.FALSE); } public void setHotDeployment(boolean hotDeployment) { setConfigValue(Config.HOT_DEPLOYMENT.key, hotDeployment); } public boolean isWatchStatus() { return getConfigValue(Config.WATCH_STATUS.key, Boolean.FALSE); } public void setWatchStatus(boolean watchStatus) { setConfigValue(Config.WATCH_STATUS.key, watchStatus); } /** * Property for persistence configuration * * @return <code>boolean</code> */ public boolean isScanForEntities() { return getPersistenceConfigValue(Config.SCAN_FOR_ENTITIES.key, Boolean.FALSE); } public void setScanForEntities(boolean scanForEntities) { setPersistenceConfigValue(Config.SCAN_FOR_ENTITIES.key, scanForEntities); } public String getAnnotatedUnitName() { return getPersistenceConfigValue(Config.ANNOTATED_UNIT_NAME.key); } public void setAnnotatedUnitName(String annotatedUnitName) { setPersistenceConfigValue(Config.ANNOTATED_UNIT_NAME.key, annotatedUnitName); } public String getPersXmlPath() { return getPersistenceConfigValue(Config.PERSISTENCE_XML_PATH.key); } public void setPersXmlPath(String persXmlPath) { setPersistenceConfigValue(Config.PERSISTENCE_XML_PATH.key, persXmlPath); } public boolean isPersXmlFromJar() { return getPersistenceConfigValue(Config.PERSISTENCE_XML_FROM_JAR.key, Boolean.FALSE); } public void setPersXmlFromJar(boolean persXmlFromJar) { setPersistenceConfigValue(Config.PERSISTENCE_XML_FROM_JAR.key, persXmlFromJar); } public boolean isSwapDataSource() { return getPersistenceConfigValue(Config.SWAP_DATASOURCE.key, Boolean.FALSE); } public void setSwapDataSource(boolean swapDataSource) { setPersistenceConfigValue(Config.SWAP_DATASOURCE.key, swapDataSource); } public boolean isScanArchives() { return getPersistenceConfigValue(Config.SCAN_ARCHIVES.key, Boolean.FALSE); } public void setScanArchives(boolean scanArchives) { setPersistenceConfigValue(Config.SCAN_ARCHIVES.key, scanArchives); } public boolean isPooledDataSource() { return getPersistenceConfigValue(Config.POOLED_DATA_SOURCE.key, Boolean.FALSE); } public void setPooledDataSource(boolean pooledDataSource) { setPersistenceConfigValue(Config.POOLED_DATA_SOURCE.key, pooledDataSource); } public Map<Object, Object> getPersistenceProperties() { return getPersistenceConfigValue(Config.PERSISTENCE_PROPERTIES.key); } public void setPersistenceProperties( Map<Object, Object> persistenceProperties) { setPersistenceConfigValue(Config.PERSISTENCE_PROPERTIES.key, persistenceProperties); } /** * Property for connection pool configuration * * @return {@link PoolConfig} */ public static PoolConfig getPoolConfig() { return POOL_CONFIG; } public void setDataSourcePooledType(boolean dsPooledType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPooledDataSource(dsPooledType); } public void setPoolPropertiesPath(String path) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolPath(path); } public void setPoolProperties( Map<? extends Object, ? extends Object> properties) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().putAll(properties); } public void addPoolProperty(Object key, Object value) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().put(key, value); } public void setPoolProviderType(PoolProviderType poolProviderType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolProviderType(poolProviderType); } @Override public Object clone() throws CloneNotSupportedException { Configuration cloneConfig = (Configuration) super.clone(); cloneConfig.config.clear(); cloneConfig.configure(this.config); return cloneConfig; } }
package org.lightmare.config; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.log4j.Logger; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.jpa.datasource.PoolConfig; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.IOUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; import org.yaml.snakeyaml.Yaml; /** * Easy way to retrieve configuration properties from configuration file * * @author levan * */ public class Configuration implements Cloneable { // Cache for all configuration passed from API or read from file private final Map<Object, Object> config = new HashMap<Object, Object>(); // Instance of pool configuration private static final PoolConfig POOL_CONFIG = new PoolConfig(); // Runtime to get available processors private static final Runtime RUNTIME = Runtime.getRuntime(); // Resource path (META-INF) private static final String META_INF_PATH = "META-INF/"; // Error messages private static final String COULD_NOT_LOAD_CONFIG_ERROR = "Could not load configuration"; private static final String COULD_NOT_OPEN_FILE_ERROR = "Could not open config file"; private static final String RESOURCE_NOT_EXISTS_ERROR = "Configuration resource doesn't exist"; private static final Logger LOG = Logger.getLogger(Configuration.class); public Configuration() { } private <K, V> Map<K, V> getAsMap(Object key, Map<Object, Object> from) { if (from == null) { from = config; } Map<K, V> value = ObjectUtils.cast(CollectionUtils.getAsMap(key, from)); return value; } private <K, V> Map<K, V> getAsMap(Object key) { return getAsMap(key, null); } private <K, V> void setSubConfigValue(Object key, K subKey, V value) { Map<K, V> subConfig = getAsMap(key); if (subConfig == null) { subConfig = new HashMap<K, V>(); config.put(key, subConfig); } subConfig.put(subKey, value); } private <K, V> V getSubConfigValue(Object key, K subKey, V defaultValue) { V def; Map<K, V> subConfig = getAsMap(key); if (CollectionUtils.valid(subConfig)) { def = subConfig.get(subKey); if (def == null) { def = defaultValue; } } else { def = defaultValue; } return def; } private <K> boolean containsSubConfigKey(Object key, K subKey) { Map<K, ?> subConfig = getAsMap(key); boolean valid = CollectionUtils.valid(subConfig); if (valid) { valid = subConfig.containsKey(subKey); } return valid; } private <K> boolean containsConfigKey(K key) { return containsSubConfigKey(ConfigKeys.DEPLOY_CONFIG.key, key); } private <K, V> V getSubConfigValue(Object key, K subKey) { return getSubConfigValue(key, subKey, null); } private <K, V> void setConfigValue(K subKey, V value) { setSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey, value); } private <K, V> V getConfigValue(K subKey, V defaultValue) { return getSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey, defaultValue); } private <K, V> V getConfigValue(K subKey) { return getSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey); } private <K, V> Map<K, V> getWithInitialization(Object key) { Map<K, V> result = getConfigValue(key); if (result == null) { result = new HashMap<K, V>(); setConfigValue(key, result); } return result; } private <K, V> void setWithInitialization(Object key, K subKey, V value) { Map<K, V> result = getWithInitialization(key); result.put(subKey, value); } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration if value is null then returns passed default value * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key, V defaultValue) { V value = CollectionUtils.getSubValue(config, ConfigKeys.DEPLOY_CONFIG.key, ConfigKeys.PERSISTENCE_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection persistence sub {@link Map} * of configuration * * @param key * @return <code>V</code> */ public <V> V getPersistenceConfigValue(Object key) { return getPersistenceConfigValue(key, null); } /** * Sets specific value for appropriated key in persistence configuration sub * {@link Map} of configuration * * @param key * @param value */ public void setPersistenceConfigValue(Object key, Object value) { setWithInitialization(ConfigKeys.PERSISTENCE_CONFIG.key, key, value); } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration if value is null then returns passed default * value * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key, V defaultValue) { V value = CollectionUtils.getSubValue(config, ConfigKeys.DEPLOY_CONFIG.key, ConfigKeys.POOL_CONFIG.key, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key) { V value = getPoolConfigValue(key, null); return value; } /** * Sets specific value for appropriated key in connection pool configuration * sub {@link Map} of configuration * * @param key * @param value */ public void setPoolConfigValue(Object key, Object value) { setWithInitialization(ConfigKeys.POOL_CONFIG.key, key, value); } /** * Configuration for {@link PoolConfig} instance */ private void configurePool() { Map<Object, Object> poolProperties = getPoolConfigValue(ConfigKeys.POOL_PROPERTIES.key); if (CollectionUtils.valid(poolProperties)) { setPoolProperties(poolProperties); } String type = getPoolConfigValue(ConfigKeys.POOL_PROVIDER_TYPE.key); if (StringUtils.valid(type)) { getPoolConfig().setPoolProviderType(type); } String path = getPoolConfigValue(ConfigKeys.POOL_PROPERTIES_PATH.key); if (StringUtils.valid(path)) { setPoolPropertiesPath(path); } } /** * Configures server from properties and default values */ private void configureServer() { // Sets default values to remote server configuration boolean contains = containsConfigKey(ConfigKeys.IP_ADDRESS.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.IP_ADDRESS.key, ConfigKeys.IP_ADDRESS.value); } contains = containsConfigKey(ConfigKeys.PORT.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.PORT.key, ConfigKeys.PORT.value); } contains = containsConfigKey(ConfigKeys.BOSS_POOL.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.BOSS_POOL.key, ConfigKeys.BOSS_POOL.value); } contains = containsConfigKey(ConfigKeys.WORKER_POOL.key); if (ObjectUtils.notTrue(contains)) { int defaultWorkers = ConfigKeys.WORKER_POOL.getValue(); int workers = RUNTIME.availableProcessors() * defaultWorkers; String workerProperty = String.valueOf(workers); setConfigValue(ConfigKeys.WORKER_POOL.key, workerProperty); } contains = containsConfigKey(ConfigKeys.CONNECTION_TIMEOUT.key); if (ObjectUtils.notTrue(contains)) { setConfigValue(ConfigKeys.CONNECTION_TIMEOUT.key, ConfigKeys.CONNECTION_TIMEOUT.value); } } /** * Merges configuration with default properties */ public void configureDeployments() { // Checks if application run in hot deployment mode Boolean hotDeployment = getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key); if (hotDeployment == null) { setConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, Boolean.FALSE); hotDeployment = getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key); } // Check if application needs directory watch service boolean watchStatus; if (ObjectUtils.notTrue(hotDeployment)) { watchStatus = Boolean.TRUE; } else { watchStatus = Boolean.FALSE; } setConfigValue(ConfigKeys.WATCH_STATUS.key, watchStatus); // Sets deployments directories Set<DeploymentDirectory> deploymentPaths = getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = ConfigKeys.DEMPLOYMENT_PATH.getValue(); setConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key, deploymentPaths); } } /** * Configures server and connection pooling */ public void configure() { configureServer(); configureDeployments(); configurePool(); } /** * Merges two {@link Map}s and if second {@link Map}'s value is instance of * {@link Map} merges this value with first {@link Map}'s value recursively * * @param map1 * @param map2 * @return <code>{@link Map}<Object, Object></code> */ protected Map<Object, Object> deepMerge(Map<Object, Object> map1, Map<Object, Object> map2) { if (map1 == null) { map1 = map2; } else { Set<Map.Entry<Object, Object>> entries2 = map2.entrySet(); Object key; Map<Object, Object> value1; Object value2; Map<Object, Object> mapValue2; Object mergedValue; for (Map.Entry<Object, Object> entry2 : entries2) { key = entry2.getKey(); value2 = entry2.getValue(); if (value2 instanceof Map) { value1 = CollectionUtils.getAsMap(key, map1); mapValue2 = ObjectUtils.cast(value2); mergedValue = deepMerge(value1, mapValue2); } else { mergedValue = value2; } if (ObjectUtils.notNull(mergedValue)) { map1.put(key, mergedValue); } } } return map1; } /** * Reads configuration from passed properties * * @param configuration */ public void configure(Map<Object, Object> configuration) { deepMerge(config, configuration); } /** * Reads configuration from passed file path * * @param configuration */ public void configure(String path) throws IOException { File yamlFile = new File(path); if (yamlFile.exists()) { InputStream stream = new FileInputStream(yamlFile); try { Yaml yaml = new Yaml(); Object configuration = yaml.load(stream); if (configuration instanceof Map) { Map<Object, Object> innerConfig = ObjectUtils .cast(configuration); configure(innerConfig); } } finally { IOUtils.close(stream); } } } /** * Gets value associated with particular key as {@link String} instance * * @param key * @return {@link String} */ public String getStringValue(String key) { String textValue; Object value = config.get(key); if (value == null) { textValue = null; } else { textValue = value.toString(); } return textValue; } /** * Gets value associated with particular key as <code>int</code> instance * * @param key * @return {@link String} */ public int getIntValue(String key) { String value = getStringValue(key); return Integer.parseInt(value); } /** * Gets value associated with particular key as <code>long</code> instance * * @param key * @return {@link String} */ public long getLongValue(String key) { String value = getStringValue(key); return Long.parseLong(value); } /** * Gets value associated with particular key as <code>boolean</code> * instance * * @param key * @return {@link String} */ public boolean getBooleanValue(String key) { String value = getStringValue(key); return Boolean.parseBoolean(value); } public void putValue(String key, String value) { config.put(key, value); } /** * Load {@link Configuration} in memory as {@link Map} of parameters * * @throws IOException */ public void loadFromStream(InputStream propertiesStream) throws IOException { try { Properties props = new Properties(); props.load(propertiesStream); for (String propertyName : props.stringPropertyNames()) { config.put(propertyName, props.getProperty(propertyName)); } } catch (IOException ex) { LOG.error(COULD_NOT_LOAD_CONFIG_ERROR, ex); } finally { IOUtils.close(propertiesStream); } } /** * Loads configuration form file * * @throws IOException */ public void loadFromFile() throws IOException { String configFilePath = ConfigKeys.CONFIG_FILE.getValue(); try { File configFile = new File(configFilePath); if (configFile.exists()) { InputStream propertiesStream = new FileInputStream(configFile); loadFromStream(propertiesStream); } else { configFile.mkdirs(); } } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration form file by passed file path * * @param configFilename * @throws IOException */ public void loadFromFile(String configFilename) throws IOException { try { InputStream propertiesStream = new FileInputStream(new File( configFilename)); loadFromStream(propertiesStream); } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration from file contained in classpath * * @param resourceName * @param loader */ public void loadFromResource(String resourceName, ClassLoader loader) throws IOException { InputStream resourceStream = loader.getResourceAsStream(StringUtils .concat(META_INF_PATH, resourceName)); if (resourceStream == null) { LOG.error(RESOURCE_NOT_EXISTS_ERROR); } else { loadFromStream(resourceStream); } } public static String getAdminUsersPath() { return ConfigKeys.ADMIN_USERS_PATH.getValue(); } public static void setAdminUsersPath(String adminUsersPath) { ConfigKeys.ADMIN_USERS_PATH.value = adminUsersPath; } public boolean isRemote() { return ConfigKeys.REMOTE.getValue(); } public void setRemote(boolean remote) { ConfigKeys.REMOTE.value = remote; } public static boolean isServer() { return ConfigKeys.SERVER.getValue(); } public static void setServer(boolean server) { ConfigKeys.SERVER.value = server; } public boolean isClient() { return getConfigValue(ConfigKeys.CLIENT.key, Boolean.FALSE); } public void setClient(boolean client) { setConfigValue(ConfigKeys.CLIENT.key, client); } /** * Adds path for deployments file or directory * * @param path * @param scan */ public void addDeploymentPath(String path, boolean scan) { Set<DeploymentDirectory> deploymentPaths = getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); if (deploymentPaths == null) { deploymentPaths = new HashSet<DeploymentDirectory>(); setConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key, deploymentPaths); } deploymentPaths.add(new DeploymentDirectory(path, scan)); } /** * Adds path for data source file * * @param path */ public void addDataSourcePath(String path) { Set<String> dataSourcePaths = getConfigValue(ConfigKeys.DATA_SOURCE_PATH.key); if (dataSourcePaths == null) { dataSourcePaths = new HashSet<String>(); setConfigValue(ConfigKeys.DATA_SOURCE_PATH.key, dataSourcePaths); } dataSourcePaths.add(path); } public Set<DeploymentDirectory> getDeploymentPath() { return getConfigValue(ConfigKeys.DEMPLOYMENT_PATH.key); } public Set<String> getDataSourcePath() { return getConfigValue(ConfigKeys.DATA_SOURCE_PATH.key); } public String[] getLibraryPaths() { return getConfigValue(ConfigKeys.LIBRARY_PATH.key); } public void setLibraryPaths(String[] libraryPaths) { setConfigValue(ConfigKeys.LIBRARY_PATH.key, libraryPaths); } public boolean isHotDeployment() { return getConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, Boolean.FALSE); } public void setHotDeployment(boolean hotDeployment) { setConfigValue(ConfigKeys.HOT_DEPLOYMENT.key, hotDeployment); } public boolean isWatchStatus() { return getConfigValue(ConfigKeys.WATCH_STATUS.key, Boolean.FALSE); } public void setWatchStatus(boolean watchStatus) { setConfigValue(ConfigKeys.WATCH_STATUS.key, watchStatus); } /** * Property for persistence configuration * * @return <code>boolean</code> */ public boolean isScanForEntities() { return getPersistenceConfigValue(ConfigKeys.SCAN_FOR_ENTITIES.key, Boolean.FALSE); } public void setScanForEntities(boolean scanForEntities) { setPersistenceConfigValue(ConfigKeys.SCAN_FOR_ENTITIES.key, scanForEntities); } public String getAnnotatedUnitName() { return getPersistenceConfigValue(ConfigKeys.ANNOTATED_UNIT_NAME.key); } public void setAnnotatedUnitName(String annotatedUnitName) { setPersistenceConfigValue(ConfigKeys.ANNOTATED_UNIT_NAME.key, annotatedUnitName); } public String getPersXmlPath() { return getPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_PATH.key); } public void setPersXmlPath(String persXmlPath) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_PATH.key, persXmlPath); } public boolean isPersXmlFromJar() { return getPersistenceConfigValue( ConfigKeys.PERSISTENCE_XML_FROM_JAR.key, Boolean.FALSE); } public void setPersXmlFromJar(boolean persXmlFromJar) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_XML_FROM_JAR.key, persXmlFromJar); } public boolean isSwapDataSource() { return getPersistenceConfigValue(ConfigKeys.SWAP_DATASOURCE.key, Boolean.FALSE); } public void setSwapDataSource(boolean swapDataSource) { setPersistenceConfigValue(ConfigKeys.SWAP_DATASOURCE.key, swapDataSource); } public boolean isScanArchives() { return getPersistenceConfigValue(ConfigKeys.SCAN_ARCHIVES.key, Boolean.FALSE); } public void setScanArchives(boolean scanArchives) { setPersistenceConfigValue(ConfigKeys.SCAN_ARCHIVES.key, scanArchives); } public boolean isPooledDataSource() { return getPersistenceConfigValue(ConfigKeys.POOLED_DATA_SOURCE.key, Boolean.FALSE); } public void setPooledDataSource(boolean pooledDataSource) { setPersistenceConfigValue(ConfigKeys.POOLED_DATA_SOURCE.key, pooledDataSource); } public Map<Object, Object> getPersistenceProperties() { return getPersistenceConfigValue(ConfigKeys.PERSISTENCE_PROPERTIES.key); } public void setPersistenceProperties( Map<Object, Object> persistenceProperties) { setPersistenceConfigValue(ConfigKeys.PERSISTENCE_PROPERTIES.key, persistenceProperties); } /** * Gets cached {@link PoolConfig} instance a connection pool configuration * * @return {@link PoolConfig} */ public static PoolConfig getPoolConfig() { return POOL_CONFIG; } public void setDataSourcePooledType(boolean dsPooledType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPooledDataSource(dsPooledType); } public void setPoolPropertiesPath(String path) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolPath(path); } public void setPoolProperties( Map<? extends Object, ? extends Object> properties) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().putAll(properties); } public void addPoolProperty(Object key, Object value) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().put(key, value); } public void setPoolProviderType(PoolProviderType poolProviderType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolProviderType(poolProviderType); } @Override public Object clone() throws CloneNotSupportedException { // Deep clone for configuration Configuration cloneConfig = (Configuration) super.clone(); cloneConfig.config.clear(); cloneConfig.configure(this.config); return cloneConfig; } }
package org.osiam.client.oauth; import static org.apache.http.HttpStatus.SC_BAD_REQUEST; import static org.apache.http.HttpStatus.SC_NOT_FOUND; import static org.apache.http.HttpStatus.SC_OK; import static org.apache.http.HttpStatus.SC_UNAUTHORIZED; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import org.apache.commons.codec.binary.Base64; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicNameValuePair; import org.codehaus.jackson.map.ObjectMapper; import org.osiam.client.exception.ConflictException; import org.osiam.client.exception.ConnectionInitializationException; import org.osiam.client.exception.ForbiddenException; import org.osiam.client.exception.InvalidAttributeException; import org.osiam.client.exception.OsiamErrorMessage; import org.osiam.client.exception.UnauthorizedException; /** * The AuthService provides access to the OAuth2 service used to authorize requests. Please use the * {@link AuthService.Builder} to construct one. */ public final class AuthService { // NOSONAR - Builder constructs instances of this class private static final Charset CHARSET = Charset.forName("UTF-8"); private HttpPost post; private final String endpoint; private Header[] headers; private String clientId; private String clientSecret; private String clientRedirectUri; private String scopes; private String password; private String userName; private GrantType grantType; private HttpEntity body; private AuthService(Builder builder) { endpoint = builder.endpoint; scopes = builder.scopes; grantType = builder.grantType; userName = builder.userName; password = builder.password; clientId = builder.clientId; clientSecret = builder.clientSecret; clientRedirectUri = builder.clientRedirectUri; } private HttpResponse performRequest() { if(post == null){// NOSONAR - false-positive from clover; if-expression is correct buildHead(); buildBody(); post = new HttpPost(getFinalEndpoint()); post.setHeaders(headers); post.setEntity(body); } HttpClient defaultHttpClient = new DefaultHttpClient(); final HttpResponse response; try { response = defaultHttpClient.execute(post); } catch (IOException e) { throw new ConnectionInitializationException("Unable to perform Request ", e); } return response; } private void buildHead() { String authHeaderValue = "Basic " + encodeClientCredentials(clientId, clientSecret); Header authHeader = new BasicHeader("Authorization", authHeaderValue); headers = new Header[]{ authHeader }; } private String encodeClientCredentials(String clientId, String clientSecret) { String clientCredentials = clientId + ":" + clientSecret; return new String(Base64.encodeBase64(clientCredentials.getBytes(CHARSET)), CHARSET); } private void buildBody() { List<NameValuePair> nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair("scope", scopes)); nameValuePairs.add(new BasicNameValuePair("grant_type", grantType.getUrlParam())); // NOSONAR - we check before that the grantType is not null if(userName != null){// NOSONAR - false-positive from clover; if-expression is correct nameValuePairs.add(new BasicNameValuePair("username", userName)); } if(password != null){// NOSONAR - false-positive from clover; if-expression is correct nameValuePairs.add(new BasicNameValuePair("password", password)); } try { body = new UrlEncodedFormEntity(nameValuePairs); } catch (UnsupportedEncodingException e) { throw new ConnectionInitializationException("Unable to Build Request in this encoding.", e); } } /** * Provide an {@link AccessToken} for the given parameters of this service. * * @return a valid AccessToken * @throws ConnectionInitializationException * If the Service is unable to connect to the configured OAuth2 service. * @throws UnauthorizedException If the configured credentials for this service are not permitted * to retrieve an {@link AccessToken} */ public AccessToken retrieveAccessToken() { if(grantType == GrantType.AUTHORIZATION_CODE){// NOSONAR - false-positive from clover; if-expression is correct throw new IllegalAccessError("For the grant type " + GrantType.AUTHORIZATION_CODE + " you need to retrieve a authentication code first."); } HttpResponse response = performRequest(); int status = response.getStatusLine().getStatusCode(); if (status != SC_OK) { // NOSONAR - false-positive from clover; if-expression is correct String errorMessage; String defaultMessage; switch (status) { case SC_BAD_REQUEST: defaultMessage = "Unable to create Connection. Please make sure that you have the correct grants."; errorMessage = getErrorMessage(response, defaultMessage); throw new ConnectionInitializationException(errorMessage); case SC_UNAUTHORIZED: defaultMessage = "You are not authorized to directly retrieve a access token."; errorMessage = getErrorMessage(response, defaultMessage); throw new UnauthorizedException(errorMessage); case SC_NOT_FOUND: defaultMessage = "Unable to find the given OSIAM service (" + getFinalEndpoint() + ")"; errorMessage = getErrorMessage(response, defaultMessage); throw new ConnectionInitializationException(errorMessage); default: defaultMessage = String.format("Unable to setup connection (HTTP Status Code: %d)", status); errorMessage = getErrorMessage(response, defaultMessage); throw new ConnectionInitializationException(errorMessage); } } return getAccessToken(response); } private String getErrorMessage(HttpResponse httpResponse, String defaultErrorMessage) { InputStream content = null; String errorMessage; try{ content = httpResponse.getEntity().getContent(); ObjectMapper mapper = new ObjectMapper(); OsiamErrorMessage error = mapper.readValue(content, OsiamErrorMessage.class); errorMessage = error.getDescription(); } catch (Exception e){ // NOSONAR - we catch everything errorMessage = defaultErrorMessage; }finally{ try{ if(content != null) { content.close(); }// NOSONAR - false-positive from clover; if-expression is correct }catch(IOException notNeeded){/**doesn't matter**/} } if(errorMessage == null){// NOSONAR - false-positive from clover; if-expression is correct errorMessage = defaultErrorMessage; } return errorMessage; } /** * provides the needed URI which is needed to reconect the User to the OSIAM server to login. * A detailed example how to use this methode, can be seen in our wiki in gitHub * @return */ public URI getRedirectLoginUri() { if(grantType != GrantType.AUTHORIZATION_CODE){// NOSONAR - false-positive from clover; if-expression is correct throw new IllegalAccessError("You need to use the GrantType " + GrantType.AUTHORIZATION_CODE + " to be able to use this method."); } URI returnUri; try { returnUri = new URIBuilder().setPath(getFinalEndpoint()) .addParameter("client_id", clientId) .addParameter("response_type", "code") .addParameter("redirect_uri", clientRedirectUri) .addParameter("scope", scopes) .build(); } catch (URISyntaxException e){ throw new ConnectionInitializationException("Unable to create redirect URI", e); } return returnUri; } /** * Provide an {@link AccessToken} for the given parameters of this service and the given {@link HttpResponse}. * If the User acepted your request for the needed data you will get an access token. * If the User denied your request a {@link ForbiddenException} will be thrown. * If the {@linkplain HttpResponse} does not contain a value named "code" or "error" a * {@linkplain InvalidAttributeException} will be thrown * @param authCodeResponse response goven from the OSIAM server. * For more information please look at the wiki at github * @return a valid AccessToken */ public AccessToken retrieveAccessToken(HttpResponse authCodeResponse) { String authCode = null; Header header = authCodeResponse.getLastHeader("Location"); HeaderElement[] elements = header.getElements(); for (HeaderElement actHeaderElement : elements) { if(actHeaderElement.getName().contains("code")){// NOSONAR - false-positive from clover; if-expression is correct authCode = actHeaderElement.getValue(); break; } if(actHeaderElement.getName().contains("error")){// NOSONAR - false-positive from clover; if-expression is correct throw new ForbiddenException("The user had denied the acces to his data."); } } if(authCode == null){// NOSONAR - false-positive from clover; if-expression is correct throw new InvalidAttributeException("Could not find any auth code or error message in the given Response"); } return retrieveAccessToken(authCode); } /** * Provide an {@link AccessToken} for the given parameters of this service and the given authCode. * @param authCode authentication code retrieved from the OSIAM Server by using the oauth2 login flow. * For more information please look at the wiki at github * @return a valid AccessToken */ public AccessToken retrieveAccessToken(String authCode) { if (authCode == null) { // NOSONAR - false-positive from clover; if-expression is correct throw new IllegalArgumentException("The given authentication code can't be null."); } HttpPost realWebResource = getWebRessourceToEchangeAuthCode(authCode); DefaultHttpClient httpclient = new DefaultHttpClient(); HttpResponse response; int httpStatus = 0; try{ response = httpclient.execute(realWebResource); httpStatus = response.getStatusLine().getStatusCode(); }catch(IOException e){ throw new ConnectionInitializationException("Unable to setup connection", e); } if (httpStatus != SC_OK) { // NOSONAR - false-positive from clover; if-expression is correct String errorMessage; switch (httpStatus) { case SC_BAD_REQUEST: errorMessage = getErrorMessage(response, "Could not exchange yout authentication code against a access token."); throw new ConflictException(errorMessage); default: errorMessage = getErrorMessage(response, String.format("Unable to setup connection (HTTP Status Code: %d)", httpStatus)); throw new ConnectionInitializationException(errorMessage); } } return getAccessToken(response); } private AccessToken getAccessToken(HttpResponse response){ final AccessToken accessToken; try { InputStream content = response.getEntity().getContent(); ObjectMapper mapper = new ObjectMapper(); accessToken = mapper.readValue(content, AccessToken.class); } catch (IOException e) { throw new ConnectionInitializationException("Unable to retrieve access token: IOException", e); } return accessToken; } private String getFinalEndpoint(){ String finalEndpoint = endpoint; if(grantType.equals(GrantType.AUTHORIZATION_CODE)){// NOSONAR - we check before that the grantType is not null finalEndpoint += "/oauth/authorize"; }else{ finalEndpoint += "/oauth/token"; } return finalEndpoint; } private HttpPost getWebRessourceToEchangeAuthCode(String authCode){ HttpPost realWebResource = new HttpPost(endpoint + "/oauth/token"); String authHeaderValue = "Basic " + encodeClientCredentials(clientId, clientSecret); realWebResource.addHeader("Authorization", authHeaderValue); List<NameValuePair> nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair("code", authCode)); nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code")); nameValuePairs.add(new BasicNameValuePair("redirect_uri", clientRedirectUri)); try{ realWebResource.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); }catch(UnsupportedEncodingException e){ throw new ConnectionInitializationException("Unable to Build Request in this encoding.", e); } return realWebResource; } /** * The Builder class is used to construct instances of the {@link AuthService}. */ public static class Builder { private String clientId; private String clientSecret; private GrantType grantType; private String scopes; private String endpoint; private String password; private String userName; private String clientRedirectUri; /** * Set up the Builder for the construction of an {@link AuthService} instance for the OAuth2 service at * the given endpoint * * @param endpoint The URL at which the OAuth2 service lives. */ public Builder(String endpoint) { this.endpoint = endpoint; } /** * Use the given {@link Scope} to for the request. * @param scope the needed scope * @param scopes the needed scopes * @return The builder itself */ public Builder setScope(Scope scope, Scope... scopes){ List<Scope> scopeList = new ArrayList<>(); scopeList.add(scope); for (Scope actScope : scopes) { scopeList.add(actScope); } if(scopeList.contains(Scope.ALL)){// NOSONAR - false-positive from clover; if-expression is correct this.scopes = Scope.ALL.toString(); }else{ StringBuilder scopeBuilder = new StringBuilder(); for (Scope actScope : scopeList) { scopeBuilder.append(" ").append(actScope.toString()); } this.scopes = scopeBuilder.toString().trim(); } return this; } /** * The needed access token scopes as String like 'GET PATCH' * @param scope the needed scope * @return The builder itself */ public Builder setScope(String scope){ this.scopes = scope; return this; } /** * Use the given {@link GrantType} to for the request. * * @param grantType of the requested AuthCode * @return The builder itself * @throws UnsupportedOperationException If the GrantType is anything else than GrantType.PASSWORD */ public Builder setGrantType(GrantType grantType) { this.grantType = grantType; return this; } /** * Add a ClientId to the OAuth2 request * * @param clientId The client-Id * @return The builder itself */ public Builder setClientId(String clientId) { this.clientId = clientId; return this; } /** * Add a Client redirect URI to the OAuth2 request * * @param clientRedirectUri the clientRedirectUri which is known to the OSIAM server * @return The builder itself */ public Builder setClientRedirectUri(String clientRedirectUri) { this.clientRedirectUri = clientRedirectUri; return this; } /** * Add a clientSecret to the OAuth2 request * * @param clientSecret The client secret * @return The builder itself */ public Builder setClientSecret(String clientSecret) { this.clientSecret = clientSecret; return this; } /** * Add the given username to the OAuth2 request * * @param userName The username * @return The builder itself */ public Builder setUsername(String userName) { this.userName = userName; return this; } /** * Add the given password to the OAuth2 request * * @param password The password * @return The builder itself */ public Builder setPassword(String password) { this.password = password; return this; } /** * Construct the {@link AuthService} with the parameters passed to this builder. * * @return An AuthService configured accordingly. * @throws ConnectionInitializationException * If either the provided client credentials (clientId/clientSecret) * or, if the requested grant type is 'password', the user credentials (userName/password) are incomplete. */ public AuthService build() { ensureAllNeededParameterAreCorrect(); return new AuthService(this); } private void ensureAllNeededParameterAreCorrect(){// NOSONAR - this is a test method the Cyclomatic Complexity can be over 10. if (clientId == null || clientSecret == null) { // NOSONAR - false-positive from clover; if-expression is correct throw new IllegalArgumentException("The provided client credentials are incomplete."); } if(scopes == null){// NOSONAR - false-positive from clover; if-expression is correct throw new IllegalArgumentException("At least one scope needs to be set."); } if (grantType == null) { // NOSONAR - false-positive from clover; if-expression is correct throw new IllegalArgumentException("The grant type is not set."); } if (grantType.equals(GrantType.PASSWORD) && (userName == null && password == null)) { // NOSONAR - false-positive from clover; if-expression is correct throw new IllegalArgumentException("The grant type 'password' requires username and password"); } if ((grantType.equals(GrantType.CLIENT_CREDENTIALS) || grantType.equals(GrantType.AUTHORIZATION_CODE))// NOSONAR - false-positive from clover; if-expression is correct && (userName != null || password != null)) { // NOSONAR - false-positive from clover; if-expression is correct throw new IllegalArgumentException("For the grant type '" + grantType + "' setting of password and username are not allowed."); } if (grantType.equals(GrantType.AUTHORIZATION_CODE) && clientRedirectUri == null) { // NOSONAR - false-positive from clover; if-expression is correct throw new IllegalArgumentException("For the grant type '" + grantType + "' the redirect Uri is needed."); } } } }
package org.osiam.client.update; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.osiam.client.query.metamodel.User_; import org.osiam.resources.scim.Address; import org.osiam.resources.scim.Meta; import org.osiam.resources.scim.MultiValuedAttribute; import org.osiam.resources.scim.Name; import org.osiam.resources.scim.User; /** * Class to create a UpdateUser Object to update a existing User */ public final class UpdateUser {// NOSONAR - Builder constructs instances of this class private User user; private UpdateUser(Builder builder) { user = builder.updateUser.build(); } /** * the Scim conform User to be used to update a existing User * * @return User to update */ public User getScimConformUpdateUser() { return user; } /** * The Builder is used to construct instances of the {@link UpdateUser} * */ public static class Builder { private String userName; private String nickName; private String externalId; private String locale; private String password; private String preferredLanguage; private String profileUrl; private String timezone; private String title; private Name name; private String userType; private String displayName; private Boolean active; private User.Builder updateUser = null; private Set<String> deleteFields = new HashSet<>(); private List<MultiValuedAttribute> emails = new ArrayList<>(); private List<MultiValuedAttribute> ims = new ArrayList<>(); private List<MultiValuedAttribute> phoneNumbers = new ArrayList<>(); private List<Address> addresses = new ArrayList<>(); private List<MultiValuedAttribute> entitlements = new ArrayList<>(); private List<MultiValuedAttribute> photos = new ArrayList<>(); private List<MultiValuedAttribute> roles = new ArrayList<>(); private List<MultiValuedAttribute> certificates = new ArrayList<>(); private static final String DELETE = "delete"; public Builder() { } // start username /** * updates the nickName of a existing user * * @param userName * the new user name * @return The builder itself */ public Builder updateUserName(String userName) { this.userName = userName; return this; } // end username // start address /** * adds a new address to the existing addresses of a existing user * * @param address * the new address * @return The builder itself */ public Builder addAddress(Address address) { addresses.add(address); return this; } /** * deletes the given address from the list of existing addresses of a existing user * * @param address * address to be deleted * @return The builder itself */ public Builder deleteAddress(Address address) { Address deleteAddress = new Address.Builder(address) .setOperation(DELETE) .build(); addresses.add(deleteAddress); return this; } /** * deletes all existing addresses of the a existing user * * @return The builder itself */ public Builder deleteAddresses() { deleteFields.add("addresses"); return this; } /** * updates the old Address with the new one * * @param oldAttribute * to be replaced * @param newAttribute * new Address * @return The builder itself */ public Builder updateAddress(Address oldAttribute, Address newAttribute) { deleteAddress(oldAttribute); addAddress(newAttribute); return this; } // end address // start Nickname /** * deletes the nickName of a existing user * * @return The builder itself */ public Builder deleteNickName() { deleteFields.add(User_.nickName.toString()); return this; } /** * updates the nickName of a existing user * * @param nickName * the new nickName * @return The builder itself */ public Builder updateNickName(String nickName) { this.nickName = nickName; return this; } // end Nickname // start ExternalID /** * delete the external Id of a existing user * * @return The builder itself */ public Builder deleteExternalId() { deleteFields.add(User_.externalId.toString()); return this; } /** * updates the external id of a existing user * * @param externalId * new external id * @return The builder itself */ public Builder updateExternalId(String externalId) { this.externalId = externalId; return this; } // end ExternalID // start local /** * delete the local value of a existing user * * @return The builder itself */ public Builder deleteLocal() { deleteFields.add(User_.locale.toString()); return this; } /** * updates the local of a existing user * * @param locale * new local * @return The builder itself */ public Builder updateLocale(String locale) { this.locale = locale; return this; } // end local // start password /** * updates the password of a existing user * * @param password * new password * @return The builder itself */ public Builder updatePassword(String password) { this.password = password; return this; } // end password // start preferredLanguage /** * delete the preferred Language of a existing user * * @return The builder itself */ public Builder deletePreferredLanguage() { deleteFields.add(User_.preferredLanguage.toString()); return this; } /** * updates the preferred language of a existing user * * @param preferredLanguage * new preferred language * @return The builder itself */ public Builder updatePreferredLanguage(String preferredLanguage) { this.preferredLanguage = preferredLanguage; return this; } // end preferredLanguage // start ProfileUrl /** * deletes the profil Url of a existing user * * @return The builder itself */ public Builder deleteProfileUrl() { deleteFields.add(User_.profileUrl.toString()); return this; } /** * updates the profil URL of a existing user * * @param profileUrl * new profilUrl * @return The builder itself */ public Builder updateProfileUrl(String profileUrl) { this.profileUrl = profileUrl; return this; } // end ProfileUrl // start timezone /** * deletes the timezone of a existing user * * @return The builder itself */ public Builder deleteTimezone() { deleteFields.add(User_.timezone.toString()); return this; } /** * updates the timezone of a existing user * * @param timezone * new timeZone * @return The builder itself */ public Builder updateTimezone(String timezone) { this.timezone = timezone; return this; } // end timezone // start title /** * deletes the title of a existing user * * @return The builder itself */ public Builder deleteTitle() { deleteFields.add(User_.title.toString()); return this; } /** * updates the title of a existing user * * @param title * new tile * @return The builder itself */ public Builder updateTitle(String title) { this.title = title; return this; } // end title // start name /** * deletes the name of a existing user * * @return The builder itself */ public Builder deleteName() { deleteFields.add("name"); return this; } /** * updates the name of a existing user * * @param name * new Name * @return The builder itself */ public Builder updateName(Name name) { this.name = name; return this; } // end name // start UserType /** * deletes the user type of a existing user * * @return The builder itself */ public Builder deleteUserType() { deleteFields.add(User_.userType.toString()); return this; } /** * updates the user type of a existing user * * @param userType * new user type * @return The builder itself */ public Builder updateUserType(String userType) { this.userType = userType; return this; } // end UserType // start DisplayName /** * deletes the display name of a existing user * * @return The builder itself */ public Builder deleteDisplayName() { deleteFields.add(User_.displayName.toString()); return this; } /** * updates the display name of a existing user * * @param displayName * new display name * @return The builder itself */ public Builder updateDisplayName(String displayName) { this.displayName = displayName; return this; } // end DisplayName // start email /** * deletes all emails of a existing user * * @return The builder itself */ public Builder deleteEmails() { deleteFields.add("emails"); return this; } /** * deletes the given email of a existing user * * @param email * to be deleted * @return The builder itself */ public Builder deleteEmail(MultiValuedAttribute email) { MultiValuedAttribute deleteEmail = new MultiValuedAttribute.Builder() .setValue(email.getValue()) .setType(email.getType()) .setOperation(DELETE).build(); emails.add(deleteEmail); return this; } /** * adds or updates a emil of an existing user if the .getValue() already exists a update will be done. If not a * new one will be added * * @param email * new email * @return The builder itself */ public Builder addEmail(MultiValuedAttribute email) { emails.add(email); return this; } /** * updates the old Email with the new one * * @param oldAttribute * to be replaced * @param newAttribute * new Email * @return The builder itself */ public Builder updateEmail(MultiValuedAttribute oldAttribute, MultiValuedAttribute newAttribute) { deleteEmail(oldAttribute); addEmail(newAttribute); return this; } // end email // start certificates /** * deletes all X509Certificates of a existing user * * @return The builder itself */ public Builder deleteX509Certificates() { deleteFields.add("x509Certificates"); return this; } /** * deletes the given certificate of a existing user * * @param certificate * to be deleted * @return The builder itself */ public Builder deleteX509Certificate(MultiValuedAttribute certificate) { MultiValuedAttribute deleteCertificates = new MultiValuedAttribute.Builder() .setValue(certificate.getValue()) .setOperation(DELETE).build(); certificates.add(deleteCertificates); return this; } /** * adds or updates certificate to an existing user if the .getValue() already exists a update will be done. If * not a new one will be added * * @param certificate * new certificate * @return The builder itself */ public Builder addX509Certificate(MultiValuedAttribute certificate) { certificates.add(certificate); return this; } /** * updates the old X509Certificate with the new one * * @param oldAttribute * to be replaced * @param newAttribute * new X509Certificate * @return The builder itself */ public Builder updateX509Certificate(MultiValuedAttribute oldAttribute, MultiValuedAttribute newAttribute) { deleteX509Certificate(oldAttribute); addX509Certificate(newAttribute); return this; } // end certificates // start roles /** * deletes all roles of a existing user * * @return The builder itself */ public Builder deleteRoles() { deleteFields.add("roles"); return this; } /** * deletes the given role of a existing user * * @param role * to be deleted * @return The builder itself */ public Builder deleteRole(MultiValuedAttribute role) { MultiValuedAttribute deleteRole = new MultiValuedAttribute.Builder() .setValue(role.getValue()) .setOperation(DELETE).build(); roles.add(deleteRole); return this; } /** * deletes the given role of a existing user * * @param role * to be deleted * @return The builder itself */ public Builder deleteRole(String role) { MultiValuedAttribute deleteRole = new MultiValuedAttribute.Builder() .setValue(role) .setOperation(DELETE).build(); roles.add(deleteRole); return this; } /** * adds or updates a role of an existing user if the .getValue() already exists a update will be done. If not a * new one will be added * * @param role * new role * @return The builder itself */ public Builder addRole(MultiValuedAttribute role) { roles.add(role); return this; } /** * updates the old Role with the new one * * @param oldAttribute * to be replaced * @param newAttribute * new Role * @return The builder itself */ public Builder updateRole(MultiValuedAttribute oldAttribute, MultiValuedAttribute newAttribute) { deleteRole(oldAttribute); addRole(newAttribute); return this; } // end roles // start ims /** * deletes all ims of a existing user * * @return The builder itself */ public Builder deleteIms() { deleteFields.add("ims"); return this; } /** * deletes the ims of a existing user * * @param ims * to be deleted * @return The builder itself */ public Builder deleteIms(MultiValuedAttribute ims) { MultiValuedAttribute deleteIms = new MultiValuedAttribute.Builder() .setValue(ims.getValue()) .setType(ims.getType()) .setOperation(DELETE).build(); this.ims.add(deleteIms); return this; } /** * adds or updates a ims to an existing user if the .getValue() already exists a update will be done. If not a * new one will be added * * @param ims * new ims * @return The builder itself */ public Builder addIms(MultiValuedAttribute ims) { this.ims.add(ims); return this; } /** * updates the old Ims with the new one * * @param oldAttribute * to be replaced * @param newAttribute * new Ims * @return The builder itself */ public Builder updateIms(MultiValuedAttribute oldAttribute, MultiValuedAttribute newAttribute) { deleteIms(oldAttribute); addIms(newAttribute); return this; } // end ims // start phonenumbers /** * adds or updates a phoneNumber to an existing user if the .getValue() already exists a update will be done. If * not a new one will be added * * @param phoneNumber * new phoneNumber * @return The builder itself */ public Builder addPhoneNumber(MultiValuedAttribute phoneNumber) { phoneNumbers.add(phoneNumber); return this; } /** * deletes the phonenumber of a existing user * * @param phoneNumber * to be deleted * @return The builder itself */ public Builder deletePhoneNumber(MultiValuedAttribute phoneNumber) { MultiValuedAttribute deletePhoneNumber = new MultiValuedAttribute.Builder() .setValue(phoneNumber.getValue()) .setType(phoneNumber.getType()) .setOperation(DELETE).build(); phoneNumbers.add(deletePhoneNumber); return this; } /** * deletes all phonenumbers of a existing user * * @return The builder itself */ public Builder deletePhoneNumbers() { deleteFields.add("phoneNumbers"); return this; } /** * updates the old PhoneNumber with the new one * * @param oldAttribute * to be replaced * @param newAttribute * new PhoneNumber * @return The builder itself */ public Builder updatePhoneNumber(MultiValuedAttribute oldAttribute, MultiValuedAttribute newAttribute) { deletePhoneNumber(oldAttribute); addPhoneNumber(newAttribute); return this; } // end phonenumbers // start photos /** * adds or updates a photo to an existing user if the .getValue() already exists a update will be done. If not a * new one will be added * * @param photo * new photo * @return The builder itself */ public Builder addPhoto(MultiValuedAttribute photo) { photos.add(photo); return this; } /** * deletes the photo of a existing user * * @param photo * to be deleted * @return The builder itself */ public Builder deletePhoto(MultiValuedAttribute photo) { MultiValuedAttribute deletePhoto = new MultiValuedAttribute.Builder() .setValue(photo.getValue()) .setType(photo.getType()) .setOperation(DELETE) .build(); photos.add(deletePhoto); return this; } /** * deletes all photos of a existing user * * @return The builder itself */ public Builder deletePhotos() { deleteFields.add("photos"); return this; } /** * updates the old Photo with the new one * * @param oldAttribute * to be replaced * @param newAttribute * new Photo * @return The builder itself */ public Builder updatePhotos(MultiValuedAttribute oldAttribute, MultiValuedAttribute newAttribute) { deletePhoto(oldAttribute); addPhoto(newAttribute); return this; } // end photos // start entitlement /** * deletes all entitlements of a existing user * * @return The builder itself */ public Builder deleteEntitlements() { deleteFields.add("entitlements"); return this; } /** * deletes the entitlement of a existing user * * @param entitlement * to be deleted * @return The builder itself */ public Builder deleteEntitlement(MultiValuedAttribute entitlement) { MultiValuedAttribute deleteEntitlement = new MultiValuedAttribute.Builder() .setValue(entitlement.getValue()) .setType(entitlement.getType()) .setOperation(DELETE) .build(); entitlements.add(deleteEntitlement); return this; } /** * adds or updates a entitlement to an existing user if the .getValue() already exists a update will be done. If * not a new one will be added * * @param entitlement * new entitlement * @return The builder itself */ public Builder addEntitlement(MultiValuedAttribute entitlement) { entitlements.add(entitlement); return this; } /** * updates the old Entitlement with the new one * * @param oldAttribute * to be replaced * @param newAttribute * new Entitlement * @return The builder itself */ public Builder updateEntitlement(MultiValuedAttribute oldAttribute, MultiValuedAttribute newAttribute) { deleteEntitlement(oldAttribute); addEntitlement(newAttribute); return this; } // end entitlement // start active /** * updates the active status of a existing User to the given value * * @param active * new active status * @return The builder itself */ public Builder updateActive(boolean active) { this.active = active; return this; } // end activ /** * constructs a UpdateUser with the given values * * @return a valid {@link UpdateUser} */ public UpdateUser build() {// NOSONAR - Since we build a User it is ok that the Cyclomatic Complexity is over 10 if (userName == null || userName.isEmpty()) { updateUser = new User.Builder(); } else { updateUser = new User.Builder(userName); } if (nickName != null) {// NOSONAR - false-positive from clover; if-expression is correct updateUser.setNickName(nickName); } if (externalId != null) {// NOSONAR - false-positive from clover; if-expression is correct updateUser.setExternalId(externalId); } if (locale != null) {// NOSONAR - false-positive from clover; if-expression is correct updateUser.setLocale(locale); } if (password != null) {// NOSONAR - false-positive from clover; if-expression is correct updateUser.setPassword(password); } if (preferredLanguage != null) {// NOSONAR - false-positive from clover; if-expression is correct updateUser.setPreferredLanguage(preferredLanguage); } if (profileUrl != null) {// NOSONAR - false-positive from clover; if-expression is correct updateUser.setProfileUrl(profileUrl); } if (timezone != null) {// NOSONAR - false-positive from clover; if-expression is correct updateUser.setTimezone(timezone); } if (title != null) {// NOSONAR - false-positive from clover; if-expression is correct updateUser.setTitle(title); } if (name != null) {// NOSONAR - false-positive from clover; if-expression is correct updateUser.setName(name); } if (userType != null) {// NOSONAR - false-positive from clover; if-expression is correct updateUser.setUserType(userType); } if (displayName != null) {// NOSONAR - false-positive from clover; if-expression is correct updateUser.setDisplayName(displayName); } if (active != null) {// NOSONAR - false-positive from clover; if-expression is correct updateUser.setActive(active); } if (deleteFields.size() > 0) {// NOSONAR - false-positive from clover; if-expression is correct Meta meta = new Meta.Builder() .setAttributes(deleteFields).build(); updateUser.setMeta(meta); } if (emails.size() > 0) { updateUser.setEmails(emails); } if (phoneNumbers.size() > 0) { updateUser.setPhoneNumbers(phoneNumbers); } if (addresses.size() > 0) { updateUser.setAddresses(addresses); } if (entitlements.size() > 0) { updateUser.setEntitlements(entitlements); } if (ims.size() > 0) { updateUser.setIms(ims); } if (photos.size() > 0) { updateUser.setPhotos(photos); } if (roles.size() > 0) { updateUser.setRoles(roles); } if (certificates.size() > 0) { updateUser.setX509Certificates(certificates); } return new UpdateUser(this); } } }
// Programmer: Maciej Szpakowski, Muhammad Habib Khan, Muhammad Khalil Khan // Assignment: Project 2, Monopoly // Description: Game class that models main game object that stores all back end data // such as players and board fields, manages game state, and implements functions that // connect the back end with the front end package src; import java.util.LinkedList; import java.util.Queue; import com.sun.xml.internal.bind.v2.runtime.Location; import sun.security.action.GetLongAction; public class Game { public static final int DICE_COUNT = 2; // how many dice to roll public static final boolean DEMO_MODE = true; // flag that enabled/disables demo mode private final BoardLocation[] board; // array of all board locations private Player currentPlayer; // current player private Player[] players; // array of all players private int dice; // current dice value private Queue<Player> queuePlayer; // queue of players, maintains the order public Game(int playerNum) // PRE: playerNum must be between 2 and 8 // POST: initializes board, players, currentPlayer, queuePlayer class members // in case of demo mode initializes the game to run in demo mode { if(DEMO_MODE) // demo mode active { playerNum = 2; } board = makeBoard(); this.players = makePlayers(playerNum); BoardLocation.Link(board); queuePlayer = setUpPlayersQueue(); currentPlayer = queuePlayer.peek(); if(DEMO_MODE) // demo mode active { initDemoMode(); } } private void initDemoMode() // PRE: players and board must be initialized // POST: 12 to 18 properties are randomly distributed among players // some houses/hotels are placed on distributed lots { int previousPersonLastMove; // what was the person last location int propertyPurchased; // how many properties has player purchased previousPersonLastMove = 0; for (Player player : players ) { int propToPurchase; // how properties to purchase for the player player.setMoney(9000); player.move(previousPersonLastMove); propertyPurchased = 0; propToPurchase = (int)(Math.random()*(12-8))+8; while ( propertyPurchased < propToPurchase ) { player.move(1); previousPersonLastMove++; if ( player.getLocation() instanceof Property ) // is my current location a property { player.buyLocation((Property) player.getLocation()); propertyPurchased++; } if ( player.getProperties().size() > 3 ) // do i have 3 props and a factor of 2 { for ( Property p : player.getProperties()) // for all my properties { if ( p instanceof Lot ) // is p a lot than imrpove it { ((Lot) p).improve(); } } } } } } public Player getCurrentPlayer() // POST:FCTVAL: this.currentPlayer { return currentPlayer; } public BoardLocation[] getBoard() // POST:FCTVAL: this.board { return board; } public Player[] getPlayers() // POST:FCTVAL: this.players { return players; } private Queue<Player> setUpPlayersQueue() // PRE: players class member must be initialized // POST: FCTVAL: returns initialized queue of players // first player is chosen randomly { int rand; // random number Queue<Player> queuePlayers = new LinkedList<>(); for(Player p : players) // add all players to queue queuePlayers.add(p); rand = (int)(Math.random()*players.length); // choose random number between [0,#players-1] for ( int i = 0; i < rand; i++ ) // enqueue dequeue random number of times { queuePlayers.add(queuePlayers.poll()); } return queuePlayers; } public void printPlayers() // PRE: players class member must be initialized // POST: prints all players to stdout { for (Player p : players) { System.out.println(p); } } public void printBoardInfo() // PRE: players class members must be initialized // POST: prints all board locations to stdout { for ( BoardLocation b : board ) { System.out.println(b); } } private BoardLocation[] makeBoard() // POST: FCTVAL: array of board locations of monopoly game // fully initialized { BoardLocation[] result; result = new BoardLocation[] { new CornerSquare("Go", 0), new Lot("MEDITERRANEAN AVE", 1, 60, "Dark Purple", 50, new int[] { 2, 10, 30, 90, 160, 230}), new CardSquare("Community Chest", 2), new Lot("BALTIC AVE.", 3, 60, "Dark Purple", 50, new int[] { 4, 20, 60, 180, 320, 450}), new TaxSquare("Income Tax", 4, 200), new RailRoad("READING RAILROAD", 5, 200), new Lot("ORIENTAL AVE.", 6, 100, "Light Blue", 50, new int[] { 6, 30, 90, 270, 400, 550}), new CardSquare("Chance", 7), new Lot("VERMONT AVE.", 8, 100, "Light Blue", 50, new int[] { 6, 30, 90, 270, 400, 550}), new Lot("CONNECTICUT AVE.", 9, 120, "Light Blue", 50, new int[] { 8, 40, 100, 300, 450, 600}), new CornerSquare("Jail/Just Visiting", 10), new Lot("ST. CHARLES PLACE", 11, 140, "Light Purple", 100, new int[] { 10, 50, 150, 450, 625, 750}), new Utility("ELECTRIC COMPANY", 12, 150), new Lot("STATES AVE.", 13, 140, "Light Purple", 100, new int[] { 10, 50, 150, 450, 625, 750}), new Lot("VIRGINIA AVE.", 14, 160, "Light Purple", 100, new int[] { 12, 60, 180, 500, 700, 900}), new RailRoad("PENNSYLVANIA RAILROAD", 15, 200), new Lot("ST. JAMES PLACE", 16, 180, "Orange", 100, new int[] { 14, 70, 200, 550, 750, 950}), new CardSquare("Community Chest", 17), new Lot("TENNESSEE AVE.", 18, 180, "Orange", 100, new int[] { 14, 70, 200, 550, 750, 950}), new Lot("NEW YORK AVE.", 19, 200, "Orange", 100, new int[] { 16, 80, 220, 600, 800, 1000}), new CornerSquare("Free Parking", 20), new Lot("KENTUCKY AVE.", 21, 220, "Red", 150, new int[] { 18, 90, 250, 700, 875, 1050}), new CardSquare("Chance", 22), new Lot("INDIANA AVE.", 23, 220, "Red", 150, new int[] { 18, 90, 250, 700, 875, 1050}), new Lot("ILLINOIS AVE.", 24, 240, "Red", 150, new int[] { 20, 100, 300, 750, 925, 1100}), new RailRoad("B & O RAILROAD", 25, 200), new Lot("ATLANTIC AVE.", 26, 260, "Yellow", 150, new int[] { 22, 110, 330, 800, 975, 1150}), new Lot("VENTNOR AVE.", 27, 260, "Yellow", 150, new int[] { 22, 110, 330, 800, 975, 1150}), new Utility("WATER WORKS", 28, 150), new Lot("MARVIN GARDENS", 29, 280, "Yellow", 150, new int[] { 24, 120, 360, 850, 1025, 1200}), new CornerSquare("Go To Jail", 30), new Lot("PACIFIC AVE.", 31, 300, "Green", 200, new int[] { 26, 130, 390, 900, 1100, 1275}), new Lot("NO. CAROLINA AVE.", 32, 300, "Green", 200, new int[] { 26, 130, 390, 900, 1100, 1275}), new CardSquare("Community Chest", 33), new Lot("PENNSYLVANIA AVE.", 34, 320, "Green", 200, new int[] { 28, 150, 450, 1000, 1200, 1400}), new RailRoad("SHORT LINE RAILROAD", 35, 200), new CardSquare("Chance", 36), new Lot("PARK PLACE", 37, 350, "Dark Blue", 200, new int[] { 35, 175, 500, 1100, 1300, 1500}), new TaxSquare("Luxury Tax", 38, 75), new Lot("BOARDWALK", 39, 400, "Dark Blue", 200, new int[] { 50, 200, 600, 1400, 1700, 2000}), }; BoardLocation.Link(result); Utility.setOther((Utility)result[28], (Utility)result[12]); RailRoad.setOthers((RailRoad)result[5], (RailRoad)result[15], (RailRoad)result[25], (RailRoad)result[35]); return result; } private Player[] makePlayers(int pCount) // PRE: pCount has to be between 2 and 8 // board class member has to be initialized // POST:FCTVAL: returns initialized array of players { String[] token; Player[] result; token = new String[] {"car", "boot", "top hat", "ship", "wheelbarrow", "iron", "thimble", "dog"}; result = new Player[pCount]; for ( int i = 0; i < pCount; i++ ) { result[i] = new Player(token[i], board[0]); } return result; } public Property getProperty(String property) // PRE: property should be a name of a property on the board // POST:FCTVAL: return Property which names matches property arg // returns null otherwise { for(BoardLocation p: board) { if(p.getName().equals(property)) { return (Property)p; } } return null; } public String move() // PRE: currentPlayer class member must be initialized // dice must be rolled before calling this func // POST: calls move() on current player // FCTVAL: returns the message of what happened on the field where player moved to { return currentPlayer.move(dice); } public int rollDice() // POST: rolls DICE_COUNT dices // FCTVAL: dice value rolled { dice = 0; for(int i=0;i<DICE_COUNT;i++) // dice { dice += (int) (((double)Math.random()*6)+1); } Player.setDice(dice); return dice; } public void giveTurn() // PRE: currentPlayer and queuePlayer must be initialized // POST: gives turn to the next player in the queue // puts the currentPlayer at the end { if(currentPlayer.isBankrupt()) { queuePlayer.poll(); } queuePlayer.add(queuePlayer.poll()); currentPlayer = queuePlayer.peek(); } public boolean checkBankruptcy(Player player) // PRE: // POST:FCTVAL: { if(player.isBankrupt()) { } return false; } }
package uk.bl.api; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLDecoder; import java.sql.Timestamp; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TimeZone; import java.util.UUID; import com.avaje.ebean.Ebean; import com.avaje.ebean.SqlUpdate; import play.Logger; import uk.bl.Const; import org.apache.commons.lang3.StringUtils; import org.postgresql.util.PGInterval; /** * Helper class. */ public enum Utils { INSTANCE; /** * This method generates random Long ID. * @return new ID as Long value */ public Long createId() { UUID id = UUID.randomUUID(); Logger.debug("id: " + id.toString()); Long res = id.getMostSignificantBits(); if (res < 0) { res = res*(-1); } return res; } /** * This method normalizes boolean values expressed in different string values. * @param value * @return normalized boolean value (true or false) */ public boolean getNormalizeBooleanString(String value) { boolean res = false; if (value != null && value.length() > 0) { if (value.equals("Yes") || value.equals("yes") || value.equals("True") || value.equals("true") || value.equals("On") || value.equals("on") || value.equals("Y") || value.equals("y")) { res = true; } } return res; } /** * This method converts Boolean value to string * @param value * @return */ public String getStringFromBoolean(Boolean value) { String res = ""; if (value != null && value.toString().length() > 0) { res = value.toString(); } return res; } /** * This method creates CSV file for passed data. * @param sFileName */ public File generateCsvFile(String sFileName, String data) { File file = new File(sFileName); try { FileWriter writer = new FileWriter(file); String decodedData = replacer(data); //URLDecoder.decode(data, Const.STR_FORMAT); // Logger.debug("generateCsvFile: " + decodedData); writer.append(decodedData); writer.flush(); writer.close(); } catch(IOException e) { e.printStackTrace(); } return file; } /** * This method secures handling of percent in string. * @param data * @return */ public String replacer(String data) { try { StringBuffer tempBuffer = new StringBuffer(); int incrementor = 0; int dataLength = data.length(); while (incrementor < dataLength) { char charecterAt = data.charAt(incrementor); if (charecterAt == '%') { tempBuffer.append("<percentage>"); } else if (charecterAt == '+') { tempBuffer.append("<plus>"); } else { tempBuffer.append(charecterAt); } incrementor++; } data = tempBuffer.toString(); data = URLDecoder.decode(data, Const.STR_FORMAT); data = data.replaceAll("<percentage>", "%"); data = data.replaceAll("<plus>", "+"); } catch (Exception e) { e.printStackTrace(); } return data; } /** * This method generates current date for e.g. licence form. * @return */ public String getCurrentDate() { return new SimpleDateFormat("dd-MM-yyyy").format(Calendar.getInstance().getTime()); } /** * This method performs a conversion of date in string format 'dd-MM-yyyy' to unix date. * @param curDate * @return long value of the unix date in string format */ public String getUnixDateStringFromDate(String curDate) { String res = ""; try { Logger.debug("getUnixDateStringFromDate curDate: " + curDate); Date resDate = new SimpleDateFormat(Const.DATE_FORMAT).parse(curDate); /** * 86400 seconds stand for one day. We add it because simple date format conversion * creates timestamp for one day older than the current day. */ Long longTime = new Long(resDate.getTime()/1000 + 86400); Logger.debug("long time: " + longTime); res = String.valueOf(longTime); Logger.debug("res date: " + res); Logger.debug("check stored date - convert back to human date: " + getDateFromUnixDate(res)); } catch (ParseException e) { Logger.debug("Conversion of date in string format dd-MM-yyyy to unix date: " + e); } return res; } /** * This method performs a conversion of date in string format 'dd-MM-yyyy' to unix date without * modifying the date. * @param curDate * @return long value of the unix date in string format */ public String getUnixDateStringFromDateExt(String curDate) { String res = ""; try { Logger.debug("getUnixDateStringFromDate curDate: " + curDate); Date resDate = new SimpleDateFormat(Const.DATE_FORMAT).parse(curDate); Long longTime = new Long(resDate.getTime()/1000); Logger.debug("long time: " + longTime); res = String.valueOf(longTime); Logger.debug("res date: " + res); Logger.debug("check stored date - convert back to human date: " + getDateFromUnixDate(res)); } catch (ParseException e) { Logger.debug("Conversion of date in string format dd-MM-yyyy to unix date: " + e); } return res; } /** * This method converts unix date to date. * @param unixDate * @return date as a string */ public String getDateFromUnixDate(String unixDate) { String res = ""; if (unixDate != null && unixDate.length() > 0) { long unixSeconds = Long.valueOf(unixDate); Date date = new Date(unixSeconds*1000L); // *1000 is to convert seconds to milliseconds SimpleDateFormat sdf = new SimpleDateFormat(Const.DATE_FORMAT); // the format of your date sdf.setTimeZone(TimeZone.getTimeZone("GMT-4")); res = sdf.format(date); } return res; } /** * Retrieve formatted timestamp * @param timestamp * @return formatted timestamp */ public String showTimestamp(String timestamp) { String res = ""; if (timestamp.length() > 0) { try { Date resDate = new SimpleDateFormat("yyyyMMddHHMMss").parse(timestamp); if (resDate != null) { Calendar mydate = new GregorianCalendar(); mydate.setTime(resDate); res = Integer.toString(mydate.get(Calendar.DAY_OF_MONTH)) + "/" + Integer.toString(mydate.get(Calendar.MONTH)) + "/" + Integer.toString(mydate.get(Calendar.YEAR)); } } catch (ParseException e) { Logger.debug("QA timestamp conversion error: " + e); } } return res; } /** * Show timestamp in HTML page * @param timestamp * @return formatted timestamp */ public String showTimestampInHtml(String timestamp) { String res = ""; Logger.debug("showTimestampInHtml timestamp: " + timestamp); if (timestamp.length() > 0) { try { Date resDate = new SimpleDateFormat("yyyyMMddHHMMss").parse(timestamp); if (resDate != null) { Calendar mydate = new GregorianCalendar(); mydate.setTime(resDate); res = Integer.toString(mydate.get(Calendar.DAY_OF_MONTH)) + "-" + Integer.toString(mydate.get(Calendar.MONTH)) + "-" + Integer.toString(mydate.get(Calendar.YEAR)); } } catch (ParseException e) { Logger.debug("QA timestamp conversion error: " + e); } } return res; } /** * Convert long timestamp to a date for presentation in a table. * @param long timestamp * @return formatted timestamp "dd/MM/yyyy" */ public String showTimestampInTable(String timestamp) { String res = ""; if (timestamp.length() > 0) { try { Date resDate = new Date(Long.parseLong(timestamp)*1000L); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // the format of date res = sdf.format(resDate); } catch (Exception e) { Logger.debug("Long timestamp conversion error: " + e); } } return res; } /** * This method evaluates if element is in a list separated by list delimiter e.g. ', '. * @param elem The given element for searching * @param list The list that contains elements * @return true if in list */ public boolean hasElementInList(String elem, String list) { boolean res = false; if (list != null) { if (list.contains(Const.LIST_DELIMITER)) { String[] parts = list.split(Const.LIST_DELIMITER); for (String part: parts) { if (part.equals(elem)) { res = true; break; } } } else { if (list.equals(elem)) { res = true; } } } return res; } /** * This method evaluates if object is in a list. * @param object The given object for searching * @param list The list that contains objects of the same type * @return true if in list */ public boolean hasObjectInList(String object, List<String> list) { boolean res = false; if (list != null && object != null) { Iterator<String> itr = list.iterator(); while (itr.hasNext()) { String entry = itr.next(); if (entry.equals(object)) { res = true; break; } } } return res; } /** * This method removes duplicated entries from the string list with values separated by ', '. * @param list The list that contains elements * @return result list */ public String removeDuplicatesFromList(String list) { String res = ""; boolean firstIteration = true; if (list != null) { if (list.contains(Const.LIST_DELIMITER)) { String[] parts = list.split(Const.LIST_DELIMITER); for (String part: parts) { boolean isAlreadyInList = false; String[] resListParts = res.split(Const.LIST_DELIMITER); for (String resListPart: resListParts) { if (resListPart.equals(part)) { isAlreadyInList = true; break; } } if (!isAlreadyInList) { if (firstIteration) { res = res + part; firstIteration = false; } else { res = res + Const.LIST_DELIMITER + part; } } } } else { res = list; } } return res; } /** * This method evaluates if element is in a list separated by list delimiter e.g. ', '. * @param elem The given element for searching * @param list The list that contains elements * @return true if in list */ public String[] getMailArray(String list) { String[] mailArray = {"None"}; if (list != null) { if (list.contains(Const.LIST_DELIMITER)) { mailArray = list.split(Const.LIST_DELIMITER); } else { mailArray[0] = list; } } return mailArray; } /** * This method converts string array to a string. * @param arr * @return string value */ public String convertStringArrayToString(String[] arr) { StringBuilder builder = new StringBuilder(); for(String s : arr) { builder.append(s); } return builder.toString(); } /** * This class reads text from a given text file. * @param fileName * @return string value */ public String readTextFile(String fileName) { String res = ""; try { Logger.debug("template path: " + fileName); BufferedReader br = new BufferedReader(new FileReader(fileName)); try { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append(System.getProperty("line.separator")); line = br.readLine(); } res = sb.toString(); } finally { br.close(); } } catch (Exception e) { Logger.error("read text file error: " + e); } return res; } /** * This method creates a web request for passed parameter, processes a call and returns * a server response. * @param resourceUrl The web site URL * @param target The target string in site content * @return target row */ public String buildWebRequestByUrl(String resourceUrl, String target) { String res = ""; try { URL github = new URL(resourceUrl); URLConnection yc = github.openConnection(); BufferedReader in = new BufferedReader( new InputStreamReader( yc.getInputStream())); while ((res = in.readLine()) != null) { if (res.contains(target)) { break; } } in.close(); } catch (MalformedURLException e) { Logger.debug("Reading last github hash: " + e); } catch (Exception e) { Logger.debug("Reading last github hash: " + e); } return res; } /** * This method presents boolean value as sting in a view. * @param value The boolean value * @return value as a string */ public String showBooleanAsString(boolean value) { String res = Const.NO; if (value) { res = Const.YES; } return res; } /** * This method checks whether given string is * a numeric value. * @param str * @return true if numeric */ public boolean isNumeric(String str) { try { Double.parseDouble(str); String regex = "[0-9]+"; if (str.matches(regex) == false) { return false; } } catch (NumberFormatException nfe) { return false; } return true; } /** * This method checks whether given string is * a numeric value of type Long. * @param str * @return true if numeric */ public boolean isNumericLong(String str) { try { Long.parseLong(str); } catch (NumberFormatException nfe) { return false; } return true; } /** * Replace domain field names by GUI field names * @param fields * @return */ public String showMissingFields(String fields) { if (fields != null && fields.length() > 0) { // for (Map.Entry<String, String> entry : Const.guiMap.entrySet()) { // if (fields.contains(entry.getKey())) { // fields = fields.replace(entry.getKey(), entry.getValue()); } return fields; } /** * Replace domain field name by GUI field name * @param fields * @return */ public String showMissingField(String field) { String res = field; if (field != null && field.length() > 0) { // res = Const.guiMap.get(field); } return res; } /** * This method cuts only the first selected value in a string list separated by comma. * @param str The string list * @return first value */ public String cutFirstSelection(String str) { String res = str; if (str != null && str.contains(Const.COMMA)) { int commaPos = str.indexOf(Const.COMMA); res = str.substring(0, commaPos - 1); } return res; } /** * This method removes associations from join table in database * for given table name and id in the case of ManyToMany association. * @param tableName * @param id */ public void removeAssociationFromDb(String tableName, String columnName, Long id) { SqlUpdate removeOldAssociation = Ebean.createSqlUpdate("DELETE FROM " + tableName + " WHERE " + columnName + " = " + id); removeOldAssociation.execute(); } public String formatSqlTimestamp(Timestamp timestamp) { if (timestamp != null) { String formatted = new SimpleDateFormat("E dd MMM yyyy HH:mm:ss ").format(timestamp); return formatted; } return ""; } public String convertPGIntervalToDate(Object object) { PGInterval pgInterval = (PGInterval)object; int years = pgInterval.getYears(); int months = pgInterval.getMonths(); int days = pgInterval.getDays(); int hours = pgInterval.getHours(); int minutes = pgInterval.getMinutes(); double seconds = pgInterval.getSeconds(); StringBuilder builder = new StringBuilder(""); if (years > 0) builder.append(years + " years "); if (months > 0) builder.append(months + " months "); if (days > 0) builder.append(days + " days " ); if (hours > 0) builder.append(hours + " hours "); if (minutes > 0) builder.append(minutes + " minutes "); if (seconds > 0) builder.append(Math.round(seconds) + " seconds "); return builder.toString(); } public Date convertDate(String dateText) throws ParseException { Date date = null; if (StringUtils.isNotEmpty(dateText)) { DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); date = formatter.parse(dateText); } return date; } public Date getDateFromSeconds(Long seconds) { Date date = null; if (seconds != null) { date = new Date(seconds*1000L); } return date; } public Date getDateFromLongValue(String dateValue) throws ParseException { Date date = null; if (StringUtils.isNotEmpty(dateValue)) { // 20090617 083042 DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); date = formatter.parse(dateValue); } return date; } public Set<String> getVaryingUrls(String url) { Set<String> varyingUrls = new HashSet<String>(); // remove all slashes if (url.endsWith("/")) { url = removeSlash(url); } String http = convertHttpToHttps(url); varyingUrls.add(http); String httpSlash = addSlash(http); varyingUrls.add(httpSlash); String httpNoWww = removeWww(http); varyingUrls.add(httpNoWww); String httpNoWwwSlash = addSlash(httpNoWww); varyingUrls.add(httpNoWwwSlash); String httpWww = addWww(http); varyingUrls.add(httpWww); String httpWwwSlash = addSlash(httpWww); varyingUrls.add(httpWwwSlash); String https = convertHttpsToHttp(url); varyingUrls.add(https); String httpsSlash = addSlash(https); varyingUrls.add(httpsSlash); String httpsNoWww = removeWww(https); varyingUrls.add(httpsNoWww); String httpsNoWwwSlash = addSlash(httpsNoWww); varyingUrls.add(httpsNoWwwSlash); String httpsWww = addWww(https); varyingUrls.add(httpsWww); String httpsWwwSlash = addSlash(httpsWww); varyingUrls.add(httpsWwwSlash); return varyingUrls; } private String removeSlash(String url) { return url.substring(0, url.length()-1); } private String convertHttpToHttps(String url) { return url.replace("http: } private String convertHttpsToHttp(String url) { return url.replace("https: } private String addSlash(String url) { return url + "/"; } private String removeWww(String url) { return url.replace("www.", ""); } private String addWww(String url) { if (!url.contains("www.")) { StringBuilder builder = new StringBuilder(url); int offset = 7; if (url.startsWith("https: offset = 8; } builder.insert(offset, "www."); return builder.toString(); } return url; } public boolean validUrl(String url) { String urlRegex = "^((http(s?))\\://)?(www.|[a-zA-Z0-9].)[a-zA-Z0-9\\-\\.]+\\.*(\\:[0-9]+)*(/($|[a-zA-Z0-9\\.\\,\\;\\?\\:\\(\\)\\@\\#\\!\\'\\\\\\+&amp;%\\$#\\=~_\\-]+))*$"; return url.matches(urlRegex); } public String convertToDateTime(Date date) { String formatted = null; if (date != null) { DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); formatted = dateFormat.format(date); } return formatted; } public String convertToDateTimeUTC(Date date) { String formatted = null; if (date != null) { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); // "yyyy-MM-dd'T'HH:mm:ss.SSSZ" 2001-07-04T12:08:56.235-0700 dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); formatted = dateFormat.format(date); } return formatted; } }
package org.qoders.easywallet.domain; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; /** * * @author Bisoo * */ @Entity(name="WalletGroup") @Table(name="wallet_group") public class Group { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; @Column(nullable=false, length=255) private String title; @ManyToOne private User owner; @ManyToMany(fetch=FetchType.EAGER) private List<User> members; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public User getOwner() { return owner; } public void setOwner(User owner) { this.owner = owner; } public List<User> getMembers() { return members; } public void setMembers(List<User> members) { this.members = members; } public void addMember(User user){ this.members.add(user); } public String toString(){ return this.getTitle(); } }
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.geom.Ellipse2D; import java.awt.geom.Rectangle2D; import java.util.ArrayDeque; import javax.swing.BoxLayout; import javax.swing.JLabel; import javax.swing.JPanel; public class Game extends JPanel implements KeyListener { private static final long serialVersionUID = 469989049178129651L; protected static final int LASER_COOLDOWN = 200; protected static final int WORD_DISPLAY_HEIGHT = 40; public ArrayDeque<WorldObject> objects; private Context ctx; private JLabel wordDisplay; private WorldObject cannon; private boolean cmdLeft; private boolean cmdRight; private boolean cmdShoot; private long timeLastShot; private Direction direction; Game() { cmdLeft = false; cmdRight = false; timeLastShot = 0; direction = Direction.NEUTRAL; wordDisplay = new JLabel(); objects = new ArrayDeque<>(); cannon = new WorldObject(); setLayout(new BorderLayout()); setBackground(Color.WHITE); objects.add(cannon); //cannon.addShape(new Rectangle2D.Double(30, 40, 100, 20)); cannon.addShape(new Rectangle2D.Double(30, 40, 100, 20)).color( new Color(0x60, 0x7D, 0x8B)); Double[] center = cannon.addShape(new Ellipse2D.Double(0, 0, 100, 100)).color(new Color(0x9E, 0x9E, 0x9E)) .center(); cannon.setCenter(center); cannon.getTransform().translate(590, 660 - WORD_DISPLAY_HEIGHT); cannon.setRotation(-Math.PI / 2); JPanel wordPanel = new JPanel(); wordPanel.setLayout(new BoxLayout(wordPanel, BoxLayout.X_AXIS)); wordPanel.setPreferredSize(new Dimension(1280, WORD_DISPLAY_HEIGHT)); add(wordPanel, BorderLayout.SOUTH); wordPanel.add(wordDisplay); } @Override public void paintComponent(Graphics graphics) { super.paintComponent(graphics); Graphics2D g = (Graphics2D) graphics; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); objects.forEach((o) -> { o.render(g); }); } public void tick() { // decay laser beam objects.removeIf(o -> o instanceof LaserBeam && ((LaserBeam) o).dead()); // travel laser beam objects.forEach(o -> { if (o instanceof LaserBeam) { ((LaserBeam) o).update(); } }); if (cmdShoot && System.currentTimeMillis() - timeLastShot > LASER_COOLDOWN) { Double[] center = cannon.getCenter(); // Don't mutate center Double[] position = { center[0] + cannon.getTransform().getTranslateX(), center[1] + cannon.getTransform().getTranslateY() }; objects.addFirst(new LaserBeam(cannon.getRotation(), position)); timeLastShot = System.currentTimeMillis(); } if (direction == Direction.LEFT && cannon.getRotation() > -Math.PI) { cannon.rotate(-Math.PI/ Context.TICK); } else if (direction == Direction.RIGHT && cannon.getRotation() < 0) { cannon.rotate(Math.PI/ Context.TICK); } if (this.isVisible()) { repaint(); } } public Context getContext() { return ctx; } public void setContext(Context ctx) { this.ctx = ctx; } @Override public void keyTyped(KeyEvent e) { // if (!this.isVisible()) { // return; } @Override public void keyPressed(KeyEvent e) { if (!this.isVisible()) { return; } switch (e.getKeyCode()) { case KeyEvent.VK_LEFT: cmdLeft = true; direction = Direction.LEFT; break; case KeyEvent.VK_RIGHT: cmdRight = true; direction = Direction.RIGHT; break; case KeyEvent.VK_SPACE: cmdShoot = true; break; } } @Override public void keyReleased(KeyEvent e) { if (!this.isVisible()) { return; } switch (e.getKeyCode()) { case KeyEvent.VK_LEFT: cmdLeft = false; direction = cmdRight ? Direction.RIGHT : Direction.NEUTRAL; break; case KeyEvent.VK_RIGHT: cmdRight = false; direction = cmdLeft ? Direction.LEFT : Direction.NEUTRAL; break; case KeyEvent.VK_SPACE: cmdShoot = false; break; } } private enum Direction { RIGHT, NEUTRAL, LEFT } }
package org.simplemc.commands; import com.sk89q.squirrelid.Profile; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.simplemc.Account; import org.simplemc.SimpleEconomy; import java.util.HashMap; import java.util.UUID; public class MoneyCommand implements CommandExecutor { protected final SimpleEconomy economy; public MoneyCommand(SimpleEconomy economy) { this.economy = economy; } @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] args) { boolean isHandled = false; if (args.length >= 1) { try { SubCommand sub = SubCommand.valueOf(args[0].toUpperCase()); isHandled = true; if (args.length >= sub.minArgs && args.length <= sub.maxArgs) { sub.execute(economy, commandSender, args); } else { commandSender.sendMessage(economy.formatPhrase("error.syntax.base", economy.formatPhrase("error.syntax." + sub.name().toLowerCase()))); } } catch (IllegalArgumentException e) { commandSender.sendMessage(economy.formatPhrase("error.subcommand.notfound")); } } return isHandled; } protected static void sendBalance(SimpleEconomy economy, CommandSender commandSender, String name, Double amount) { Profile profile = economy.getProfileFromName(name); if (profile != null) { Account sender = economy.getAccount(((Player) commandSender).getUniqueId()); Account reciver = economy.getAccount(profile.getUniqueId()); if (sender.getBalance() - amount <= 0) { commandSender.sendMessage(economy.formatPhrase("error.balance.toolow")); } else if (sender.getUuid().equals(reciver.getUuid())) { commandSender.sendMessage(economy.formatPhrase("error.player.self")); } else { sender.setBalance(sender.getBalance() - amount); sender.save(); reciver.setBalance(reciver.getBalance() + amount); reciver.save(); commandSender.sendMessage(economy.formatPhrase("balance.send", amount, profile.getName())); } } else { commandSender.sendMessage(economy.formatPhrase("error.player.notfound", name)); } } protected static void giveBalance(SimpleEconomy economy, CommandSender sender, String name, Double amount) { Profile profile = economy.getProfileFromName(name); if (profile != null) { Account account = economy.getAccount(profile.getUniqueId()); account.setBalance(account.getBalance() + amount); account.save(); sender.sendMessage(economy.formatPhrase("balance.give", amount, profile.getName())); } else { sender.sendMessage(economy.formatPhrase("error.player.notfound", name)); } } protected static void takeBalance(SimpleEconomy economy, CommandSender sender, String name, Double amount) { Profile profile = economy.getProfileFromName(name); if (profile != null) { Account account = economy.getAccount(profile.getUniqueId()); account.setBalance(account.getBalance() - amount); account.save(); sender.sendMessage(economy.formatPhrase("balance.take", amount, profile.getName())); } else { sender.sendMessage(economy.formatPhrase("error.player.notfound", name)); } } protected static void setBalance(SimpleEconomy economy, CommandSender sender, String name, Double amount) { if (name != null) { Profile profile = economy.getProfileFromName(name); if (profile != null) { Account account = economy.getAccount(profile.getUniqueId()); account.setBalance(amount); account.save(); sender.sendMessage(economy.formatPhrase("balance.set.other", profile.getName(), account.getBalance())); } else { sender.sendMessage(economy.formatPhrase("error.player.notfound", name)); } } else { Account account = economy.getAccount(((Player) sender).getUniqueId()); account.setBalance(amount); account.save(); sender.sendMessage(economy.formatPhrase("balance.set.self", account.getBalance())); } } protected static void getBalance(SimpleEconomy economy, CommandSender sender, String name) { if (name == null) { Account account = economy.getAccount(((Player) sender).getUniqueId()); sender.sendMessage(economy.formatPhrase("balance.get.self", account.getBalance())); } else { Profile profile = economy.getProfileFromName(name); if (profile != null) { Account account = economy.getAccount(profile.getUniqueId()); sender.sendMessage(economy.formatPhrase("balance.get.other", profile.getName(), account.getBalance())); } else { sender.sendMessage(economy.formatPhrase("error.player.notfound", name)); } } } } enum SubCommand { GET(1, 2) { @Override public void execute(SimpleEconomy economy, CommandSender sender, String... args) { if (args.length == 2) { MoneyCommand.getBalance(economy, sender, args[1]); } else { MoneyCommand.getBalance(economy, sender, null); } } }, SET(2, 3) { @Override public void execute(SimpleEconomy economy, CommandSender sender, String... args) { if (args.length == 2) { MoneyCommand.setBalance(economy, sender, null, Double.parseDouble(args[1])); } else if (args.length == 3) { MoneyCommand.setBalance(economy, sender, args[1], Double.parseDouble(args[2])); } } }, GIVE(3,3) { @Override public void execute(SimpleEconomy economy, CommandSender sender, String... args) { MoneyCommand.giveBalance(economy, sender, args[1], Double.parseDouble(args[2])); } }, TAKE(3, 3) { @Override public void execute(SimpleEconomy economy, CommandSender sender, String... args) { MoneyCommand.takeBalance(economy, sender, args[1], Double.parseDouble(args[2])); } }, SEND(3, 3) { @Override public void execute(SimpleEconomy economy, CommandSender sender, String... args) { MoneyCommand.sendBalance(economy, sender, args[1], Double.parseDouble(args[2])); } }, TOP { @Override public void execute(SimpleEconomy economy, CommandSender sender, String... args) { HashMap<UUID, Double> top = economy.getDatabaseManager().getTop(10); top.entrySet().stream().map(x -> { Profile profile = economy.getProfileFromUUID(x.getKey()); if (profile != null) { return String.format("%s - %f", profile.getName(), x.getValue()); } else { return ""; } }).filter(x -> !x.isEmpty()).forEach(sender::sendMessage); } }, HELP { @Override public void execute(SimpleEconomy economy, CommandSender sender, String... args) { sender.sendMessage(economy.formatPhrase("help")); } }; final int minArgs; // (minimum) number of arguments subcommand expects final int maxArgs; // (maximum) number of arguments subcommand expects /** * Create subcommand * * @param minArgs (minimun) number of arguments subcommand expects * @param maxArgs (maximum) number of arguments subcommand expects */ SubCommand(int minArgs, int maxArgs) { this.minArgs = minArgs; this.maxArgs = maxArgs; } /** * Default to no required arguments */ SubCommand() { this(1, 1); } public abstract void execute(SimpleEconomy economy, CommandSender sender, String... args); }