repo_name
stringlengths 7
104
| file_path
stringlengths 13
198
| context
stringlengths 67
7.15k
| import_statement
stringlengths 16
4.43k
| code
stringlengths 40
6.98k
| prompt
stringlengths 227
8.27k
| next_line
stringlengths 8
795
|
---|---|---|---|---|---|---|
googleapis/java-pubsublite-spark | samples/snippets/src/main/java/pubsublite/spark/ReadResults.java | // Path: samples/snippets/src/main/java/pubsublite/spark/AdminUtils.java
// public static Queue<PubsubMessage> subscriberExample(
// String cloudRegion, char zoneId, long projectNumber, String subscriptionId)
// throws ApiException {
// // Sample has at most 200 messages.
// Queue<PubsubMessage> result = new ArrayBlockingQueue<>(1000);
//
// SubscriptionPath subscriptionPath =
// SubscriptionPath.newBuilder()
// .setLocation(CloudZone.of(CloudRegion.of(cloudRegion), zoneId))
// .setProject(ProjectNumber.of(projectNumber))
// .setName(SubscriptionName.of(subscriptionId))
// .build();
//
// MessageReceiver receiver =
// (PubsubMessage message, AckReplyConsumer consumer) -> {
// result.add(message);
// consumer.ack();
// };
// FlowControlSettings flowControlSettings =
// FlowControlSettings.builder()
// .setBytesOutstanding(10 * 1024 * 1024L)
// .setMessagesOutstanding(1000L)
// .build();
//
// SubscriberSettings subscriberSettings =
// SubscriberSettings.newBuilder()
// .setSubscriptionPath(subscriptionPath)
// .setReceiver(receiver)
// .setPerPartitionFlowControlSettings(flowControlSettings)
// .build();
//
// Subscriber subscriber = Subscriber.create(subscriberSettings);
//
// // Start the subscriber. Upon successful starting, its state will become RUNNING.
// subscriber.startAsync().awaitRunning();
//
// try {
// System.out.println(subscriber.state());
// // Wait 90 seconds for the subscriber to reach TERMINATED state. If it encounters
// // unrecoverable errors before then, its state will change to FAILED and an
// // IllegalStateException will be thrown.
// subscriber.awaitTerminated(90, TimeUnit.SECONDS);
// } catch (TimeoutException t) {
// // Shut down the subscriber. This will change the state of the subscriber to TERMINATED.
// subscriber.stopAsync().awaitTerminated();
// System.out.println("Subscriber is shut down: " + subscriber.state());
// }
//
// return result;
// }
| import static pubsublite.spark.AdminUtils.subscriberExample;
import java.util.Map; | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package pubsublite.spark;
public class ReadResults {
private static final String REGION = "REGION";
private static final String ZONE_ID = "ZONE_ID";
private static final String DESTINATION_SUBSCRIPTION_ID = "DESTINATION_SUBSCRIPTION_ID";
private static final String PROJECT_NUMBER = "PROJECT_NUMBER";
public static void main(String[] args) {
Map<String, String> env =
CommonUtils.getAndValidateEnvVars(
REGION, ZONE_ID, DESTINATION_SUBSCRIPTION_ID, PROJECT_NUMBER);
String cloudRegion = env.get(REGION);
char zoneId = env.get(ZONE_ID).charAt(0);
String destinationSubscriptionId = env.get(DESTINATION_SUBSCRIPTION_ID);
long projectNumber = Long.parseLong(env.get(PROJECT_NUMBER));
System.out.println("Results from Pub/Sub Lite:"); | // Path: samples/snippets/src/main/java/pubsublite/spark/AdminUtils.java
// public static Queue<PubsubMessage> subscriberExample(
// String cloudRegion, char zoneId, long projectNumber, String subscriptionId)
// throws ApiException {
// // Sample has at most 200 messages.
// Queue<PubsubMessage> result = new ArrayBlockingQueue<>(1000);
//
// SubscriptionPath subscriptionPath =
// SubscriptionPath.newBuilder()
// .setLocation(CloudZone.of(CloudRegion.of(cloudRegion), zoneId))
// .setProject(ProjectNumber.of(projectNumber))
// .setName(SubscriptionName.of(subscriptionId))
// .build();
//
// MessageReceiver receiver =
// (PubsubMessage message, AckReplyConsumer consumer) -> {
// result.add(message);
// consumer.ack();
// };
// FlowControlSettings flowControlSettings =
// FlowControlSettings.builder()
// .setBytesOutstanding(10 * 1024 * 1024L)
// .setMessagesOutstanding(1000L)
// .build();
//
// SubscriberSettings subscriberSettings =
// SubscriberSettings.newBuilder()
// .setSubscriptionPath(subscriptionPath)
// .setReceiver(receiver)
// .setPerPartitionFlowControlSettings(flowControlSettings)
// .build();
//
// Subscriber subscriber = Subscriber.create(subscriberSettings);
//
// // Start the subscriber. Upon successful starting, its state will become RUNNING.
// subscriber.startAsync().awaitRunning();
//
// try {
// System.out.println(subscriber.state());
// // Wait 90 seconds for the subscriber to reach TERMINATED state. If it encounters
// // unrecoverable errors before then, its state will change to FAILED and an
// // IllegalStateException will be thrown.
// subscriber.awaitTerminated(90, TimeUnit.SECONDS);
// } catch (TimeoutException t) {
// // Shut down the subscriber. This will change the state of the subscriber to TERMINATED.
// subscriber.stopAsync().awaitTerminated();
// System.out.println("Subscriber is shut down: " + subscriber.state());
// }
//
// return result;
// }
// Path: samples/snippets/src/main/java/pubsublite/spark/ReadResults.java
import static pubsublite.spark.AdminUtils.subscriberExample;
import java.util.Map;
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package pubsublite.spark;
public class ReadResults {
private static final String REGION = "REGION";
private static final String ZONE_ID = "ZONE_ID";
private static final String DESTINATION_SUBSCRIPTION_ID = "DESTINATION_SUBSCRIPTION_ID";
private static final String PROJECT_NUMBER = "PROJECT_NUMBER";
public static void main(String[] args) {
Map<String, String> env =
CommonUtils.getAndValidateEnvVars(
REGION, ZONE_ID, DESTINATION_SUBSCRIPTION_ID, PROJECT_NUMBER);
String cloudRegion = env.get(REGION);
char zoneId = env.get(ZONE_ID).charAt(0);
String destinationSubscriptionId = env.get(DESTINATION_SUBSCRIPTION_ID);
long projectNumber = Long.parseLong(env.get(PROJECT_NUMBER));
System.out.println("Results from Pub/Sub Lite:"); | subscriberExample(cloudRegion, zoneId, projectNumber, destinationSubscriptionId) |
googleapis/java-pubsublite-spark | src/test/java/com/google/cloud/pubsublite/spark/internal/MultiPartitionCommitterImplTest.java | // Path: src/test/java/com/google/cloud/pubsublite/spark/TestingUtils.java
// public static PslSourceOffset createPslSourceOffset(long... offsets) {
// Map<Partition, Offset> map = new HashMap<>();
// int idx = 0;
// for (long offset : offsets) {
// map.put(Partition.of(idx++), Offset.of(offset));
// }
// return PslSourceOffset.builder().partitionOffsetMap(map).build();
// }
//
// Path: src/main/java/com/google/cloud/pubsublite/spark/PslSourceOffset.java
// @AutoValue
// public abstract class PslSourceOffset {
//
// public abstract Map<Partition, Offset> partitionOffsetMap();
//
// public static Builder builder() {
// return new AutoValue_PslSourceOffset.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder partitionOffsetMap(Map<Partition, Offset> partitionOffsetMap);
//
// public abstract PslSourceOffset build();
// }
// }
| import static com.google.cloud.pubsublite.spark.TestingUtils.createPslSourceOffset;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
import com.google.api.core.SettableApiFuture;
import com.google.cloud.pubsublite.*;
import com.google.cloud.pubsublite.internal.wire.Committer;
import com.google.cloud.pubsublite.spark.PslSourceOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.mockito.ArgumentCaptor; | Committer committer = mock(Committer.class);
when(committer.startAsync())
.thenReturn(committer)
.thenThrow(new IllegalStateException("should only init once"));
when(committer.commitOffset(eq(Offset.of(10L)))).thenReturn(SettableApiFuture.create());
committerList.add(committer);
}
ScheduledExecutorService mockExecutor = mock(ScheduledExecutorService.class);
ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
when(mockExecutor.scheduleWithFixedDelay(
taskCaptor.capture(), anyLong(), anyLong(), any(TimeUnit.class)))
.thenReturn(null);
MultiPartitionCommitterImpl multiCommitter =
new MultiPartitionCommitterImpl(
initialPartitions, p -> committerList.get((int) p.value()), mockExecutor);
task = taskCaptor.getValue();
return multiCommitter;
}
private MultiPartitionCommitterImpl createCommitter(int initialPartitions) {
return createCommitter(initialPartitions, initialPartitions);
}
@Test
public void testCommit() {
MultiPartitionCommitterImpl multiCommitter = createCommitter(2);
verify(committerList.get(0)).startAsync();
verify(committerList.get(1)).startAsync();
| // Path: src/test/java/com/google/cloud/pubsublite/spark/TestingUtils.java
// public static PslSourceOffset createPslSourceOffset(long... offsets) {
// Map<Partition, Offset> map = new HashMap<>();
// int idx = 0;
// for (long offset : offsets) {
// map.put(Partition.of(idx++), Offset.of(offset));
// }
// return PslSourceOffset.builder().partitionOffsetMap(map).build();
// }
//
// Path: src/main/java/com/google/cloud/pubsublite/spark/PslSourceOffset.java
// @AutoValue
// public abstract class PslSourceOffset {
//
// public abstract Map<Partition, Offset> partitionOffsetMap();
//
// public static Builder builder() {
// return new AutoValue_PslSourceOffset.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder partitionOffsetMap(Map<Partition, Offset> partitionOffsetMap);
//
// public abstract PslSourceOffset build();
// }
// }
// Path: src/test/java/com/google/cloud/pubsublite/spark/internal/MultiPartitionCommitterImplTest.java
import static com.google.cloud.pubsublite.spark.TestingUtils.createPslSourceOffset;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
import com.google.api.core.SettableApiFuture;
import com.google.cloud.pubsublite.*;
import com.google.cloud.pubsublite.internal.wire.Committer;
import com.google.cloud.pubsublite.spark.PslSourceOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
Committer committer = mock(Committer.class);
when(committer.startAsync())
.thenReturn(committer)
.thenThrow(new IllegalStateException("should only init once"));
when(committer.commitOffset(eq(Offset.of(10L)))).thenReturn(SettableApiFuture.create());
committerList.add(committer);
}
ScheduledExecutorService mockExecutor = mock(ScheduledExecutorService.class);
ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
when(mockExecutor.scheduleWithFixedDelay(
taskCaptor.capture(), anyLong(), anyLong(), any(TimeUnit.class)))
.thenReturn(null);
MultiPartitionCommitterImpl multiCommitter =
new MultiPartitionCommitterImpl(
initialPartitions, p -> committerList.get((int) p.value()), mockExecutor);
task = taskCaptor.getValue();
return multiCommitter;
}
private MultiPartitionCommitterImpl createCommitter(int initialPartitions) {
return createCommitter(initialPartitions, initialPartitions);
}
@Test
public void testCommit() {
MultiPartitionCommitterImpl multiCommitter = createCommitter(2);
verify(committerList.get(0)).startAsync();
verify(committerList.get(1)).startAsync();
| PslSourceOffset offset = createPslSourceOffset(10L, 8L); |
googleapis/java-pubsublite-spark | src/test/java/com/google/cloud/pubsublite/spark/internal/MultiPartitionCommitterImplTest.java | // Path: src/test/java/com/google/cloud/pubsublite/spark/TestingUtils.java
// public static PslSourceOffset createPslSourceOffset(long... offsets) {
// Map<Partition, Offset> map = new HashMap<>();
// int idx = 0;
// for (long offset : offsets) {
// map.put(Partition.of(idx++), Offset.of(offset));
// }
// return PslSourceOffset.builder().partitionOffsetMap(map).build();
// }
//
// Path: src/main/java/com/google/cloud/pubsublite/spark/PslSourceOffset.java
// @AutoValue
// public abstract class PslSourceOffset {
//
// public abstract Map<Partition, Offset> partitionOffsetMap();
//
// public static Builder builder() {
// return new AutoValue_PslSourceOffset.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder partitionOffsetMap(Map<Partition, Offset> partitionOffsetMap);
//
// public abstract PslSourceOffset build();
// }
// }
| import static com.google.cloud.pubsublite.spark.TestingUtils.createPslSourceOffset;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
import com.google.api.core.SettableApiFuture;
import com.google.cloud.pubsublite.*;
import com.google.cloud.pubsublite.internal.wire.Committer;
import com.google.cloud.pubsublite.spark.PslSourceOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.mockito.ArgumentCaptor; | Committer committer = mock(Committer.class);
when(committer.startAsync())
.thenReturn(committer)
.thenThrow(new IllegalStateException("should only init once"));
when(committer.commitOffset(eq(Offset.of(10L)))).thenReturn(SettableApiFuture.create());
committerList.add(committer);
}
ScheduledExecutorService mockExecutor = mock(ScheduledExecutorService.class);
ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
when(mockExecutor.scheduleWithFixedDelay(
taskCaptor.capture(), anyLong(), anyLong(), any(TimeUnit.class)))
.thenReturn(null);
MultiPartitionCommitterImpl multiCommitter =
new MultiPartitionCommitterImpl(
initialPartitions, p -> committerList.get((int) p.value()), mockExecutor);
task = taskCaptor.getValue();
return multiCommitter;
}
private MultiPartitionCommitterImpl createCommitter(int initialPartitions) {
return createCommitter(initialPartitions, initialPartitions);
}
@Test
public void testCommit() {
MultiPartitionCommitterImpl multiCommitter = createCommitter(2);
verify(committerList.get(0)).startAsync();
verify(committerList.get(1)).startAsync();
| // Path: src/test/java/com/google/cloud/pubsublite/spark/TestingUtils.java
// public static PslSourceOffset createPslSourceOffset(long... offsets) {
// Map<Partition, Offset> map = new HashMap<>();
// int idx = 0;
// for (long offset : offsets) {
// map.put(Partition.of(idx++), Offset.of(offset));
// }
// return PslSourceOffset.builder().partitionOffsetMap(map).build();
// }
//
// Path: src/main/java/com/google/cloud/pubsublite/spark/PslSourceOffset.java
// @AutoValue
// public abstract class PslSourceOffset {
//
// public abstract Map<Partition, Offset> partitionOffsetMap();
//
// public static Builder builder() {
// return new AutoValue_PslSourceOffset.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder partitionOffsetMap(Map<Partition, Offset> partitionOffsetMap);
//
// public abstract PslSourceOffset build();
// }
// }
// Path: src/test/java/com/google/cloud/pubsublite/spark/internal/MultiPartitionCommitterImplTest.java
import static com.google.cloud.pubsublite.spark.TestingUtils.createPslSourceOffset;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
import com.google.api.core.SettableApiFuture;
import com.google.cloud.pubsublite.*;
import com.google.cloud.pubsublite.internal.wire.Committer;
import com.google.cloud.pubsublite.spark.PslSourceOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
Committer committer = mock(Committer.class);
when(committer.startAsync())
.thenReturn(committer)
.thenThrow(new IllegalStateException("should only init once"));
when(committer.commitOffset(eq(Offset.of(10L)))).thenReturn(SettableApiFuture.create());
committerList.add(committer);
}
ScheduledExecutorService mockExecutor = mock(ScheduledExecutorService.class);
ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
when(mockExecutor.scheduleWithFixedDelay(
taskCaptor.capture(), anyLong(), anyLong(), any(TimeUnit.class)))
.thenReturn(null);
MultiPartitionCommitterImpl multiCommitter =
new MultiPartitionCommitterImpl(
initialPartitions, p -> committerList.get((int) p.value()), mockExecutor);
task = taskCaptor.getValue();
return multiCommitter;
}
private MultiPartitionCommitterImpl createCommitter(int initialPartitions) {
return createCommitter(initialPartitions, initialPartitions);
}
@Test
public void testCommit() {
MultiPartitionCommitterImpl multiCommitter = createCommitter(2);
verify(committerList.get(0)).startAsync();
verify(committerList.get(1)).startAsync();
| PslSourceOffset offset = createPslSourceOffset(10L, 8L); |
googleapis/java-pubsublite-spark | src/main/java/com/google/cloud/pubsublite/spark/PslDataWriter.java | // Path: src/main/java/com/google/cloud/pubsublite/spark/internal/PublisherFactory.java
// public interface PublisherFactory extends Serializable {
//
// Publisher<MessageMetadata> newPublisher();
// }
| import org.apache.spark.sql.sources.v2.writer.DataWriter;
import org.apache.spark.sql.sources.v2.writer.WriterCommitMessage;
import org.apache.spark.sql.types.StructType;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiService;
import com.google.cloud.pubsublite.MessageMetadata;
import com.google.cloud.pubsublite.internal.Publisher;
import com.google.cloud.pubsublite.spark.internal.PublisherFactory;
import com.google.common.flogger.GoogleLogger;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import javax.annotation.concurrent.GuardedBy;
import org.apache.spark.sql.catalyst.InternalRow; | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.pubsublite.spark;
public class PslDataWriter implements DataWriter<InternalRow> {
private static final GoogleLogger log = GoogleLogger.forEnclosingClass();
private final long partitionId, taskId, epochId;
private final StructType inputSchema; | // Path: src/main/java/com/google/cloud/pubsublite/spark/internal/PublisherFactory.java
// public interface PublisherFactory extends Serializable {
//
// Publisher<MessageMetadata> newPublisher();
// }
// Path: src/main/java/com/google/cloud/pubsublite/spark/PslDataWriter.java
import org.apache.spark.sql.sources.v2.writer.DataWriter;
import org.apache.spark.sql.sources.v2.writer.WriterCommitMessage;
import org.apache.spark.sql.types.StructType;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiService;
import com.google.cloud.pubsublite.MessageMetadata;
import com.google.cloud.pubsublite.internal.Publisher;
import com.google.cloud.pubsublite.spark.internal.PublisherFactory;
import com.google.common.flogger.GoogleLogger;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import javax.annotation.concurrent.GuardedBy;
import org.apache.spark.sql.catalyst.InternalRow;
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.pubsublite.spark;
public class PslDataWriter implements DataWriter<InternalRow> {
private static final GoogleLogger log = GoogleLogger.forEnclosingClass();
private final long partitionId, taskId, epochId;
private final StructType inputSchema; | private final PublisherFactory publisherFactory; |
googleapis/java-pubsublite-spark | src/main/java/com/google/cloud/pubsublite/spark/PslContinuousInputPartition.java | // Path: src/main/java/com/google/cloud/pubsublite/spark/internal/PartitionSubscriberFactory.java
// public interface PartitionSubscriberFactory extends Serializable {
// Subscriber newSubscriber(
// Partition partition, Offset offset, Consumer<List<SequencedMessage>> message_consumer)
// throws ApiException;
// }
| import static com.google.common.base.Preconditions.checkArgument;
import com.google.cloud.pubsublite.SubscriptionPath;
import com.google.cloud.pubsublite.cloudpubsub.FlowControlSettings;
import com.google.cloud.pubsublite.internal.BlockingPullSubscriberImpl;
import com.google.cloud.pubsublite.internal.CheckedApiException;
import com.google.cloud.pubsublite.spark.internal.PartitionSubscriberFactory;
import java.io.Serializable;
import org.apache.spark.sql.catalyst.InternalRow;
import org.apache.spark.sql.sources.v2.reader.ContinuousInputPartition;
import org.apache.spark.sql.sources.v2.reader.InputPartitionReader;
import org.apache.spark.sql.sources.v2.reader.streaming.PartitionOffset; | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.pubsublite.spark;
public class PslContinuousInputPartition
implements ContinuousInputPartition<InternalRow>, Serializable {
| // Path: src/main/java/com/google/cloud/pubsublite/spark/internal/PartitionSubscriberFactory.java
// public interface PartitionSubscriberFactory extends Serializable {
// Subscriber newSubscriber(
// Partition partition, Offset offset, Consumer<List<SequencedMessage>> message_consumer)
// throws ApiException;
// }
// Path: src/main/java/com/google/cloud/pubsublite/spark/PslContinuousInputPartition.java
import static com.google.common.base.Preconditions.checkArgument;
import com.google.cloud.pubsublite.SubscriptionPath;
import com.google.cloud.pubsublite.cloudpubsub.FlowControlSettings;
import com.google.cloud.pubsublite.internal.BlockingPullSubscriberImpl;
import com.google.cloud.pubsublite.internal.CheckedApiException;
import com.google.cloud.pubsublite.spark.internal.PartitionSubscriberFactory;
import java.io.Serializable;
import org.apache.spark.sql.catalyst.InternalRow;
import org.apache.spark.sql.sources.v2.reader.ContinuousInputPartition;
import org.apache.spark.sql.sources.v2.reader.InputPartitionReader;
import org.apache.spark.sql.sources.v2.reader.streaming.PartitionOffset;
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.pubsublite.spark;
public class PslContinuousInputPartition
implements ContinuousInputPartition<InternalRow>, Serializable {
| private final PartitionSubscriberFactory subscriberFactory; |
googleapis/java-pubsublite-spark | src/main/java/com/google/cloud/pubsublite/spark/internal/MultiPartitionCommitterImpl.java | // Path: src/main/java/com/google/cloud/pubsublite/spark/PslSourceOffset.java
// @AutoValue
// public abstract class PslSourceOffset {
//
// public abstract Map<Partition, Offset> partitionOffsetMap();
//
// public static Builder builder() {
// return new AutoValue_PslSourceOffset.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder partitionOffsetMap(Map<Partition, Offset> partitionOffsetMap);
//
// public abstract PslSourceOffset build();
// }
// }
| import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.annotation.concurrent.GuardedBy;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutureCallback;
import com.google.api.core.ApiFutures;
import com.google.cloud.pubsublite.Offset;
import com.google.cloud.pubsublite.Partition;
import com.google.cloud.pubsublite.internal.wire.Committer;
import com.google.cloud.pubsublite.spark.PslSourceOffset;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.flogger.GoogleLogger;
import com.google.common.util.concurrent.MoreExecutors;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set; | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.pubsublite.spark.internal;
/**
* A {@link MultiPartitionCommitter} that lazily adjusts for partition changes when {@link
* MultiPartitionCommitter#commit(PslSourceOffset)} is called.
*/
public class MultiPartitionCommitterImpl implements MultiPartitionCommitter {
private static final GoogleLogger log = GoogleLogger.forEnclosingClass();
private final CommitterFactory committerFactory;
@GuardedBy("this")
private final Map<Partition, Committer> committerMap = new HashMap<>();
@GuardedBy("this")
private final Set<Partition> partitionsCleanUp = new HashSet<>();
public MultiPartitionCommitterImpl(long topicPartitionCount, CommitterFactory committerFactory) {
this(
topicPartitionCount,
committerFactory,
MoreExecutors.getExitingScheduledExecutorService(new ScheduledThreadPoolExecutor(1)));
}
@VisibleForTesting
MultiPartitionCommitterImpl(
long topicPartitionCount,
CommitterFactory committerFactory,
ScheduledExecutorService executorService) {
this.committerFactory = committerFactory;
for (int i = 0; i < topicPartitionCount; i++) {
Partition p = Partition.of(i);
committerMap.put(p, createCommitter(p));
}
executorService.scheduleWithFixedDelay(this::cleanUpCommitterMap, 10, 10, TimeUnit.MINUTES);
}
@Override
public synchronized void close() {
committerMap.values().forEach(c -> c.stopAsync().awaitTerminated());
}
/** Adjust committerMap based on the partitions that needs to be committed. */ | // Path: src/main/java/com/google/cloud/pubsublite/spark/PslSourceOffset.java
// @AutoValue
// public abstract class PslSourceOffset {
//
// public abstract Map<Partition, Offset> partitionOffsetMap();
//
// public static Builder builder() {
// return new AutoValue_PslSourceOffset.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder partitionOffsetMap(Map<Partition, Offset> partitionOffsetMap);
//
// public abstract PslSourceOffset build();
// }
// }
// Path: src/main/java/com/google/cloud/pubsublite/spark/internal/MultiPartitionCommitterImpl.java
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.annotation.concurrent.GuardedBy;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutureCallback;
import com.google.api.core.ApiFutures;
import com.google.cloud.pubsublite.Offset;
import com.google.cloud.pubsublite.Partition;
import com.google.cloud.pubsublite.internal.wire.Committer;
import com.google.cloud.pubsublite.spark.PslSourceOffset;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.flogger.GoogleLogger;
import com.google.common.util.concurrent.MoreExecutors;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.pubsublite.spark.internal;
/**
* A {@link MultiPartitionCommitter} that lazily adjusts for partition changes when {@link
* MultiPartitionCommitter#commit(PslSourceOffset)} is called.
*/
public class MultiPartitionCommitterImpl implements MultiPartitionCommitter {
private static final GoogleLogger log = GoogleLogger.forEnclosingClass();
private final CommitterFactory committerFactory;
@GuardedBy("this")
private final Map<Partition, Committer> committerMap = new HashMap<>();
@GuardedBy("this")
private final Set<Partition> partitionsCleanUp = new HashSet<>();
public MultiPartitionCommitterImpl(long topicPartitionCount, CommitterFactory committerFactory) {
this(
topicPartitionCount,
committerFactory,
MoreExecutors.getExitingScheduledExecutorService(new ScheduledThreadPoolExecutor(1)));
}
@VisibleForTesting
MultiPartitionCommitterImpl(
long topicPartitionCount,
CommitterFactory committerFactory,
ScheduledExecutorService executorService) {
this.committerFactory = committerFactory;
for (int i = 0; i < topicPartitionCount; i++) {
Partition p = Partition.of(i);
committerMap.put(p, createCommitter(p));
}
executorService.scheduleWithFixedDelay(this::cleanUpCommitterMap, 10, 10, TimeUnit.MINUTES);
}
@Override
public synchronized void close() {
committerMap.values().forEach(c -> c.stopAsync().awaitTerminated());
}
/** Adjust committerMap based on the partitions that needs to be committed. */ | private synchronized void updateCommitterMap(PslSourceOffset offset) { |
googleapis/java-pubsublite-spark | src/main/java/com/google/cloud/pubsublite/spark/PslWriteDataSourceOptions.java | // Path: src/main/java/com/google/cloud/pubsublite/spark/internal/PslCredentialsProvider.java
// public class PslCredentialsProvider implements CredentialsProvider {
//
// private final Credentials credentials;
//
// public PslCredentialsProvider(@Nullable String credentialsKey) {
// this.credentials =
// credentialsKey != null
// ? createCredentialsFromKey(credentialsKey)
// : createDefaultCredentials();
// }
//
// private static Credentials createCredentialsFromKey(String key) {
// try {
// return GoogleCredentials.fromStream(new ByteArrayInputStream(Base64.decodeBase64(key)))
// .createScoped("https://www.googleapis.com/auth/cloud-platform");
// } catch (IOException e) {
// throw new UncheckedIOException("Failed to create Credentials from key", e);
// }
// }
//
// public static Credentials createDefaultCredentials() {
// try {
// return GoogleCredentials.getApplicationDefault()
// .createScoped("https://www.googleapis.com/auth/cloud-platform");
// } catch (IOException e) {
// throw new UncheckedIOException("Failed to create default Credentials", e);
// }
// }
//
// @Override
// public Credentials getCredentials() {
// return credentials;
// }
// }
| import static com.google.cloud.pubsublite.internal.ExtractStatus.toCanonical;
import static com.google.cloud.pubsublite.internal.wire.ServiceClients.addDefaultSettings;
import static com.google.cloud.pubsublite.internal.wire.ServiceClients.getCallContext;
import com.google.api.gax.rpc.ApiCallContext;
import com.google.api.gax.rpc.ApiException;
import com.google.auto.value.AutoValue;
import com.google.cloud.pubsublite.AdminClient;
import com.google.cloud.pubsublite.AdminClientSettings;
import com.google.cloud.pubsublite.MessageMetadata;
import com.google.cloud.pubsublite.Partition;
import com.google.cloud.pubsublite.TopicPath;
import com.google.cloud.pubsublite.cloudpubsub.PublisherSettings;
import com.google.cloud.pubsublite.internal.Publisher;
import com.google.cloud.pubsublite.internal.wire.PartitionCountWatchingPublisherSettings;
import com.google.cloud.pubsublite.internal.wire.PartitionPublisherFactory;
import com.google.cloud.pubsublite.internal.wire.PubsubContext;
import com.google.cloud.pubsublite.internal.wire.RoutingMetadata;
import com.google.cloud.pubsublite.internal.wire.SinglePartitionPublisherBuilder;
import com.google.cloud.pubsublite.spark.internal.PslCredentialsProvider;
import com.google.cloud.pubsublite.v1.AdminServiceClient;
import com.google.cloud.pubsublite.v1.AdminServiceSettings;
import com.google.cloud.pubsublite.v1.PublisherServiceClient;
import com.google.cloud.pubsublite.v1.PublisherServiceSettings;
import java.io.Serializable;
import javax.annotation.Nullable;
import org.apache.spark.sql.sources.v2.DataSourceOptions; | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.pubsublite.spark;
@AutoValue
public abstract class PslWriteDataSourceOptions implements Serializable {
@Nullable
public abstract String credentialsKey();
public abstract TopicPath topicPath();
public static Builder builder() {
return new AutoValue_PslWriteDataSourceOptions.Builder().setCredentialsKey(null);
}
@AutoValue.Builder
public abstract static class Builder {
public abstract PslWriteDataSourceOptions.Builder setCredentialsKey(String credentialsKey);
public abstract PslWriteDataSourceOptions.Builder setTopicPath(TopicPath topicPath);
public abstract PslWriteDataSourceOptions build();
}
public static PslWriteDataSourceOptions fromSparkDataSourceOptions(DataSourceOptions options) {
if (!options.get(Constants.TOPIC_CONFIG_KEY).isPresent()) {
throw new IllegalArgumentException(Constants.TOPIC_CONFIG_KEY + " is required.");
}
Builder builder = builder();
String topicPathVal = options.get(Constants.TOPIC_CONFIG_KEY).get();
try {
builder.setTopicPath(TopicPath.parse(topicPathVal));
} catch (ApiException e) {
throw new IllegalArgumentException("Unable to parse topic path " + topicPathVal, e);
}
options.get(Constants.CREDENTIALS_KEY_CONFIG_KEY).ifPresent(builder::setCredentialsKey);
return builder.build();
}
| // Path: src/main/java/com/google/cloud/pubsublite/spark/internal/PslCredentialsProvider.java
// public class PslCredentialsProvider implements CredentialsProvider {
//
// private final Credentials credentials;
//
// public PslCredentialsProvider(@Nullable String credentialsKey) {
// this.credentials =
// credentialsKey != null
// ? createCredentialsFromKey(credentialsKey)
// : createDefaultCredentials();
// }
//
// private static Credentials createCredentialsFromKey(String key) {
// try {
// return GoogleCredentials.fromStream(new ByteArrayInputStream(Base64.decodeBase64(key)))
// .createScoped("https://www.googleapis.com/auth/cloud-platform");
// } catch (IOException e) {
// throw new UncheckedIOException("Failed to create Credentials from key", e);
// }
// }
//
// public static Credentials createDefaultCredentials() {
// try {
// return GoogleCredentials.getApplicationDefault()
// .createScoped("https://www.googleapis.com/auth/cloud-platform");
// } catch (IOException e) {
// throw new UncheckedIOException("Failed to create default Credentials", e);
// }
// }
//
// @Override
// public Credentials getCredentials() {
// return credentials;
// }
// }
// Path: src/main/java/com/google/cloud/pubsublite/spark/PslWriteDataSourceOptions.java
import static com.google.cloud.pubsublite.internal.ExtractStatus.toCanonical;
import static com.google.cloud.pubsublite.internal.wire.ServiceClients.addDefaultSettings;
import static com.google.cloud.pubsublite.internal.wire.ServiceClients.getCallContext;
import com.google.api.gax.rpc.ApiCallContext;
import com.google.api.gax.rpc.ApiException;
import com.google.auto.value.AutoValue;
import com.google.cloud.pubsublite.AdminClient;
import com.google.cloud.pubsublite.AdminClientSettings;
import com.google.cloud.pubsublite.MessageMetadata;
import com.google.cloud.pubsublite.Partition;
import com.google.cloud.pubsublite.TopicPath;
import com.google.cloud.pubsublite.cloudpubsub.PublisherSettings;
import com.google.cloud.pubsublite.internal.Publisher;
import com.google.cloud.pubsublite.internal.wire.PartitionCountWatchingPublisherSettings;
import com.google.cloud.pubsublite.internal.wire.PartitionPublisherFactory;
import com.google.cloud.pubsublite.internal.wire.PubsubContext;
import com.google.cloud.pubsublite.internal.wire.RoutingMetadata;
import com.google.cloud.pubsublite.internal.wire.SinglePartitionPublisherBuilder;
import com.google.cloud.pubsublite.spark.internal.PslCredentialsProvider;
import com.google.cloud.pubsublite.v1.AdminServiceClient;
import com.google.cloud.pubsublite.v1.AdminServiceSettings;
import com.google.cloud.pubsublite.v1.PublisherServiceClient;
import com.google.cloud.pubsublite.v1.PublisherServiceSettings;
import java.io.Serializable;
import javax.annotation.Nullable;
import org.apache.spark.sql.sources.v2.DataSourceOptions;
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.pubsublite.spark;
@AutoValue
public abstract class PslWriteDataSourceOptions implements Serializable {
@Nullable
public abstract String credentialsKey();
public abstract TopicPath topicPath();
public static Builder builder() {
return new AutoValue_PslWriteDataSourceOptions.Builder().setCredentialsKey(null);
}
@AutoValue.Builder
public abstract static class Builder {
public abstract PslWriteDataSourceOptions.Builder setCredentialsKey(String credentialsKey);
public abstract PslWriteDataSourceOptions.Builder setTopicPath(TopicPath topicPath);
public abstract PslWriteDataSourceOptions build();
}
public static PslWriteDataSourceOptions fromSparkDataSourceOptions(DataSourceOptions options) {
if (!options.get(Constants.TOPIC_CONFIG_KEY).isPresent()) {
throw new IllegalArgumentException(Constants.TOPIC_CONFIG_KEY + " is required.");
}
Builder builder = builder();
String topicPathVal = options.get(Constants.TOPIC_CONFIG_KEY).get();
try {
builder.setTopicPath(TopicPath.parse(topicPathVal));
} catch (ApiException e) {
throw new IllegalArgumentException("Unable to parse topic path " + topicPathVal, e);
}
options.get(Constants.CREDENTIALS_KEY_CONFIG_KEY).ifPresent(builder::setCredentialsKey);
return builder.build();
}
| public PslCredentialsProvider getCredentialProvider() { |
googleapis/java-pubsublite-spark | src/main/java/com/google/cloud/pubsublite/spark/PslDataSource.java | // Path: src/main/java/com/google/cloud/pubsublite/spark/internal/CachedPartitionCountReader.java
// @ThreadSafe
// public class CachedPartitionCountReader implements PartitionCountReader {
// private final AdminClient adminClient;
// private final Supplier<Integer> supplier;
//
// public CachedPartitionCountReader(AdminClient adminClient, TopicPath topicPath) {
// this.adminClient = adminClient;
// this.supplier =
// Suppliers.memoizeWithExpiration(
// () -> PartitionLookupUtils.numPartitions(topicPath, adminClient), 1, TimeUnit.MINUTES);
// }
//
// @Override
// public void close() {
// adminClient.close();
// }
//
// public int getPartitionCount() {
// return supplier.get();
// }
// }
//
// Path: src/main/java/com/google/cloud/pubsublite/spark/internal/LimitingHeadOffsetReader.java
// public class LimitingHeadOffsetReader implements PerTopicHeadOffsetReader {
// private static final GoogleLogger log = GoogleLogger.forEnclosingClass();
//
// private final TopicStatsClient topicStatsClient;
// private final TopicPath topic;
// private final PartitionCountReader partitionCountReader;
// private final AsyncLoadingCache<Partition, Offset> cachedHeadOffsets;
//
// @VisibleForTesting
// public LimitingHeadOffsetReader(
// TopicStatsClient topicStatsClient,
// TopicPath topic,
// PartitionCountReader partitionCountReader,
// Ticker ticker) {
// this.topicStatsClient = topicStatsClient;
// this.topic = topic;
// this.partitionCountReader = partitionCountReader;
// this.cachedHeadOffsets =
// Caffeine.newBuilder()
// .ticker(ticker)
// .expireAfterWrite(1, TimeUnit.MINUTES)
// .buildAsync(this::loadHeadOffset);
// }
//
// private CompletableFuture<Offset> loadHeadOffset(Partition partition, Executor executor) {
//
// CompletableFuture<Offset> result = new CompletableFuture<>();
// ApiFutures.addCallback(
// topicStatsClient.computeHeadCursor(topic, partition),
// new ApiFutureCallback<Cursor>() {
// @Override
// public void onFailure(Throwable t) {
// result.completeExceptionally(t);
// }
//
// @Override
// public void onSuccess(Cursor c) {
// result.complete(Offset.of(c.getOffset()));
// }
// },
// MoreExecutors.directExecutor());
// return result;
// }
//
// @Override
// public PslSourceOffset getHeadOffset() {
// Set<Partition> keySet = new HashSet<>();
// for (int i = 0; i < partitionCountReader.getPartitionCount(); i++) {
// keySet.add(Partition.of(i));
// }
// CompletableFuture<Map<Partition, Offset>> future = cachedHeadOffsets.getAll(keySet);
// try {
// return PslSourceOffset.builder().partitionOffsetMap(future.get()).build();
// } catch (Throwable t) {
// throw new IllegalStateException("Unable to compute head offset for topic: " + topic, t);
// }
// }
//
// @Override
// public void close() {
// try (AutoCloseable a = topicStatsClient;
// Closeable b = partitionCountReader) {
// } catch (Exception e) {
// log.atWarning().withCause(e).log("Unable to close LimitingHeadOffsetReader.");
// }
// }
// }
//
// Path: src/main/java/com/google/cloud/pubsublite/spark/internal/PartitionCountReader.java
// public interface PartitionCountReader extends Closeable {
// int getPartitionCount();
//
// @Override
// void close();
// }
| import static com.google.cloud.pubsublite.internal.ExtractStatus.toCanonical;
import com.github.benmanes.caffeine.cache.Ticker;
import com.google.auto.service.AutoService;
import com.google.cloud.pubsublite.AdminClient;
import com.google.cloud.pubsublite.SubscriptionPath;
import com.google.cloud.pubsublite.TopicPath;
import com.google.cloud.pubsublite.spark.internal.CachedPartitionCountReader;
import com.google.cloud.pubsublite.spark.internal.LimitingHeadOffsetReader;
import com.google.cloud.pubsublite.spark.internal.PartitionCountReader;
import java.util.Objects;
import java.util.Optional;
import org.apache.spark.sql.sources.DataSourceRegister;
import org.apache.spark.sql.sources.v2.ContinuousReadSupport;
import org.apache.spark.sql.sources.v2.DataSourceOptions;
import org.apache.spark.sql.sources.v2.DataSourceV2;
import org.apache.spark.sql.sources.v2.MicroBatchReadSupport;
import org.apache.spark.sql.sources.v2.StreamWriteSupport;
import org.apache.spark.sql.sources.v2.reader.streaming.ContinuousReader;
import org.apache.spark.sql.sources.v2.reader.streaming.MicroBatchReader;
import org.apache.spark.sql.sources.v2.writer.streaming.StreamWriter;
import org.apache.spark.sql.streaming.OutputMode;
import org.apache.spark.sql.types.StructType; | pslReadDataSourceOptions.getSubscriberFactory(),
subscriptionPath,
Objects.requireNonNull(pslReadDataSourceOptions.flowControlSettings()),
partitionCountReader);
}
@Override
public MicroBatchReader createMicroBatchReader(
Optional<StructType> schema, String checkpointLocation, DataSourceOptions options) {
if (schema.isPresent()) {
throw new IllegalArgumentException(
"PubSub Lite uses fixed schema and custom schema is not allowed");
}
PslReadDataSourceOptions pslReadDataSourceOptions =
PslReadDataSourceOptions.fromSparkDataSourceOptions(options);
SubscriptionPath subscriptionPath = pslReadDataSourceOptions.subscriptionPath();
TopicPath topicPath;
try (AdminClient adminClient = pslReadDataSourceOptions.newAdminClient()) {
topicPath = TopicPath.parse(adminClient.getSubscription(subscriptionPath).get().getTopic());
} catch (Throwable t) {
throw toCanonical(t).underlying;
}
PartitionCountReader partitionCountReader =
new CachedPartitionCountReader(pslReadDataSourceOptions.newAdminClient(), topicPath);
return new PslMicroBatchReader(
pslReadDataSourceOptions.newCursorClient(),
pslReadDataSourceOptions.newMultiPartitionCommitter(
partitionCountReader.getPartitionCount()),
pslReadDataSourceOptions.getSubscriberFactory(), | // Path: src/main/java/com/google/cloud/pubsublite/spark/internal/CachedPartitionCountReader.java
// @ThreadSafe
// public class CachedPartitionCountReader implements PartitionCountReader {
// private final AdminClient adminClient;
// private final Supplier<Integer> supplier;
//
// public CachedPartitionCountReader(AdminClient adminClient, TopicPath topicPath) {
// this.adminClient = adminClient;
// this.supplier =
// Suppliers.memoizeWithExpiration(
// () -> PartitionLookupUtils.numPartitions(topicPath, adminClient), 1, TimeUnit.MINUTES);
// }
//
// @Override
// public void close() {
// adminClient.close();
// }
//
// public int getPartitionCount() {
// return supplier.get();
// }
// }
//
// Path: src/main/java/com/google/cloud/pubsublite/spark/internal/LimitingHeadOffsetReader.java
// public class LimitingHeadOffsetReader implements PerTopicHeadOffsetReader {
// private static final GoogleLogger log = GoogleLogger.forEnclosingClass();
//
// private final TopicStatsClient topicStatsClient;
// private final TopicPath topic;
// private final PartitionCountReader partitionCountReader;
// private final AsyncLoadingCache<Partition, Offset> cachedHeadOffsets;
//
// @VisibleForTesting
// public LimitingHeadOffsetReader(
// TopicStatsClient topicStatsClient,
// TopicPath topic,
// PartitionCountReader partitionCountReader,
// Ticker ticker) {
// this.topicStatsClient = topicStatsClient;
// this.topic = topic;
// this.partitionCountReader = partitionCountReader;
// this.cachedHeadOffsets =
// Caffeine.newBuilder()
// .ticker(ticker)
// .expireAfterWrite(1, TimeUnit.MINUTES)
// .buildAsync(this::loadHeadOffset);
// }
//
// private CompletableFuture<Offset> loadHeadOffset(Partition partition, Executor executor) {
//
// CompletableFuture<Offset> result = new CompletableFuture<>();
// ApiFutures.addCallback(
// topicStatsClient.computeHeadCursor(topic, partition),
// new ApiFutureCallback<Cursor>() {
// @Override
// public void onFailure(Throwable t) {
// result.completeExceptionally(t);
// }
//
// @Override
// public void onSuccess(Cursor c) {
// result.complete(Offset.of(c.getOffset()));
// }
// },
// MoreExecutors.directExecutor());
// return result;
// }
//
// @Override
// public PslSourceOffset getHeadOffset() {
// Set<Partition> keySet = new HashSet<>();
// for (int i = 0; i < partitionCountReader.getPartitionCount(); i++) {
// keySet.add(Partition.of(i));
// }
// CompletableFuture<Map<Partition, Offset>> future = cachedHeadOffsets.getAll(keySet);
// try {
// return PslSourceOffset.builder().partitionOffsetMap(future.get()).build();
// } catch (Throwable t) {
// throw new IllegalStateException("Unable to compute head offset for topic: " + topic, t);
// }
// }
//
// @Override
// public void close() {
// try (AutoCloseable a = topicStatsClient;
// Closeable b = partitionCountReader) {
// } catch (Exception e) {
// log.atWarning().withCause(e).log("Unable to close LimitingHeadOffsetReader.");
// }
// }
// }
//
// Path: src/main/java/com/google/cloud/pubsublite/spark/internal/PartitionCountReader.java
// public interface PartitionCountReader extends Closeable {
// int getPartitionCount();
//
// @Override
// void close();
// }
// Path: src/main/java/com/google/cloud/pubsublite/spark/PslDataSource.java
import static com.google.cloud.pubsublite.internal.ExtractStatus.toCanonical;
import com.github.benmanes.caffeine.cache.Ticker;
import com.google.auto.service.AutoService;
import com.google.cloud.pubsublite.AdminClient;
import com.google.cloud.pubsublite.SubscriptionPath;
import com.google.cloud.pubsublite.TopicPath;
import com.google.cloud.pubsublite.spark.internal.CachedPartitionCountReader;
import com.google.cloud.pubsublite.spark.internal.LimitingHeadOffsetReader;
import com.google.cloud.pubsublite.spark.internal.PartitionCountReader;
import java.util.Objects;
import java.util.Optional;
import org.apache.spark.sql.sources.DataSourceRegister;
import org.apache.spark.sql.sources.v2.ContinuousReadSupport;
import org.apache.spark.sql.sources.v2.DataSourceOptions;
import org.apache.spark.sql.sources.v2.DataSourceV2;
import org.apache.spark.sql.sources.v2.MicroBatchReadSupport;
import org.apache.spark.sql.sources.v2.StreamWriteSupport;
import org.apache.spark.sql.sources.v2.reader.streaming.ContinuousReader;
import org.apache.spark.sql.sources.v2.reader.streaming.MicroBatchReader;
import org.apache.spark.sql.sources.v2.writer.streaming.StreamWriter;
import org.apache.spark.sql.streaming.OutputMode;
import org.apache.spark.sql.types.StructType;
pslReadDataSourceOptions.getSubscriberFactory(),
subscriptionPath,
Objects.requireNonNull(pslReadDataSourceOptions.flowControlSettings()),
partitionCountReader);
}
@Override
public MicroBatchReader createMicroBatchReader(
Optional<StructType> schema, String checkpointLocation, DataSourceOptions options) {
if (schema.isPresent()) {
throw new IllegalArgumentException(
"PubSub Lite uses fixed schema and custom schema is not allowed");
}
PslReadDataSourceOptions pslReadDataSourceOptions =
PslReadDataSourceOptions.fromSparkDataSourceOptions(options);
SubscriptionPath subscriptionPath = pslReadDataSourceOptions.subscriptionPath();
TopicPath topicPath;
try (AdminClient adminClient = pslReadDataSourceOptions.newAdminClient()) {
topicPath = TopicPath.parse(adminClient.getSubscription(subscriptionPath).get().getTopic());
} catch (Throwable t) {
throw toCanonical(t).underlying;
}
PartitionCountReader partitionCountReader =
new CachedPartitionCountReader(pslReadDataSourceOptions.newAdminClient(), topicPath);
return new PslMicroBatchReader(
pslReadDataSourceOptions.newCursorClient(),
pslReadDataSourceOptions.newMultiPartitionCommitter(
partitionCountReader.getPartitionCount()),
pslReadDataSourceOptions.getSubscriberFactory(), | new LimitingHeadOffsetReader( |
googleapis/java-pubsublite-spark | src/main/java/com/google/cloud/pubsublite/spark/internal/LimitingHeadOffsetReader.java | // Path: src/main/java/com/google/cloud/pubsublite/spark/PslSourceOffset.java
// @AutoValue
// public abstract class PslSourceOffset {
//
// public abstract Map<Partition, Offset> partitionOffsetMap();
//
// public static Builder builder() {
// return new AutoValue_PslSourceOffset.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder partitionOffsetMap(Map<Partition, Offset> partitionOffsetMap);
//
// public abstract PslSourceOffset build();
// }
// }
| import com.github.benmanes.caffeine.cache.AsyncLoadingCache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.Ticker;
import com.google.api.core.ApiFutureCallback;
import com.google.api.core.ApiFutures;
import com.google.cloud.pubsublite.Offset;
import com.google.cloud.pubsublite.Partition;
import com.google.cloud.pubsublite.TopicPath;
import com.google.cloud.pubsublite.internal.TopicStatsClient;
import com.google.cloud.pubsublite.proto.Cursor;
import com.google.cloud.pubsublite.spark.PslSourceOffset;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.flogger.GoogleLogger;
import com.google.common.util.concurrent.MoreExecutors;
import java.io.Closeable;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit; | this.topic = topic;
this.partitionCountReader = partitionCountReader;
this.cachedHeadOffsets =
Caffeine.newBuilder()
.ticker(ticker)
.expireAfterWrite(1, TimeUnit.MINUTES)
.buildAsync(this::loadHeadOffset);
}
private CompletableFuture<Offset> loadHeadOffset(Partition partition, Executor executor) {
CompletableFuture<Offset> result = new CompletableFuture<>();
ApiFutures.addCallback(
topicStatsClient.computeHeadCursor(topic, partition),
new ApiFutureCallback<Cursor>() {
@Override
public void onFailure(Throwable t) {
result.completeExceptionally(t);
}
@Override
public void onSuccess(Cursor c) {
result.complete(Offset.of(c.getOffset()));
}
},
MoreExecutors.directExecutor());
return result;
}
@Override | // Path: src/main/java/com/google/cloud/pubsublite/spark/PslSourceOffset.java
// @AutoValue
// public abstract class PslSourceOffset {
//
// public abstract Map<Partition, Offset> partitionOffsetMap();
//
// public static Builder builder() {
// return new AutoValue_PslSourceOffset.Builder();
// }
//
// @AutoValue.Builder
// public abstract static class Builder {
//
// public abstract Builder partitionOffsetMap(Map<Partition, Offset> partitionOffsetMap);
//
// public abstract PslSourceOffset build();
// }
// }
// Path: src/main/java/com/google/cloud/pubsublite/spark/internal/LimitingHeadOffsetReader.java
import com.github.benmanes.caffeine.cache.AsyncLoadingCache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.Ticker;
import com.google.api.core.ApiFutureCallback;
import com.google.api.core.ApiFutures;
import com.google.cloud.pubsublite.Offset;
import com.google.cloud.pubsublite.Partition;
import com.google.cloud.pubsublite.TopicPath;
import com.google.cloud.pubsublite.internal.TopicStatsClient;
import com.google.cloud.pubsublite.proto.Cursor;
import com.google.cloud.pubsublite.spark.PslSourceOffset;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.flogger.GoogleLogger;
import com.google.common.util.concurrent.MoreExecutors;
import java.io.Closeable;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
this.topic = topic;
this.partitionCountReader = partitionCountReader;
this.cachedHeadOffsets =
Caffeine.newBuilder()
.ticker(ticker)
.expireAfterWrite(1, TimeUnit.MINUTES)
.buildAsync(this::loadHeadOffset);
}
private CompletableFuture<Offset> loadHeadOffset(Partition partition, Executor executor) {
CompletableFuture<Offset> result = new CompletableFuture<>();
ApiFutures.addCallback(
topicStatsClient.computeHeadCursor(topic, partition),
new ApiFutureCallback<Cursor>() {
@Override
public void onFailure(Throwable t) {
result.completeExceptionally(t);
}
@Override
public void onSuccess(Cursor c) {
result.complete(Offset.of(c.getOffset()));
}
},
MoreExecutors.directExecutor());
return result;
}
@Override | public PslSourceOffset getHeadOffset() { |
niteshpatel/ministocks | src/test/java/nitezh/ministock/domain/AndroidWidgetTests.java | // Path: src/main/java/nitezh/ministock/Storage.java
// public interface Storage {
//
// HashMap<String, ?> getAll();
//
// int getInt(String widgetSize, int defaultVal);
//
// String getString(String key, String defaultVal);
//
// boolean getBoolean(String large_font, boolean defaultVal);
//
// void putInt(String key, int value);
//
// Storage putString(String key, String value);
//
// void putBoolean(String key, Boolean value);
//
// void putFloat(String key, Float value);
//
// void putLong(String key, Long value);
//
// void apply();
// }
| import nitezh.ministock.Storage;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment; | /*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.domain;
@RunWith(RobolectricTestRunner.class)
public class AndroidWidgetTests {
private Widget widget;
@Before
public void setUp() {
int WIDGET_ID = 1;
int WIDGET_SIZE = 0;
widget = new AndroidWidgetRepository(RuntimeEnvironment.application)
.addWidget(WIDGET_ID, WIDGET_SIZE);
}
@Test
public void testShouldUpdateOnRightTouchReturnsFalseByDefault() {
// Act and Assert
assertFalse(widget.shouldUpdateOnRightTouch());
}
@Test
public void testShouldUpdateOnRightTouchReturnsTrueIfSet() {
// Arrange | // Path: src/main/java/nitezh/ministock/Storage.java
// public interface Storage {
//
// HashMap<String, ?> getAll();
//
// int getInt(String widgetSize, int defaultVal);
//
// String getString(String key, String defaultVal);
//
// boolean getBoolean(String large_font, boolean defaultVal);
//
// void putInt(String key, int value);
//
// Storage putString(String key, String value);
//
// void putBoolean(String key, Boolean value);
//
// void putFloat(String key, Float value);
//
// void putLong(String key, Long value);
//
// void apply();
// }
// Path: src/test/java/nitezh/ministock/domain/AndroidWidgetTests.java
import nitezh.ministock.Storage;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
/*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.domain;
@RunWith(RobolectricTestRunner.class)
public class AndroidWidgetTests {
private Widget widget;
@Before
public void setUp() {
int WIDGET_ID = 1;
int WIDGET_SIZE = 0;
widget = new AndroidWidgetRepository(RuntimeEnvironment.application)
.addWidget(WIDGET_ID, WIDGET_SIZE);
}
@Test
public void testShouldUpdateOnRightTouchReturnsFalseByDefault() {
// Act and Assert
assertFalse(widget.shouldUpdateOnRightTouch());
}
@Test
public void testShouldUpdateOnRightTouchReturnsTrueIfSet() {
// Arrange | Storage storage = widget.getStorage(); |
niteshpatel/ministocks | src/main/java/nitezh/ministock/domain/AndroidWidget.java | // Path: src/main/java/nitezh/ministock/PreferenceStorage.java
// public class PreferenceStorage implements Storage {
//
// private final SharedPreferences preferences;
// private SharedPreferences.Editor editor;
//
// public PreferenceStorage(SharedPreferences preferences) {
// this.preferences = preferences;
// }
//
// public static PreferenceStorage getInstance(Context context) {
// return new PreferenceStorage(context.getSharedPreferences(
// context.getString(R.string.prefs_name), 0));
// }
//
// @Override
// public int getInt(String key, int defaultVal) {
// return this.preferences.getInt(key, defaultVal);
// }
//
// @Override
// public String getString(String key, String defaultVal) {
// return this.preferences.getString(key, defaultVal);
// }
//
// @Override
// public boolean getBoolean(String key, boolean defaultVal) {
// return this.preferences.getBoolean(key, defaultVal);
// }
//
// @Override
// public void putInt(String key, int value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putInt(key, value);
// }
//
// @Override
// public void apply() {
// if (this.editor != null) this.editor.apply();
// this.editor = null;
// }
//
// @Override
// public HashMap<String, ?> getAll() {
// HashMap<String, Object> items = new HashMap<>();
// for (Map.Entry<String, ?> entry : this.preferences.getAll().entrySet()) {
// items.put(entry.getKey(), entry.getValue());
// }
//
// return items;
// }
//
// @Override
// public Storage putString(String key, String value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putString(key, value);
// return this;
// }
//
// @Override
// public void putBoolean(String key, Boolean value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putBoolean(key, value);
// }
//
// @Override
// public void putFloat(String key, Float value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putFloat(key, value);
// }
//
// @Override
// public void putLong(String key, Long value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putFloat(key, value);
// }
// }
//
// Path: src/main/java/nitezh/ministock/Storage.java
// public interface Storage {
//
// HashMap<String, ?> getAll();
//
// int getInt(String widgetSize, int defaultVal);
//
// String getString(String key, String defaultVal);
//
// boolean getBoolean(String large_font, boolean defaultVal);
//
// void putInt(String key, int value);
//
// Storage putString(String key, String value);
//
// void putBoolean(String key, Boolean value);
//
// void putFloat(String key, Float value);
//
// void putLong(String key, Long value);
//
// void apply();
// }
| import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import nitezh.ministock.PreferenceStorage;
import nitezh.ministock.R;
import nitezh.ministock.Storage;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import org.json.JSONException; | /*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.domain;
class AndroidWidget implements Widget {
private final Storage storage;
private final Context context;
private final int id;
private final List<String> preferencesToNotRestore = Arrays.asList("widgetSize", "widgetView");
private int size;
AndroidWidget(Context context, int id) {
this.context = context;
this.id = id;
this.storage = this.getStorage();
this.size = this._getSize(); // This is used a lot so don't get from storage each time
}
@Override
public Storage getStorage() {
SharedPreferences widgetPreferences = null;
try {
widgetPreferences = context.getApplicationContext().getSharedPreferences(context.getString(R.string.prefs_name) + this.id, 0);
} catch (Resources.NotFoundException ignored) {
}
| // Path: src/main/java/nitezh/ministock/PreferenceStorage.java
// public class PreferenceStorage implements Storage {
//
// private final SharedPreferences preferences;
// private SharedPreferences.Editor editor;
//
// public PreferenceStorage(SharedPreferences preferences) {
// this.preferences = preferences;
// }
//
// public static PreferenceStorage getInstance(Context context) {
// return new PreferenceStorage(context.getSharedPreferences(
// context.getString(R.string.prefs_name), 0));
// }
//
// @Override
// public int getInt(String key, int defaultVal) {
// return this.preferences.getInt(key, defaultVal);
// }
//
// @Override
// public String getString(String key, String defaultVal) {
// return this.preferences.getString(key, defaultVal);
// }
//
// @Override
// public boolean getBoolean(String key, boolean defaultVal) {
// return this.preferences.getBoolean(key, defaultVal);
// }
//
// @Override
// public void putInt(String key, int value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putInt(key, value);
// }
//
// @Override
// public void apply() {
// if (this.editor != null) this.editor.apply();
// this.editor = null;
// }
//
// @Override
// public HashMap<String, ?> getAll() {
// HashMap<String, Object> items = new HashMap<>();
// for (Map.Entry<String, ?> entry : this.preferences.getAll().entrySet()) {
// items.put(entry.getKey(), entry.getValue());
// }
//
// return items;
// }
//
// @Override
// public Storage putString(String key, String value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putString(key, value);
// return this;
// }
//
// @Override
// public void putBoolean(String key, Boolean value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putBoolean(key, value);
// }
//
// @Override
// public void putFloat(String key, Float value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putFloat(key, value);
// }
//
// @Override
// public void putLong(String key, Long value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putFloat(key, value);
// }
// }
//
// Path: src/main/java/nitezh/ministock/Storage.java
// public interface Storage {
//
// HashMap<String, ?> getAll();
//
// int getInt(String widgetSize, int defaultVal);
//
// String getString(String key, String defaultVal);
//
// boolean getBoolean(String large_font, boolean defaultVal);
//
// void putInt(String key, int value);
//
// Storage putString(String key, String value);
//
// void putBoolean(String key, Boolean value);
//
// void putFloat(String key, Float value);
//
// void putLong(String key, Long value);
//
// void apply();
// }
// Path: src/main/java/nitezh/ministock/domain/AndroidWidget.java
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import nitezh.ministock.PreferenceStorage;
import nitezh.ministock.R;
import nitezh.ministock.Storage;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import org.json.JSONException;
/*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.domain;
class AndroidWidget implements Widget {
private final Storage storage;
private final Context context;
private final int id;
private final List<String> preferencesToNotRestore = Arrays.asList("widgetSize", "widgetView");
private int size;
AndroidWidget(Context context, int id) {
this.context = context;
this.id = id;
this.storage = this.getStorage();
this.size = this._getSize(); // This is used a lot so don't get from storage each time
}
@Override
public Storage getStorage() {
SharedPreferences widgetPreferences = null;
try {
widgetPreferences = context.getApplicationContext().getSharedPreferences(context.getString(R.string.prefs_name) + this.id, 0);
} catch (Resources.NotFoundException ignored) {
}
| return new PreferenceStorage(widgetPreferences); |
niteshpatel/ministocks | src/main/java/nitezh/ministock/domain/AndroidWidgetRepository.java | // Path: src/main/java/nitezh/ministock/PreferenceStorage.java
// public class PreferenceStorage implements Storage {
//
// private final SharedPreferences preferences;
// private SharedPreferences.Editor editor;
//
// public PreferenceStorage(SharedPreferences preferences) {
// this.preferences = preferences;
// }
//
// public static PreferenceStorage getInstance(Context context) {
// return new PreferenceStorage(context.getSharedPreferences(
// context.getString(R.string.prefs_name), 0));
// }
//
// @Override
// public int getInt(String key, int defaultVal) {
// return this.preferences.getInt(key, defaultVal);
// }
//
// @Override
// public String getString(String key, String defaultVal) {
// return this.preferences.getString(key, defaultVal);
// }
//
// @Override
// public boolean getBoolean(String key, boolean defaultVal) {
// return this.preferences.getBoolean(key, defaultVal);
// }
//
// @Override
// public void putInt(String key, int value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putInt(key, value);
// }
//
// @Override
// public void apply() {
// if (this.editor != null) this.editor.apply();
// this.editor = null;
// }
//
// @Override
// public HashMap<String, ?> getAll() {
// HashMap<String, Object> items = new HashMap<>();
// for (Map.Entry<String, ?> entry : this.preferences.getAll().entrySet()) {
// items.put(entry.getKey(), entry.getValue());
// }
//
// return items;
// }
//
// @Override
// public Storage putString(String key, String value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putString(key, value);
// return this;
// }
//
// @Override
// public void putBoolean(String key, Boolean value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putBoolean(key, value);
// }
//
// @Override
// public void putFloat(String key, Float value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putFloat(key, value);
// }
//
// @Override
// public void putLong(String key, Long value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putFloat(key, value);
// }
// }
//
// Path: src/main/java/nitezh/ministock/Storage.java
// public interface Storage {
//
// HashMap<String, ?> getAll();
//
// int getInt(String widgetSize, int defaultVal);
//
// String getString(String key, String defaultVal);
//
// boolean getBoolean(String large_font, boolean defaultVal);
//
// void putInt(String key, int value);
//
// Storage putString(String key, String value);
//
// void putBoolean(String key, Boolean value);
//
// void putFloat(String key, Float value);
//
// void putLong(String key, Long value);
//
// void apply();
// }
| import java.util.Set;
import nitezh.ministock.PreferenceStorage;
import nitezh.ministock.Storage;
import android.content.Context;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List; | /*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.domain;
public class AndroidWidgetRepository implements WidgetRepository {
private final Context context; | // Path: src/main/java/nitezh/ministock/PreferenceStorage.java
// public class PreferenceStorage implements Storage {
//
// private final SharedPreferences preferences;
// private SharedPreferences.Editor editor;
//
// public PreferenceStorage(SharedPreferences preferences) {
// this.preferences = preferences;
// }
//
// public static PreferenceStorage getInstance(Context context) {
// return new PreferenceStorage(context.getSharedPreferences(
// context.getString(R.string.prefs_name), 0));
// }
//
// @Override
// public int getInt(String key, int defaultVal) {
// return this.preferences.getInt(key, defaultVal);
// }
//
// @Override
// public String getString(String key, String defaultVal) {
// return this.preferences.getString(key, defaultVal);
// }
//
// @Override
// public boolean getBoolean(String key, boolean defaultVal) {
// return this.preferences.getBoolean(key, defaultVal);
// }
//
// @Override
// public void putInt(String key, int value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putInt(key, value);
// }
//
// @Override
// public void apply() {
// if (this.editor != null) this.editor.apply();
// this.editor = null;
// }
//
// @Override
// public HashMap<String, ?> getAll() {
// HashMap<String, Object> items = new HashMap<>();
// for (Map.Entry<String, ?> entry : this.preferences.getAll().entrySet()) {
// items.put(entry.getKey(), entry.getValue());
// }
//
// return items;
// }
//
// @Override
// public Storage putString(String key, String value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putString(key, value);
// return this;
// }
//
// @Override
// public void putBoolean(String key, Boolean value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putBoolean(key, value);
// }
//
// @Override
// public void putFloat(String key, Float value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putFloat(key, value);
// }
//
// @Override
// public void putLong(String key, Long value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putFloat(key, value);
// }
// }
//
// Path: src/main/java/nitezh/ministock/Storage.java
// public interface Storage {
//
// HashMap<String, ?> getAll();
//
// int getInt(String widgetSize, int defaultVal);
//
// String getString(String key, String defaultVal);
//
// boolean getBoolean(String large_font, boolean defaultVal);
//
// void putInt(String key, int value);
//
// Storage putString(String key, String value);
//
// void putBoolean(String key, Boolean value);
//
// void putFloat(String key, Float value);
//
// void putLong(String key, Long value);
//
// void apply();
// }
// Path: src/main/java/nitezh/ministock/domain/AndroidWidgetRepository.java
import java.util.Set;
import nitezh.ministock.PreferenceStorage;
import nitezh.ministock.Storage;
import android.content.Context;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
/*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.domain;
public class AndroidWidgetRepository implements WidgetRepository {
private final Context context; | private final Storage appStorage; |
niteshpatel/ministocks | src/main/java/nitezh/ministock/domain/AndroidWidgetRepository.java | // Path: src/main/java/nitezh/ministock/PreferenceStorage.java
// public class PreferenceStorage implements Storage {
//
// private final SharedPreferences preferences;
// private SharedPreferences.Editor editor;
//
// public PreferenceStorage(SharedPreferences preferences) {
// this.preferences = preferences;
// }
//
// public static PreferenceStorage getInstance(Context context) {
// return new PreferenceStorage(context.getSharedPreferences(
// context.getString(R.string.prefs_name), 0));
// }
//
// @Override
// public int getInt(String key, int defaultVal) {
// return this.preferences.getInt(key, defaultVal);
// }
//
// @Override
// public String getString(String key, String defaultVal) {
// return this.preferences.getString(key, defaultVal);
// }
//
// @Override
// public boolean getBoolean(String key, boolean defaultVal) {
// return this.preferences.getBoolean(key, defaultVal);
// }
//
// @Override
// public void putInt(String key, int value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putInt(key, value);
// }
//
// @Override
// public void apply() {
// if (this.editor != null) this.editor.apply();
// this.editor = null;
// }
//
// @Override
// public HashMap<String, ?> getAll() {
// HashMap<String, Object> items = new HashMap<>();
// for (Map.Entry<String, ?> entry : this.preferences.getAll().entrySet()) {
// items.put(entry.getKey(), entry.getValue());
// }
//
// return items;
// }
//
// @Override
// public Storage putString(String key, String value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putString(key, value);
// return this;
// }
//
// @Override
// public void putBoolean(String key, Boolean value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putBoolean(key, value);
// }
//
// @Override
// public void putFloat(String key, Float value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putFloat(key, value);
// }
//
// @Override
// public void putLong(String key, Long value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putFloat(key, value);
// }
// }
//
// Path: src/main/java/nitezh/ministock/Storage.java
// public interface Storage {
//
// HashMap<String, ?> getAll();
//
// int getInt(String widgetSize, int defaultVal);
//
// String getString(String key, String defaultVal);
//
// boolean getBoolean(String large_font, boolean defaultVal);
//
// void putInt(String key, int value);
//
// Storage putString(String key, String value);
//
// void putBoolean(String key, Boolean value);
//
// void putFloat(String key, Float value);
//
// void putLong(String key, Long value);
//
// void apply();
// }
| import java.util.Set;
import nitezh.ministock.PreferenceStorage;
import nitezh.ministock.Storage;
import android.content.Context;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List; | /*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.domain;
public class AndroidWidgetRepository implements WidgetRepository {
private final Context context;
private final Storage appStorage;
public AndroidWidgetRepository(Context context) {
this.context = context; | // Path: src/main/java/nitezh/ministock/PreferenceStorage.java
// public class PreferenceStorage implements Storage {
//
// private final SharedPreferences preferences;
// private SharedPreferences.Editor editor;
//
// public PreferenceStorage(SharedPreferences preferences) {
// this.preferences = preferences;
// }
//
// public static PreferenceStorage getInstance(Context context) {
// return new PreferenceStorage(context.getSharedPreferences(
// context.getString(R.string.prefs_name), 0));
// }
//
// @Override
// public int getInt(String key, int defaultVal) {
// return this.preferences.getInt(key, defaultVal);
// }
//
// @Override
// public String getString(String key, String defaultVal) {
// return this.preferences.getString(key, defaultVal);
// }
//
// @Override
// public boolean getBoolean(String key, boolean defaultVal) {
// return this.preferences.getBoolean(key, defaultVal);
// }
//
// @Override
// public void putInt(String key, int value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putInt(key, value);
// }
//
// @Override
// public void apply() {
// if (this.editor != null) this.editor.apply();
// this.editor = null;
// }
//
// @Override
// public HashMap<String, ?> getAll() {
// HashMap<String, Object> items = new HashMap<>();
// for (Map.Entry<String, ?> entry : this.preferences.getAll().entrySet()) {
// items.put(entry.getKey(), entry.getValue());
// }
//
// return items;
// }
//
// @Override
// public Storage putString(String key, String value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putString(key, value);
// return this;
// }
//
// @Override
// public void putBoolean(String key, Boolean value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putBoolean(key, value);
// }
//
// @Override
// public void putFloat(String key, Float value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putFloat(key, value);
// }
//
// @Override
// public void putLong(String key, Long value) {
// if (this.editor == null) this.editor = this.preferences.edit();
// this.editor.putFloat(key, value);
// }
// }
//
// Path: src/main/java/nitezh/ministock/Storage.java
// public interface Storage {
//
// HashMap<String, ?> getAll();
//
// int getInt(String widgetSize, int defaultVal);
//
// String getString(String key, String defaultVal);
//
// boolean getBoolean(String large_font, boolean defaultVal);
//
// void putInt(String key, int value);
//
// Storage putString(String key, String value);
//
// void putBoolean(String key, Boolean value);
//
// void putFloat(String key, Float value);
//
// void putLong(String key, Long value);
//
// void apply();
// }
// Path: src/main/java/nitezh/ministock/domain/AndroidWidgetRepository.java
import java.util.Set;
import nitezh.ministock.PreferenceStorage;
import nitezh.ministock.Storage;
import android.content.Context;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
/*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.domain;
public class AndroidWidgetRepository implements WidgetRepository {
private final Context context;
private final Storage appStorage;
public AndroidWidgetRepository(Context context) {
this.context = context; | this.appStorage = PreferenceStorage.getInstance(context); |
niteshpatel/ministocks | src/test/java/nitezh/ministock/dataaccess/YahooStockQuoteRepository2Tests.java | // Path: src/main/java/nitezh/ministock/domain/StockQuote.java
// public class StockQuote {
//
// private String symbol;
// private String price;
// private String change;
// private String percent;
// private final String exchange;
// private final String volume;
// private final String name;
//
// public StockQuote(
// String symbol,
// String price,
// String change,
// String percent,
// String exchange,
// String volume,
// String name,
// Locale locale) {
//
// this(
// symbol,
// price,
// change,
// percent,
// exchange,
// volume,
// name,
// null,
// locale
// );
// }
//
// public StockQuote(
// String symbol,
// String price,
// String change,
// String percent,
// String exchange,
// String volume,
// String name,
// String previousPrice,
// Locale locale) {
//
// this.symbol = symbol;
// this.exchange = exchange;
// this.volume = volume;
// this.name = name;
//
// // Get additional FX data if applicable
// Double p0 = null;
// boolean isFx = symbol.contains("=");
// if (isFx) {
// try {
// p0 = NumberTools.parseDouble(previousPrice, locale);
// } catch (Exception ignored) {
// }
// }
//
// // Set stock prices to 2 decimal places
// Double p = null;
// if (!price.equals("0.00")) {
// try {
// p = NumberTools.parseDouble(price, locale);
// if (isFx) {
// this.price = NumberTools.getTrimmedDouble2(p, 6);
// } else {
// this.price = NumberTools.trim(price, locale);
// }
// } catch (Exception e) {
// this.price = "0.00";
// }
//
// // Note that if the change or percent == "N/A" set to 0
// if (!this.isNonEmptyNumber(price) && p0 == null) {
// change = "0.00";
// }
// if (!this.isNonEmptyNumber(percent) && p0 == null) {
// percent = "0.00";
// }
// }
//
// // Changes are only set to 5 significant figures
// Double c = null;
// if (this.isNonEmptyNumber(change)) {
// try {
// c = NumberTools.parseDouble(change, locale);
// } catch (ParseException ignored) {
// }
// } else if (p0 != null && p != null) {
// c = p - p0;
// }
// if (c != null) {
// if (p != null && (p < 10 || isFx)) {
// this.change = NumberTools.getTrimmedDouble(c, 5, 3);
// } else {
// this.change = NumberTools.getTrimmedDouble(c, 5);
// }
// }
//
// // Percentage changes are only set to one decimal place
// Double pc = null;
// if (this.isNonEmptyNumber(percent)) {
// try {
// pc = NumberTools.parseDouble(percent.replace("%", ""), locale);
// } catch (ParseException ignored) {
//
// }
// } else {
// if (c != null && p != null) {
// pc = (c / p) * 100;
// }
// }
// if (pc != null) {
// this.percent = String.format(Locale.getDefault(), "%.1f", pc) + "%";
// }
// }
//
// private boolean isNonEmptyNumber(String value) {
// return !value.equals("N/A")
// && !value.equals("")
// && !value.equals("null");
// }
//
// public String getSymbol() {
// return symbol;
// }
//
// public void setSymbol(String symbol) {
// this.symbol = symbol;
// }
//
// public String getPrice() {
// return price;
// }
//
// public String getChange() {
// return change;
// }
//
// public String getPercent() {
// return percent;
// }
//
// public String getExchange() {
// return exchange;
// }
//
// public String getVolume() {
// return volume;
// }
//
// public String getName() {
// return name;
// }
// }
//
// Path: src/test/java/nitezh/ministock/mocks/MockCache.java
// public class MockCache extends Cache {
//
// @Override
// protected JSONObject loadCache() {
// return new JSONObject();
// }
//
// @Override
// protected void persistCache(JSONObject cache) {
// }
// }
| import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import nitezh.ministock.domain.StockQuote;
import nitezh.ministock.mocks.MockCache;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.Assume; | "NasdaqGS"
).contains(aaplJson.optString("exchange")));
assertEquals("Apple Inc.", aaplJson.optString("name"));
JSONObject googJson = json.optJSONObject(1);
assertEquals("GOOG", googJson.optString("symbol"));
assertTrue(Arrays.asList(
"NasdaqNM",
"NMS",
"Nasdaq Global Select",
"NasdaqGS"
).contains(googJson.optString("exchange")));
assertEquals("Alphabet Inc.", googJson.optString("name"));
JSONObject djiJson = json.optJSONObject(2);
assertEquals("^DJI", djiJson.optString("symbol"));
assertEquals("DJI", djiJson.optString("exchange"));
assertEquals("Dow Jones Industrial Average", djiJson.optString("name"));
}
@Test
public void getQuotes() {
// Skipif
Assume.assumeTrue(System.getenv("TRAVIS_CI") == null);
// Arrange
List<String> symbols = Arrays.asList("AAPL", "GOOG", "^DJI");
// Act | // Path: src/main/java/nitezh/ministock/domain/StockQuote.java
// public class StockQuote {
//
// private String symbol;
// private String price;
// private String change;
// private String percent;
// private final String exchange;
// private final String volume;
// private final String name;
//
// public StockQuote(
// String symbol,
// String price,
// String change,
// String percent,
// String exchange,
// String volume,
// String name,
// Locale locale) {
//
// this(
// symbol,
// price,
// change,
// percent,
// exchange,
// volume,
// name,
// null,
// locale
// );
// }
//
// public StockQuote(
// String symbol,
// String price,
// String change,
// String percent,
// String exchange,
// String volume,
// String name,
// String previousPrice,
// Locale locale) {
//
// this.symbol = symbol;
// this.exchange = exchange;
// this.volume = volume;
// this.name = name;
//
// // Get additional FX data if applicable
// Double p0 = null;
// boolean isFx = symbol.contains("=");
// if (isFx) {
// try {
// p0 = NumberTools.parseDouble(previousPrice, locale);
// } catch (Exception ignored) {
// }
// }
//
// // Set stock prices to 2 decimal places
// Double p = null;
// if (!price.equals("0.00")) {
// try {
// p = NumberTools.parseDouble(price, locale);
// if (isFx) {
// this.price = NumberTools.getTrimmedDouble2(p, 6);
// } else {
// this.price = NumberTools.trim(price, locale);
// }
// } catch (Exception e) {
// this.price = "0.00";
// }
//
// // Note that if the change or percent == "N/A" set to 0
// if (!this.isNonEmptyNumber(price) && p0 == null) {
// change = "0.00";
// }
// if (!this.isNonEmptyNumber(percent) && p0 == null) {
// percent = "0.00";
// }
// }
//
// // Changes are only set to 5 significant figures
// Double c = null;
// if (this.isNonEmptyNumber(change)) {
// try {
// c = NumberTools.parseDouble(change, locale);
// } catch (ParseException ignored) {
// }
// } else if (p0 != null && p != null) {
// c = p - p0;
// }
// if (c != null) {
// if (p != null && (p < 10 || isFx)) {
// this.change = NumberTools.getTrimmedDouble(c, 5, 3);
// } else {
// this.change = NumberTools.getTrimmedDouble(c, 5);
// }
// }
//
// // Percentage changes are only set to one decimal place
// Double pc = null;
// if (this.isNonEmptyNumber(percent)) {
// try {
// pc = NumberTools.parseDouble(percent.replace("%", ""), locale);
// } catch (ParseException ignored) {
//
// }
// } else {
// if (c != null && p != null) {
// pc = (c / p) * 100;
// }
// }
// if (pc != null) {
// this.percent = String.format(Locale.getDefault(), "%.1f", pc) + "%";
// }
// }
//
// private boolean isNonEmptyNumber(String value) {
// return !value.equals("N/A")
// && !value.equals("")
// && !value.equals("null");
// }
//
// public String getSymbol() {
// return symbol;
// }
//
// public void setSymbol(String symbol) {
// this.symbol = symbol;
// }
//
// public String getPrice() {
// return price;
// }
//
// public String getChange() {
// return change;
// }
//
// public String getPercent() {
// return percent;
// }
//
// public String getExchange() {
// return exchange;
// }
//
// public String getVolume() {
// return volume;
// }
//
// public String getName() {
// return name;
// }
// }
//
// Path: src/test/java/nitezh/ministock/mocks/MockCache.java
// public class MockCache extends Cache {
//
// @Override
// protected JSONObject loadCache() {
// return new JSONObject();
// }
//
// @Override
// protected void persistCache(JSONObject cache) {
// }
// }
// Path: src/test/java/nitezh/ministock/dataaccess/YahooStockQuoteRepository2Tests.java
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import nitezh.ministock.domain.StockQuote;
import nitezh.ministock.mocks.MockCache;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.Assume;
"NasdaqGS"
).contains(aaplJson.optString("exchange")));
assertEquals("Apple Inc.", aaplJson.optString("name"));
JSONObject googJson = json.optJSONObject(1);
assertEquals("GOOG", googJson.optString("symbol"));
assertTrue(Arrays.asList(
"NasdaqNM",
"NMS",
"Nasdaq Global Select",
"NasdaqGS"
).contains(googJson.optString("exchange")));
assertEquals("Alphabet Inc.", googJson.optString("name"));
JSONObject djiJson = json.optJSONObject(2);
assertEquals("^DJI", djiJson.optString("symbol"));
assertEquals("DJI", djiJson.optString("exchange"));
assertEquals("Dow Jones Industrial Average", djiJson.optString("name"));
}
@Test
public void getQuotes() {
// Skipif
Assume.assumeTrue(System.getenv("TRAVIS_CI") == null);
// Arrange
List<String> symbols = Arrays.asList("AAPL", "GOOG", "^DJI");
// Act | HashMap<String, StockQuote> stockQuotes = quoteRepository.getQuotes(new MockCache(), symbols); |
niteshpatel/ministocks | src/test/java/nitezh/ministock/domain/PortfolioStockRepositoryTests.java | // Path: src/test/java/nitezh/ministock/mocks/MockStorage.java
// public class MockStorage implements Storage {
//
// @Override
// public HashMap<String, ?> getAll() {
// return new HashMap<>();
// }
//
// @Override
// public int getInt(String widgetSize, int defaultVal) {
// return 0;
// }
//
// @Override
// public String getString(String key, String defaultVal) {
// return "";
// }
//
// @Override
// public boolean getBoolean(String large_font, boolean defaultVal) {
// return false;
// }
//
// @Override
// public void putInt(String key, int value) {
// }
//
// @Override
// public Storage putString(String key, String value) {
// return this;
// }
//
// @Override
// public void putBoolean(String key, Boolean value) {
// }
//
// @Override
// public void putFloat(String key, Float value) {
// }
//
// @Override
// public void putLong(String key, Long value) {
// }
//
// @Override
// public void apply() {
// }
// }
//
// Path: src/test/java/nitezh/ministock/mocks/MockWidgetRepository.java
// public class MockWidgetRepository implements WidgetRepository {
//
// private HashSet<String> widgetsStockSymbols;
//
// @Override
// public List<Integer> getIds() {
// return new ArrayList<>();
// }
//
// @Override
// public boolean isEmpty() {
// return false;
// }
//
// @Override
// public Set<String> getWidgetsStockSymbols() {
// if (this.widgetsStockSymbols != null) {
// return this.widgetsStockSymbols;
// }
// return new HashSet<>();
// }
//
// public void setWidgetsStockSymbols(HashSet<String> widgetsStockSymbols) {
// this.widgetsStockSymbols = widgetsStockSymbols;
// }
//
// @Override
// public void delWidget(int id) {
// }
//
// @Override
// public Widget getWidget(int id) {
// return new MockWidget();
// }
//
// @Override
// public Widget addWidget(int id, int size) {
// return this.getWidget(id);
// }
//
// }
| import org.junit.Before;
import org.junit.Test;
import nitezh.ministock.mocks.MockStorage;
import nitezh.ministock.mocks.MockWidgetRepository; | /*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.domain;
public class PortfolioStockRepositoryTests {
private PortfolioStockRepository stockRepository;
@Before
public void setUp() { | // Path: src/test/java/nitezh/ministock/mocks/MockStorage.java
// public class MockStorage implements Storage {
//
// @Override
// public HashMap<String, ?> getAll() {
// return new HashMap<>();
// }
//
// @Override
// public int getInt(String widgetSize, int defaultVal) {
// return 0;
// }
//
// @Override
// public String getString(String key, String defaultVal) {
// return "";
// }
//
// @Override
// public boolean getBoolean(String large_font, boolean defaultVal) {
// return false;
// }
//
// @Override
// public void putInt(String key, int value) {
// }
//
// @Override
// public Storage putString(String key, String value) {
// return this;
// }
//
// @Override
// public void putBoolean(String key, Boolean value) {
// }
//
// @Override
// public void putFloat(String key, Float value) {
// }
//
// @Override
// public void putLong(String key, Long value) {
// }
//
// @Override
// public void apply() {
// }
// }
//
// Path: src/test/java/nitezh/ministock/mocks/MockWidgetRepository.java
// public class MockWidgetRepository implements WidgetRepository {
//
// private HashSet<String> widgetsStockSymbols;
//
// @Override
// public List<Integer> getIds() {
// return new ArrayList<>();
// }
//
// @Override
// public boolean isEmpty() {
// return false;
// }
//
// @Override
// public Set<String> getWidgetsStockSymbols() {
// if (this.widgetsStockSymbols != null) {
// return this.widgetsStockSymbols;
// }
// return new HashSet<>();
// }
//
// public void setWidgetsStockSymbols(HashSet<String> widgetsStockSymbols) {
// this.widgetsStockSymbols = widgetsStockSymbols;
// }
//
// @Override
// public void delWidget(int id) {
// }
//
// @Override
// public Widget getWidget(int id) {
// return new MockWidget();
// }
//
// @Override
// public Widget addWidget(int id, int size) {
// return this.getWidget(id);
// }
//
// }
// Path: src/test/java/nitezh/ministock/domain/PortfolioStockRepositoryTests.java
import org.junit.Before;
import org.junit.Test;
import nitezh.ministock.mocks.MockStorage;
import nitezh.ministock.mocks.MockWidgetRepository;
/*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.domain;
public class PortfolioStockRepositoryTests {
private PortfolioStockRepository stockRepository;
@Before
public void setUp() { | MockWidgetRepository widgetRepository = new MockWidgetRepository(); |
niteshpatel/ministocks | src/test/java/nitezh/ministock/domain/PortfolioStockRepositoryTests.java | // Path: src/test/java/nitezh/ministock/mocks/MockStorage.java
// public class MockStorage implements Storage {
//
// @Override
// public HashMap<String, ?> getAll() {
// return new HashMap<>();
// }
//
// @Override
// public int getInt(String widgetSize, int defaultVal) {
// return 0;
// }
//
// @Override
// public String getString(String key, String defaultVal) {
// return "";
// }
//
// @Override
// public boolean getBoolean(String large_font, boolean defaultVal) {
// return false;
// }
//
// @Override
// public void putInt(String key, int value) {
// }
//
// @Override
// public Storage putString(String key, String value) {
// return this;
// }
//
// @Override
// public void putBoolean(String key, Boolean value) {
// }
//
// @Override
// public void putFloat(String key, Float value) {
// }
//
// @Override
// public void putLong(String key, Long value) {
// }
//
// @Override
// public void apply() {
// }
// }
//
// Path: src/test/java/nitezh/ministock/mocks/MockWidgetRepository.java
// public class MockWidgetRepository implements WidgetRepository {
//
// private HashSet<String> widgetsStockSymbols;
//
// @Override
// public List<Integer> getIds() {
// return new ArrayList<>();
// }
//
// @Override
// public boolean isEmpty() {
// return false;
// }
//
// @Override
// public Set<String> getWidgetsStockSymbols() {
// if (this.widgetsStockSymbols != null) {
// return this.widgetsStockSymbols;
// }
// return new HashSet<>();
// }
//
// public void setWidgetsStockSymbols(HashSet<String> widgetsStockSymbols) {
// this.widgetsStockSymbols = widgetsStockSymbols;
// }
//
// @Override
// public void delWidget(int id) {
// }
//
// @Override
// public Widget getWidget(int id) {
// return new MockWidget();
// }
//
// @Override
// public Widget addWidget(int id, int size) {
// return this.getWidget(id);
// }
//
// }
| import org.junit.Before;
import org.junit.Test;
import nitezh.ministock.mocks.MockStorage;
import nitezh.ministock.mocks.MockWidgetRepository; | /*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.domain;
public class PortfolioStockRepositoryTests {
private PortfolioStockRepository stockRepository;
@Before
public void setUp() {
MockWidgetRepository widgetRepository = new MockWidgetRepository();
stockRepository = new PortfolioStockRepository( | // Path: src/test/java/nitezh/ministock/mocks/MockStorage.java
// public class MockStorage implements Storage {
//
// @Override
// public HashMap<String, ?> getAll() {
// return new HashMap<>();
// }
//
// @Override
// public int getInt(String widgetSize, int defaultVal) {
// return 0;
// }
//
// @Override
// public String getString(String key, String defaultVal) {
// return "";
// }
//
// @Override
// public boolean getBoolean(String large_font, boolean defaultVal) {
// return false;
// }
//
// @Override
// public void putInt(String key, int value) {
// }
//
// @Override
// public Storage putString(String key, String value) {
// return this;
// }
//
// @Override
// public void putBoolean(String key, Boolean value) {
// }
//
// @Override
// public void putFloat(String key, Float value) {
// }
//
// @Override
// public void putLong(String key, Long value) {
// }
//
// @Override
// public void apply() {
// }
// }
//
// Path: src/test/java/nitezh/ministock/mocks/MockWidgetRepository.java
// public class MockWidgetRepository implements WidgetRepository {
//
// private HashSet<String> widgetsStockSymbols;
//
// @Override
// public List<Integer> getIds() {
// return new ArrayList<>();
// }
//
// @Override
// public boolean isEmpty() {
// return false;
// }
//
// @Override
// public Set<String> getWidgetsStockSymbols() {
// if (this.widgetsStockSymbols != null) {
// return this.widgetsStockSymbols;
// }
// return new HashSet<>();
// }
//
// public void setWidgetsStockSymbols(HashSet<String> widgetsStockSymbols) {
// this.widgetsStockSymbols = widgetsStockSymbols;
// }
//
// @Override
// public void delWidget(int id) {
// }
//
// @Override
// public Widget getWidget(int id) {
// return new MockWidget();
// }
//
// @Override
// public Widget addWidget(int id, int size) {
// return this.getWidget(id);
// }
//
// }
// Path: src/test/java/nitezh/ministock/domain/PortfolioStockRepositoryTests.java
import org.junit.Before;
import org.junit.Test;
import nitezh.ministock.mocks.MockStorage;
import nitezh.ministock.mocks.MockWidgetRepository;
/*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.domain;
public class PortfolioStockRepositoryTests {
private PortfolioStockRepository stockRepository;
@Before
public void setUp() {
MockWidgetRepository widgetRepository = new MockWidgetRepository();
stockRepository = new PortfolioStockRepository( | new MockStorage(), |
niteshpatel/ministocks | src/main/java/nitezh/ministock/domain/PortfolioStock.java | // Path: src/main/java/nitezh/ministock/domain/PortfolioStockRepository.java
// public enum PortfolioField {
// PRICE, DATE, QUANTITY, LIMIT_HIGH, LIMIT_LOW, CUSTOM_DISPLAY, SYMBOL_2
// }
| import org.json.JSONException;
import org.json.JSONObject;
import static nitezh.ministock.domain.PortfolioStockRepository.PortfolioField; | }
public String getPrice() {
return price;
}
public String getDate() {
return date;
}
String getQuantity() {
return quantity;
}
String getHighLimit() {
return highLimit;
}
String getLowLimit() {
return lowLimit;
}
String getCustomName() {
return customName;
}
private String getSymbol2() {
return symbol2;
}
| // Path: src/main/java/nitezh/ministock/domain/PortfolioStockRepository.java
// public enum PortfolioField {
// PRICE, DATE, QUANTITY, LIMIT_HIGH, LIMIT_LOW, CUSTOM_DISPLAY, SYMBOL_2
// }
// Path: src/main/java/nitezh/ministock/domain/PortfolioStock.java
import org.json.JSONException;
import org.json.JSONObject;
import static nitezh.ministock.domain.PortfolioStockRepository.PortfolioField;
}
public String getPrice() {
return price;
}
public String getDate() {
return date;
}
String getQuantity() {
return quantity;
}
String getHighLimit() {
return highLimit;
}
String getLowLimit() {
return lowLimit;
}
String getCustomName() {
return customName;
}
private String getSymbol2() {
return symbol2;
}
| private void setJsonValue(JSONObject json, PortfolioField key, String value) { |
niteshpatel/ministocks | src/main/java/nitezh/ministock/utils/StorageCache.java | // Path: src/main/java/nitezh/ministock/Storage.java
// public interface Storage {
//
// HashMap<String, ?> getAll();
//
// int getInt(String widgetSize, int defaultVal);
//
// String getString(String key, String defaultVal);
//
// boolean getBoolean(String large_font, boolean defaultVal);
//
// void putInt(String key, int value);
//
// Storage putString(String key, String value);
//
// void putBoolean(String key, Boolean value);
//
// void putFloat(String key, Float value);
//
// void putLong(String key, Long value);
//
// void apply();
// }
| import org.json.JSONException;
import org.json.JSONObject;
import nitezh.ministock.Storage; | /*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.utils;
public class StorageCache extends Cache {
private static final String JSON_CACHE = "JsonCache";
private static String mCache = ""; | // Path: src/main/java/nitezh/ministock/Storage.java
// public interface Storage {
//
// HashMap<String, ?> getAll();
//
// int getInt(String widgetSize, int defaultVal);
//
// String getString(String key, String defaultVal);
//
// boolean getBoolean(String large_font, boolean defaultVal);
//
// void putInt(String key, int value);
//
// Storage putString(String key, String value);
//
// void putBoolean(String key, Boolean value);
//
// void putFloat(String key, Float value);
//
// void putLong(String key, Long value);
//
// void apply();
// }
// Path: src/main/java/nitezh/ministock/utils/StorageCache.java
import org.json.JSONException;
import org.json.JSONObject;
import nitezh.ministock.Storage;
/*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.utils;
public class StorageCache extends Cache {
private static final String JSON_CACHE = "JsonCache";
private static String mCache = ""; | private Storage storage = null; |
niteshpatel/ministocks | src/main/java/nitezh/ministock/StockSuggestions.java | // Path: src/main/java/nitezh/ministock/utils/StorageCache.java
// public class StorageCache extends Cache {
//
// private static final String JSON_CACHE = "JsonCache";
// private static String mCache = "";
// private Storage storage = null;
//
// public StorageCache(Storage storage) {
// if (storage != null) {
// this.storage = storage;
// }
// }
//
// @Override
// protected void persistCache(JSONObject cache) {
// mCache = cache.toString();
// if (this.storage != null) {
// this.storage.putString(JSON_CACHE, mCache);
// this.storage.apply();
// }
// }
//
// @Override
// protected JSONObject loadCache() {
// if (storage != null && mCache.equals("")) {
// mCache = storage.getString(JSON_CACHE, "");
// }
// JSONObject cache = new JSONObject();
// try {
// cache = new JSONObject(mCache);
// } catch (JSONException ignore) {
// }
//
// return cache;
// }
// }
//
// Path: src/main/java/nitezh/ministock/utils/UrlDataTools.java
// public class UrlDataTools {
//
// private UrlDataTools() {
// }
//
// private static String inputStreamToString(InputStream stream) throws IOException {
// BufferedReader r = new BufferedReader(new InputStreamReader(stream));
// StringBuilder builder = new StringBuilder();
// String line;
// while ((line = r.readLine()) != null) {
// builder.append(line).append("\n");
// }
// return builder.toString();
// }
//
// static String urlToString(String url) throws IOException {
// URLConnection connection = new URL(url).openConnection();
// connection.setConnectTimeout(30000);
// connection.setReadTimeout(60000);
// return inputStreamToString(connection.getInputStream());
// }
//
// private static String getUrlData(String url) {
// // Ensure we always request some data
// if (!url.contains("INDU")) {
// url = url.replace("&s=", "&s=INDU+");
// }
//
// try {
// URLConnection connection = new URL(url).openConnection();
// connection.setConnectTimeout(30000);
// connection.setReadTimeout(60000);
// return inputStreamToString(connection.getInputStream());
// } catch (IOException ignored) {
// }
// return null;
// }
//
// public static String getCachedUrlData(String url, Cache cache, Integer ttl) {
// String data;
// if (ttl != null && (data = cache.get(url)) != null) {
// return data;
// }
//
// data = getUrlData(url);
// if (data != null) {
// cache.put(url, data, ttl);
// return data;
// }
// return "";
// }
// }
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import nitezh.ministock.utils.Cache;
import nitezh.ministock.utils.StorageCache;
import nitezh.ministock.utils.UrlDataTools;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; | /*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock;
class StockSuggestions {
private static final String BASE_URL = "https://s.yimg.com/aq/autoc?callback=YAHOO.Finance.SymbolSuggest.ssCallback®ion=US&lang=en-US&query=";
private static final Pattern PATTERN_RESPONSE = Pattern.compile("YAHOO\\.Finance\\.SymbolSuggest\\.ssCallback\\((\\{.*?\\})\\)");
static List<Map<String, String>> getSuggestions(String query) {
List<Map<String, String>> suggestions = new ArrayList<>();
String response;
try {
String url = BASE_URL + URLEncoder.encode(query, "UTF-8"); | // Path: src/main/java/nitezh/ministock/utils/StorageCache.java
// public class StorageCache extends Cache {
//
// private static final String JSON_CACHE = "JsonCache";
// private static String mCache = "";
// private Storage storage = null;
//
// public StorageCache(Storage storage) {
// if (storage != null) {
// this.storage = storage;
// }
// }
//
// @Override
// protected void persistCache(JSONObject cache) {
// mCache = cache.toString();
// if (this.storage != null) {
// this.storage.putString(JSON_CACHE, mCache);
// this.storage.apply();
// }
// }
//
// @Override
// protected JSONObject loadCache() {
// if (storage != null && mCache.equals("")) {
// mCache = storage.getString(JSON_CACHE, "");
// }
// JSONObject cache = new JSONObject();
// try {
// cache = new JSONObject(mCache);
// } catch (JSONException ignore) {
// }
//
// return cache;
// }
// }
//
// Path: src/main/java/nitezh/ministock/utils/UrlDataTools.java
// public class UrlDataTools {
//
// private UrlDataTools() {
// }
//
// private static String inputStreamToString(InputStream stream) throws IOException {
// BufferedReader r = new BufferedReader(new InputStreamReader(stream));
// StringBuilder builder = new StringBuilder();
// String line;
// while ((line = r.readLine()) != null) {
// builder.append(line).append("\n");
// }
// return builder.toString();
// }
//
// static String urlToString(String url) throws IOException {
// URLConnection connection = new URL(url).openConnection();
// connection.setConnectTimeout(30000);
// connection.setReadTimeout(60000);
// return inputStreamToString(connection.getInputStream());
// }
//
// private static String getUrlData(String url) {
// // Ensure we always request some data
// if (!url.contains("INDU")) {
// url = url.replace("&s=", "&s=INDU+");
// }
//
// try {
// URLConnection connection = new URL(url).openConnection();
// connection.setConnectTimeout(30000);
// connection.setReadTimeout(60000);
// return inputStreamToString(connection.getInputStream());
// } catch (IOException ignored) {
// }
// return null;
// }
//
// public static String getCachedUrlData(String url, Cache cache, Integer ttl) {
// String data;
// if (ttl != null && (data = cache.get(url)) != null) {
// return data;
// }
//
// data = getUrlData(url);
// if (data != null) {
// cache.put(url, data, ttl);
// return data;
// }
// return "";
// }
// }
// Path: src/main/java/nitezh/ministock/StockSuggestions.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import nitezh.ministock.utils.Cache;
import nitezh.ministock.utils.StorageCache;
import nitezh.ministock.utils.UrlDataTools;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock;
class StockSuggestions {
private static final String BASE_URL = "https://s.yimg.com/aq/autoc?callback=YAHOO.Finance.SymbolSuggest.ssCallback®ion=US&lang=en-US&query=";
private static final Pattern PATTERN_RESPONSE = Pattern.compile("YAHOO\\.Finance\\.SymbolSuggest\\.ssCallback\\((\\{.*?\\})\\)");
static List<Map<String, String>> getSuggestions(String query) {
List<Map<String, String>> suggestions = new ArrayList<>();
String response;
try {
String url = BASE_URL + URLEncoder.encode(query, "UTF-8"); | Cache cache = new StorageCache(null); |
niteshpatel/ministocks | src/main/java/nitezh/ministock/StockSuggestions.java | // Path: src/main/java/nitezh/ministock/utils/StorageCache.java
// public class StorageCache extends Cache {
//
// private static final String JSON_CACHE = "JsonCache";
// private static String mCache = "";
// private Storage storage = null;
//
// public StorageCache(Storage storage) {
// if (storage != null) {
// this.storage = storage;
// }
// }
//
// @Override
// protected void persistCache(JSONObject cache) {
// mCache = cache.toString();
// if (this.storage != null) {
// this.storage.putString(JSON_CACHE, mCache);
// this.storage.apply();
// }
// }
//
// @Override
// protected JSONObject loadCache() {
// if (storage != null && mCache.equals("")) {
// mCache = storage.getString(JSON_CACHE, "");
// }
// JSONObject cache = new JSONObject();
// try {
// cache = new JSONObject(mCache);
// } catch (JSONException ignore) {
// }
//
// return cache;
// }
// }
//
// Path: src/main/java/nitezh/ministock/utils/UrlDataTools.java
// public class UrlDataTools {
//
// private UrlDataTools() {
// }
//
// private static String inputStreamToString(InputStream stream) throws IOException {
// BufferedReader r = new BufferedReader(new InputStreamReader(stream));
// StringBuilder builder = new StringBuilder();
// String line;
// while ((line = r.readLine()) != null) {
// builder.append(line).append("\n");
// }
// return builder.toString();
// }
//
// static String urlToString(String url) throws IOException {
// URLConnection connection = new URL(url).openConnection();
// connection.setConnectTimeout(30000);
// connection.setReadTimeout(60000);
// return inputStreamToString(connection.getInputStream());
// }
//
// private static String getUrlData(String url) {
// // Ensure we always request some data
// if (!url.contains("INDU")) {
// url = url.replace("&s=", "&s=INDU+");
// }
//
// try {
// URLConnection connection = new URL(url).openConnection();
// connection.setConnectTimeout(30000);
// connection.setReadTimeout(60000);
// return inputStreamToString(connection.getInputStream());
// } catch (IOException ignored) {
// }
// return null;
// }
//
// public static String getCachedUrlData(String url, Cache cache, Integer ttl) {
// String data;
// if (ttl != null && (data = cache.get(url)) != null) {
// return data;
// }
//
// data = getUrlData(url);
// if (data != null) {
// cache.put(url, data, ttl);
// return data;
// }
// return "";
// }
// }
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import nitezh.ministock.utils.Cache;
import nitezh.ministock.utils.StorageCache;
import nitezh.ministock.utils.UrlDataTools;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; | /*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock;
class StockSuggestions {
private static final String BASE_URL = "https://s.yimg.com/aq/autoc?callback=YAHOO.Finance.SymbolSuggest.ssCallback®ion=US&lang=en-US&query=";
private static final Pattern PATTERN_RESPONSE = Pattern.compile("YAHOO\\.Finance\\.SymbolSuggest\\.ssCallback\\((\\{.*?\\})\\)");
static List<Map<String, String>> getSuggestions(String query) {
List<Map<String, String>> suggestions = new ArrayList<>();
String response;
try {
String url = BASE_URL + URLEncoder.encode(query, "UTF-8");
Cache cache = new StorageCache(null); | // Path: src/main/java/nitezh/ministock/utils/StorageCache.java
// public class StorageCache extends Cache {
//
// private static final String JSON_CACHE = "JsonCache";
// private static String mCache = "";
// private Storage storage = null;
//
// public StorageCache(Storage storage) {
// if (storage != null) {
// this.storage = storage;
// }
// }
//
// @Override
// protected void persistCache(JSONObject cache) {
// mCache = cache.toString();
// if (this.storage != null) {
// this.storage.putString(JSON_CACHE, mCache);
// this.storage.apply();
// }
// }
//
// @Override
// protected JSONObject loadCache() {
// if (storage != null && mCache.equals("")) {
// mCache = storage.getString(JSON_CACHE, "");
// }
// JSONObject cache = new JSONObject();
// try {
// cache = new JSONObject(mCache);
// } catch (JSONException ignore) {
// }
//
// return cache;
// }
// }
//
// Path: src/main/java/nitezh/ministock/utils/UrlDataTools.java
// public class UrlDataTools {
//
// private UrlDataTools() {
// }
//
// private static String inputStreamToString(InputStream stream) throws IOException {
// BufferedReader r = new BufferedReader(new InputStreamReader(stream));
// StringBuilder builder = new StringBuilder();
// String line;
// while ((line = r.readLine()) != null) {
// builder.append(line).append("\n");
// }
// return builder.toString();
// }
//
// static String urlToString(String url) throws IOException {
// URLConnection connection = new URL(url).openConnection();
// connection.setConnectTimeout(30000);
// connection.setReadTimeout(60000);
// return inputStreamToString(connection.getInputStream());
// }
//
// private static String getUrlData(String url) {
// // Ensure we always request some data
// if (!url.contains("INDU")) {
// url = url.replace("&s=", "&s=INDU+");
// }
//
// try {
// URLConnection connection = new URL(url).openConnection();
// connection.setConnectTimeout(30000);
// connection.setReadTimeout(60000);
// return inputStreamToString(connection.getInputStream());
// } catch (IOException ignored) {
// }
// return null;
// }
//
// public static String getCachedUrlData(String url, Cache cache, Integer ttl) {
// String data;
// if (ttl != null && (data = cache.get(url)) != null) {
// return data;
// }
//
// data = getUrlData(url);
// if (data != null) {
// cache.put(url, data, ttl);
// return data;
// }
// return "";
// }
// }
// Path: src/main/java/nitezh/ministock/StockSuggestions.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import nitezh.ministock.utils.Cache;
import nitezh.ministock.utils.StorageCache;
import nitezh.ministock.utils.UrlDataTools;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock;
class StockSuggestions {
private static final String BASE_URL = "https://s.yimg.com/aq/autoc?callback=YAHOO.Finance.SymbolSuggest.ssCallback®ion=US&lang=en-US&query=";
private static final Pattern PATTERN_RESPONSE = Pattern.compile("YAHOO\\.Finance\\.SymbolSuggest\\.ssCallback\\((\\{.*?\\})\\)");
static List<Map<String, String>> getSuggestions(String query) {
List<Map<String, String>> suggestions = new ArrayList<>();
String response;
try {
String url = BASE_URL + URLEncoder.encode(query, "UTF-8");
Cache cache = new StorageCache(null); | response = UrlDataTools.getCachedUrlData(url, cache, 86400); |
niteshpatel/ministocks | src/test/java/nitezh/ministock/dataaccess/FxChangeRepositoryTests.java | // Path: src/test/java/nitezh/ministock/mocks/MockCache.java
// public class MockCache extends Cache {
//
// @Override
// protected JSONObject loadCache() {
// return new JSONObject();
// }
//
// @Override
// protected void persistCache(JSONObject cache) {
// }
// }
| import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import nitezh.ministock.mocks.MockCache;
import static org.junit.Assert.assertNotNull; | /*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.dataaccess;
public class FxChangeRepositoryTests {
private FxChangeRepository fxRepository;
@Before
public void setUp() {
this.fxRepository = new FxChangeRepository();
}
@Test
public void testRetrieveChangesAsJson() {
// Arrange
JSONObject json = null;
// Act
try { | // Path: src/test/java/nitezh/ministock/mocks/MockCache.java
// public class MockCache extends Cache {
//
// @Override
// protected JSONObject loadCache() {
// return new JSONObject();
// }
//
// @Override
// protected void persistCache(JSONObject cache) {
// }
// }
// Path: src/test/java/nitezh/ministock/dataaccess/FxChangeRepositoryTests.java
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import nitezh.ministock.mocks.MockCache;
import static org.junit.Assert.assertNotNull;
/*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.dataaccess;
public class FxChangeRepositoryTests {
private FxChangeRepository fxRepository;
@Before
public void setUp() {
this.fxRepository = new FxChangeRepository();
}
@Test
public void testRetrieveChangesAsJson() {
// Arrange
JSONObject json = null;
// Act
try { | json = this.fxRepository.retrieveChangesAsJson(new MockCache()); |
niteshpatel/ministocks | src/test/java/nitezh/ministock/dataaccess/IexStockQuoteRepositoryTests.java | // Path: src/main/java/nitezh/ministock/domain/StockQuote.java
// public class StockQuote {
//
// private String symbol;
// private String price;
// private String change;
// private String percent;
// private final String exchange;
// private final String volume;
// private final String name;
//
// public StockQuote(
// String symbol,
// String price,
// String change,
// String percent,
// String exchange,
// String volume,
// String name,
// Locale locale) {
//
// this(
// symbol,
// price,
// change,
// percent,
// exchange,
// volume,
// name,
// null,
// locale
// );
// }
//
// public StockQuote(
// String symbol,
// String price,
// String change,
// String percent,
// String exchange,
// String volume,
// String name,
// String previousPrice,
// Locale locale) {
//
// this.symbol = symbol;
// this.exchange = exchange;
// this.volume = volume;
// this.name = name;
//
// // Get additional FX data if applicable
// Double p0 = null;
// boolean isFx = symbol.contains("=");
// if (isFx) {
// try {
// p0 = NumberTools.parseDouble(previousPrice, locale);
// } catch (Exception ignored) {
// }
// }
//
// // Set stock prices to 2 decimal places
// Double p = null;
// if (!price.equals("0.00")) {
// try {
// p = NumberTools.parseDouble(price, locale);
// if (isFx) {
// this.price = NumberTools.getTrimmedDouble2(p, 6);
// } else {
// this.price = NumberTools.trim(price, locale);
// }
// } catch (Exception e) {
// this.price = "0.00";
// }
//
// // Note that if the change or percent == "N/A" set to 0
// if (!this.isNonEmptyNumber(price) && p0 == null) {
// change = "0.00";
// }
// if (!this.isNonEmptyNumber(percent) && p0 == null) {
// percent = "0.00";
// }
// }
//
// // Changes are only set to 5 significant figures
// Double c = null;
// if (this.isNonEmptyNumber(change)) {
// try {
// c = NumberTools.parseDouble(change, locale);
// } catch (ParseException ignored) {
// }
// } else if (p0 != null && p != null) {
// c = p - p0;
// }
// if (c != null) {
// if (p != null && (p < 10 || isFx)) {
// this.change = NumberTools.getTrimmedDouble(c, 5, 3);
// } else {
// this.change = NumberTools.getTrimmedDouble(c, 5);
// }
// }
//
// // Percentage changes are only set to one decimal place
// Double pc = null;
// if (this.isNonEmptyNumber(percent)) {
// try {
// pc = NumberTools.parseDouble(percent.replace("%", ""), locale);
// } catch (ParseException ignored) {
//
// }
// } else {
// if (c != null && p != null) {
// pc = (c / p) * 100;
// }
// }
// if (pc != null) {
// this.percent = String.format(Locale.getDefault(), "%.1f", pc) + "%";
// }
// }
//
// private boolean isNonEmptyNumber(String value) {
// return !value.equals("N/A")
// && !value.equals("")
// && !value.equals("null");
// }
//
// public String getSymbol() {
// return symbol;
// }
//
// public void setSymbol(String symbol) {
// this.symbol = symbol;
// }
//
// public String getPrice() {
// return price;
// }
//
// public String getChange() {
// return change;
// }
//
// public String getPercent() {
// return percent;
// }
//
// public String getExchange() {
// return exchange;
// }
//
// public String getVolume() {
// return volume;
// }
//
// public String getName() {
// return name;
// }
// }
//
// Path: src/test/java/nitezh/ministock/mocks/MockCache.java
// public class MockCache extends Cache {
//
// @Override
// protected JSONObject loadCache() {
// return new JSONObject();
// }
//
// @Override
// protected void persistCache(JSONObject cache) {
// }
// }
| import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import nitezh.ministock.domain.StockQuote;
import nitezh.ministock.mocks.MockCache;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test; | // Act
try {
json = this.quoteRepository.retrieveQuotesAsJson(new MockCache(), symbols);
} catch (JSONException ignored) {
}
// Assert
assertNotNull(json);
assertEquals(2, json.length());
JSONObject aaplJson = json.optJSONObject(0);
assertEquals("AAPL", aaplJson.optString("symbol"));
assertTrue(Arrays.asList("NasdaqNM", "NMS", "Nasdaq Global Select").contains(aaplJson.optString("exchange")));
assertEquals("Apple Inc.", aaplJson.optString("name"));
JSONObject googJson = json.optJSONObject(1);
assertEquals("GOOG", googJson.optString("symbol"));
assertTrue(Arrays.asList("NasdaqNM", "NMS", "Nasdaq Global Select").contains(googJson.optString("exchange")));
assertEquals("Alphabet Inc.", googJson.optString("name"));
}
@Test
public void getQuotes() {
// Skipif
Assume.assumeTrue(System.getenv("TRAVIS_CI") == null);
// Arrange
List<String> symbols = Arrays.asList("AAPL", "GOOG");
// Act | // Path: src/main/java/nitezh/ministock/domain/StockQuote.java
// public class StockQuote {
//
// private String symbol;
// private String price;
// private String change;
// private String percent;
// private final String exchange;
// private final String volume;
// private final String name;
//
// public StockQuote(
// String symbol,
// String price,
// String change,
// String percent,
// String exchange,
// String volume,
// String name,
// Locale locale) {
//
// this(
// symbol,
// price,
// change,
// percent,
// exchange,
// volume,
// name,
// null,
// locale
// );
// }
//
// public StockQuote(
// String symbol,
// String price,
// String change,
// String percent,
// String exchange,
// String volume,
// String name,
// String previousPrice,
// Locale locale) {
//
// this.symbol = symbol;
// this.exchange = exchange;
// this.volume = volume;
// this.name = name;
//
// // Get additional FX data if applicable
// Double p0 = null;
// boolean isFx = symbol.contains("=");
// if (isFx) {
// try {
// p0 = NumberTools.parseDouble(previousPrice, locale);
// } catch (Exception ignored) {
// }
// }
//
// // Set stock prices to 2 decimal places
// Double p = null;
// if (!price.equals("0.00")) {
// try {
// p = NumberTools.parseDouble(price, locale);
// if (isFx) {
// this.price = NumberTools.getTrimmedDouble2(p, 6);
// } else {
// this.price = NumberTools.trim(price, locale);
// }
// } catch (Exception e) {
// this.price = "0.00";
// }
//
// // Note that if the change or percent == "N/A" set to 0
// if (!this.isNonEmptyNumber(price) && p0 == null) {
// change = "0.00";
// }
// if (!this.isNonEmptyNumber(percent) && p0 == null) {
// percent = "0.00";
// }
// }
//
// // Changes are only set to 5 significant figures
// Double c = null;
// if (this.isNonEmptyNumber(change)) {
// try {
// c = NumberTools.parseDouble(change, locale);
// } catch (ParseException ignored) {
// }
// } else if (p0 != null && p != null) {
// c = p - p0;
// }
// if (c != null) {
// if (p != null && (p < 10 || isFx)) {
// this.change = NumberTools.getTrimmedDouble(c, 5, 3);
// } else {
// this.change = NumberTools.getTrimmedDouble(c, 5);
// }
// }
//
// // Percentage changes are only set to one decimal place
// Double pc = null;
// if (this.isNonEmptyNumber(percent)) {
// try {
// pc = NumberTools.parseDouble(percent.replace("%", ""), locale);
// } catch (ParseException ignored) {
//
// }
// } else {
// if (c != null && p != null) {
// pc = (c / p) * 100;
// }
// }
// if (pc != null) {
// this.percent = String.format(Locale.getDefault(), "%.1f", pc) + "%";
// }
// }
//
// private boolean isNonEmptyNumber(String value) {
// return !value.equals("N/A")
// && !value.equals("")
// && !value.equals("null");
// }
//
// public String getSymbol() {
// return symbol;
// }
//
// public void setSymbol(String symbol) {
// this.symbol = symbol;
// }
//
// public String getPrice() {
// return price;
// }
//
// public String getChange() {
// return change;
// }
//
// public String getPercent() {
// return percent;
// }
//
// public String getExchange() {
// return exchange;
// }
//
// public String getVolume() {
// return volume;
// }
//
// public String getName() {
// return name;
// }
// }
//
// Path: src/test/java/nitezh/ministock/mocks/MockCache.java
// public class MockCache extends Cache {
//
// @Override
// protected JSONObject loadCache() {
// return new JSONObject();
// }
//
// @Override
// protected void persistCache(JSONObject cache) {
// }
// }
// Path: src/test/java/nitezh/ministock/dataaccess/IexStockQuoteRepositoryTests.java
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import nitezh.ministock.domain.StockQuote;
import nitezh.ministock.mocks.MockCache;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
// Act
try {
json = this.quoteRepository.retrieveQuotesAsJson(new MockCache(), symbols);
} catch (JSONException ignored) {
}
// Assert
assertNotNull(json);
assertEquals(2, json.length());
JSONObject aaplJson = json.optJSONObject(0);
assertEquals("AAPL", aaplJson.optString("symbol"));
assertTrue(Arrays.asList("NasdaqNM", "NMS", "Nasdaq Global Select").contains(aaplJson.optString("exchange")));
assertEquals("Apple Inc.", aaplJson.optString("name"));
JSONObject googJson = json.optJSONObject(1);
assertEquals("GOOG", googJson.optString("symbol"));
assertTrue(Arrays.asList("NasdaqNM", "NMS", "Nasdaq Global Select").contains(googJson.optString("exchange")));
assertEquals("Alphabet Inc.", googJson.optString("name"));
}
@Test
public void getQuotes() {
// Skipif
Assume.assumeTrue(System.getenv("TRAVIS_CI") == null);
// Arrange
List<String> symbols = Arrays.asList("AAPL", "GOOG");
// Act | HashMap<String, StockQuote> stockQuotes = quoteRepository.getQuotes(new MockCache(), symbols); |
niteshpatel/ministocks | src/test/java/nitezh/ministock/dataaccess/GoogleStockQuoteRepositoryTests.java | // Path: src/main/java/nitezh/ministock/domain/StockQuote.java
// public class StockQuote {
//
// private String symbol;
// private String price;
// private String change;
// private String percent;
// private final String exchange;
// private final String volume;
// private final String name;
//
// public StockQuote(
// String symbol,
// String price,
// String change,
// String percent,
// String exchange,
// String volume,
// String name,
// Locale locale) {
//
// this(
// symbol,
// price,
// change,
// percent,
// exchange,
// volume,
// name,
// null,
// locale
// );
// }
//
// public StockQuote(
// String symbol,
// String price,
// String change,
// String percent,
// String exchange,
// String volume,
// String name,
// String previousPrice,
// Locale locale) {
//
// this.symbol = symbol;
// this.exchange = exchange;
// this.volume = volume;
// this.name = name;
//
// // Get additional FX data if applicable
// Double p0 = null;
// boolean isFx = symbol.contains("=");
// if (isFx) {
// try {
// p0 = NumberTools.parseDouble(previousPrice, locale);
// } catch (Exception ignored) {
// }
// }
//
// // Set stock prices to 2 decimal places
// Double p = null;
// if (!price.equals("0.00")) {
// try {
// p = NumberTools.parseDouble(price, locale);
// if (isFx) {
// this.price = NumberTools.getTrimmedDouble2(p, 6);
// } else {
// this.price = NumberTools.trim(price, locale);
// }
// } catch (Exception e) {
// this.price = "0.00";
// }
//
// // Note that if the change or percent == "N/A" set to 0
// if (!this.isNonEmptyNumber(price) && p0 == null) {
// change = "0.00";
// }
// if (!this.isNonEmptyNumber(percent) && p0 == null) {
// percent = "0.00";
// }
// }
//
// // Changes are only set to 5 significant figures
// Double c = null;
// if (this.isNonEmptyNumber(change)) {
// try {
// c = NumberTools.parseDouble(change, locale);
// } catch (ParseException ignored) {
// }
// } else if (p0 != null && p != null) {
// c = p - p0;
// }
// if (c != null) {
// if (p != null && (p < 10 || isFx)) {
// this.change = NumberTools.getTrimmedDouble(c, 5, 3);
// } else {
// this.change = NumberTools.getTrimmedDouble(c, 5);
// }
// }
//
// // Percentage changes are only set to one decimal place
// Double pc = null;
// if (this.isNonEmptyNumber(percent)) {
// try {
// pc = NumberTools.parseDouble(percent.replace("%", ""), locale);
// } catch (ParseException ignored) {
//
// }
// } else {
// if (c != null && p != null) {
// pc = (c / p) * 100;
// }
// }
// if (pc != null) {
// this.percent = String.format(Locale.getDefault(), "%.1f", pc) + "%";
// }
// }
//
// private boolean isNonEmptyNumber(String value) {
// return !value.equals("N/A")
// && !value.equals("")
// && !value.equals("null");
// }
//
// public String getSymbol() {
// return symbol;
// }
//
// public void setSymbol(String symbol) {
// this.symbol = symbol;
// }
//
// public String getPrice() {
// return price;
// }
//
// public String getChange() {
// return change;
// }
//
// public String getPercent() {
// return percent;
// }
//
// public String getExchange() {
// return exchange;
// }
//
// public String getVolume() {
// return volume;
// }
//
// public String getName() {
// return name;
// }
// }
//
// Path: src/test/java/nitezh/ministock/mocks/MockCache.java
// public class MockCache extends Cache {
//
// @Override
// protected JSONObject loadCache() {
// return new JSONObject();
// }
//
// @Override
// protected void persistCache(JSONObject cache) {
// }
// }
| import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import nitezh.ministock.domain.StockQuote;
import nitezh.ministock.mocks.MockCache;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test; | JSONObject djiJson = json.optJSONObject(0);
assertEquals(".DJI", djiJson.optString("t"));
assertEquals("INDEXDJX", djiJson.optString("e"));
}
public void retrieveIXICQuoteAsJson() {
// Arrange
List<String> symbols = Collections.singletonList(".IXIC");
JSONArray json = null;
// Act
try {
json = googleRepository.retrieveQuotesAsJson(new MockCache(), symbols);
} catch (JSONException ignored) {
}
// Assert
assertNotNull(json);
assertEquals(1, json.length());
JSONObject ixicJson = json.optJSONObject(0);
assertEquals(".IXIC", ixicJson.optString("t"));
assertEquals("INDEXNASDAQ", ixicJson.optString("e"));
}
public void getQuotes() {
// Arrange
List<String> symbols = Arrays.asList(".DJI", ".IXIC");
// Act | // Path: src/main/java/nitezh/ministock/domain/StockQuote.java
// public class StockQuote {
//
// private String symbol;
// private String price;
// private String change;
// private String percent;
// private final String exchange;
// private final String volume;
// private final String name;
//
// public StockQuote(
// String symbol,
// String price,
// String change,
// String percent,
// String exchange,
// String volume,
// String name,
// Locale locale) {
//
// this(
// symbol,
// price,
// change,
// percent,
// exchange,
// volume,
// name,
// null,
// locale
// );
// }
//
// public StockQuote(
// String symbol,
// String price,
// String change,
// String percent,
// String exchange,
// String volume,
// String name,
// String previousPrice,
// Locale locale) {
//
// this.symbol = symbol;
// this.exchange = exchange;
// this.volume = volume;
// this.name = name;
//
// // Get additional FX data if applicable
// Double p0 = null;
// boolean isFx = symbol.contains("=");
// if (isFx) {
// try {
// p0 = NumberTools.parseDouble(previousPrice, locale);
// } catch (Exception ignored) {
// }
// }
//
// // Set stock prices to 2 decimal places
// Double p = null;
// if (!price.equals("0.00")) {
// try {
// p = NumberTools.parseDouble(price, locale);
// if (isFx) {
// this.price = NumberTools.getTrimmedDouble2(p, 6);
// } else {
// this.price = NumberTools.trim(price, locale);
// }
// } catch (Exception e) {
// this.price = "0.00";
// }
//
// // Note that if the change or percent == "N/A" set to 0
// if (!this.isNonEmptyNumber(price) && p0 == null) {
// change = "0.00";
// }
// if (!this.isNonEmptyNumber(percent) && p0 == null) {
// percent = "0.00";
// }
// }
//
// // Changes are only set to 5 significant figures
// Double c = null;
// if (this.isNonEmptyNumber(change)) {
// try {
// c = NumberTools.parseDouble(change, locale);
// } catch (ParseException ignored) {
// }
// } else if (p0 != null && p != null) {
// c = p - p0;
// }
// if (c != null) {
// if (p != null && (p < 10 || isFx)) {
// this.change = NumberTools.getTrimmedDouble(c, 5, 3);
// } else {
// this.change = NumberTools.getTrimmedDouble(c, 5);
// }
// }
//
// // Percentage changes are only set to one decimal place
// Double pc = null;
// if (this.isNonEmptyNumber(percent)) {
// try {
// pc = NumberTools.parseDouble(percent.replace("%", ""), locale);
// } catch (ParseException ignored) {
//
// }
// } else {
// if (c != null && p != null) {
// pc = (c / p) * 100;
// }
// }
// if (pc != null) {
// this.percent = String.format(Locale.getDefault(), "%.1f", pc) + "%";
// }
// }
//
// private boolean isNonEmptyNumber(String value) {
// return !value.equals("N/A")
// && !value.equals("")
// && !value.equals("null");
// }
//
// public String getSymbol() {
// return symbol;
// }
//
// public void setSymbol(String symbol) {
// this.symbol = symbol;
// }
//
// public String getPrice() {
// return price;
// }
//
// public String getChange() {
// return change;
// }
//
// public String getPercent() {
// return percent;
// }
//
// public String getExchange() {
// return exchange;
// }
//
// public String getVolume() {
// return volume;
// }
//
// public String getName() {
// return name;
// }
// }
//
// Path: src/test/java/nitezh/ministock/mocks/MockCache.java
// public class MockCache extends Cache {
//
// @Override
// protected JSONObject loadCache() {
// return new JSONObject();
// }
//
// @Override
// protected void persistCache(JSONObject cache) {
// }
// }
// Path: src/test/java/nitezh/ministock/dataaccess/GoogleStockQuoteRepositoryTests.java
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import nitezh.ministock.domain.StockQuote;
import nitezh.ministock.mocks.MockCache;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
JSONObject djiJson = json.optJSONObject(0);
assertEquals(".DJI", djiJson.optString("t"));
assertEquals("INDEXDJX", djiJson.optString("e"));
}
public void retrieveIXICQuoteAsJson() {
// Arrange
List<String> symbols = Collections.singletonList(".IXIC");
JSONArray json = null;
// Act
try {
json = googleRepository.retrieveQuotesAsJson(new MockCache(), symbols);
} catch (JSONException ignored) {
}
// Assert
assertNotNull(json);
assertEquals(1, json.length());
JSONObject ixicJson = json.optJSONObject(0);
assertEquals(".IXIC", ixicJson.optString("t"));
assertEquals("INDEXNASDAQ", ixicJson.optString("e"));
}
public void getQuotes() {
// Arrange
List<String> symbols = Arrays.asList(".DJI", ".IXIC");
// Act | HashMap<String, StockQuote> stockQuotes = googleRepository.getQuotes(new MockCache(), symbols); |
niteshpatel/ministocks | src/test/java/nitezh/ministock/mocks/MockWidget.java | // Path: src/main/java/nitezh/ministock/Storage.java
// public interface Storage {
//
// HashMap<String, ?> getAll();
//
// int getInt(String widgetSize, int defaultVal);
//
// String getString(String key, String defaultVal);
//
// boolean getBoolean(String large_font, boolean defaultVal);
//
// void putInt(String key, int value);
//
// Storage putString(String key, String value);
//
// void putBoolean(String key, Boolean value);
//
// void putFloat(String key, Float value);
//
// void putLong(String key, Long value);
//
// void apply();
// }
//
// Path: src/main/java/nitezh/ministock/domain/Widget.java
// public interface Widget {
// Storage getStorage();
//
// void setWidgetPreferencesFromJson(JSONObject jsonPrefs);
//
// JSONObject getWidgetPreferencesAsJson();
//
// void enablePercentChangeView();
//
// void enableDailyChangeView();
//
// void setStock1();
//
// void setStock1Summary();
//
// void save();
//
// int getId();
//
// int getSize();
//
// void setSize(int size);
//
// boolean isNarrow();
//
// String getStock(int i);
//
// int getPreviousView();
//
// void setView(int view);
//
// List<String> getSymbols();
//
// int getSymbolCount();
//
// String getBackgroundStyle();
//
// boolean useLargeFont();
//
// boolean getHideSuffix();
//
// boolean getTextStyle();
//
// boolean getColorsOnPrices();
//
// String getFooterVisibility();
//
// String getFooterColor();
//
// boolean showShortTime();
//
// boolean hasDailyChangeView();
//
// boolean hasTotalPercentView();
//
// boolean hasDailyPercentView();
//
// boolean hasTotalChangeView();
//
// boolean hasTotalChangeAerView();
//
// boolean hasDailyPlChangeView();
//
// boolean hasDailyPlPercentView();
//
// boolean hasTotalPlPercentView();
//
// boolean hasTotalPlChangeView();
//
// boolean hasTotalPlPercentAerView();
//
// boolean alwaysUseShortName();
//
// boolean shouldUpdateOnRightTouch();
// }
| import org.json.JSONObject;
import java.util.List;
import nitezh.ministock.Storage;
import nitezh.ministock.domain.Widget; | /*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.mocks;
public class MockWidget implements Widget {
@Override | // Path: src/main/java/nitezh/ministock/Storage.java
// public interface Storage {
//
// HashMap<String, ?> getAll();
//
// int getInt(String widgetSize, int defaultVal);
//
// String getString(String key, String defaultVal);
//
// boolean getBoolean(String large_font, boolean defaultVal);
//
// void putInt(String key, int value);
//
// Storage putString(String key, String value);
//
// void putBoolean(String key, Boolean value);
//
// void putFloat(String key, Float value);
//
// void putLong(String key, Long value);
//
// void apply();
// }
//
// Path: src/main/java/nitezh/ministock/domain/Widget.java
// public interface Widget {
// Storage getStorage();
//
// void setWidgetPreferencesFromJson(JSONObject jsonPrefs);
//
// JSONObject getWidgetPreferencesAsJson();
//
// void enablePercentChangeView();
//
// void enableDailyChangeView();
//
// void setStock1();
//
// void setStock1Summary();
//
// void save();
//
// int getId();
//
// int getSize();
//
// void setSize(int size);
//
// boolean isNarrow();
//
// String getStock(int i);
//
// int getPreviousView();
//
// void setView(int view);
//
// List<String> getSymbols();
//
// int getSymbolCount();
//
// String getBackgroundStyle();
//
// boolean useLargeFont();
//
// boolean getHideSuffix();
//
// boolean getTextStyle();
//
// boolean getColorsOnPrices();
//
// String getFooterVisibility();
//
// String getFooterColor();
//
// boolean showShortTime();
//
// boolean hasDailyChangeView();
//
// boolean hasTotalPercentView();
//
// boolean hasDailyPercentView();
//
// boolean hasTotalChangeView();
//
// boolean hasTotalChangeAerView();
//
// boolean hasDailyPlChangeView();
//
// boolean hasDailyPlPercentView();
//
// boolean hasTotalPlPercentView();
//
// boolean hasTotalPlChangeView();
//
// boolean hasTotalPlPercentAerView();
//
// boolean alwaysUseShortName();
//
// boolean shouldUpdateOnRightTouch();
// }
// Path: src/test/java/nitezh/ministock/mocks/MockWidget.java
import org.json.JSONObject;
import java.util.List;
import nitezh.ministock.Storage;
import nitezh.ministock.domain.Widget;
/*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.mocks;
public class MockWidget implements Widget {
@Override | public Storage getStorage() { |
niteshpatel/ministocks | src/test/java/nitezh/ministock/mocks/MockWidgetRepository.java | // Path: src/main/java/nitezh/ministock/domain/Widget.java
// public interface Widget {
// Storage getStorage();
//
// void setWidgetPreferencesFromJson(JSONObject jsonPrefs);
//
// JSONObject getWidgetPreferencesAsJson();
//
// void enablePercentChangeView();
//
// void enableDailyChangeView();
//
// void setStock1();
//
// void setStock1Summary();
//
// void save();
//
// int getId();
//
// int getSize();
//
// void setSize(int size);
//
// boolean isNarrow();
//
// String getStock(int i);
//
// int getPreviousView();
//
// void setView(int view);
//
// List<String> getSymbols();
//
// int getSymbolCount();
//
// String getBackgroundStyle();
//
// boolean useLargeFont();
//
// boolean getHideSuffix();
//
// boolean getTextStyle();
//
// boolean getColorsOnPrices();
//
// String getFooterVisibility();
//
// String getFooterColor();
//
// boolean showShortTime();
//
// boolean hasDailyChangeView();
//
// boolean hasTotalPercentView();
//
// boolean hasDailyPercentView();
//
// boolean hasTotalChangeView();
//
// boolean hasTotalChangeAerView();
//
// boolean hasDailyPlChangeView();
//
// boolean hasDailyPlPercentView();
//
// boolean hasTotalPlPercentView();
//
// boolean hasTotalPlChangeView();
//
// boolean hasTotalPlPercentAerView();
//
// boolean alwaysUseShortName();
//
// boolean shouldUpdateOnRightTouch();
// }
| import nitezh.ministock.domain.WidgetRepository;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import nitezh.ministock.domain.Widget; | /*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.mocks;
public class MockWidgetRepository implements WidgetRepository {
private HashSet<String> widgetsStockSymbols;
@Override
public List<Integer> getIds() {
return new ArrayList<>();
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public Set<String> getWidgetsStockSymbols() {
if (this.widgetsStockSymbols != null) {
return this.widgetsStockSymbols;
}
return new HashSet<>();
}
public void setWidgetsStockSymbols(HashSet<String> widgetsStockSymbols) {
this.widgetsStockSymbols = widgetsStockSymbols;
}
@Override
public void delWidget(int id) {
}
@Override | // Path: src/main/java/nitezh/ministock/domain/Widget.java
// public interface Widget {
// Storage getStorage();
//
// void setWidgetPreferencesFromJson(JSONObject jsonPrefs);
//
// JSONObject getWidgetPreferencesAsJson();
//
// void enablePercentChangeView();
//
// void enableDailyChangeView();
//
// void setStock1();
//
// void setStock1Summary();
//
// void save();
//
// int getId();
//
// int getSize();
//
// void setSize(int size);
//
// boolean isNarrow();
//
// String getStock(int i);
//
// int getPreviousView();
//
// void setView(int view);
//
// List<String> getSymbols();
//
// int getSymbolCount();
//
// String getBackgroundStyle();
//
// boolean useLargeFont();
//
// boolean getHideSuffix();
//
// boolean getTextStyle();
//
// boolean getColorsOnPrices();
//
// String getFooterVisibility();
//
// String getFooterColor();
//
// boolean showShortTime();
//
// boolean hasDailyChangeView();
//
// boolean hasTotalPercentView();
//
// boolean hasDailyPercentView();
//
// boolean hasTotalChangeView();
//
// boolean hasTotalChangeAerView();
//
// boolean hasDailyPlChangeView();
//
// boolean hasDailyPlPercentView();
//
// boolean hasTotalPlPercentView();
//
// boolean hasTotalPlChangeView();
//
// boolean hasTotalPlPercentAerView();
//
// boolean alwaysUseShortName();
//
// boolean shouldUpdateOnRightTouch();
// }
// Path: src/test/java/nitezh/ministock/mocks/MockWidgetRepository.java
import nitezh.ministock.domain.WidgetRepository;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import nitezh.ministock.domain.Widget;
/*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.mocks;
public class MockWidgetRepository implements WidgetRepository {
private HashSet<String> widgetsStockSymbols;
@Override
public List<Integer> getIds() {
return new ArrayList<>();
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public Set<String> getWidgetsStockSymbols() {
if (this.widgetsStockSymbols != null) {
return this.widgetsStockSymbols;
}
return new HashSet<>();
}
public void setWidgetsStockSymbols(HashSet<String> widgetsStockSymbols) {
this.widgetsStockSymbols = widgetsStockSymbols;
}
@Override
public void delWidget(int id) {
}
@Override | public Widget getWidget(int id) { |
niteshpatel/ministocks | src/test/java/nitezh/ministock/domain/StockQuoteRepositoryTests.java | // Path: src/test/java/nitezh/ministock/mocks/MockCache.java
// public class MockCache extends Cache {
//
// @Override
// protected JSONObject loadCache() {
// return new JSONObject();
// }
//
// @Override
// protected void persistCache(JSONObject cache) {
// }
// }
//
// Path: src/test/java/nitezh/ministock/mocks/MockStorage.java
// public class MockStorage implements Storage {
//
// @Override
// public HashMap<String, ?> getAll() {
// return new HashMap<>();
// }
//
// @Override
// public int getInt(String widgetSize, int defaultVal) {
// return 0;
// }
//
// @Override
// public String getString(String key, String defaultVal) {
// return "";
// }
//
// @Override
// public boolean getBoolean(String large_font, boolean defaultVal) {
// return false;
// }
//
// @Override
// public void putInt(String key, int value) {
// }
//
// @Override
// public Storage putString(String key, String value) {
// return this;
// }
//
// @Override
// public void putBoolean(String key, Boolean value) {
// }
//
// @Override
// public void putFloat(String key, Float value) {
// }
//
// @Override
// public void putLong(String key, Long value) {
// }
//
// @Override
// public void apply() {
// }
// }
//
// Path: src/test/java/nitezh/ministock/mocks/MockWidgetRepository.java
// public class MockWidgetRepository implements WidgetRepository {
//
// private HashSet<String> widgetsStockSymbols;
//
// @Override
// public List<Integer> getIds() {
// return new ArrayList<>();
// }
//
// @Override
// public boolean isEmpty() {
// return false;
// }
//
// @Override
// public Set<String> getWidgetsStockSymbols() {
// if (this.widgetsStockSymbols != null) {
// return this.widgetsStockSymbols;
// }
// return new HashSet<>();
// }
//
// public void setWidgetsStockSymbols(HashSet<String> widgetsStockSymbols) {
// this.widgetsStockSymbols = widgetsStockSymbols;
// }
//
// @Override
// public void delWidget(int id) {
// }
//
// @Override
// public Widget getWidget(int id) {
// return new MockWidget();
// }
//
// @Override
// public Widget addWidget(int id, int size) {
// return this.getWidget(id);
// }
//
// }
| import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import nitezh.ministock.mocks.MockCache;
import nitezh.ministock.mocks.MockStorage;
import nitezh.ministock.mocks.MockWidgetRepository;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test; | /*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.domain;
public class StockQuoteRepositoryTests {
private StockQuoteRepository stockRepository;
@Before
public void setUp() { | // Path: src/test/java/nitezh/ministock/mocks/MockCache.java
// public class MockCache extends Cache {
//
// @Override
// protected JSONObject loadCache() {
// return new JSONObject();
// }
//
// @Override
// protected void persistCache(JSONObject cache) {
// }
// }
//
// Path: src/test/java/nitezh/ministock/mocks/MockStorage.java
// public class MockStorage implements Storage {
//
// @Override
// public HashMap<String, ?> getAll() {
// return new HashMap<>();
// }
//
// @Override
// public int getInt(String widgetSize, int defaultVal) {
// return 0;
// }
//
// @Override
// public String getString(String key, String defaultVal) {
// return "";
// }
//
// @Override
// public boolean getBoolean(String large_font, boolean defaultVal) {
// return false;
// }
//
// @Override
// public void putInt(String key, int value) {
// }
//
// @Override
// public Storage putString(String key, String value) {
// return this;
// }
//
// @Override
// public void putBoolean(String key, Boolean value) {
// }
//
// @Override
// public void putFloat(String key, Float value) {
// }
//
// @Override
// public void putLong(String key, Long value) {
// }
//
// @Override
// public void apply() {
// }
// }
//
// Path: src/test/java/nitezh/ministock/mocks/MockWidgetRepository.java
// public class MockWidgetRepository implements WidgetRepository {
//
// private HashSet<String> widgetsStockSymbols;
//
// @Override
// public List<Integer> getIds() {
// return new ArrayList<>();
// }
//
// @Override
// public boolean isEmpty() {
// return false;
// }
//
// @Override
// public Set<String> getWidgetsStockSymbols() {
// if (this.widgetsStockSymbols != null) {
// return this.widgetsStockSymbols;
// }
// return new HashSet<>();
// }
//
// public void setWidgetsStockSymbols(HashSet<String> widgetsStockSymbols) {
// this.widgetsStockSymbols = widgetsStockSymbols;
// }
//
// @Override
// public void delWidget(int id) {
// }
//
// @Override
// public Widget getWidget(int id) {
// return new MockWidget();
// }
//
// @Override
// public Widget addWidget(int id, int size) {
// return this.getWidget(id);
// }
//
// }
// Path: src/test/java/nitezh/ministock/domain/StockQuoteRepositoryTests.java
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import nitezh.ministock.mocks.MockCache;
import nitezh.ministock.mocks.MockStorage;
import nitezh.ministock.mocks.MockWidgetRepository;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
/*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.domain;
public class StockQuoteRepositoryTests {
private StockQuoteRepository stockRepository;
@Before
public void setUp() { | MockWidgetRepository mockWidgetRepository = new MockWidgetRepository(); |
niteshpatel/ministocks | src/test/java/nitezh/ministock/domain/StockQuoteRepositoryTests.java | // Path: src/test/java/nitezh/ministock/mocks/MockCache.java
// public class MockCache extends Cache {
//
// @Override
// protected JSONObject loadCache() {
// return new JSONObject();
// }
//
// @Override
// protected void persistCache(JSONObject cache) {
// }
// }
//
// Path: src/test/java/nitezh/ministock/mocks/MockStorage.java
// public class MockStorage implements Storage {
//
// @Override
// public HashMap<String, ?> getAll() {
// return new HashMap<>();
// }
//
// @Override
// public int getInt(String widgetSize, int defaultVal) {
// return 0;
// }
//
// @Override
// public String getString(String key, String defaultVal) {
// return "";
// }
//
// @Override
// public boolean getBoolean(String large_font, boolean defaultVal) {
// return false;
// }
//
// @Override
// public void putInt(String key, int value) {
// }
//
// @Override
// public Storage putString(String key, String value) {
// return this;
// }
//
// @Override
// public void putBoolean(String key, Boolean value) {
// }
//
// @Override
// public void putFloat(String key, Float value) {
// }
//
// @Override
// public void putLong(String key, Long value) {
// }
//
// @Override
// public void apply() {
// }
// }
//
// Path: src/test/java/nitezh/ministock/mocks/MockWidgetRepository.java
// public class MockWidgetRepository implements WidgetRepository {
//
// private HashSet<String> widgetsStockSymbols;
//
// @Override
// public List<Integer> getIds() {
// return new ArrayList<>();
// }
//
// @Override
// public boolean isEmpty() {
// return false;
// }
//
// @Override
// public Set<String> getWidgetsStockSymbols() {
// if (this.widgetsStockSymbols != null) {
// return this.widgetsStockSymbols;
// }
// return new HashSet<>();
// }
//
// public void setWidgetsStockSymbols(HashSet<String> widgetsStockSymbols) {
// this.widgetsStockSymbols = widgetsStockSymbols;
// }
//
// @Override
// public void delWidget(int id) {
// }
//
// @Override
// public Widget getWidget(int id) {
// return new MockWidget();
// }
//
// @Override
// public Widget addWidget(int id, int size) {
// return this.getWidget(id);
// }
//
// }
| import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import nitezh.ministock.mocks.MockCache;
import nitezh.ministock.mocks.MockStorage;
import nitezh.ministock.mocks.MockWidgetRepository;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test; | /*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.domain;
public class StockQuoteRepositoryTests {
private StockQuoteRepository stockRepository;
@Before
public void setUp() {
MockWidgetRepository mockWidgetRepository = new MockWidgetRepository();
mockWidgetRepository.setWidgetsStockSymbols(new HashSet<>(Arrays.asList(
"AAPL",
"GOOG",
"^DJI",
"^IXIC")));
stockRepository = new StockQuoteRepository( | // Path: src/test/java/nitezh/ministock/mocks/MockCache.java
// public class MockCache extends Cache {
//
// @Override
// protected JSONObject loadCache() {
// return new JSONObject();
// }
//
// @Override
// protected void persistCache(JSONObject cache) {
// }
// }
//
// Path: src/test/java/nitezh/ministock/mocks/MockStorage.java
// public class MockStorage implements Storage {
//
// @Override
// public HashMap<String, ?> getAll() {
// return new HashMap<>();
// }
//
// @Override
// public int getInt(String widgetSize, int defaultVal) {
// return 0;
// }
//
// @Override
// public String getString(String key, String defaultVal) {
// return "";
// }
//
// @Override
// public boolean getBoolean(String large_font, boolean defaultVal) {
// return false;
// }
//
// @Override
// public void putInt(String key, int value) {
// }
//
// @Override
// public Storage putString(String key, String value) {
// return this;
// }
//
// @Override
// public void putBoolean(String key, Boolean value) {
// }
//
// @Override
// public void putFloat(String key, Float value) {
// }
//
// @Override
// public void putLong(String key, Long value) {
// }
//
// @Override
// public void apply() {
// }
// }
//
// Path: src/test/java/nitezh/ministock/mocks/MockWidgetRepository.java
// public class MockWidgetRepository implements WidgetRepository {
//
// private HashSet<String> widgetsStockSymbols;
//
// @Override
// public List<Integer> getIds() {
// return new ArrayList<>();
// }
//
// @Override
// public boolean isEmpty() {
// return false;
// }
//
// @Override
// public Set<String> getWidgetsStockSymbols() {
// if (this.widgetsStockSymbols != null) {
// return this.widgetsStockSymbols;
// }
// return new HashSet<>();
// }
//
// public void setWidgetsStockSymbols(HashSet<String> widgetsStockSymbols) {
// this.widgetsStockSymbols = widgetsStockSymbols;
// }
//
// @Override
// public void delWidget(int id) {
// }
//
// @Override
// public Widget getWidget(int id) {
// return new MockWidget();
// }
//
// @Override
// public Widget addWidget(int id, int size) {
// return this.getWidget(id);
// }
//
// }
// Path: src/test/java/nitezh/ministock/domain/StockQuoteRepositoryTests.java
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import nitezh.ministock.mocks.MockCache;
import nitezh.ministock.mocks.MockStorage;
import nitezh.ministock.mocks.MockWidgetRepository;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
/*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.domain;
public class StockQuoteRepositoryTests {
private StockQuoteRepository stockRepository;
@Before
public void setUp() {
MockWidgetRepository mockWidgetRepository = new MockWidgetRepository();
mockWidgetRepository.setWidgetsStockSymbols(new HashSet<>(Arrays.asList(
"AAPL",
"GOOG",
"^DJI",
"^IXIC")));
stockRepository = new StockQuoteRepository( | new MockStorage(), new MockCache(), mockWidgetRepository); |
niteshpatel/ministocks | src/test/java/nitezh/ministock/domain/StockQuoteRepositoryTests.java | // Path: src/test/java/nitezh/ministock/mocks/MockCache.java
// public class MockCache extends Cache {
//
// @Override
// protected JSONObject loadCache() {
// return new JSONObject();
// }
//
// @Override
// protected void persistCache(JSONObject cache) {
// }
// }
//
// Path: src/test/java/nitezh/ministock/mocks/MockStorage.java
// public class MockStorage implements Storage {
//
// @Override
// public HashMap<String, ?> getAll() {
// return new HashMap<>();
// }
//
// @Override
// public int getInt(String widgetSize, int defaultVal) {
// return 0;
// }
//
// @Override
// public String getString(String key, String defaultVal) {
// return "";
// }
//
// @Override
// public boolean getBoolean(String large_font, boolean defaultVal) {
// return false;
// }
//
// @Override
// public void putInt(String key, int value) {
// }
//
// @Override
// public Storage putString(String key, String value) {
// return this;
// }
//
// @Override
// public void putBoolean(String key, Boolean value) {
// }
//
// @Override
// public void putFloat(String key, Float value) {
// }
//
// @Override
// public void putLong(String key, Long value) {
// }
//
// @Override
// public void apply() {
// }
// }
//
// Path: src/test/java/nitezh/ministock/mocks/MockWidgetRepository.java
// public class MockWidgetRepository implements WidgetRepository {
//
// private HashSet<String> widgetsStockSymbols;
//
// @Override
// public List<Integer> getIds() {
// return new ArrayList<>();
// }
//
// @Override
// public boolean isEmpty() {
// return false;
// }
//
// @Override
// public Set<String> getWidgetsStockSymbols() {
// if (this.widgetsStockSymbols != null) {
// return this.widgetsStockSymbols;
// }
// return new HashSet<>();
// }
//
// public void setWidgetsStockSymbols(HashSet<String> widgetsStockSymbols) {
// this.widgetsStockSymbols = widgetsStockSymbols;
// }
//
// @Override
// public void delWidget(int id) {
// }
//
// @Override
// public Widget getWidget(int id) {
// return new MockWidget();
// }
//
// @Override
// public Widget addWidget(int id, int size) {
// return this.getWidget(id);
// }
//
// }
| import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import nitezh.ministock.mocks.MockCache;
import nitezh.ministock.mocks.MockStorage;
import nitezh.ministock.mocks.MockWidgetRepository;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test; | /*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.domain;
public class StockQuoteRepositoryTests {
private StockQuoteRepository stockRepository;
@Before
public void setUp() {
MockWidgetRepository mockWidgetRepository = new MockWidgetRepository();
mockWidgetRepository.setWidgetsStockSymbols(new HashSet<>(Arrays.asList(
"AAPL",
"GOOG",
"^DJI",
"^IXIC")));
stockRepository = new StockQuoteRepository( | // Path: src/test/java/nitezh/ministock/mocks/MockCache.java
// public class MockCache extends Cache {
//
// @Override
// protected JSONObject loadCache() {
// return new JSONObject();
// }
//
// @Override
// protected void persistCache(JSONObject cache) {
// }
// }
//
// Path: src/test/java/nitezh/ministock/mocks/MockStorage.java
// public class MockStorage implements Storage {
//
// @Override
// public HashMap<String, ?> getAll() {
// return new HashMap<>();
// }
//
// @Override
// public int getInt(String widgetSize, int defaultVal) {
// return 0;
// }
//
// @Override
// public String getString(String key, String defaultVal) {
// return "";
// }
//
// @Override
// public boolean getBoolean(String large_font, boolean defaultVal) {
// return false;
// }
//
// @Override
// public void putInt(String key, int value) {
// }
//
// @Override
// public Storage putString(String key, String value) {
// return this;
// }
//
// @Override
// public void putBoolean(String key, Boolean value) {
// }
//
// @Override
// public void putFloat(String key, Float value) {
// }
//
// @Override
// public void putLong(String key, Long value) {
// }
//
// @Override
// public void apply() {
// }
// }
//
// Path: src/test/java/nitezh/ministock/mocks/MockWidgetRepository.java
// public class MockWidgetRepository implements WidgetRepository {
//
// private HashSet<String> widgetsStockSymbols;
//
// @Override
// public List<Integer> getIds() {
// return new ArrayList<>();
// }
//
// @Override
// public boolean isEmpty() {
// return false;
// }
//
// @Override
// public Set<String> getWidgetsStockSymbols() {
// if (this.widgetsStockSymbols != null) {
// return this.widgetsStockSymbols;
// }
// return new HashSet<>();
// }
//
// public void setWidgetsStockSymbols(HashSet<String> widgetsStockSymbols) {
// this.widgetsStockSymbols = widgetsStockSymbols;
// }
//
// @Override
// public void delWidget(int id) {
// }
//
// @Override
// public Widget getWidget(int id) {
// return new MockWidget();
// }
//
// @Override
// public Widget addWidget(int id, int size) {
// return this.getWidget(id);
// }
//
// }
// Path: src/test/java/nitezh/ministock/domain/StockQuoteRepositoryTests.java
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import nitezh.ministock.mocks.MockCache;
import nitezh.ministock.mocks.MockStorage;
import nitezh.ministock.mocks.MockWidgetRepository;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
/*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock.domain;
public class StockQuoteRepositoryTests {
private StockQuoteRepository stockRepository;
@Before
public void setUp() {
MockWidgetRepository mockWidgetRepository = new MockWidgetRepository();
mockWidgetRepository.setWidgetsStockSymbols(new HashSet<>(Arrays.asList(
"AAPL",
"GOOG",
"^DJI",
"^IXIC")));
stockRepository = new StockQuoteRepository( | new MockStorage(), new MockCache(), mockWidgetRepository); |
niteshpatel/ministocks | src/main/java/nitezh/ministock/CustomAlarmManager.java | // Path: src/main/java/nitezh/ministock/utils/DateTools.java
// public class DateTools {
//
// private DateTools() {
// }
//
// public static double elapsedDays(String dateString) {
// double daysElapsed = 0;
// if (dateString != null) {
// SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
// try {
// double elapsed = (new Date().getTime() - formatter.parse(dateString).getTime()) / 1000;
// daysElapsed = elapsed / 86400;
// } catch (ParseException ignored) {
// }
// }
// return daysElapsed;
// }
//
// public static double elapsedTime(String dateString) {
// double daysElapsed = 0;
// if (dateString != null) {
// SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
// try {
// daysElapsed = (new Date().getTime() - formatter.parse(dateString).getTime());
// } catch (ParseException ignored) {
// }
// }
// return daysElapsed;
// }
//
// public static Date parseSimpleDate(String dateString) {
// String[] items = dateString.split(":");
//
// Calendar cal = Calendar.getInstance();
// cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(items[0]));
// cal.set(Calendar.MINUTE, Integer.parseInt(items[1]));
// return cal.getTime();
// }
//
// public static int compareToNow(Date date) {
// Long now = new Date().getTime();
// if (date.getTime() > now) {
// return 1;
// } else if (date.getTime() < now) {
// return -1;
// } else {
// return 0;
// }
// }
//
// public static String getNowAsString() {
// return new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date());
// }
//
// public static String timeDigitPad(int c) {
// if (c >= 10)
// return String.valueOf(c);
// else
// return "0" + String.valueOf(c);
// }
// }
| import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import nitezh.ministock.utils.DateTools;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent; | /*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock;
public class CustomAlarmManager {
private final PreferenceStorage appStorage;
private final AlarmManager alarmManager;
private final PendingIntent pendingIntent;
public CustomAlarmManager(Context context) {
this.appStorage = PreferenceStorage.getInstance(context);
this.alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent("UPDATE", null, context, WidgetProvider.class);
this.pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
}
private Long getUpdateInterval() {
return Long.parseLong((this.appStorage.getString("update_interval",
Long.toString(AlarmManager.INTERVAL_HALF_HOUR))));
}
private int getTimeToNextUpdate(Long updateInterval) {
Double timeToNextUpdate = updateInterval.doubleValue(); | // Path: src/main/java/nitezh/ministock/utils/DateTools.java
// public class DateTools {
//
// private DateTools() {
// }
//
// public static double elapsedDays(String dateString) {
// double daysElapsed = 0;
// if (dateString != null) {
// SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
// try {
// double elapsed = (new Date().getTime() - formatter.parse(dateString).getTime()) / 1000;
// daysElapsed = elapsed / 86400;
// } catch (ParseException ignored) {
// }
// }
// return daysElapsed;
// }
//
// public static double elapsedTime(String dateString) {
// double daysElapsed = 0;
// if (dateString != null) {
// SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
// try {
// daysElapsed = (new Date().getTime() - formatter.parse(dateString).getTime());
// } catch (ParseException ignored) {
// }
// }
// return daysElapsed;
// }
//
// public static Date parseSimpleDate(String dateString) {
// String[] items = dateString.split(":");
//
// Calendar cal = Calendar.getInstance();
// cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(items[0]));
// cal.set(Calendar.MINUTE, Integer.parseInt(items[1]));
// return cal.getTime();
// }
//
// public static int compareToNow(Date date) {
// Long now = new Date().getTime();
// if (date.getTime() > now) {
// return 1;
// } else if (date.getTime() < now) {
// return -1;
// } else {
// return 0;
// }
// }
//
// public static String getNowAsString() {
// return new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date());
// }
//
// public static String timeDigitPad(int c) {
// if (c >= 10)
// return String.valueOf(c);
// else
// return "0" + String.valueOf(c);
// }
// }
// Path: src/main/java/nitezh/ministock/CustomAlarmManager.java
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import nitezh.ministock.utils.DateTools;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
/*
The MIT License
Copyright (c) 2013 Nitesh Patel http://niteshpatel.github.io/ministocks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package nitezh.ministock;
public class CustomAlarmManager {
private final PreferenceStorage appStorage;
private final AlarmManager alarmManager;
private final PendingIntent pendingIntent;
public CustomAlarmManager(Context context) {
this.appStorage = PreferenceStorage.getInstance(context);
this.alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent("UPDATE", null, context, WidgetProvider.class);
this.pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
}
private Long getUpdateInterval() {
return Long.parseLong((this.appStorage.getString("update_interval",
Long.toString(AlarmManager.INTERVAL_HALF_HOUR))));
}
private int getTimeToNextUpdate(Long updateInterval) {
Double timeToNextUpdate = updateInterval.doubleValue(); | Double elapsedTime = DateTools.elapsedTime(this.appStorage.getString("last_update1", null)); |
bcgov/sbc-qsystem | QSmartboardPlugin/src/ru/apertum/qsystem/smartboard/PrintRecordsList.java | // Path: QSystem/src/ru/apertum/qsystem/server/model/QOffice.java
// @Entity
// @Table(name = "offices")
// public class QOffice implements IidGetter, Serializable {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Expose
// @SerializedName("id")
// @Column(name = "id")
// private Long id;
//
// @Expose
// @SerializedName("name")
// @Column(name = "name")
// private String name;
//
// @Expose
// @Column(name = "smartboard_type")
// @SerializedName("smartboard_type")
// private String smartboard_type;
//
// @Column(name = "deleted")
// @Temporal(javax.persistence.TemporalType.DATE)
// private Date deleted;
//
// @Expose
// @Column(name = "office_number")
// @SerializedName("office_number")
// private Integer office_number;
//
// @ManyToMany(mappedBy = "offices", fetch = FetchType.LAZY)
// private Set<QService> services = new HashSet<>();
//
// public QOffice() {
// super();
// }
//
// @Override
// public String toString() {
// return getName();
// }
//
// @Override
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getSmartboardType() {
// return smartboard_type;
// }
//
// public void setSmartboardType(String smartboard_type) {
// this.smartboard_type = smartboard_type;
// }
//
// public Integer getOfficeNumber() {
// return office_number;
// }
//
// public void setOfficeNumber(Integer office_num) {
// this.office_number = office_num;
// }
//
// public Date getDeleted() {
// return deleted;
// }
//
// public void setDeleted(Date deleted) {
// this.deleted = deleted;
// }
//
// public Set<QService> getServices() {
// return services;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj != null && obj instanceof QOffice) {
// final QOffice o = (QOffice) obj;
// return (id == null ? o.getId() == null : id.equals(o.getId()))
// && (name == null ? o.getName() == null : name.equals(o.getName()));
// } else {
// return false;
// }
// }
// }
//
// Path: QSystem/src/ru/apertum/qsystem/server/model/QOfficeList.java
// public class QOfficeList extends ATListModel<QOffice> {
//
// private QOfficeList() {
// super();
// }
//
// public static QOfficeList getInstance() {
// return QOfficeListHolder.INSTANCE;
// }
//
// @Override
// protected LinkedList<QOffice> load() {
// final LinkedList<QOffice> offices = new LinkedList<>(
// Spring.getInstance().getHt().findByCriteria(
// DetachedCriteria.forClass(QOffice.class)
// .add(Property.forName("deleted").isNull())
// .setResultTransformer((Criteria.DISTINCT_ROOT_ENTITY))));
// return offices;
// }
//
// @Override
// public void save() {
// deleted.stream().forEach((qOffice) -> {
// qOffice.setDeleted(new Date());
// });
// Spring.getInstance().getHt().saveOrUpdateAll(deleted);
// deleted.clear();
// Spring.getInstance().getHt().saveOrUpdateAll(getItems());
// }
//
// public void refresh() {
// setItems(load());
// }
//
// private static class QOfficeListHolder {
//
// private static final QOfficeList INSTANCE = new QOfficeList();
// }
// }
| import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import javax.swing.AbstractListModel;
import ru.apertum.qsystem.common.QLog;
import ru.apertum.qsystem.server.model.QOffice;
import ru.apertum.qsystem.server.model.QOfficeList; | package ru.apertum.qsystem.smartboard;
/**
* Keeps a list of all PrintRecords objects for each office. Uses the standard QSystem method of the
* private Holder object to keep the list in the cache
*
* @author Sean Rumsby
*/
public class PrintRecordsList extends AbstractListModel implements List {
private final List<PrintRecords> printRecords = new LinkedList<>();
public PrintRecordsList() { | // Path: QSystem/src/ru/apertum/qsystem/server/model/QOffice.java
// @Entity
// @Table(name = "offices")
// public class QOffice implements IidGetter, Serializable {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Expose
// @SerializedName("id")
// @Column(name = "id")
// private Long id;
//
// @Expose
// @SerializedName("name")
// @Column(name = "name")
// private String name;
//
// @Expose
// @Column(name = "smartboard_type")
// @SerializedName("smartboard_type")
// private String smartboard_type;
//
// @Column(name = "deleted")
// @Temporal(javax.persistence.TemporalType.DATE)
// private Date deleted;
//
// @Expose
// @Column(name = "office_number")
// @SerializedName("office_number")
// private Integer office_number;
//
// @ManyToMany(mappedBy = "offices", fetch = FetchType.LAZY)
// private Set<QService> services = new HashSet<>();
//
// public QOffice() {
// super();
// }
//
// @Override
// public String toString() {
// return getName();
// }
//
// @Override
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getSmartboardType() {
// return smartboard_type;
// }
//
// public void setSmartboardType(String smartboard_type) {
// this.smartboard_type = smartboard_type;
// }
//
// public Integer getOfficeNumber() {
// return office_number;
// }
//
// public void setOfficeNumber(Integer office_num) {
// this.office_number = office_num;
// }
//
// public Date getDeleted() {
// return deleted;
// }
//
// public void setDeleted(Date deleted) {
// this.deleted = deleted;
// }
//
// public Set<QService> getServices() {
// return services;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj != null && obj instanceof QOffice) {
// final QOffice o = (QOffice) obj;
// return (id == null ? o.getId() == null : id.equals(o.getId()))
// && (name == null ? o.getName() == null : name.equals(o.getName()));
// } else {
// return false;
// }
// }
// }
//
// Path: QSystem/src/ru/apertum/qsystem/server/model/QOfficeList.java
// public class QOfficeList extends ATListModel<QOffice> {
//
// private QOfficeList() {
// super();
// }
//
// public static QOfficeList getInstance() {
// return QOfficeListHolder.INSTANCE;
// }
//
// @Override
// protected LinkedList<QOffice> load() {
// final LinkedList<QOffice> offices = new LinkedList<>(
// Spring.getInstance().getHt().findByCriteria(
// DetachedCriteria.forClass(QOffice.class)
// .add(Property.forName("deleted").isNull())
// .setResultTransformer((Criteria.DISTINCT_ROOT_ENTITY))));
// return offices;
// }
//
// @Override
// public void save() {
// deleted.stream().forEach((qOffice) -> {
// qOffice.setDeleted(new Date());
// });
// Spring.getInstance().getHt().saveOrUpdateAll(deleted);
// deleted.clear();
// Spring.getInstance().getHt().saveOrUpdateAll(getItems());
// }
//
// public void refresh() {
// setItems(load());
// }
//
// private static class QOfficeListHolder {
//
// private static final QOfficeList INSTANCE = new QOfficeList();
// }
// }
// Path: QSmartboardPlugin/src/ru/apertum/qsystem/smartboard/PrintRecordsList.java
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import javax.swing.AbstractListModel;
import ru.apertum.qsystem.common.QLog;
import ru.apertum.qsystem.server.model.QOffice;
import ru.apertum.qsystem.server.model.QOfficeList;
package ru.apertum.qsystem.smartboard;
/**
* Keeps a list of all PrintRecords objects for each office. Uses the standard QSystem method of the
* private Holder object to keep the list in the cache
*
* @author Sean Rumsby
*/
public class PrintRecordsList extends AbstractListModel implements List {
private final List<PrintRecords> printRecords = new LinkedList<>();
public PrintRecordsList() { | QOfficeList officeList = QOfficeList.getInstance(); |
bcgov/sbc-qsystem | QSmartboardPlugin/src/ru/apertum/qsystem/smartboard/PrintRecordsList.java | // Path: QSystem/src/ru/apertum/qsystem/server/model/QOffice.java
// @Entity
// @Table(name = "offices")
// public class QOffice implements IidGetter, Serializable {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Expose
// @SerializedName("id")
// @Column(name = "id")
// private Long id;
//
// @Expose
// @SerializedName("name")
// @Column(name = "name")
// private String name;
//
// @Expose
// @Column(name = "smartboard_type")
// @SerializedName("smartboard_type")
// private String smartboard_type;
//
// @Column(name = "deleted")
// @Temporal(javax.persistence.TemporalType.DATE)
// private Date deleted;
//
// @Expose
// @Column(name = "office_number")
// @SerializedName("office_number")
// private Integer office_number;
//
// @ManyToMany(mappedBy = "offices", fetch = FetchType.LAZY)
// private Set<QService> services = new HashSet<>();
//
// public QOffice() {
// super();
// }
//
// @Override
// public String toString() {
// return getName();
// }
//
// @Override
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getSmartboardType() {
// return smartboard_type;
// }
//
// public void setSmartboardType(String smartboard_type) {
// this.smartboard_type = smartboard_type;
// }
//
// public Integer getOfficeNumber() {
// return office_number;
// }
//
// public void setOfficeNumber(Integer office_num) {
// this.office_number = office_num;
// }
//
// public Date getDeleted() {
// return deleted;
// }
//
// public void setDeleted(Date deleted) {
// this.deleted = deleted;
// }
//
// public Set<QService> getServices() {
// return services;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj != null && obj instanceof QOffice) {
// final QOffice o = (QOffice) obj;
// return (id == null ? o.getId() == null : id.equals(o.getId()))
// && (name == null ? o.getName() == null : name.equals(o.getName()));
// } else {
// return false;
// }
// }
// }
//
// Path: QSystem/src/ru/apertum/qsystem/server/model/QOfficeList.java
// public class QOfficeList extends ATListModel<QOffice> {
//
// private QOfficeList() {
// super();
// }
//
// public static QOfficeList getInstance() {
// return QOfficeListHolder.INSTANCE;
// }
//
// @Override
// protected LinkedList<QOffice> load() {
// final LinkedList<QOffice> offices = new LinkedList<>(
// Spring.getInstance().getHt().findByCriteria(
// DetachedCriteria.forClass(QOffice.class)
// .add(Property.forName("deleted").isNull())
// .setResultTransformer((Criteria.DISTINCT_ROOT_ENTITY))));
// return offices;
// }
//
// @Override
// public void save() {
// deleted.stream().forEach((qOffice) -> {
// qOffice.setDeleted(new Date());
// });
// Spring.getInstance().getHt().saveOrUpdateAll(deleted);
// deleted.clear();
// Spring.getInstance().getHt().saveOrUpdateAll(getItems());
// }
//
// public void refresh() {
// setItems(load());
// }
//
// private static class QOfficeListHolder {
//
// private static final QOfficeList INSTANCE = new QOfficeList();
// }
// }
| import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import javax.swing.AbstractListModel;
import ru.apertum.qsystem.common.QLog;
import ru.apertum.qsystem.server.model.QOffice;
import ru.apertum.qsystem.server.model.QOfficeList; | package ru.apertum.qsystem.smartboard;
/**
* Keeps a list of all PrintRecords objects for each office. Uses the standard QSystem method of the
* private Holder object to keep the list in the cache
*
* @author Sean Rumsby
*/
public class PrintRecordsList extends AbstractListModel implements List {
private final List<PrintRecords> printRecords = new LinkedList<>();
public PrintRecordsList() {
QOfficeList officeList = QOfficeList.getInstance();
| // Path: QSystem/src/ru/apertum/qsystem/server/model/QOffice.java
// @Entity
// @Table(name = "offices")
// public class QOffice implements IidGetter, Serializable {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Expose
// @SerializedName("id")
// @Column(name = "id")
// private Long id;
//
// @Expose
// @SerializedName("name")
// @Column(name = "name")
// private String name;
//
// @Expose
// @Column(name = "smartboard_type")
// @SerializedName("smartboard_type")
// private String smartboard_type;
//
// @Column(name = "deleted")
// @Temporal(javax.persistence.TemporalType.DATE)
// private Date deleted;
//
// @Expose
// @Column(name = "office_number")
// @SerializedName("office_number")
// private Integer office_number;
//
// @ManyToMany(mappedBy = "offices", fetch = FetchType.LAZY)
// private Set<QService> services = new HashSet<>();
//
// public QOffice() {
// super();
// }
//
// @Override
// public String toString() {
// return getName();
// }
//
// @Override
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getSmartboardType() {
// return smartboard_type;
// }
//
// public void setSmartboardType(String smartboard_type) {
// this.smartboard_type = smartboard_type;
// }
//
// public Integer getOfficeNumber() {
// return office_number;
// }
//
// public void setOfficeNumber(Integer office_num) {
// this.office_number = office_num;
// }
//
// public Date getDeleted() {
// return deleted;
// }
//
// public void setDeleted(Date deleted) {
// this.deleted = deleted;
// }
//
// public Set<QService> getServices() {
// return services;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj != null && obj instanceof QOffice) {
// final QOffice o = (QOffice) obj;
// return (id == null ? o.getId() == null : id.equals(o.getId()))
// && (name == null ? o.getName() == null : name.equals(o.getName()));
// } else {
// return false;
// }
// }
// }
//
// Path: QSystem/src/ru/apertum/qsystem/server/model/QOfficeList.java
// public class QOfficeList extends ATListModel<QOffice> {
//
// private QOfficeList() {
// super();
// }
//
// public static QOfficeList getInstance() {
// return QOfficeListHolder.INSTANCE;
// }
//
// @Override
// protected LinkedList<QOffice> load() {
// final LinkedList<QOffice> offices = new LinkedList<>(
// Spring.getInstance().getHt().findByCriteria(
// DetachedCriteria.forClass(QOffice.class)
// .add(Property.forName("deleted").isNull())
// .setResultTransformer((Criteria.DISTINCT_ROOT_ENTITY))));
// return offices;
// }
//
// @Override
// public void save() {
// deleted.stream().forEach((qOffice) -> {
// qOffice.setDeleted(new Date());
// });
// Spring.getInstance().getHt().saveOrUpdateAll(deleted);
// deleted.clear();
// Spring.getInstance().getHt().saveOrUpdateAll(getItems());
// }
//
// public void refresh() {
// setItems(load());
// }
//
// private static class QOfficeListHolder {
//
// private static final QOfficeList INSTANCE = new QOfficeList();
// }
// }
// Path: QSmartboardPlugin/src/ru/apertum/qsystem/smartboard/PrintRecordsList.java
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import javax.swing.AbstractListModel;
import ru.apertum.qsystem.common.QLog;
import ru.apertum.qsystem.server.model.QOffice;
import ru.apertum.qsystem.server.model.QOfficeList;
package ru.apertum.qsystem.smartboard;
/**
* Keeps a list of all PrintRecords objects for each office. Uses the standard QSystem method of the
* private Holder object to keep the list in the cache
*
* @author Sean Rumsby
*/
public class PrintRecordsList extends AbstractListModel implements List {
private final List<PrintRecords> printRecords = new LinkedList<>();
public PrintRecordsList() {
QOfficeList officeList = QOfficeList.getInstance();
| for (QOffice office : officeList.getItems()) { |
simo415/spc | src/com/sijobe/spc/wrapper/MinecraftServer.java | // Path: src/com/sijobe/spc/core/Constants.java
// public class Constants {
//
// /**
// * Contains the version string of the current Minecraft version
// */
// public static final String VERSION = "4.9";
//
// /**
// * The name of the mod
// */
// public static final String NAME = "Single Player Commands";
//
// /**
// * The current version of the mod
// */
// public static final ModVersion SPC_VERSION = new ModVersion(NAME, VERSION, new Date(1374315917859L)); // 2013-07-20 20:25:17
//
// /**
// * The directory that the mod saves/loads global settings from
// */
// public static final File MOD_DIR = new File(Minecraft.getMinecraftDirectory(), "mods/spc");
//
// // Creates the mod directory if it doesn't already exist
// static {
// if (!MOD_DIR.exists()) {
// MOD_DIR.mkdirs();
// }
// }
//
// /**
// * The default settings file to use
// */
// public static final Settings DEFAULT_SETTINGS = new Settings(new File(MOD_DIR, "default.properties"));
//
// /**
// * Directory where the Minecraft level saves are located
// */
// public static final File SAVES_DIR = new File(Minecraft.getMinecraftDirectory(), "saves");
//
// /**
// * @return the version
// */
// public static String getVersion() {
// return VERSION;
// }
//
// /**
// * @return the name
// */
// public static String getName() {
// return NAME;
// }
//
// /**
// * @return the spcVersion
// */
// public static ModVersion getSpcVersion() {
// return SPC_VERSION;
// }
//
// /**
// * @return the modDir
// */
// public static File getModDir() {
// return MOD_DIR;
// }
// }
| import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.sijobe.spc.core.Constants; |
/**
* Runs the specified command (with parameters) on the server. Note that
* this sends through the command as a server instance rather than with a
* player. If you need to send through a command using a sender please see
* CommandManager.runCommand
*
* @param command - The command to run on the server
* @return A String of the output received
* @see CommandManager#runCommand(CommandSender, String)
*/
public static String runCommand(String command) {
return getMinecraftServer().executeCommand(command);
}
/**
* Gets the directory name of the loaded world
*
* @return The directory name of the world
*/
public static String getDirectoryName() {
return getMinecraftServer().getFolderName();
}
/**
* Gets the directory that the currently loaded world is located at
*
* @return The location where the world is located
*/
public static File getWorldDirectory() { | // Path: src/com/sijobe/spc/core/Constants.java
// public class Constants {
//
// /**
// * Contains the version string of the current Minecraft version
// */
// public static final String VERSION = "4.9";
//
// /**
// * The name of the mod
// */
// public static final String NAME = "Single Player Commands";
//
// /**
// * The current version of the mod
// */
// public static final ModVersion SPC_VERSION = new ModVersion(NAME, VERSION, new Date(1374315917859L)); // 2013-07-20 20:25:17
//
// /**
// * The directory that the mod saves/loads global settings from
// */
// public static final File MOD_DIR = new File(Minecraft.getMinecraftDirectory(), "mods/spc");
//
// // Creates the mod directory if it doesn't already exist
// static {
// if (!MOD_DIR.exists()) {
// MOD_DIR.mkdirs();
// }
// }
//
// /**
// * The default settings file to use
// */
// public static final Settings DEFAULT_SETTINGS = new Settings(new File(MOD_DIR, "default.properties"));
//
// /**
// * Directory where the Minecraft level saves are located
// */
// public static final File SAVES_DIR = new File(Minecraft.getMinecraftDirectory(), "saves");
//
// /**
// * @return the version
// */
// public static String getVersion() {
// return VERSION;
// }
//
// /**
// * @return the name
// */
// public static String getName() {
// return NAME;
// }
//
// /**
// * @return the spcVersion
// */
// public static ModVersion getSpcVersion() {
// return SPC_VERSION;
// }
//
// /**
// * @return the modDir
// */
// public static File getModDir() {
// return MOD_DIR;
// }
// }
// Path: src/com/sijobe/spc/wrapper/MinecraftServer.java
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.sijobe.spc.core.Constants;
/**
* Runs the specified command (with parameters) on the server. Note that
* this sends through the command as a server instance rather than with a
* player. If you need to send through a command using a sender please see
* CommandManager.runCommand
*
* @param command - The command to run on the server
* @return A String of the output received
* @see CommandManager#runCommand(CommandSender, String)
*/
public static String runCommand(String command) {
return getMinecraftServer().executeCommand(command);
}
/**
* Gets the directory name of the loaded world
*
* @return The directory name of the world
*/
public static String getDirectoryName() {
return getMinecraftServer().getFolderName();
}
/**
* Gets the directory that the currently loaded world is located at
*
* @return The location where the world is located
*/
public static File getWorldDirectory() { | return new File(Constants.SAVES_DIR, getDirectoryName()); |
simo415/spc | src/com/sijobe/spc/command/EnderChest.java | // Path: src/com/sijobe/spc/wrapper/CommandException.java
// public class CommandException extends Exception {
//
// /**
// * GUID
// */
// private static final long serialVersionUID = -2082390336460702125L;
//
// public CommandException() {
// super();
// }
//
// public CommandException(String message) {
// super(message);
// }
//
// public CommandException(Throwable t) {
// super(t);
// }
// }
//
// Path: src/com/sijobe/spc/wrapper/CommandSender.java
// public class CommandSender {
// private final ICommandSender sender;
//
// /**
// * Standard constructor that accepts the sender to wrap
// *
// * @param sender - The sender to wrap
// */
// public CommandSender(ICommandSender sender) {
// this.sender = sender;
// }
//
// /**
// * Creates an instance of a command sender using the player instance
// *
// * @param player - The player to create a command sender
// */
// public CommandSender(Player player) {
// this (player.getMinecraftPlayer());
// }
//
// /**
// * Gets the senders name, commonly this is the player's username
// *
// * @return The senders name
// */
// public String getSenderName() {
// return sender.getCommandSenderName();
// }
//
// /**
// * Returns true if the sender can use the specified command
// *
// * @param command - The command name
// * @return True is returned if the sender can use the specified command
// */
// public boolean canUseCommand(String command) {
// return sender.canCommandSenderUseCommand(4, command);
// }
//
// /**
// * Sends the specified message to the sender. The sender should display this
// * message.
// *
// * @param message - The message to display
// */
// public void sendMessageToPlayer(String message) {
// sender.sendChatToPlayer(ChatMessageComponent.func_111066_d(message));
// }
//
// /**
// * Translates the provided key translate with the provided parameters
// *
// * @param translate - The string to translate
// * @param params - The parameters
// * @return The translated String
// */
// public String translateString(String translate, Object ... params) {
// return StatCollector.translateToLocalFormatted(translate, params);
// }
//
// /**
// * Gets the raw data object that this class is wrapping around
// *
// * @return The ICommandSender class
// */
// public ICommandSender getMinecraftISender() {
// return sender;
// }
//
// /**
// * Returns true if this command sender object is a player
// *
// * @return True if the command sender is a player, false otherwise
// */
// public boolean isPlayer() {
// return sender instanceof EntityPlayer;
// }
// }
| import com.sijobe.spc.wrapper.CommandException;
import com.sijobe.spc.wrapper.CommandSender;
import net.minecraft.src.EntityPlayer;
import java.util.List;
| package com.sijobe.spc.command;
/**
* Open enderchest GUI anywhere
*
* @author q3hardcore
* @version 1.4.2
*/
@Command (
name = "enderchest",
description = "Opens EnderChest GUI without having EnderChest",
example = "",
version = "1.4.2"
)
public class EnderChest extends StandardCommand {
/**
* @see com.sijobe.spc.wrapper.CommandBase#execute(com.sijobe.spc.wrapper.CommandSender, java.util.List)
*/
@Override
| // Path: src/com/sijobe/spc/wrapper/CommandException.java
// public class CommandException extends Exception {
//
// /**
// * GUID
// */
// private static final long serialVersionUID = -2082390336460702125L;
//
// public CommandException() {
// super();
// }
//
// public CommandException(String message) {
// super(message);
// }
//
// public CommandException(Throwable t) {
// super(t);
// }
// }
//
// Path: src/com/sijobe/spc/wrapper/CommandSender.java
// public class CommandSender {
// private final ICommandSender sender;
//
// /**
// * Standard constructor that accepts the sender to wrap
// *
// * @param sender - The sender to wrap
// */
// public CommandSender(ICommandSender sender) {
// this.sender = sender;
// }
//
// /**
// * Creates an instance of a command sender using the player instance
// *
// * @param player - The player to create a command sender
// */
// public CommandSender(Player player) {
// this (player.getMinecraftPlayer());
// }
//
// /**
// * Gets the senders name, commonly this is the player's username
// *
// * @return The senders name
// */
// public String getSenderName() {
// return sender.getCommandSenderName();
// }
//
// /**
// * Returns true if the sender can use the specified command
// *
// * @param command - The command name
// * @return True is returned if the sender can use the specified command
// */
// public boolean canUseCommand(String command) {
// return sender.canCommandSenderUseCommand(4, command);
// }
//
// /**
// * Sends the specified message to the sender. The sender should display this
// * message.
// *
// * @param message - The message to display
// */
// public void sendMessageToPlayer(String message) {
// sender.sendChatToPlayer(ChatMessageComponent.func_111066_d(message));
// }
//
// /**
// * Translates the provided key translate with the provided parameters
// *
// * @param translate - The string to translate
// * @param params - The parameters
// * @return The translated String
// */
// public String translateString(String translate, Object ... params) {
// return StatCollector.translateToLocalFormatted(translate, params);
// }
//
// /**
// * Gets the raw data object that this class is wrapping around
// *
// * @return The ICommandSender class
// */
// public ICommandSender getMinecraftISender() {
// return sender;
// }
//
// /**
// * Returns true if this command sender object is a player
// *
// * @return True if the command sender is a player, false otherwise
// */
// public boolean isPlayer() {
// return sender instanceof EntityPlayer;
// }
// }
// Path: src/com/sijobe/spc/command/EnderChest.java
import com.sijobe.spc.wrapper.CommandException;
import com.sijobe.spc.wrapper.CommandSender;
import net.minecraft.src.EntityPlayer;
import java.util.List;
package com.sijobe.spc.command;
/**
* Open enderchest GUI anywhere
*
* @author q3hardcore
* @version 1.4.2
*/
@Command (
name = "enderchest",
description = "Opens EnderChest GUI without having EnderChest",
example = "",
version = "1.4.2"
)
public class EnderChest extends StandardCommand {
/**
* @see com.sijobe.spc.wrapper.CommandBase#execute(com.sijobe.spc.wrapper.CommandSender, java.util.List)
*/
@Override
| public void execute(CommandSender sender, List<?> params) throws CommandException {
|
simo415/spc | src/com/sijobe/spc/command/EnderChest.java | // Path: src/com/sijobe/spc/wrapper/CommandException.java
// public class CommandException extends Exception {
//
// /**
// * GUID
// */
// private static final long serialVersionUID = -2082390336460702125L;
//
// public CommandException() {
// super();
// }
//
// public CommandException(String message) {
// super(message);
// }
//
// public CommandException(Throwable t) {
// super(t);
// }
// }
//
// Path: src/com/sijobe/spc/wrapper/CommandSender.java
// public class CommandSender {
// private final ICommandSender sender;
//
// /**
// * Standard constructor that accepts the sender to wrap
// *
// * @param sender - The sender to wrap
// */
// public CommandSender(ICommandSender sender) {
// this.sender = sender;
// }
//
// /**
// * Creates an instance of a command sender using the player instance
// *
// * @param player - The player to create a command sender
// */
// public CommandSender(Player player) {
// this (player.getMinecraftPlayer());
// }
//
// /**
// * Gets the senders name, commonly this is the player's username
// *
// * @return The senders name
// */
// public String getSenderName() {
// return sender.getCommandSenderName();
// }
//
// /**
// * Returns true if the sender can use the specified command
// *
// * @param command - The command name
// * @return True is returned if the sender can use the specified command
// */
// public boolean canUseCommand(String command) {
// return sender.canCommandSenderUseCommand(4, command);
// }
//
// /**
// * Sends the specified message to the sender. The sender should display this
// * message.
// *
// * @param message - The message to display
// */
// public void sendMessageToPlayer(String message) {
// sender.sendChatToPlayer(ChatMessageComponent.func_111066_d(message));
// }
//
// /**
// * Translates the provided key translate with the provided parameters
// *
// * @param translate - The string to translate
// * @param params - The parameters
// * @return The translated String
// */
// public String translateString(String translate, Object ... params) {
// return StatCollector.translateToLocalFormatted(translate, params);
// }
//
// /**
// * Gets the raw data object that this class is wrapping around
// *
// * @return The ICommandSender class
// */
// public ICommandSender getMinecraftISender() {
// return sender;
// }
//
// /**
// * Returns true if this command sender object is a player
// *
// * @return True if the command sender is a player, false otherwise
// */
// public boolean isPlayer() {
// return sender instanceof EntityPlayer;
// }
// }
| import com.sijobe.spc.wrapper.CommandException;
import com.sijobe.spc.wrapper.CommandSender;
import net.minecraft.src.EntityPlayer;
import java.util.List;
| package com.sijobe.spc.command;
/**
* Open enderchest GUI anywhere
*
* @author q3hardcore
* @version 1.4.2
*/
@Command (
name = "enderchest",
description = "Opens EnderChest GUI without having EnderChest",
example = "",
version = "1.4.2"
)
public class EnderChest extends StandardCommand {
/**
* @see com.sijobe.spc.wrapper.CommandBase#execute(com.sijobe.spc.wrapper.CommandSender, java.util.List)
*/
@Override
| // Path: src/com/sijobe/spc/wrapper/CommandException.java
// public class CommandException extends Exception {
//
// /**
// * GUID
// */
// private static final long serialVersionUID = -2082390336460702125L;
//
// public CommandException() {
// super();
// }
//
// public CommandException(String message) {
// super(message);
// }
//
// public CommandException(Throwable t) {
// super(t);
// }
// }
//
// Path: src/com/sijobe/spc/wrapper/CommandSender.java
// public class CommandSender {
// private final ICommandSender sender;
//
// /**
// * Standard constructor that accepts the sender to wrap
// *
// * @param sender - The sender to wrap
// */
// public CommandSender(ICommandSender sender) {
// this.sender = sender;
// }
//
// /**
// * Creates an instance of a command sender using the player instance
// *
// * @param player - The player to create a command sender
// */
// public CommandSender(Player player) {
// this (player.getMinecraftPlayer());
// }
//
// /**
// * Gets the senders name, commonly this is the player's username
// *
// * @return The senders name
// */
// public String getSenderName() {
// return sender.getCommandSenderName();
// }
//
// /**
// * Returns true if the sender can use the specified command
// *
// * @param command - The command name
// * @return True is returned if the sender can use the specified command
// */
// public boolean canUseCommand(String command) {
// return sender.canCommandSenderUseCommand(4, command);
// }
//
// /**
// * Sends the specified message to the sender. The sender should display this
// * message.
// *
// * @param message - The message to display
// */
// public void sendMessageToPlayer(String message) {
// sender.sendChatToPlayer(ChatMessageComponent.func_111066_d(message));
// }
//
// /**
// * Translates the provided key translate with the provided parameters
// *
// * @param translate - The string to translate
// * @param params - The parameters
// * @return The translated String
// */
// public String translateString(String translate, Object ... params) {
// return StatCollector.translateToLocalFormatted(translate, params);
// }
//
// /**
// * Gets the raw data object that this class is wrapping around
// *
// * @return The ICommandSender class
// */
// public ICommandSender getMinecraftISender() {
// return sender;
// }
//
// /**
// * Returns true if this command sender object is a player
// *
// * @return True if the command sender is a player, false otherwise
// */
// public boolean isPlayer() {
// return sender instanceof EntityPlayer;
// }
// }
// Path: src/com/sijobe/spc/command/EnderChest.java
import com.sijobe.spc.wrapper.CommandException;
import com.sijobe.spc.wrapper.CommandSender;
import net.minecraft.src.EntityPlayer;
import java.util.List;
package com.sijobe.spc.command;
/**
* Open enderchest GUI anywhere
*
* @author q3hardcore
* @version 1.4.2
*/
@Command (
name = "enderchest",
description = "Opens EnderChest GUI without having EnderChest",
example = "",
version = "1.4.2"
)
public class EnderChest extends StandardCommand {
/**
* @see com.sijobe.spc.wrapper.CommandBase#execute(com.sijobe.spc.wrapper.CommandSender, java.util.List)
*/
@Override
| public void execute(CommandSender sender, List<?> params) throws CommandException {
|
simo415/spc | src/com/sijobe/spc/worldedit/PropertiesConfiguration.java | // Path: src/com/sijobe/spc/core/Constants.java
// public class Constants {
//
// /**
// * Contains the version string of the current Minecraft version
// */
// public static final String VERSION = "4.9";
//
// /**
// * The name of the mod
// */
// public static final String NAME = "Single Player Commands";
//
// /**
// * The current version of the mod
// */
// public static final ModVersion SPC_VERSION = new ModVersion(NAME, VERSION, new Date(1374315917859L)); // 2013-07-20 20:25:17
//
// /**
// * The directory that the mod saves/loads global settings from
// */
// public static final File MOD_DIR = new File(Minecraft.getMinecraftDirectory(), "mods/spc");
//
// // Creates the mod directory if it doesn't already exist
// static {
// if (!MOD_DIR.exists()) {
// MOD_DIR.mkdirs();
// }
// }
//
// /**
// * The default settings file to use
// */
// public static final Settings DEFAULT_SETTINGS = new Settings(new File(MOD_DIR, "default.properties"));
//
// /**
// * Directory where the Minecraft level saves are located
// */
// public static final File SAVES_DIR = new File(Minecraft.getMinecraftDirectory(), "saves");
//
// /**
// * @return the version
// */
// public static String getVersion() {
// return VERSION;
// }
//
// /**
// * @return the name
// */
// public static String getName() {
// return NAME;
// }
//
// /**
// * @return the spcVersion
// */
// public static ModVersion getSpcVersion() {
// return SPC_VERSION;
// }
//
// /**
// * @return the modDir
// */
// public static File getModDir() {
// return MOD_DIR;
// }
// }
| import com.sijobe.spc.core.Constants;
import java.io.File; | package com.sijobe.spc.worldedit;
public class PropertiesConfiguration extends com.sk89q.worldedit.util.PropertiesConfiguration {
/**
* Initialises the class
*/
public PropertiesConfiguration() { | // Path: src/com/sijobe/spc/core/Constants.java
// public class Constants {
//
// /**
// * Contains the version string of the current Minecraft version
// */
// public static final String VERSION = "4.9";
//
// /**
// * The name of the mod
// */
// public static final String NAME = "Single Player Commands";
//
// /**
// * The current version of the mod
// */
// public static final ModVersion SPC_VERSION = new ModVersion(NAME, VERSION, new Date(1374315917859L)); // 2013-07-20 20:25:17
//
// /**
// * The directory that the mod saves/loads global settings from
// */
// public static final File MOD_DIR = new File(Minecraft.getMinecraftDirectory(), "mods/spc");
//
// // Creates the mod directory if it doesn't already exist
// static {
// if (!MOD_DIR.exists()) {
// MOD_DIR.mkdirs();
// }
// }
//
// /**
// * The default settings file to use
// */
// public static final Settings DEFAULT_SETTINGS = new Settings(new File(MOD_DIR, "default.properties"));
//
// /**
// * Directory where the Minecraft level saves are located
// */
// public static final File SAVES_DIR = new File(Minecraft.getMinecraftDirectory(), "saves");
//
// /**
// * @return the version
// */
// public static String getVersion() {
// return VERSION;
// }
//
// /**
// * @return the name
// */
// public static String getName() {
// return NAME;
// }
//
// /**
// * @return the spcVersion
// */
// public static ModVersion getSpcVersion() {
// return SPC_VERSION;
// }
//
// /**
// * @return the modDir
// */
// public static File getModDir() {
// return MOD_DIR;
// }
// }
// Path: src/com/sijobe/spc/worldedit/PropertiesConfiguration.java
import com.sijobe.spc.core.Constants;
import java.io.File;
package com.sijobe.spc.worldedit;
public class PropertiesConfiguration extends com.sk89q.worldedit.util.PropertiesConfiguration {
/**
* Initialises the class
*/
public PropertiesConfiguration() { | super(new File(Constants.MOD_DIR,"worldedit.properties")); |
simo415/spc | src/com/sijobe/spc/validation/ParameterPlayer.java | // Path: src/com/sijobe/spc/wrapper/MinecraftServer.java
// public class MinecraftServer {
//
// /**
// * Gets the instance of the Minecraft server that is running
// *
// * @return The Minecraft server instance
// */
// public static net.minecraft.server.MinecraftServer getMinecraftServer() {
// return net.minecraft.server.MinecraftServer.getServer();
// }
//
// /**
// * Gets the version of Minecraft that the server currently is
// *
// * @return The server version
// */
// public static String getVersion() {
// return getMinecraftServer().getMinecraftVersion();
// }
//
// /**
// * Returns a List of all currently logged in users
// *
// * @return A List of all the usernames of logged in users
// */
// public static List<String> getPlayers() {
// List<String> players = new ArrayList<String>();
// for (String username : getMinecraftServer().getAllUsernames()) {
// players.add(username.toLowerCase());
// }
// return players;
// }
//
// /**
// * Checks if the specified user is currently logged in, if so true is
// * returned, otherwise false
// *
// * @param username - The username to check
// * @return True if the user is logged in
// */
// public static boolean isLoggedIn(String username) {
// return getPlayers().indexOf(username.toLowerCase()) != -1;
// }
//
// /**
// * Gets the player object that matches the provided username or null if the
// * username cannot be found
// *
// * @param username - The username to search for
// * @return The Player object that wraps the Minecraft instance
// */
// public static Player getPlayerByUsername(String username) {
// if (isLoggedIn(username)) {
// return new Player(getMinecraftServer().getConfigurationManager().getPlayerForUsername(username));
// }
// return null;
// }
//
// /**
// * Runs the specified command (with parameters) on the server. Note that
// * this sends through the command as a server instance rather than with a
// * player. If you need to send through a command using a sender please see
// * CommandManager.runCommand
// *
// * @param command - The command to run on the server
// * @return A String of the output received
// * @see CommandManager#runCommand(CommandSender, String)
// */
// public static String runCommand(String command) {
// return getMinecraftServer().executeCommand(command);
// }
//
// /**
// * Gets the directory name of the loaded world
// *
// * @return The directory name of the world
// */
// public static String getDirectoryName() {
// return getMinecraftServer().getFolderName();
// }
//
// /**
// * Gets the directory that the currently loaded world is located at
// *
// * @return The location where the world is located
// */
// public static File getWorldDirectory() {
// return new File(Constants.SAVES_DIR, getDirectoryName());
// }
// }
| import com.sijobe.spc.wrapper.MinecraftServer; | package com.sijobe.spc.validation;
/**
* Validates that the provided value is a logged in players name
*
* @author simo_415
* @version 1.0
*/
public class ParameterPlayer extends Parameter {
/**
* Initialises the instance using the set parameters
*
* @param label - The name of the parameter
* @param optional - True if the parameter is optional
*/
public ParameterPlayer(String label, boolean optional) {
super(label,optional);
}
/**
* @see com.sijobe.spc.validation.Parameter#validate(java.lang.String)
*/
@Override
public Object validate(String parameter) throws ValidationException {
// Need to loop through rather than use List.contains due to case sensitivity | // Path: src/com/sijobe/spc/wrapper/MinecraftServer.java
// public class MinecraftServer {
//
// /**
// * Gets the instance of the Minecraft server that is running
// *
// * @return The Minecraft server instance
// */
// public static net.minecraft.server.MinecraftServer getMinecraftServer() {
// return net.minecraft.server.MinecraftServer.getServer();
// }
//
// /**
// * Gets the version of Minecraft that the server currently is
// *
// * @return The server version
// */
// public static String getVersion() {
// return getMinecraftServer().getMinecraftVersion();
// }
//
// /**
// * Returns a List of all currently logged in users
// *
// * @return A List of all the usernames of logged in users
// */
// public static List<String> getPlayers() {
// List<String> players = new ArrayList<String>();
// for (String username : getMinecraftServer().getAllUsernames()) {
// players.add(username.toLowerCase());
// }
// return players;
// }
//
// /**
// * Checks if the specified user is currently logged in, if so true is
// * returned, otherwise false
// *
// * @param username - The username to check
// * @return True if the user is logged in
// */
// public static boolean isLoggedIn(String username) {
// return getPlayers().indexOf(username.toLowerCase()) != -1;
// }
//
// /**
// * Gets the player object that matches the provided username or null if the
// * username cannot be found
// *
// * @param username - The username to search for
// * @return The Player object that wraps the Minecraft instance
// */
// public static Player getPlayerByUsername(String username) {
// if (isLoggedIn(username)) {
// return new Player(getMinecraftServer().getConfigurationManager().getPlayerForUsername(username));
// }
// return null;
// }
//
// /**
// * Runs the specified command (with parameters) on the server. Note that
// * this sends through the command as a server instance rather than with a
// * player. If you need to send through a command using a sender please see
// * CommandManager.runCommand
// *
// * @param command - The command to run on the server
// * @return A String of the output received
// * @see CommandManager#runCommand(CommandSender, String)
// */
// public static String runCommand(String command) {
// return getMinecraftServer().executeCommand(command);
// }
//
// /**
// * Gets the directory name of the loaded world
// *
// * @return The directory name of the world
// */
// public static String getDirectoryName() {
// return getMinecraftServer().getFolderName();
// }
//
// /**
// * Gets the directory that the currently loaded world is located at
// *
// * @return The location where the world is located
// */
// public static File getWorldDirectory() {
// return new File(Constants.SAVES_DIR, getDirectoryName());
// }
// }
// Path: src/com/sijobe/spc/validation/ParameterPlayer.java
import com.sijobe.spc.wrapper.MinecraftServer;
package com.sijobe.spc.validation;
/**
* Validates that the provided value is a logged in players name
*
* @author simo_415
* @version 1.0
*/
public class ParameterPlayer extends Parameter {
/**
* Initialises the instance using the set parameters
*
* @param label - The name of the parameter
* @param optional - True if the parameter is optional
*/
public ParameterPlayer(String label, boolean optional) {
super(label,optional);
}
/**
* @see com.sijobe.spc.validation.Parameter#validate(java.lang.String)
*/
@Override
public Object validate(String parameter) throws ValidationException {
// Need to loop through rather than use List.contains due to case sensitivity | for (String player : MinecraftServer.getPlayers()) { |
simo415/spc | src/com/sijobe/spc/command/Test.java | // Path: src/com/sijobe/spc/util/FontColour.java
// public enum FontColour {
//
// BLACK("\2470"),
// DARK_BLUE("\2471"),
// DARK_GREEN("\2472"),
// DARK_AQUA("\2473"),
// DARK_RED("\2474"),
// PURPLE("\2475"),
// ORANGE("\2476"),
// GREY("\2477"),
// DARK_GREY("\2478"),
// BLUE("\2479"),
// GREEN("\247a"),
// AQUA("\247b"),
// RED("\247c"),
// PINK("\247d"),
// YELLOW("\247e"),
// WHITE("\247f"),
// // Special case - random
// RANDOM("\247k");
//
// /**
// * Holds the random variables
// */
// private Random random;
//
// /**
// * The value of the enum
// */
// private final String value;
//
// /**
// * Initialises the enum using the specified value
// *
// * @param value - The value of the FontColour
// */
// private FontColour(String value) {
// this.value = value;
// random = new Random();
// }
//
// /**
// * Overrides the default toString method to return the value of the Enum
// *
// * @see java.lang.Enum#toString()
// */
// @Override
// public String toString() {
// if (value.equalsIgnoreCase("\247k")) {
// return values()[random.nextInt(values().length - 1)].toString();
// }
// return value;
// }
// }
//
// Path: src/com/sijobe/spc/wrapper/CommandException.java
// public class CommandException extends Exception {
//
// /**
// * GUID
// */
// private static final long serialVersionUID = -2082390336460702125L;
//
// public CommandException() {
// super();
// }
//
// public CommandException(String message) {
// super(message);
// }
//
// public CommandException(Throwable t) {
// super(t);
// }
// }
//
// Path: src/com/sijobe/spc/wrapper/CommandSender.java
// public class CommandSender {
// private final ICommandSender sender;
//
// /**
// * Standard constructor that accepts the sender to wrap
// *
// * @param sender - The sender to wrap
// */
// public CommandSender(ICommandSender sender) {
// this.sender = sender;
// }
//
// /**
// * Creates an instance of a command sender using the player instance
// *
// * @param player - The player to create a command sender
// */
// public CommandSender(Player player) {
// this (player.getMinecraftPlayer());
// }
//
// /**
// * Gets the senders name, commonly this is the player's username
// *
// * @return The senders name
// */
// public String getSenderName() {
// return sender.getCommandSenderName();
// }
//
// /**
// * Returns true if the sender can use the specified command
// *
// * @param command - The command name
// * @return True is returned if the sender can use the specified command
// */
// public boolean canUseCommand(String command) {
// return sender.canCommandSenderUseCommand(4, command);
// }
//
// /**
// * Sends the specified message to the sender. The sender should display this
// * message.
// *
// * @param message - The message to display
// */
// public void sendMessageToPlayer(String message) {
// sender.sendChatToPlayer(ChatMessageComponent.func_111066_d(message));
// }
//
// /**
// * Translates the provided key translate with the provided parameters
// *
// * @param translate - The string to translate
// * @param params - The parameters
// * @return The translated String
// */
// public String translateString(String translate, Object ... params) {
// return StatCollector.translateToLocalFormatted(translate, params);
// }
//
// /**
// * Gets the raw data object that this class is wrapping around
// *
// * @return The ICommandSender class
// */
// public ICommandSender getMinecraftISender() {
// return sender;
// }
//
// /**
// * Returns true if this command sender object is a player
// *
// * @return True if the command sender is a player, false otherwise
// */
// public boolean isPlayer() {
// return sender instanceof EntityPlayer;
// }
// }
| import com.sijobe.spc.util.FontColour;
import com.sijobe.spc.wrapper.CommandException;
import com.sijobe.spc.wrapper.CommandSender;
import java.util.List; | package com.sijobe.spc.command;
public class Test extends MultipleCommands {
public Test(String name) {
super(name);
}
@Override | // Path: src/com/sijobe/spc/util/FontColour.java
// public enum FontColour {
//
// BLACK("\2470"),
// DARK_BLUE("\2471"),
// DARK_GREEN("\2472"),
// DARK_AQUA("\2473"),
// DARK_RED("\2474"),
// PURPLE("\2475"),
// ORANGE("\2476"),
// GREY("\2477"),
// DARK_GREY("\2478"),
// BLUE("\2479"),
// GREEN("\247a"),
// AQUA("\247b"),
// RED("\247c"),
// PINK("\247d"),
// YELLOW("\247e"),
// WHITE("\247f"),
// // Special case - random
// RANDOM("\247k");
//
// /**
// * Holds the random variables
// */
// private Random random;
//
// /**
// * The value of the enum
// */
// private final String value;
//
// /**
// * Initialises the enum using the specified value
// *
// * @param value - The value of the FontColour
// */
// private FontColour(String value) {
// this.value = value;
// random = new Random();
// }
//
// /**
// * Overrides the default toString method to return the value of the Enum
// *
// * @see java.lang.Enum#toString()
// */
// @Override
// public String toString() {
// if (value.equalsIgnoreCase("\247k")) {
// return values()[random.nextInt(values().length - 1)].toString();
// }
// return value;
// }
// }
//
// Path: src/com/sijobe/spc/wrapper/CommandException.java
// public class CommandException extends Exception {
//
// /**
// * GUID
// */
// private static final long serialVersionUID = -2082390336460702125L;
//
// public CommandException() {
// super();
// }
//
// public CommandException(String message) {
// super(message);
// }
//
// public CommandException(Throwable t) {
// super(t);
// }
// }
//
// Path: src/com/sijobe/spc/wrapper/CommandSender.java
// public class CommandSender {
// private final ICommandSender sender;
//
// /**
// * Standard constructor that accepts the sender to wrap
// *
// * @param sender - The sender to wrap
// */
// public CommandSender(ICommandSender sender) {
// this.sender = sender;
// }
//
// /**
// * Creates an instance of a command sender using the player instance
// *
// * @param player - The player to create a command sender
// */
// public CommandSender(Player player) {
// this (player.getMinecraftPlayer());
// }
//
// /**
// * Gets the senders name, commonly this is the player's username
// *
// * @return The senders name
// */
// public String getSenderName() {
// return sender.getCommandSenderName();
// }
//
// /**
// * Returns true if the sender can use the specified command
// *
// * @param command - The command name
// * @return True is returned if the sender can use the specified command
// */
// public boolean canUseCommand(String command) {
// return sender.canCommandSenderUseCommand(4, command);
// }
//
// /**
// * Sends the specified message to the sender. The sender should display this
// * message.
// *
// * @param message - The message to display
// */
// public void sendMessageToPlayer(String message) {
// sender.sendChatToPlayer(ChatMessageComponent.func_111066_d(message));
// }
//
// /**
// * Translates the provided key translate with the provided parameters
// *
// * @param translate - The string to translate
// * @param params - The parameters
// * @return The translated String
// */
// public String translateString(String translate, Object ... params) {
// return StatCollector.translateToLocalFormatted(translate, params);
// }
//
// /**
// * Gets the raw data object that this class is wrapping around
// *
// * @return The ICommandSender class
// */
// public ICommandSender getMinecraftISender() {
// return sender;
// }
//
// /**
// * Returns true if this command sender object is a player
// *
// * @return True if the command sender is a player, false otherwise
// */
// public boolean isPlayer() {
// return sender instanceof EntityPlayer;
// }
// }
// Path: src/com/sijobe/spc/command/Test.java
import com.sijobe.spc.util.FontColour;
import com.sijobe.spc.wrapper.CommandException;
import com.sijobe.spc.wrapper.CommandSender;
import java.util.List;
package com.sijobe.spc.command;
public class Test extends MultipleCommands {
public Test(String name) {
super(name);
}
@Override | public void execute(CommandSender sender, List<?> params) throws CommandException { |
simo415/spc | src/com/sijobe/spc/command/Test.java | // Path: src/com/sijobe/spc/util/FontColour.java
// public enum FontColour {
//
// BLACK("\2470"),
// DARK_BLUE("\2471"),
// DARK_GREEN("\2472"),
// DARK_AQUA("\2473"),
// DARK_RED("\2474"),
// PURPLE("\2475"),
// ORANGE("\2476"),
// GREY("\2477"),
// DARK_GREY("\2478"),
// BLUE("\2479"),
// GREEN("\247a"),
// AQUA("\247b"),
// RED("\247c"),
// PINK("\247d"),
// YELLOW("\247e"),
// WHITE("\247f"),
// // Special case - random
// RANDOM("\247k");
//
// /**
// * Holds the random variables
// */
// private Random random;
//
// /**
// * The value of the enum
// */
// private final String value;
//
// /**
// * Initialises the enum using the specified value
// *
// * @param value - The value of the FontColour
// */
// private FontColour(String value) {
// this.value = value;
// random = new Random();
// }
//
// /**
// * Overrides the default toString method to return the value of the Enum
// *
// * @see java.lang.Enum#toString()
// */
// @Override
// public String toString() {
// if (value.equalsIgnoreCase("\247k")) {
// return values()[random.nextInt(values().length - 1)].toString();
// }
// return value;
// }
// }
//
// Path: src/com/sijobe/spc/wrapper/CommandException.java
// public class CommandException extends Exception {
//
// /**
// * GUID
// */
// private static final long serialVersionUID = -2082390336460702125L;
//
// public CommandException() {
// super();
// }
//
// public CommandException(String message) {
// super(message);
// }
//
// public CommandException(Throwable t) {
// super(t);
// }
// }
//
// Path: src/com/sijobe/spc/wrapper/CommandSender.java
// public class CommandSender {
// private final ICommandSender sender;
//
// /**
// * Standard constructor that accepts the sender to wrap
// *
// * @param sender - The sender to wrap
// */
// public CommandSender(ICommandSender sender) {
// this.sender = sender;
// }
//
// /**
// * Creates an instance of a command sender using the player instance
// *
// * @param player - The player to create a command sender
// */
// public CommandSender(Player player) {
// this (player.getMinecraftPlayer());
// }
//
// /**
// * Gets the senders name, commonly this is the player's username
// *
// * @return The senders name
// */
// public String getSenderName() {
// return sender.getCommandSenderName();
// }
//
// /**
// * Returns true if the sender can use the specified command
// *
// * @param command - The command name
// * @return True is returned if the sender can use the specified command
// */
// public boolean canUseCommand(String command) {
// return sender.canCommandSenderUseCommand(4, command);
// }
//
// /**
// * Sends the specified message to the sender. The sender should display this
// * message.
// *
// * @param message - The message to display
// */
// public void sendMessageToPlayer(String message) {
// sender.sendChatToPlayer(ChatMessageComponent.func_111066_d(message));
// }
//
// /**
// * Translates the provided key translate with the provided parameters
// *
// * @param translate - The string to translate
// * @param params - The parameters
// * @return The translated String
// */
// public String translateString(String translate, Object ... params) {
// return StatCollector.translateToLocalFormatted(translate, params);
// }
//
// /**
// * Gets the raw data object that this class is wrapping around
// *
// * @return The ICommandSender class
// */
// public ICommandSender getMinecraftISender() {
// return sender;
// }
//
// /**
// * Returns true if this command sender object is a player
// *
// * @return True if the command sender is a player, false otherwise
// */
// public boolean isPlayer() {
// return sender instanceof EntityPlayer;
// }
// }
| import com.sijobe.spc.util.FontColour;
import com.sijobe.spc.wrapper.CommandException;
import com.sijobe.spc.wrapper.CommandSender;
import java.util.List; | package com.sijobe.spc.command;
public class Test extends MultipleCommands {
public Test(String name) {
super(name);
}
@Override | // Path: src/com/sijobe/spc/util/FontColour.java
// public enum FontColour {
//
// BLACK("\2470"),
// DARK_BLUE("\2471"),
// DARK_GREEN("\2472"),
// DARK_AQUA("\2473"),
// DARK_RED("\2474"),
// PURPLE("\2475"),
// ORANGE("\2476"),
// GREY("\2477"),
// DARK_GREY("\2478"),
// BLUE("\2479"),
// GREEN("\247a"),
// AQUA("\247b"),
// RED("\247c"),
// PINK("\247d"),
// YELLOW("\247e"),
// WHITE("\247f"),
// // Special case - random
// RANDOM("\247k");
//
// /**
// * Holds the random variables
// */
// private Random random;
//
// /**
// * The value of the enum
// */
// private final String value;
//
// /**
// * Initialises the enum using the specified value
// *
// * @param value - The value of the FontColour
// */
// private FontColour(String value) {
// this.value = value;
// random = new Random();
// }
//
// /**
// * Overrides the default toString method to return the value of the Enum
// *
// * @see java.lang.Enum#toString()
// */
// @Override
// public String toString() {
// if (value.equalsIgnoreCase("\247k")) {
// return values()[random.nextInt(values().length - 1)].toString();
// }
// return value;
// }
// }
//
// Path: src/com/sijobe/spc/wrapper/CommandException.java
// public class CommandException extends Exception {
//
// /**
// * GUID
// */
// private static final long serialVersionUID = -2082390336460702125L;
//
// public CommandException() {
// super();
// }
//
// public CommandException(String message) {
// super(message);
// }
//
// public CommandException(Throwable t) {
// super(t);
// }
// }
//
// Path: src/com/sijobe/spc/wrapper/CommandSender.java
// public class CommandSender {
// private final ICommandSender sender;
//
// /**
// * Standard constructor that accepts the sender to wrap
// *
// * @param sender - The sender to wrap
// */
// public CommandSender(ICommandSender sender) {
// this.sender = sender;
// }
//
// /**
// * Creates an instance of a command sender using the player instance
// *
// * @param player - The player to create a command sender
// */
// public CommandSender(Player player) {
// this (player.getMinecraftPlayer());
// }
//
// /**
// * Gets the senders name, commonly this is the player's username
// *
// * @return The senders name
// */
// public String getSenderName() {
// return sender.getCommandSenderName();
// }
//
// /**
// * Returns true if the sender can use the specified command
// *
// * @param command - The command name
// * @return True is returned if the sender can use the specified command
// */
// public boolean canUseCommand(String command) {
// return sender.canCommandSenderUseCommand(4, command);
// }
//
// /**
// * Sends the specified message to the sender. The sender should display this
// * message.
// *
// * @param message - The message to display
// */
// public void sendMessageToPlayer(String message) {
// sender.sendChatToPlayer(ChatMessageComponent.func_111066_d(message));
// }
//
// /**
// * Translates the provided key translate with the provided parameters
// *
// * @param translate - The string to translate
// * @param params - The parameters
// * @return The translated String
// */
// public String translateString(String translate, Object ... params) {
// return StatCollector.translateToLocalFormatted(translate, params);
// }
//
// /**
// * Gets the raw data object that this class is wrapping around
// *
// * @return The ICommandSender class
// */
// public ICommandSender getMinecraftISender() {
// return sender;
// }
//
// /**
// * Returns true if this command sender object is a player
// *
// * @return True if the command sender is a player, false otherwise
// */
// public boolean isPlayer() {
// return sender instanceof EntityPlayer;
// }
// }
// Path: src/com/sijobe/spc/command/Test.java
import com.sijobe.spc.util.FontColour;
import com.sijobe.spc.wrapper.CommandException;
import com.sijobe.spc.wrapper.CommandSender;
import java.util.List;
package com.sijobe.spc.command;
public class Test extends MultipleCommands {
public Test(String name) {
super(name);
}
@Override | public void execute(CommandSender sender, List<?> params) throws CommandException { |
simo415/spc | src/com/sijobe/spc/command/Test.java | // Path: src/com/sijobe/spc/util/FontColour.java
// public enum FontColour {
//
// BLACK("\2470"),
// DARK_BLUE("\2471"),
// DARK_GREEN("\2472"),
// DARK_AQUA("\2473"),
// DARK_RED("\2474"),
// PURPLE("\2475"),
// ORANGE("\2476"),
// GREY("\2477"),
// DARK_GREY("\2478"),
// BLUE("\2479"),
// GREEN("\247a"),
// AQUA("\247b"),
// RED("\247c"),
// PINK("\247d"),
// YELLOW("\247e"),
// WHITE("\247f"),
// // Special case - random
// RANDOM("\247k");
//
// /**
// * Holds the random variables
// */
// private Random random;
//
// /**
// * The value of the enum
// */
// private final String value;
//
// /**
// * Initialises the enum using the specified value
// *
// * @param value - The value of the FontColour
// */
// private FontColour(String value) {
// this.value = value;
// random = new Random();
// }
//
// /**
// * Overrides the default toString method to return the value of the Enum
// *
// * @see java.lang.Enum#toString()
// */
// @Override
// public String toString() {
// if (value.equalsIgnoreCase("\247k")) {
// return values()[random.nextInt(values().length - 1)].toString();
// }
// return value;
// }
// }
//
// Path: src/com/sijobe/spc/wrapper/CommandException.java
// public class CommandException extends Exception {
//
// /**
// * GUID
// */
// private static final long serialVersionUID = -2082390336460702125L;
//
// public CommandException() {
// super();
// }
//
// public CommandException(String message) {
// super(message);
// }
//
// public CommandException(Throwable t) {
// super(t);
// }
// }
//
// Path: src/com/sijobe/spc/wrapper/CommandSender.java
// public class CommandSender {
// private final ICommandSender sender;
//
// /**
// * Standard constructor that accepts the sender to wrap
// *
// * @param sender - The sender to wrap
// */
// public CommandSender(ICommandSender sender) {
// this.sender = sender;
// }
//
// /**
// * Creates an instance of a command sender using the player instance
// *
// * @param player - The player to create a command sender
// */
// public CommandSender(Player player) {
// this (player.getMinecraftPlayer());
// }
//
// /**
// * Gets the senders name, commonly this is the player's username
// *
// * @return The senders name
// */
// public String getSenderName() {
// return sender.getCommandSenderName();
// }
//
// /**
// * Returns true if the sender can use the specified command
// *
// * @param command - The command name
// * @return True is returned if the sender can use the specified command
// */
// public boolean canUseCommand(String command) {
// return sender.canCommandSenderUseCommand(4, command);
// }
//
// /**
// * Sends the specified message to the sender. The sender should display this
// * message.
// *
// * @param message - The message to display
// */
// public void sendMessageToPlayer(String message) {
// sender.sendChatToPlayer(ChatMessageComponent.func_111066_d(message));
// }
//
// /**
// * Translates the provided key translate with the provided parameters
// *
// * @param translate - The string to translate
// * @param params - The parameters
// * @return The translated String
// */
// public String translateString(String translate, Object ... params) {
// return StatCollector.translateToLocalFormatted(translate, params);
// }
//
// /**
// * Gets the raw data object that this class is wrapping around
// *
// * @return The ICommandSender class
// */
// public ICommandSender getMinecraftISender() {
// return sender;
// }
//
// /**
// * Returns true if this command sender object is a player
// *
// * @return True if the command sender is a player, false otherwise
// */
// public boolean isPlayer() {
// return sender instanceof EntityPlayer;
// }
// }
| import com.sijobe.spc.util.FontColour;
import com.sijobe.spc.wrapper.CommandException;
import com.sijobe.spc.wrapper.CommandSender;
import java.util.List; | package com.sijobe.spc.command;
public class Test extends MultipleCommands {
public Test(String name) {
super(name);
}
@Override
public void execute(CommandSender sender, List<?> params) throws CommandException {
for (int i = 0; i < 16; i++) { | // Path: src/com/sijobe/spc/util/FontColour.java
// public enum FontColour {
//
// BLACK("\2470"),
// DARK_BLUE("\2471"),
// DARK_GREEN("\2472"),
// DARK_AQUA("\2473"),
// DARK_RED("\2474"),
// PURPLE("\2475"),
// ORANGE("\2476"),
// GREY("\2477"),
// DARK_GREY("\2478"),
// BLUE("\2479"),
// GREEN("\247a"),
// AQUA("\247b"),
// RED("\247c"),
// PINK("\247d"),
// YELLOW("\247e"),
// WHITE("\247f"),
// // Special case - random
// RANDOM("\247k");
//
// /**
// * Holds the random variables
// */
// private Random random;
//
// /**
// * The value of the enum
// */
// private final String value;
//
// /**
// * Initialises the enum using the specified value
// *
// * @param value - The value of the FontColour
// */
// private FontColour(String value) {
// this.value = value;
// random = new Random();
// }
//
// /**
// * Overrides the default toString method to return the value of the Enum
// *
// * @see java.lang.Enum#toString()
// */
// @Override
// public String toString() {
// if (value.equalsIgnoreCase("\247k")) {
// return values()[random.nextInt(values().length - 1)].toString();
// }
// return value;
// }
// }
//
// Path: src/com/sijobe/spc/wrapper/CommandException.java
// public class CommandException extends Exception {
//
// /**
// * GUID
// */
// private static final long serialVersionUID = -2082390336460702125L;
//
// public CommandException() {
// super();
// }
//
// public CommandException(String message) {
// super(message);
// }
//
// public CommandException(Throwable t) {
// super(t);
// }
// }
//
// Path: src/com/sijobe/spc/wrapper/CommandSender.java
// public class CommandSender {
// private final ICommandSender sender;
//
// /**
// * Standard constructor that accepts the sender to wrap
// *
// * @param sender - The sender to wrap
// */
// public CommandSender(ICommandSender sender) {
// this.sender = sender;
// }
//
// /**
// * Creates an instance of a command sender using the player instance
// *
// * @param player - The player to create a command sender
// */
// public CommandSender(Player player) {
// this (player.getMinecraftPlayer());
// }
//
// /**
// * Gets the senders name, commonly this is the player's username
// *
// * @return The senders name
// */
// public String getSenderName() {
// return sender.getCommandSenderName();
// }
//
// /**
// * Returns true if the sender can use the specified command
// *
// * @param command - The command name
// * @return True is returned if the sender can use the specified command
// */
// public boolean canUseCommand(String command) {
// return sender.canCommandSenderUseCommand(4, command);
// }
//
// /**
// * Sends the specified message to the sender. The sender should display this
// * message.
// *
// * @param message - The message to display
// */
// public void sendMessageToPlayer(String message) {
// sender.sendChatToPlayer(ChatMessageComponent.func_111066_d(message));
// }
//
// /**
// * Translates the provided key translate with the provided parameters
// *
// * @param translate - The string to translate
// * @param params - The parameters
// * @return The translated String
// */
// public String translateString(String translate, Object ... params) {
// return StatCollector.translateToLocalFormatted(translate, params);
// }
//
// /**
// * Gets the raw data object that this class is wrapping around
// *
// * @return The ICommandSender class
// */
// public ICommandSender getMinecraftISender() {
// return sender;
// }
//
// /**
// * Returns true if this command sender object is a player
// *
// * @return True if the command sender is a player, false otherwise
// */
// public boolean isPlayer() {
// return sender instanceof EntityPlayer;
// }
// }
// Path: src/com/sijobe/spc/command/Test.java
import com.sijobe.spc.util.FontColour;
import com.sijobe.spc.wrapper.CommandException;
import com.sijobe.spc.wrapper.CommandSender;
import java.util.List;
package com.sijobe.spc.command;
public class Test extends MultipleCommands {
public Test(String name) {
super(name);
}
@Override
public void execute(CommandSender sender, List<?> params) throws CommandException {
for (int i = 0; i < 16; i++) { | sender.sendMessageToPlayer(FontColour.RANDOM + "Coloured!"); |
simo415/spc | src/com/sijobe/spc/command/CriticalHit.java | // Path: src/com/sijobe/spc/validation/Parameters.java
// public class Parameters {
//
// /**
// * Optional String of variable length arguments - ie: any input
// */
// public static final Parameters DEFAULT = new Parameters(
// new Parameter[] {
// new ParameterString("",true,true)
// }
// );
// /**
// * Parameters of the command
// */
// public static final Parameters DEFAULT_BOOLEAN = new Parameters (
// new Parameter[] {
// new ParameterBoolean("[enable|disable]", true, "enable", "disable")
// }
// );
//
// /**
// * Each of the parameter validators to use to validate
// */
// private Parameter params[];
//
// /**
// * Initialises the class using the specified validation parameters
// *
// * @param params - The validation parameters to use
// */
// public Parameters(Parameter params[]) {
// this.params = params;
// }
//
// /**
// * Validates the input against the parameters for this command. The input
// * is validated by each of the validators and which results in a List of
// * type correct Object returned.
// *
// * If more parameters are specified than validators and the last validator
// * is not variable length then any extra parameters are ignored.
// *
// * @param parameters - The parameters to validate
// * @return A list of validated objects that match their validation type
// * @throws ValidationException - when a validation error occurs an expection
// * is thrown detailing the problem
// */
// public List<?> validate(String parameters[]) throws ValidationException {
// List<Object> validated = new ArrayList<Object>();
// for (int i = 0; i < params.length; i++) {
// // Checks for the correct number of arguments
// if (i + 1 > parameters.length) {
// if (params[i].isOptional()) {
// continue;
// } else {
// throw new ValidationException("Not enough arguments");
// }
// }
//
// try {
// if (i == params.length - 1 && parameters.length > params.length && params[i].isVariableLength()) {
// // Last Parameter and variable length - combine parameters and validate
// String variableLength = "";
// for (int j = i; j < parameters.length; j++) {
// if (j == i) {
// variableLength = parameters[j];
// } else {
// variableLength = variableLength + " " + parameters[j];
// }
// }
// validated.add(params[i].validate(variableLength));
// } else {
// // Validate the parameter
// validated.add(params[i].validate(parameters[i]));
// }
// } catch (ValidationException v) {
// throw v;
// } catch (Exception e) {
// throw new ValidationException("Problem with the command: " + e);
// }
// }
// return validated;
// }
//
// /**
// * Gets how to use the command
// *
// * @return The String representing how to use the command
// */
// public String getUsage() {
// String usage = "";
// for (Parameter param : params) {
// usage += param.getLabel() + " ";
// }
// return usage.trim();
// }
// }
//
// Path: src/com/sijobe/spc/wrapper/CommandSender.java
// public class CommandSender {
// private final ICommandSender sender;
//
// /**
// * Standard constructor that accepts the sender to wrap
// *
// * @param sender - The sender to wrap
// */
// public CommandSender(ICommandSender sender) {
// this.sender = sender;
// }
//
// /**
// * Creates an instance of a command sender using the player instance
// *
// * @param player - The player to create a command sender
// */
// public CommandSender(Player player) {
// this (player.getMinecraftPlayer());
// }
//
// /**
// * Gets the senders name, commonly this is the player's username
// *
// * @return The senders name
// */
// public String getSenderName() {
// return sender.getCommandSenderName();
// }
//
// /**
// * Returns true if the sender can use the specified command
// *
// * @param command - The command name
// * @return True is returned if the sender can use the specified command
// */
// public boolean canUseCommand(String command) {
// return sender.canCommandSenderUseCommand(4, command);
// }
//
// /**
// * Sends the specified message to the sender. The sender should display this
// * message.
// *
// * @param message - The message to display
// */
// public void sendMessageToPlayer(String message) {
// sender.sendChatToPlayer(ChatMessageComponent.func_111066_d(message));
// }
//
// /**
// * Translates the provided key translate with the provided parameters
// *
// * @param translate - The string to translate
// * @param params - The parameters
// * @return The translated String
// */
// public String translateString(String translate, Object ... params) {
// return StatCollector.translateToLocalFormatted(translate, params);
// }
//
// /**
// * Gets the raw data object that this class is wrapping around
// *
// * @return The ICommandSender class
// */
// public ICommandSender getMinecraftISender() {
// return sender;
// }
//
// /**
// * Returns true if this command sender object is a player
// *
// * @return True if the command sender is a player, false otherwise
// */
// public boolean isPlayer() {
// return sender instanceof EntityPlayer;
// }
// }
| import com.sijobe.spc.validation.Parameters;
import com.sijobe.spc.wrapper.CommandSender;
import java.util.List; | package com.sijobe.spc.command;
public class CriticalHit extends StandardCommand {
@Override
public String getName() {
return "criticalhit";
}
@Override | // Path: src/com/sijobe/spc/validation/Parameters.java
// public class Parameters {
//
// /**
// * Optional String of variable length arguments - ie: any input
// */
// public static final Parameters DEFAULT = new Parameters(
// new Parameter[] {
// new ParameterString("",true,true)
// }
// );
// /**
// * Parameters of the command
// */
// public static final Parameters DEFAULT_BOOLEAN = new Parameters (
// new Parameter[] {
// new ParameterBoolean("[enable|disable]", true, "enable", "disable")
// }
// );
//
// /**
// * Each of the parameter validators to use to validate
// */
// private Parameter params[];
//
// /**
// * Initialises the class using the specified validation parameters
// *
// * @param params - The validation parameters to use
// */
// public Parameters(Parameter params[]) {
// this.params = params;
// }
//
// /**
// * Validates the input against the parameters for this command. The input
// * is validated by each of the validators and which results in a List of
// * type correct Object returned.
// *
// * If more parameters are specified than validators and the last validator
// * is not variable length then any extra parameters are ignored.
// *
// * @param parameters - The parameters to validate
// * @return A list of validated objects that match their validation type
// * @throws ValidationException - when a validation error occurs an expection
// * is thrown detailing the problem
// */
// public List<?> validate(String parameters[]) throws ValidationException {
// List<Object> validated = new ArrayList<Object>();
// for (int i = 0; i < params.length; i++) {
// // Checks for the correct number of arguments
// if (i + 1 > parameters.length) {
// if (params[i].isOptional()) {
// continue;
// } else {
// throw new ValidationException("Not enough arguments");
// }
// }
//
// try {
// if (i == params.length - 1 && parameters.length > params.length && params[i].isVariableLength()) {
// // Last Parameter and variable length - combine parameters and validate
// String variableLength = "";
// for (int j = i; j < parameters.length; j++) {
// if (j == i) {
// variableLength = parameters[j];
// } else {
// variableLength = variableLength + " " + parameters[j];
// }
// }
// validated.add(params[i].validate(variableLength));
// } else {
// // Validate the parameter
// validated.add(params[i].validate(parameters[i]));
// }
// } catch (ValidationException v) {
// throw v;
// } catch (Exception e) {
// throw new ValidationException("Problem with the command: " + e);
// }
// }
// return validated;
// }
//
// /**
// * Gets how to use the command
// *
// * @return The String representing how to use the command
// */
// public String getUsage() {
// String usage = "";
// for (Parameter param : params) {
// usage += param.getLabel() + " ";
// }
// return usage.trim();
// }
// }
//
// Path: src/com/sijobe/spc/wrapper/CommandSender.java
// public class CommandSender {
// private final ICommandSender sender;
//
// /**
// * Standard constructor that accepts the sender to wrap
// *
// * @param sender - The sender to wrap
// */
// public CommandSender(ICommandSender sender) {
// this.sender = sender;
// }
//
// /**
// * Creates an instance of a command sender using the player instance
// *
// * @param player - The player to create a command sender
// */
// public CommandSender(Player player) {
// this (player.getMinecraftPlayer());
// }
//
// /**
// * Gets the senders name, commonly this is the player's username
// *
// * @return The senders name
// */
// public String getSenderName() {
// return sender.getCommandSenderName();
// }
//
// /**
// * Returns true if the sender can use the specified command
// *
// * @param command - The command name
// * @return True is returned if the sender can use the specified command
// */
// public boolean canUseCommand(String command) {
// return sender.canCommandSenderUseCommand(4, command);
// }
//
// /**
// * Sends the specified message to the sender. The sender should display this
// * message.
// *
// * @param message - The message to display
// */
// public void sendMessageToPlayer(String message) {
// sender.sendChatToPlayer(ChatMessageComponent.func_111066_d(message));
// }
//
// /**
// * Translates the provided key translate with the provided parameters
// *
// * @param translate - The string to translate
// * @param params - The parameters
// * @return The translated String
// */
// public String translateString(String translate, Object ... params) {
// return StatCollector.translateToLocalFormatted(translate, params);
// }
//
// /**
// * Gets the raw data object that this class is wrapping around
// *
// * @return The ICommandSender class
// */
// public ICommandSender getMinecraftISender() {
// return sender;
// }
//
// /**
// * Returns true if this command sender object is a player
// *
// * @return True if the command sender is a player, false otherwise
// */
// public boolean isPlayer() {
// return sender instanceof EntityPlayer;
// }
// }
// Path: src/com/sijobe/spc/command/CriticalHit.java
import com.sijobe.spc.validation.Parameters;
import com.sijobe.spc.wrapper.CommandSender;
import java.util.List;
package com.sijobe.spc.command;
public class CriticalHit extends StandardCommand {
@Override
public String getName() {
return "criticalhit";
}
@Override | public void execute(CommandSender sender, List<?> params) { |
simo415/spc | src/com/sijobe/spc/command/CriticalHit.java | // Path: src/com/sijobe/spc/validation/Parameters.java
// public class Parameters {
//
// /**
// * Optional String of variable length arguments - ie: any input
// */
// public static final Parameters DEFAULT = new Parameters(
// new Parameter[] {
// new ParameterString("",true,true)
// }
// );
// /**
// * Parameters of the command
// */
// public static final Parameters DEFAULT_BOOLEAN = new Parameters (
// new Parameter[] {
// new ParameterBoolean("[enable|disable]", true, "enable", "disable")
// }
// );
//
// /**
// * Each of the parameter validators to use to validate
// */
// private Parameter params[];
//
// /**
// * Initialises the class using the specified validation parameters
// *
// * @param params - The validation parameters to use
// */
// public Parameters(Parameter params[]) {
// this.params = params;
// }
//
// /**
// * Validates the input against the parameters for this command. The input
// * is validated by each of the validators and which results in a List of
// * type correct Object returned.
// *
// * If more parameters are specified than validators and the last validator
// * is not variable length then any extra parameters are ignored.
// *
// * @param parameters - The parameters to validate
// * @return A list of validated objects that match their validation type
// * @throws ValidationException - when a validation error occurs an expection
// * is thrown detailing the problem
// */
// public List<?> validate(String parameters[]) throws ValidationException {
// List<Object> validated = new ArrayList<Object>();
// for (int i = 0; i < params.length; i++) {
// // Checks for the correct number of arguments
// if (i + 1 > parameters.length) {
// if (params[i].isOptional()) {
// continue;
// } else {
// throw new ValidationException("Not enough arguments");
// }
// }
//
// try {
// if (i == params.length - 1 && parameters.length > params.length && params[i].isVariableLength()) {
// // Last Parameter and variable length - combine parameters and validate
// String variableLength = "";
// for (int j = i; j < parameters.length; j++) {
// if (j == i) {
// variableLength = parameters[j];
// } else {
// variableLength = variableLength + " " + parameters[j];
// }
// }
// validated.add(params[i].validate(variableLength));
// } else {
// // Validate the parameter
// validated.add(params[i].validate(parameters[i]));
// }
// } catch (ValidationException v) {
// throw v;
// } catch (Exception e) {
// throw new ValidationException("Problem with the command: " + e);
// }
// }
// return validated;
// }
//
// /**
// * Gets how to use the command
// *
// * @return The String representing how to use the command
// */
// public String getUsage() {
// String usage = "";
// for (Parameter param : params) {
// usage += param.getLabel() + " ";
// }
// return usage.trim();
// }
// }
//
// Path: src/com/sijobe/spc/wrapper/CommandSender.java
// public class CommandSender {
// private final ICommandSender sender;
//
// /**
// * Standard constructor that accepts the sender to wrap
// *
// * @param sender - The sender to wrap
// */
// public CommandSender(ICommandSender sender) {
// this.sender = sender;
// }
//
// /**
// * Creates an instance of a command sender using the player instance
// *
// * @param player - The player to create a command sender
// */
// public CommandSender(Player player) {
// this (player.getMinecraftPlayer());
// }
//
// /**
// * Gets the senders name, commonly this is the player's username
// *
// * @return The senders name
// */
// public String getSenderName() {
// return sender.getCommandSenderName();
// }
//
// /**
// * Returns true if the sender can use the specified command
// *
// * @param command - The command name
// * @return True is returned if the sender can use the specified command
// */
// public boolean canUseCommand(String command) {
// return sender.canCommandSenderUseCommand(4, command);
// }
//
// /**
// * Sends the specified message to the sender. The sender should display this
// * message.
// *
// * @param message - The message to display
// */
// public void sendMessageToPlayer(String message) {
// sender.sendChatToPlayer(ChatMessageComponent.func_111066_d(message));
// }
//
// /**
// * Translates the provided key translate with the provided parameters
// *
// * @param translate - The string to translate
// * @param params - The parameters
// * @return The translated String
// */
// public String translateString(String translate, Object ... params) {
// return StatCollector.translateToLocalFormatted(translate, params);
// }
//
// /**
// * Gets the raw data object that this class is wrapping around
// *
// * @return The ICommandSender class
// */
// public ICommandSender getMinecraftISender() {
// return sender;
// }
//
// /**
// * Returns true if this command sender object is a player
// *
// * @return True if the command sender is a player, false otherwise
// */
// public boolean isPlayer() {
// return sender instanceof EntityPlayer;
// }
// }
| import com.sijobe.spc.validation.Parameters;
import com.sijobe.spc.wrapper.CommandSender;
import java.util.List; | package com.sijobe.spc.command;
public class CriticalHit extends StandardCommand {
@Override
public String getName() {
return "criticalhit";
}
@Override
public void execute(CommandSender sender, List<?> params) {
// TODO: Client side
}
@Override | // Path: src/com/sijobe/spc/validation/Parameters.java
// public class Parameters {
//
// /**
// * Optional String of variable length arguments - ie: any input
// */
// public static final Parameters DEFAULT = new Parameters(
// new Parameter[] {
// new ParameterString("",true,true)
// }
// );
// /**
// * Parameters of the command
// */
// public static final Parameters DEFAULT_BOOLEAN = new Parameters (
// new Parameter[] {
// new ParameterBoolean("[enable|disable]", true, "enable", "disable")
// }
// );
//
// /**
// * Each of the parameter validators to use to validate
// */
// private Parameter params[];
//
// /**
// * Initialises the class using the specified validation parameters
// *
// * @param params - The validation parameters to use
// */
// public Parameters(Parameter params[]) {
// this.params = params;
// }
//
// /**
// * Validates the input against the parameters for this command. The input
// * is validated by each of the validators and which results in a List of
// * type correct Object returned.
// *
// * If more parameters are specified than validators and the last validator
// * is not variable length then any extra parameters are ignored.
// *
// * @param parameters - The parameters to validate
// * @return A list of validated objects that match their validation type
// * @throws ValidationException - when a validation error occurs an expection
// * is thrown detailing the problem
// */
// public List<?> validate(String parameters[]) throws ValidationException {
// List<Object> validated = new ArrayList<Object>();
// for (int i = 0; i < params.length; i++) {
// // Checks for the correct number of arguments
// if (i + 1 > parameters.length) {
// if (params[i].isOptional()) {
// continue;
// } else {
// throw new ValidationException("Not enough arguments");
// }
// }
//
// try {
// if (i == params.length - 1 && parameters.length > params.length && params[i].isVariableLength()) {
// // Last Parameter and variable length - combine parameters and validate
// String variableLength = "";
// for (int j = i; j < parameters.length; j++) {
// if (j == i) {
// variableLength = parameters[j];
// } else {
// variableLength = variableLength + " " + parameters[j];
// }
// }
// validated.add(params[i].validate(variableLength));
// } else {
// // Validate the parameter
// validated.add(params[i].validate(parameters[i]));
// }
// } catch (ValidationException v) {
// throw v;
// } catch (Exception e) {
// throw new ValidationException("Problem with the command: " + e);
// }
// }
// return validated;
// }
//
// /**
// * Gets how to use the command
// *
// * @return The String representing how to use the command
// */
// public String getUsage() {
// String usage = "";
// for (Parameter param : params) {
// usage += param.getLabel() + " ";
// }
// return usage.trim();
// }
// }
//
// Path: src/com/sijobe/spc/wrapper/CommandSender.java
// public class CommandSender {
// private final ICommandSender sender;
//
// /**
// * Standard constructor that accepts the sender to wrap
// *
// * @param sender - The sender to wrap
// */
// public CommandSender(ICommandSender sender) {
// this.sender = sender;
// }
//
// /**
// * Creates an instance of a command sender using the player instance
// *
// * @param player - The player to create a command sender
// */
// public CommandSender(Player player) {
// this (player.getMinecraftPlayer());
// }
//
// /**
// * Gets the senders name, commonly this is the player's username
// *
// * @return The senders name
// */
// public String getSenderName() {
// return sender.getCommandSenderName();
// }
//
// /**
// * Returns true if the sender can use the specified command
// *
// * @param command - The command name
// * @return True is returned if the sender can use the specified command
// */
// public boolean canUseCommand(String command) {
// return sender.canCommandSenderUseCommand(4, command);
// }
//
// /**
// * Sends the specified message to the sender. The sender should display this
// * message.
// *
// * @param message - The message to display
// */
// public void sendMessageToPlayer(String message) {
// sender.sendChatToPlayer(ChatMessageComponent.func_111066_d(message));
// }
//
// /**
// * Translates the provided key translate with the provided parameters
// *
// * @param translate - The string to translate
// * @param params - The parameters
// * @return The translated String
// */
// public String translateString(String translate, Object ... params) {
// return StatCollector.translateToLocalFormatted(translate, params);
// }
//
// /**
// * Gets the raw data object that this class is wrapping around
// *
// * @return The ICommandSender class
// */
// public ICommandSender getMinecraftISender() {
// return sender;
// }
//
// /**
// * Returns true if this command sender object is a player
// *
// * @return True if the command sender is a player, false otherwise
// */
// public boolean isPlayer() {
// return sender instanceof EntityPlayer;
// }
// }
// Path: src/com/sijobe/spc/command/CriticalHit.java
import com.sijobe.spc.validation.Parameters;
import com.sijobe.spc.wrapper.CommandSender;
import java.util.List;
package com.sijobe.spc.command;
public class CriticalHit extends StandardCommand {
@Override
public String getName() {
return "criticalhit";
}
@Override
public void execute(CommandSender sender, List<?> params) {
// TODO: Client side
}
@Override | public Parameters getParameters() { |
aleven/jpec-server | src/main/java/it/attocchi/jpec/server/entities/RegolaPec.java | // Path: src/main/java/it/attocchi/jpec/server/bl/RegolaPecEventoEnum.java
// public enum RegolaPecEventoEnum {
//
// IMPORTA_MESSAGGIO,
// PROTOCOLLA_MESSAGGIO,
// AGGIORNA_STATO,
// AGGIORNA_SEGNATURA,
// NOTIFICA
//
// }
| import it.attocchi.jpa2.entities.AbstractEntityMarksWithIdLong;
import it.attocchi.jpa2.entities.EntityMarks;
import it.attocchi.jpec.server.bl.RegolaPecEventoEnum;
import java.util.logging.Logger;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
| package it.attocchi.jpec.server.entities;
@Entity
@Table(schema = "", name = "pec06_regole")
public class RegolaPec extends AbstractEntityMarksWithIdLong<RegolaPec> {
protected static final Logger logger = Logger.getLogger(RegolaPec.class.getName());
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "pec06_id")
private long id;
@Column(name = "pec06_nome")
private String nome;
@Column(name = "pec06_note")
@Lob
private String note;
@Column(name = "pec06_evento")
@Enumerated(EnumType.STRING)
| // Path: src/main/java/it/attocchi/jpec/server/bl/RegolaPecEventoEnum.java
// public enum RegolaPecEventoEnum {
//
// IMPORTA_MESSAGGIO,
// PROTOCOLLA_MESSAGGIO,
// AGGIORNA_STATO,
// AGGIORNA_SEGNATURA,
// NOTIFICA
//
// }
// Path: src/main/java/it/attocchi/jpec/server/entities/RegolaPec.java
import it.attocchi.jpa2.entities.AbstractEntityMarksWithIdLong;
import it.attocchi.jpa2.entities.EntityMarks;
import it.attocchi.jpec.server.bl.RegolaPecEventoEnum;
import java.util.logging.Logger;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
package it.attocchi.jpec.server.entities;
@Entity
@Table(schema = "", name = "pec06_regole")
public class RegolaPec extends AbstractEntityMarksWithIdLong<RegolaPec> {
protected static final Logger logger = Logger.getLogger(RegolaPec.class.getName());
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "pec06_id")
private long id;
@Column(name = "pec06_nome")
private String nome;
@Column(name = "pec06_note")
@Lob
private String note;
@Column(name = "pec06_evento")
@Enumerated(EnumType.STRING)
| private RegolaPecEventoEnum evento;
|
aleven/jpec-server | src/test/java/TestDaticert.java | // Path: src/main/java/it/attocchi/jpec/server/pec/DaticertInfo.java
// public class DaticertInfo {
//
// protected final Logger logger = LoggerFactory.getLogger(DaticertInfo.class);
//
// public List<DaticertDestinatario> leggiRicevutaDaFile(String file) throws Exception {
// logger.debug("leggiRicevutaDaFile= {}", file);
// List<DaticertDestinatario> destinatari = new ArrayList<DaticertDestinatario>();
//
// DocumentBuilderFactory strumentiDati = DocumentBuilderFactory.newInstance();
// DocumentBuilder manipoloDati = strumentiDati.newDocumentBuilder();
// Document doc = manipoloDati.parse(file);
// destinatari = leggiRicevuta(doc);
// return destinatari;
// }
//
// public List<DaticertDestinatario> leggiRicevutaDaXml(String xml) throws Exception {
// logger.debug("leggiRicevutaDaXml");
// List<DaticertDestinatario> destinatari = new ArrayList<DaticertDestinatario>();
//
// if (StringUtils.isNotBlank(xml)) {
// DocumentBuilderFactory strumentiDati = DocumentBuilderFactory.newInstance();
// DocumentBuilder manipoloDati = strumentiDati.newDocumentBuilder();
// Document doc = manipoloDati.parse(new ByteArrayInputStream(xml.getBytes()));
// destinatari = leggiRicevuta(doc);
// }
// return destinatari;
// }
//
// public List<DaticertDestinatario> leggiRicevuta(Document doc) throws Exception {
// List<DaticertDestinatario> destinatari = new ArrayList<DaticertDestinatario>();
//
// try {
//
// doc.getDocumentElement().normalize();
//
// NodeList destinatariNodeList = doc.getElementsByTagName("destinatari");
//
// for (int i = 0; i < destinatariNodeList.getLength(); i++) {
// Node destinatariNode = destinatariNodeList.item(i);
//
// // NodeList intestazioneChildNodeList =
// // intestazioneNode.getChildNodes();
// // for (int k = 0; i < intestazioneChildNodeList.getLength();
// // k++) {
// // Node intestazioneChildNode =
// // intestazioneChildNodeList.item(k);
// // logger.info("{}: type ({}):",
// // intestazioneChildNode.getNodeName(),
// // intestazioneChildNode.getNodeType());
// // }
//
// if (destinatariNode.getNodeType() == Node.ELEMENT_NODE) {
// Element elemento = (Element) destinatariNode;
//
// String tipo = elemento.getAttribute("tipo");
// logger.debug("tipo= {}", tipo);
//
// Node destintariNodeChild = destinatariNode.getFirstChild();
// if (destintariNodeChild.getNodeType() == Node.TEXT_NODE) {
// Text textNode = (Text) destintariNodeChild;
// String destinatario = textNode.getNodeValue();
// logger.debug("destinatario= {}", destinatario);
//
// destinatari.add(new DaticertDestinatario(tipo, destinatario));
// }
//
// // String destinatario =
// // elemento.getElementsByTagName("destinatari").item(0).getTextContent();
// // logger.info("destinatario= {}", destinatario);
//
// // titoli.add();
// // descrizioni.add(elemento.getElementsByTagName("descrizione").item(0).getTextContent());
// // links.add(elemento.getElementsByTagName("link").item(0).getTextContent());
// // prezzo.add(elemento.getElementsByTagName("prezzo").item(0).getTextContent());
//
// }
// }
//
// } catch (Exception ex) {
// logger.error("test", ex);
// } finally {
//
// }
//
// return destinatari;
// }
//
// }
| import it.attocchi.jpec.server.pec.DaticertInfo;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; |
public class TestDaticert {
protected final Logger logger = LoggerFactory.getLogger(TestDaticert.class);
@Test
public void test() throws Exception {
| // Path: src/main/java/it/attocchi/jpec/server/pec/DaticertInfo.java
// public class DaticertInfo {
//
// protected final Logger logger = LoggerFactory.getLogger(DaticertInfo.class);
//
// public List<DaticertDestinatario> leggiRicevutaDaFile(String file) throws Exception {
// logger.debug("leggiRicevutaDaFile= {}", file);
// List<DaticertDestinatario> destinatari = new ArrayList<DaticertDestinatario>();
//
// DocumentBuilderFactory strumentiDati = DocumentBuilderFactory.newInstance();
// DocumentBuilder manipoloDati = strumentiDati.newDocumentBuilder();
// Document doc = manipoloDati.parse(file);
// destinatari = leggiRicevuta(doc);
// return destinatari;
// }
//
// public List<DaticertDestinatario> leggiRicevutaDaXml(String xml) throws Exception {
// logger.debug("leggiRicevutaDaXml");
// List<DaticertDestinatario> destinatari = new ArrayList<DaticertDestinatario>();
//
// if (StringUtils.isNotBlank(xml)) {
// DocumentBuilderFactory strumentiDati = DocumentBuilderFactory.newInstance();
// DocumentBuilder manipoloDati = strumentiDati.newDocumentBuilder();
// Document doc = manipoloDati.parse(new ByteArrayInputStream(xml.getBytes()));
// destinatari = leggiRicevuta(doc);
// }
// return destinatari;
// }
//
// public List<DaticertDestinatario> leggiRicevuta(Document doc) throws Exception {
// List<DaticertDestinatario> destinatari = new ArrayList<DaticertDestinatario>();
//
// try {
//
// doc.getDocumentElement().normalize();
//
// NodeList destinatariNodeList = doc.getElementsByTagName("destinatari");
//
// for (int i = 0; i < destinatariNodeList.getLength(); i++) {
// Node destinatariNode = destinatariNodeList.item(i);
//
// // NodeList intestazioneChildNodeList =
// // intestazioneNode.getChildNodes();
// // for (int k = 0; i < intestazioneChildNodeList.getLength();
// // k++) {
// // Node intestazioneChildNode =
// // intestazioneChildNodeList.item(k);
// // logger.info("{}: type ({}):",
// // intestazioneChildNode.getNodeName(),
// // intestazioneChildNode.getNodeType());
// // }
//
// if (destinatariNode.getNodeType() == Node.ELEMENT_NODE) {
// Element elemento = (Element) destinatariNode;
//
// String tipo = elemento.getAttribute("tipo");
// logger.debug("tipo= {}", tipo);
//
// Node destintariNodeChild = destinatariNode.getFirstChild();
// if (destintariNodeChild.getNodeType() == Node.TEXT_NODE) {
// Text textNode = (Text) destintariNodeChild;
// String destinatario = textNode.getNodeValue();
// logger.debug("destinatario= {}", destinatario);
//
// destinatari.add(new DaticertDestinatario(tipo, destinatario));
// }
//
// // String destinatario =
// // elemento.getElementsByTagName("destinatari").item(0).getTextContent();
// // logger.info("destinatario= {}", destinatario);
//
// // titoli.add();
// // descrizioni.add(elemento.getElementsByTagName("descrizione").item(0).getTextContent());
// // links.add(elemento.getElementsByTagName("link").item(0).getTextContent());
// // prezzo.add(elemento.getElementsByTagName("prezzo").item(0).getTextContent());
//
// }
// }
//
// } catch (Exception ex) {
// logger.error("test", ex);
// } finally {
//
// }
//
// return destinatari;
// }
//
// }
// Path: src/test/java/TestDaticert.java
import it.attocchi.jpec.server.pec.DaticertInfo;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestDaticert {
protected final Logger logger = LoggerFactory.getLogger(TestDaticert.class);
@Test
public void test() throws Exception {
| new DaticertInfo().leggiRicevutaDaFile("/home/mirco/Progetti/ivSource/jpec-server/stuff/daticert/pec_daticert.xml"); |
aleven/jpec-server | src/test/java/TestProtocolloEsito.java | // Path: src/main/java/it/attocchi/jpec/server/protocollo/AzioneEsito.java
// public class AzioneEsito {
//
// public enum AzioneEsitoStato {
// OK,
// REGOLA_NON_APPLICABILE,
// NOTIFICA,
// ERRORE
// }
//
// private AzioneEsito() {
// this.stato = AzioneEsitoStato.ERRORE;
// }
//
// public static AzioneEsito ok(String protocollo, String urlDocumentale) {
// AzioneEsito esitoOk = new AzioneEsito();
// esitoOk.stato = AzioneEsitoStato.OK;
// esitoOk.protocollo = protocollo;
// esitoOk.urlDocumentale = urlDocumentale;
// return esitoOk;
// }
//
// public static AzioneEsito ok(String protocollo, String urlDocumentale, String nota) {
// AzioneEsito esitoOk = ok(protocollo, urlDocumentale);
// esitoOk.errore = nota;
// return esitoOk;
// }
//
// public static AzioneEsito notifica(String messaggio, Throwable ex) {
// AzioneEsito esitoErrore = new AzioneEsito();
// esitoErrore.stato = AzioneEsitoStato.NOTIFICA;
// esitoErrore.errore = messaggio;
// esitoErrore.eccezione = ex;
// return esitoErrore;
// }
//
// public static AzioneEsito errore(String messaggio, Throwable ex) {
// AzioneEsito esitoErrore = new AzioneEsito();
// esitoErrore.errore = messaggio;
// esitoErrore.eccezione = ex;
// return esitoErrore;
// }
//
// public static AzioneEsito regolaNonApplicabile(String messaggio) {
// AzioneEsito esito = new AzioneEsito();
// esito.stato = AzioneEsitoStato.REGOLA_NON_APPLICABILE;
// esito.errore = messaggio;
// return esito;
// }
//
// public AzioneEsitoStato stato;
// public String protocollo;
// public String urlDocumentale;
// public String errore;
// public Throwable eccezione;
//
// @Override
// public String toString() {
// return "ProtocolloEsito [stato=" + stato + ", protocollo=" + protocollo + ", errore=" + errore + "]";
// }
//
// private StringBuffer sb = new StringBuffer();
//
// public void logAndBuffer(Logger logger, String message, Object... argArray) {
// sb.append(MessageFormatter.format(message, argArray).getMessage());
// sb.append(System.getProperty("line.separator"));
// // aggiungi al log
// logger.info(message, argArray);
// }
//
// public String getBufferedLog() {
// return sb.toString();
// }
// }
| import it.attocchi.jpec.server.protocollo.AzioneEsito;
import java.util.Date;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; |
public class TestProtocolloEsito {
protected final Logger logger = LoggerFactory.getLogger(TestProtocolloEsito.class);
@Test
public void test() throws Exception {
logger.info(this.getClass().getName());
try { | // Path: src/main/java/it/attocchi/jpec/server/protocollo/AzioneEsito.java
// public class AzioneEsito {
//
// public enum AzioneEsitoStato {
// OK,
// REGOLA_NON_APPLICABILE,
// NOTIFICA,
// ERRORE
// }
//
// private AzioneEsito() {
// this.stato = AzioneEsitoStato.ERRORE;
// }
//
// public static AzioneEsito ok(String protocollo, String urlDocumentale) {
// AzioneEsito esitoOk = new AzioneEsito();
// esitoOk.stato = AzioneEsitoStato.OK;
// esitoOk.protocollo = protocollo;
// esitoOk.urlDocumentale = urlDocumentale;
// return esitoOk;
// }
//
// public static AzioneEsito ok(String protocollo, String urlDocumentale, String nota) {
// AzioneEsito esitoOk = ok(protocollo, urlDocumentale);
// esitoOk.errore = nota;
// return esitoOk;
// }
//
// public static AzioneEsito notifica(String messaggio, Throwable ex) {
// AzioneEsito esitoErrore = new AzioneEsito();
// esitoErrore.stato = AzioneEsitoStato.NOTIFICA;
// esitoErrore.errore = messaggio;
// esitoErrore.eccezione = ex;
// return esitoErrore;
// }
//
// public static AzioneEsito errore(String messaggio, Throwable ex) {
// AzioneEsito esitoErrore = new AzioneEsito();
// esitoErrore.errore = messaggio;
// esitoErrore.eccezione = ex;
// return esitoErrore;
// }
//
// public static AzioneEsito regolaNonApplicabile(String messaggio) {
// AzioneEsito esito = new AzioneEsito();
// esito.stato = AzioneEsitoStato.REGOLA_NON_APPLICABILE;
// esito.errore = messaggio;
// return esito;
// }
//
// public AzioneEsitoStato stato;
// public String protocollo;
// public String urlDocumentale;
// public String errore;
// public Throwable eccezione;
//
// @Override
// public String toString() {
// return "ProtocolloEsito [stato=" + stato + ", protocollo=" + protocollo + ", errore=" + errore + "]";
// }
//
// private StringBuffer sb = new StringBuffer();
//
// public void logAndBuffer(Logger logger, String message, Object... argArray) {
// sb.append(MessageFormatter.format(message, argArray).getMessage());
// sb.append(System.getProperty("line.separator"));
// // aggiungi al log
// logger.info(message, argArray);
// }
//
// public String getBufferedLog() {
// return sb.toString();
// }
// }
// Path: src/test/java/TestProtocolloEsito.java
import it.attocchi.jpec.server.protocollo.AzioneEsito;
import java.util.Date;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestProtocolloEsito {
protected final Logger logger = LoggerFactory.getLogger(TestProtocolloEsito.class);
@Test
public void test() throws Exception {
logger.info(this.getClass().getName());
try { | AzioneEsito e = AzioneEsito.errore("a", null); |
aleven/jpec-server | src/main/java/it/attocchi/jpec/server/bl/ConfigurazioneBL.java | // Path: src/main/java/it/attocchi/jpec/server/entities/ConfigurazionePec.java
// @Entity
// @Table(schema = "", name = "pec03_config")
// public class ConfigurazionePec extends AbstractEntityWithIdString {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "pec03_nome")
// private String nome;
//
// @Column(name = "pec03_valore")
// private String valore;
//
// @Column(name = "pec03_descrizione")
// private String descrizione;
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getValore() {
// return valore;
// }
//
// public void setValore(String valore) {
// this.valore = valore;
// }
//
// public String getDescrizione() {
// return descrizione;
// }
//
// public void setDescrizione(String descrizione) {
// this.descrizione = descrizione;
// }
//
// @Override
// public String getId() {
// return getNome();
// }
//
// }
//
// Path: src/main/java/it/attocchi/jpec/server/exceptions/PecException.java
// public class PecException extends Exception {
//
// public PecException() {
// super();
// }
//
// public PecException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
//
// public PecException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public PecException(String message) {
// super(message);
// }
//
// public PecException(Throwable cause) {
// super(cause);
// }
//
// }
| import it.attocchi.jpa2.JpaController;
import it.attocchi.jpec.server.entities.ConfigurazionePec;
import it.attocchi.jpec.server.exceptions.PecException;
import java.io.File;
import java.io.FileInputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
| package it.attocchi.jpec.server.bl;
public class ConfigurazioneBL {
protected static final Logger logger = LoggerFactory.getLogger(ConfigurazioneBL.class);
/**
*
*/
private static final long serialVersionUID = 1L;
| // Path: src/main/java/it/attocchi/jpec/server/entities/ConfigurazionePec.java
// @Entity
// @Table(schema = "", name = "pec03_config")
// public class ConfigurazionePec extends AbstractEntityWithIdString {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "pec03_nome")
// private String nome;
//
// @Column(name = "pec03_valore")
// private String valore;
//
// @Column(name = "pec03_descrizione")
// private String descrizione;
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getValore() {
// return valore;
// }
//
// public void setValore(String valore) {
// this.valore = valore;
// }
//
// public String getDescrizione() {
// return descrizione;
// }
//
// public void setDescrizione(String descrizione) {
// this.descrizione = descrizione;
// }
//
// @Override
// public String getId() {
// return getNome();
// }
//
// }
//
// Path: src/main/java/it/attocchi/jpec/server/exceptions/PecException.java
// public class PecException extends Exception {
//
// public PecException() {
// super();
// }
//
// public PecException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
//
// public PecException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public PecException(String message) {
// super(message);
// }
//
// public PecException(Throwable cause) {
// super(cause);
// }
//
// }
// Path: src/main/java/it/attocchi/jpec/server/bl/ConfigurazioneBL.java
import it.attocchi.jpa2.JpaController;
import it.attocchi.jpec.server.entities.ConfigurazionePec;
import it.attocchi.jpec.server.exceptions.PecException;
import java.io.File;
import java.io.FileInputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package it.attocchi.jpec.server.bl;
public class ConfigurazioneBL {
protected static final Logger logger = LoggerFactory.getLogger(ConfigurazioneBL.class);
/**
*
*/
private static final long serialVersionUID = 1L;
| private static Map<String, ConfigurazionePec> dbConfig = null;
|
aleven/jpec-server | src/main/java/it/attocchi/jpec/server/bl/ConfigurazioneBL.java | // Path: src/main/java/it/attocchi/jpec/server/entities/ConfigurazionePec.java
// @Entity
// @Table(schema = "", name = "pec03_config")
// public class ConfigurazionePec extends AbstractEntityWithIdString {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "pec03_nome")
// private String nome;
//
// @Column(name = "pec03_valore")
// private String valore;
//
// @Column(name = "pec03_descrizione")
// private String descrizione;
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getValore() {
// return valore;
// }
//
// public void setValore(String valore) {
// this.valore = valore;
// }
//
// public String getDescrizione() {
// return descrizione;
// }
//
// public void setDescrizione(String descrizione) {
// this.descrizione = descrizione;
// }
//
// @Override
// public String getId() {
// return getNome();
// }
//
// }
//
// Path: src/main/java/it/attocchi/jpec/server/exceptions/PecException.java
// public class PecException extends Exception {
//
// public PecException() {
// super();
// }
//
// public PecException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
//
// public PecException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public PecException(String message) {
// super(message);
// }
//
// public PecException(Throwable cause) {
// super(cause);
// }
//
// }
| import it.attocchi.jpa2.JpaController;
import it.attocchi.jpec.server.entities.ConfigurazionePec;
import it.attocchi.jpec.server.exceptions.PecException;
import java.io.File;
import java.io.FileInputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
| controller = new JpaController(emf);
ConfigurazionePec data = controller.find(ConfigurazionePec.class, chiave.name());
if (data != null && !valore.equals(data.getValore())) {
data.setValore(valore);
controller.update(data);
} else {
ConfigurazionePec newConfigurazione = new ConfigurazionePec();
newConfigurazione.setNome(chiave.name());
newConfigurazione.setValore(valore);
controller.insert(newConfigurazione);
}
} catch (Exception ex) {
logger.error("getCurrent", ex);
} finally {
if (controller != null)
controller.closeEmAndEmf();
}
}
public static void resetCurrent() {
dbConfig = null;
mailboxes = null;
}
/**
*
* @param emf
* @param contextRealPath
*/
| // Path: src/main/java/it/attocchi/jpec/server/entities/ConfigurazionePec.java
// @Entity
// @Table(schema = "", name = "pec03_config")
// public class ConfigurazionePec extends AbstractEntityWithIdString {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "pec03_nome")
// private String nome;
//
// @Column(name = "pec03_valore")
// private String valore;
//
// @Column(name = "pec03_descrizione")
// private String descrizione;
//
// public String getNome() {
// return nome;
// }
//
// public void setNome(String nome) {
// this.nome = nome;
// }
//
// public String getValore() {
// return valore;
// }
//
// public void setValore(String valore) {
// this.valore = valore;
// }
//
// public String getDescrizione() {
// return descrizione;
// }
//
// public void setDescrizione(String descrizione) {
// this.descrizione = descrizione;
// }
//
// @Override
// public String getId() {
// return getNome();
// }
//
// }
//
// Path: src/main/java/it/attocchi/jpec/server/exceptions/PecException.java
// public class PecException extends Exception {
//
// public PecException() {
// super();
// }
//
// public PecException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
//
// public PecException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public PecException(String message) {
// super(message);
// }
//
// public PecException(Throwable cause) {
// super(cause);
// }
//
// }
// Path: src/main/java/it/attocchi/jpec/server/bl/ConfigurazioneBL.java
import it.attocchi.jpa2.JpaController;
import it.attocchi.jpec.server.entities.ConfigurazionePec;
import it.attocchi.jpec.server.exceptions.PecException;
import java.io.File;
import java.io.FileInputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
controller = new JpaController(emf);
ConfigurazionePec data = controller.find(ConfigurazionePec.class, chiave.name());
if (data != null && !valore.equals(data.getValore())) {
data.setValore(valore);
controller.update(data);
} else {
ConfigurazionePec newConfigurazione = new ConfigurazionePec();
newConfigurazione.setNome(chiave.name());
newConfigurazione.setValore(valore);
controller.insert(newConfigurazione);
}
} catch (Exception ex) {
logger.error("getCurrent", ex);
} finally {
if (controller != null)
controller.closeEmAndEmf();
}
}
public static void resetCurrent() {
dbConfig = null;
mailboxes = null;
}
/**
*
* @param emf
* @param contextRealPath
*/
| public static synchronized void initializeFromContextPath(EntityManagerFactory emf, String contextRealPath) throws PecException {
|
aleven/jpec-server | src/main/java/it/attocchi/jpec/server/protocollo/impl/ProtocolloTest.java | // Path: src/main/java/it/attocchi/jpec/server/protocollo/AbstractAzione.java
// public abstract class AbstractAzione implements AzioneGenerica {
//
// private AzioneContext context;
// private boolean testMode = false;
//
// @Override
// public AzioneGenerica inizialize(AzioneContext context) {
// this.context = context;
// return this;
// }
//
// @Override
// public AzioneContext getContext() {
// return context;
// }
//
// public boolean isTestMode() {
// return testMode;
// }
//
// public void setTestMode(boolean testMode) {
// this.testMode = testMode;
// }
//
//
// }
//
// Path: src/main/java/it/attocchi/jpec/server/protocollo/AzioneEsito.java
// public class AzioneEsito {
//
// public enum AzioneEsitoStato {
// OK,
// REGOLA_NON_APPLICABILE,
// NOTIFICA,
// ERRORE
// }
//
// private AzioneEsito() {
// this.stato = AzioneEsitoStato.ERRORE;
// }
//
// public static AzioneEsito ok(String protocollo, String urlDocumentale) {
// AzioneEsito esitoOk = new AzioneEsito();
// esitoOk.stato = AzioneEsitoStato.OK;
// esitoOk.protocollo = protocollo;
// esitoOk.urlDocumentale = urlDocumentale;
// return esitoOk;
// }
//
// public static AzioneEsito ok(String protocollo, String urlDocumentale, String nota) {
// AzioneEsito esitoOk = ok(protocollo, urlDocumentale);
// esitoOk.errore = nota;
// return esitoOk;
// }
//
// public static AzioneEsito notifica(String messaggio, Throwable ex) {
// AzioneEsito esitoErrore = new AzioneEsito();
// esitoErrore.stato = AzioneEsitoStato.NOTIFICA;
// esitoErrore.errore = messaggio;
// esitoErrore.eccezione = ex;
// return esitoErrore;
// }
//
// public static AzioneEsito errore(String messaggio, Throwable ex) {
// AzioneEsito esitoErrore = new AzioneEsito();
// esitoErrore.errore = messaggio;
// esitoErrore.eccezione = ex;
// return esitoErrore;
// }
//
// public static AzioneEsito regolaNonApplicabile(String messaggio) {
// AzioneEsito esito = new AzioneEsito();
// esito.stato = AzioneEsitoStato.REGOLA_NON_APPLICABILE;
// esito.errore = messaggio;
// return esito;
// }
//
// public AzioneEsitoStato stato;
// public String protocollo;
// public String urlDocumentale;
// public String errore;
// public Throwable eccezione;
//
// @Override
// public String toString() {
// return "ProtocolloEsito [stato=" + stato + ", protocollo=" + protocollo + ", errore=" + errore + "]";
// }
//
// private StringBuffer sb = new StringBuffer();
//
// public void logAndBuffer(Logger logger, String message, Object... argArray) {
// sb.append(MessageFormatter.format(message, argArray).getMessage());
// sb.append(System.getProperty("line.separator"));
// // aggiungi al log
// logger.info(message, argArray);
// }
//
// public String getBufferedLog() {
// return sb.toString();
// }
// }
| import it.attocchi.jpec.server.protocollo.AbstractAzione;
import it.attocchi.jpec.server.protocollo.AzioneEsito;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package it.attocchi.jpec.server.protocollo.impl;
public class ProtocolloTest extends AbstractAzione {
protected final Logger logger = LoggerFactory.getLogger(ProtocolloTest.class);
private String test = "";
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
@Override | // Path: src/main/java/it/attocchi/jpec/server/protocollo/AbstractAzione.java
// public abstract class AbstractAzione implements AzioneGenerica {
//
// private AzioneContext context;
// private boolean testMode = false;
//
// @Override
// public AzioneGenerica inizialize(AzioneContext context) {
// this.context = context;
// return this;
// }
//
// @Override
// public AzioneContext getContext() {
// return context;
// }
//
// public boolean isTestMode() {
// return testMode;
// }
//
// public void setTestMode(boolean testMode) {
// this.testMode = testMode;
// }
//
//
// }
//
// Path: src/main/java/it/attocchi/jpec/server/protocollo/AzioneEsito.java
// public class AzioneEsito {
//
// public enum AzioneEsitoStato {
// OK,
// REGOLA_NON_APPLICABILE,
// NOTIFICA,
// ERRORE
// }
//
// private AzioneEsito() {
// this.stato = AzioneEsitoStato.ERRORE;
// }
//
// public static AzioneEsito ok(String protocollo, String urlDocumentale) {
// AzioneEsito esitoOk = new AzioneEsito();
// esitoOk.stato = AzioneEsitoStato.OK;
// esitoOk.protocollo = protocollo;
// esitoOk.urlDocumentale = urlDocumentale;
// return esitoOk;
// }
//
// public static AzioneEsito ok(String protocollo, String urlDocumentale, String nota) {
// AzioneEsito esitoOk = ok(protocollo, urlDocumentale);
// esitoOk.errore = nota;
// return esitoOk;
// }
//
// public static AzioneEsito notifica(String messaggio, Throwable ex) {
// AzioneEsito esitoErrore = new AzioneEsito();
// esitoErrore.stato = AzioneEsitoStato.NOTIFICA;
// esitoErrore.errore = messaggio;
// esitoErrore.eccezione = ex;
// return esitoErrore;
// }
//
// public static AzioneEsito errore(String messaggio, Throwable ex) {
// AzioneEsito esitoErrore = new AzioneEsito();
// esitoErrore.errore = messaggio;
// esitoErrore.eccezione = ex;
// return esitoErrore;
// }
//
// public static AzioneEsito regolaNonApplicabile(String messaggio) {
// AzioneEsito esito = new AzioneEsito();
// esito.stato = AzioneEsitoStato.REGOLA_NON_APPLICABILE;
// esito.errore = messaggio;
// return esito;
// }
//
// public AzioneEsitoStato stato;
// public String protocollo;
// public String urlDocumentale;
// public String errore;
// public Throwable eccezione;
//
// @Override
// public String toString() {
// return "ProtocolloEsito [stato=" + stato + ", protocollo=" + protocollo + ", errore=" + errore + "]";
// }
//
// private StringBuffer sb = new StringBuffer();
//
// public void logAndBuffer(Logger logger, String message, Object... argArray) {
// sb.append(MessageFormatter.format(message, argArray).getMessage());
// sb.append(System.getProperty("line.separator"));
// // aggiungi al log
// logger.info(message, argArray);
// }
//
// public String getBufferedLog() {
// return sb.toString();
// }
// }
// Path: src/main/java/it/attocchi/jpec/server/protocollo/impl/ProtocolloTest.java
import it.attocchi.jpec.server.protocollo.AbstractAzione;
import it.attocchi.jpec.server.protocollo.AzioneEsito;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package it.attocchi.jpec.server.protocollo.impl;
public class ProtocolloTest extends AbstractAzione {
protected final Logger logger = LoggerFactory.getLogger(ProtocolloTest.class);
private String test = "";
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
@Override | public AzioneEsito esegui() { |
aleven/jpec-server | src/main/java/it/attocchi/jpec/server/protocollo/impl/ProtocolloTestErrore.java | // Path: src/main/java/it/attocchi/jpec/server/protocollo/AbstractAzione.java
// public abstract class AbstractAzione implements AzioneGenerica {
//
// private AzioneContext context;
// private boolean testMode = false;
//
// @Override
// public AzioneGenerica inizialize(AzioneContext context) {
// this.context = context;
// return this;
// }
//
// @Override
// public AzioneContext getContext() {
// return context;
// }
//
// public boolean isTestMode() {
// return testMode;
// }
//
// public void setTestMode(boolean testMode) {
// this.testMode = testMode;
// }
//
//
// }
//
// Path: src/main/java/it/attocchi/jpec/server/protocollo/AzioneEsito.java
// public class AzioneEsito {
//
// public enum AzioneEsitoStato {
// OK,
// REGOLA_NON_APPLICABILE,
// NOTIFICA,
// ERRORE
// }
//
// private AzioneEsito() {
// this.stato = AzioneEsitoStato.ERRORE;
// }
//
// public static AzioneEsito ok(String protocollo, String urlDocumentale) {
// AzioneEsito esitoOk = new AzioneEsito();
// esitoOk.stato = AzioneEsitoStato.OK;
// esitoOk.protocollo = protocollo;
// esitoOk.urlDocumentale = urlDocumentale;
// return esitoOk;
// }
//
// public static AzioneEsito ok(String protocollo, String urlDocumentale, String nota) {
// AzioneEsito esitoOk = ok(protocollo, urlDocumentale);
// esitoOk.errore = nota;
// return esitoOk;
// }
//
// public static AzioneEsito notifica(String messaggio, Throwable ex) {
// AzioneEsito esitoErrore = new AzioneEsito();
// esitoErrore.stato = AzioneEsitoStato.NOTIFICA;
// esitoErrore.errore = messaggio;
// esitoErrore.eccezione = ex;
// return esitoErrore;
// }
//
// public static AzioneEsito errore(String messaggio, Throwable ex) {
// AzioneEsito esitoErrore = new AzioneEsito();
// esitoErrore.errore = messaggio;
// esitoErrore.eccezione = ex;
// return esitoErrore;
// }
//
// public static AzioneEsito regolaNonApplicabile(String messaggio) {
// AzioneEsito esito = new AzioneEsito();
// esito.stato = AzioneEsitoStato.REGOLA_NON_APPLICABILE;
// esito.errore = messaggio;
// return esito;
// }
//
// public AzioneEsitoStato stato;
// public String protocollo;
// public String urlDocumentale;
// public String errore;
// public Throwable eccezione;
//
// @Override
// public String toString() {
// return "ProtocolloEsito [stato=" + stato + ", protocollo=" + protocollo + ", errore=" + errore + "]";
// }
//
// private StringBuffer sb = new StringBuffer();
//
// public void logAndBuffer(Logger logger, String message, Object... argArray) {
// sb.append(MessageFormatter.format(message, argArray).getMessage());
// sb.append(System.getProperty("line.separator"));
// // aggiungi al log
// logger.info(message, argArray);
// }
//
// public String getBufferedLog() {
// return sb.toString();
// }
// }
| import it.attocchi.jpec.server.protocollo.AbstractAzione;
import it.attocchi.jpec.server.protocollo.AzioneEsito;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package it.attocchi.jpec.server.protocollo.impl;
public class ProtocolloTestErrore extends AbstractAzione {
protected final Logger logger = LoggerFactory.getLogger(ProtocolloTestErrore.class);
private String test = "";
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
@Override | // Path: src/main/java/it/attocchi/jpec/server/protocollo/AbstractAzione.java
// public abstract class AbstractAzione implements AzioneGenerica {
//
// private AzioneContext context;
// private boolean testMode = false;
//
// @Override
// public AzioneGenerica inizialize(AzioneContext context) {
// this.context = context;
// return this;
// }
//
// @Override
// public AzioneContext getContext() {
// return context;
// }
//
// public boolean isTestMode() {
// return testMode;
// }
//
// public void setTestMode(boolean testMode) {
// this.testMode = testMode;
// }
//
//
// }
//
// Path: src/main/java/it/attocchi/jpec/server/protocollo/AzioneEsito.java
// public class AzioneEsito {
//
// public enum AzioneEsitoStato {
// OK,
// REGOLA_NON_APPLICABILE,
// NOTIFICA,
// ERRORE
// }
//
// private AzioneEsito() {
// this.stato = AzioneEsitoStato.ERRORE;
// }
//
// public static AzioneEsito ok(String protocollo, String urlDocumentale) {
// AzioneEsito esitoOk = new AzioneEsito();
// esitoOk.stato = AzioneEsitoStato.OK;
// esitoOk.protocollo = protocollo;
// esitoOk.urlDocumentale = urlDocumentale;
// return esitoOk;
// }
//
// public static AzioneEsito ok(String protocollo, String urlDocumentale, String nota) {
// AzioneEsito esitoOk = ok(protocollo, urlDocumentale);
// esitoOk.errore = nota;
// return esitoOk;
// }
//
// public static AzioneEsito notifica(String messaggio, Throwable ex) {
// AzioneEsito esitoErrore = new AzioneEsito();
// esitoErrore.stato = AzioneEsitoStato.NOTIFICA;
// esitoErrore.errore = messaggio;
// esitoErrore.eccezione = ex;
// return esitoErrore;
// }
//
// public static AzioneEsito errore(String messaggio, Throwable ex) {
// AzioneEsito esitoErrore = new AzioneEsito();
// esitoErrore.errore = messaggio;
// esitoErrore.eccezione = ex;
// return esitoErrore;
// }
//
// public static AzioneEsito regolaNonApplicabile(String messaggio) {
// AzioneEsito esito = new AzioneEsito();
// esito.stato = AzioneEsitoStato.REGOLA_NON_APPLICABILE;
// esito.errore = messaggio;
// return esito;
// }
//
// public AzioneEsitoStato stato;
// public String protocollo;
// public String urlDocumentale;
// public String errore;
// public Throwable eccezione;
//
// @Override
// public String toString() {
// return "ProtocolloEsito [stato=" + stato + ", protocollo=" + protocollo + ", errore=" + errore + "]";
// }
//
// private StringBuffer sb = new StringBuffer();
//
// public void logAndBuffer(Logger logger, String message, Object... argArray) {
// sb.append(MessageFormatter.format(message, argArray).getMessage());
// sb.append(System.getProperty("line.separator"));
// // aggiungi al log
// logger.info(message, argArray);
// }
//
// public String getBufferedLog() {
// return sb.toString();
// }
// }
// Path: src/main/java/it/attocchi/jpec/server/protocollo/impl/ProtocolloTestErrore.java
import it.attocchi.jpec.server.protocollo.AbstractAzione;
import it.attocchi.jpec.server.protocollo.AzioneEsito;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package it.attocchi.jpec.server.protocollo.impl;
public class ProtocolloTestErrore extends AbstractAzione {
protected final Logger logger = LoggerFactory.getLogger(ProtocolloTestErrore.class);
private String test = "";
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
@Override | public AzioneEsito esegui() { |
aleven/jpec-server | src/main/java/it/attocchi/jpec/server/protocollo/impl/SegnaturaConferma.java | // Path: src/main/java/it/attocchi/jpec/server/protocollo/AbstractAzione.java
// public abstract class AbstractAzione implements AzioneGenerica {
//
// private AzioneContext context;
// private boolean testMode = false;
//
// @Override
// public AzioneGenerica inizialize(AzioneContext context) {
// this.context = context;
// return this;
// }
//
// @Override
// public AzioneContext getContext() {
// return context;
// }
//
// public boolean isTestMode() {
// return testMode;
// }
//
// public void setTestMode(boolean testMode) {
// this.testMode = testMode;
// }
//
//
// }
//
// Path: src/main/java/it/attocchi/jpec/server/protocollo/AzioneEsito.java
// public class AzioneEsito {
//
// public enum AzioneEsitoStato {
// OK,
// REGOLA_NON_APPLICABILE,
// NOTIFICA,
// ERRORE
// }
//
// private AzioneEsito() {
// this.stato = AzioneEsitoStato.ERRORE;
// }
//
// public static AzioneEsito ok(String protocollo, String urlDocumentale) {
// AzioneEsito esitoOk = new AzioneEsito();
// esitoOk.stato = AzioneEsitoStato.OK;
// esitoOk.protocollo = protocollo;
// esitoOk.urlDocumentale = urlDocumentale;
// return esitoOk;
// }
//
// public static AzioneEsito ok(String protocollo, String urlDocumentale, String nota) {
// AzioneEsito esitoOk = ok(protocollo, urlDocumentale);
// esitoOk.errore = nota;
// return esitoOk;
// }
//
// public static AzioneEsito notifica(String messaggio, Throwable ex) {
// AzioneEsito esitoErrore = new AzioneEsito();
// esitoErrore.stato = AzioneEsitoStato.NOTIFICA;
// esitoErrore.errore = messaggio;
// esitoErrore.eccezione = ex;
// return esitoErrore;
// }
//
// public static AzioneEsito errore(String messaggio, Throwable ex) {
// AzioneEsito esitoErrore = new AzioneEsito();
// esitoErrore.errore = messaggio;
// esitoErrore.eccezione = ex;
// return esitoErrore;
// }
//
// public static AzioneEsito regolaNonApplicabile(String messaggio) {
// AzioneEsito esito = new AzioneEsito();
// esito.stato = AzioneEsitoStato.REGOLA_NON_APPLICABILE;
// esito.errore = messaggio;
// return esito;
// }
//
// public AzioneEsitoStato stato;
// public String protocollo;
// public String urlDocumentale;
// public String errore;
// public Throwable eccezione;
//
// @Override
// public String toString() {
// return "ProtocolloEsito [stato=" + stato + ", protocollo=" + protocollo + ", errore=" + errore + "]";
// }
//
// private StringBuffer sb = new StringBuffer();
//
// public void logAndBuffer(Logger logger, String message, Object... argArray) {
// sb.append(MessageFormatter.format(message, argArray).getMessage());
// sb.append(System.getProperty("line.separator"));
// // aggiungi al log
// logger.info(message, argArray);
// }
//
// public String getBufferedLog() {
// return sb.toString();
// }
// }
| import it.attocchi.jpec.server.protocollo.AbstractAzione;
import it.attocchi.jpec.server.protocollo.AzioneEsito;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package it.attocchi.jpec.server.protocollo.impl;
public class SegnaturaConferma extends AbstractAzione {
protected final Logger logger = LoggerFactory.getLogger(SegnaturaConferma.class);
private String test = "";
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
@Override | // Path: src/main/java/it/attocchi/jpec/server/protocollo/AbstractAzione.java
// public abstract class AbstractAzione implements AzioneGenerica {
//
// private AzioneContext context;
// private boolean testMode = false;
//
// @Override
// public AzioneGenerica inizialize(AzioneContext context) {
// this.context = context;
// return this;
// }
//
// @Override
// public AzioneContext getContext() {
// return context;
// }
//
// public boolean isTestMode() {
// return testMode;
// }
//
// public void setTestMode(boolean testMode) {
// this.testMode = testMode;
// }
//
//
// }
//
// Path: src/main/java/it/attocchi/jpec/server/protocollo/AzioneEsito.java
// public class AzioneEsito {
//
// public enum AzioneEsitoStato {
// OK,
// REGOLA_NON_APPLICABILE,
// NOTIFICA,
// ERRORE
// }
//
// private AzioneEsito() {
// this.stato = AzioneEsitoStato.ERRORE;
// }
//
// public static AzioneEsito ok(String protocollo, String urlDocumentale) {
// AzioneEsito esitoOk = new AzioneEsito();
// esitoOk.stato = AzioneEsitoStato.OK;
// esitoOk.protocollo = protocollo;
// esitoOk.urlDocumentale = urlDocumentale;
// return esitoOk;
// }
//
// public static AzioneEsito ok(String protocollo, String urlDocumentale, String nota) {
// AzioneEsito esitoOk = ok(protocollo, urlDocumentale);
// esitoOk.errore = nota;
// return esitoOk;
// }
//
// public static AzioneEsito notifica(String messaggio, Throwable ex) {
// AzioneEsito esitoErrore = new AzioneEsito();
// esitoErrore.stato = AzioneEsitoStato.NOTIFICA;
// esitoErrore.errore = messaggio;
// esitoErrore.eccezione = ex;
// return esitoErrore;
// }
//
// public static AzioneEsito errore(String messaggio, Throwable ex) {
// AzioneEsito esitoErrore = new AzioneEsito();
// esitoErrore.errore = messaggio;
// esitoErrore.eccezione = ex;
// return esitoErrore;
// }
//
// public static AzioneEsito regolaNonApplicabile(String messaggio) {
// AzioneEsito esito = new AzioneEsito();
// esito.stato = AzioneEsitoStato.REGOLA_NON_APPLICABILE;
// esito.errore = messaggio;
// return esito;
// }
//
// public AzioneEsitoStato stato;
// public String protocollo;
// public String urlDocumentale;
// public String errore;
// public Throwable eccezione;
//
// @Override
// public String toString() {
// return "ProtocolloEsito [stato=" + stato + ", protocollo=" + protocollo + ", errore=" + errore + "]";
// }
//
// private StringBuffer sb = new StringBuffer();
//
// public void logAndBuffer(Logger logger, String message, Object... argArray) {
// sb.append(MessageFormatter.format(message, argArray).getMessage());
// sb.append(System.getProperty("line.separator"));
// // aggiungi al log
// logger.info(message, argArray);
// }
//
// public String getBufferedLog() {
// return sb.toString();
// }
// }
// Path: src/main/java/it/attocchi/jpec/server/protocollo/impl/SegnaturaConferma.java
import it.attocchi.jpec.server.protocollo.AbstractAzione;
import it.attocchi.jpec.server.protocollo.AzioneEsito;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package it.attocchi.jpec.server.protocollo.impl;
public class SegnaturaConferma extends AbstractAzione {
protected final Logger logger = LoggerFactory.getLogger(SegnaturaConferma.class);
private String test = "";
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
@Override | public AzioneEsito esegui() { |
jacarrichan/bis | src/main/java/com/avicit/bis/system/simple/controller/SimpleController.java | // Path: src/main/java/com/avicit/bis/system/simple/service/SimpleService.java
// public interface SimpleService {
//
// public void selectSimple();
// }
//
// Path: src/main/java/com/avicit/framework/context/spring/SpringContextBeanFactory.java
// public class SpringContextBeanFactory {
//
// @SuppressWarnings("unchecked")
// public static <T> T getBean(String name) {
// try {
// return (T) SpringApplicationContextHolder
// .getWebApplicationContext().getBean(name);
// } catch (Exception e) {
// return (T) SpringDispatcherContextHolder.getWebApplicationContext()
// .getBean(name);
// }
// }
//
// public static <T> T getBean(Class<T> clazz) {
// try {
// return SpringApplicationContextHolder.getWebApplicationContext()
// .getBean(clazz);
// } catch (Exception e) {
// return SpringDispatcherContextHolder.getWebApplicationContext()
// .getBean(clazz);
// }
//
// }
//
// public static <T> T getBean(String name, Class<T> clazz) {
// try {
// return getBean(name);
// } catch (Exception e) {
// try {
// return getBean(clazz);
// } catch (Exception ex) {
// return null;
// }
// }
// }
//
// public static Map<String, BeanDefinition> getApplicationBeanDefinitions() {
// Map<String, BeanDefinition> map = new HashMap<String, BeanDefinition>();
// XmlWebApplicationContext context = (XmlWebApplicationContext) SpringApplicationContextHolder
// .getWebApplicationContext();
// ConfigurableListableBeanFactory factory = context.getBeanFactory();
// String[] names = factory.getBeanDefinitionNames();
// for (String name : names) {
// map.put(name, factory.getBeanDefinition(name));
// }
// return map;
// }
//
// public static Map<String, BeanDefinition> getDispatcherBeanDefinitions() {
// Map<String, BeanDefinition> map = new HashMap<String, BeanDefinition>();
// XmlWebApplicationContext context = (XmlWebApplicationContext) SpringDispatcherContextHolder
// .getWebApplicationContext();
// ConfigurableListableBeanFactory factory = context.getBeanFactory();
// String[] names = factory.getBeanDefinitionNames();
// for (String name : names) {
// map.put(name, factory.getBeanDefinition(name));
// }
// return map;
// }
//
// }
| import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.avicit.bis.system.simple.service.SimpleService;
import com.avicit.framework.context.spring.SpringContextBeanFactory; | package com.avicit.bis.system.simple.controller;
@Controller
public class SimpleController {
protected static final Log logger = LogFactory.getLog(SimpleController.class);
@Autowired | // Path: src/main/java/com/avicit/bis/system/simple/service/SimpleService.java
// public interface SimpleService {
//
// public void selectSimple();
// }
//
// Path: src/main/java/com/avicit/framework/context/spring/SpringContextBeanFactory.java
// public class SpringContextBeanFactory {
//
// @SuppressWarnings("unchecked")
// public static <T> T getBean(String name) {
// try {
// return (T) SpringApplicationContextHolder
// .getWebApplicationContext().getBean(name);
// } catch (Exception e) {
// return (T) SpringDispatcherContextHolder.getWebApplicationContext()
// .getBean(name);
// }
// }
//
// public static <T> T getBean(Class<T> clazz) {
// try {
// return SpringApplicationContextHolder.getWebApplicationContext()
// .getBean(clazz);
// } catch (Exception e) {
// return SpringDispatcherContextHolder.getWebApplicationContext()
// .getBean(clazz);
// }
//
// }
//
// public static <T> T getBean(String name, Class<T> clazz) {
// try {
// return getBean(name);
// } catch (Exception e) {
// try {
// return getBean(clazz);
// } catch (Exception ex) {
// return null;
// }
// }
// }
//
// public static Map<String, BeanDefinition> getApplicationBeanDefinitions() {
// Map<String, BeanDefinition> map = new HashMap<String, BeanDefinition>();
// XmlWebApplicationContext context = (XmlWebApplicationContext) SpringApplicationContextHolder
// .getWebApplicationContext();
// ConfigurableListableBeanFactory factory = context.getBeanFactory();
// String[] names = factory.getBeanDefinitionNames();
// for (String name : names) {
// map.put(name, factory.getBeanDefinition(name));
// }
// return map;
// }
//
// public static Map<String, BeanDefinition> getDispatcherBeanDefinitions() {
// Map<String, BeanDefinition> map = new HashMap<String, BeanDefinition>();
// XmlWebApplicationContext context = (XmlWebApplicationContext) SpringDispatcherContextHolder
// .getWebApplicationContext();
// ConfigurableListableBeanFactory factory = context.getBeanFactory();
// String[] names = factory.getBeanDefinitionNames();
// for (String name : names) {
// map.put(name, factory.getBeanDefinition(name));
// }
// return map;
// }
//
// }
// Path: src/main/java/com/avicit/bis/system/simple/controller/SimpleController.java
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.avicit.bis.system.simple.service.SimpleService;
import com.avicit.framework.context.spring.SpringContextBeanFactory;
package com.avicit.bis.system.simple.controller;
@Controller
public class SimpleController {
protected static final Log logger = LogFactory.getLog(SimpleController.class);
@Autowired | protected SimpleService simpleService; |
jacarrichan/bis | src/main/java/com/avicit/bis/system/simple/controller/SimpleController.java | // Path: src/main/java/com/avicit/bis/system/simple/service/SimpleService.java
// public interface SimpleService {
//
// public void selectSimple();
// }
//
// Path: src/main/java/com/avicit/framework/context/spring/SpringContextBeanFactory.java
// public class SpringContextBeanFactory {
//
// @SuppressWarnings("unchecked")
// public static <T> T getBean(String name) {
// try {
// return (T) SpringApplicationContextHolder
// .getWebApplicationContext().getBean(name);
// } catch (Exception e) {
// return (T) SpringDispatcherContextHolder.getWebApplicationContext()
// .getBean(name);
// }
// }
//
// public static <T> T getBean(Class<T> clazz) {
// try {
// return SpringApplicationContextHolder.getWebApplicationContext()
// .getBean(clazz);
// } catch (Exception e) {
// return SpringDispatcherContextHolder.getWebApplicationContext()
// .getBean(clazz);
// }
//
// }
//
// public static <T> T getBean(String name, Class<T> clazz) {
// try {
// return getBean(name);
// } catch (Exception e) {
// try {
// return getBean(clazz);
// } catch (Exception ex) {
// return null;
// }
// }
// }
//
// public static Map<String, BeanDefinition> getApplicationBeanDefinitions() {
// Map<String, BeanDefinition> map = new HashMap<String, BeanDefinition>();
// XmlWebApplicationContext context = (XmlWebApplicationContext) SpringApplicationContextHolder
// .getWebApplicationContext();
// ConfigurableListableBeanFactory factory = context.getBeanFactory();
// String[] names = factory.getBeanDefinitionNames();
// for (String name : names) {
// map.put(name, factory.getBeanDefinition(name));
// }
// return map;
// }
//
// public static Map<String, BeanDefinition> getDispatcherBeanDefinitions() {
// Map<String, BeanDefinition> map = new HashMap<String, BeanDefinition>();
// XmlWebApplicationContext context = (XmlWebApplicationContext) SpringDispatcherContextHolder
// .getWebApplicationContext();
// ConfigurableListableBeanFactory factory = context.getBeanFactory();
// String[] names = factory.getBeanDefinitionNames();
// for (String name : names) {
// map.put(name, factory.getBeanDefinition(name));
// }
// return map;
// }
//
// }
| import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.avicit.bis.system.simple.service.SimpleService;
import com.avicit.framework.context.spring.SpringContextBeanFactory; | package com.avicit.bis.system.simple.controller;
@Controller
public class SimpleController {
protected static final Log logger = LogFactory.getLog(SimpleController.class);
@Autowired
protected SimpleService simpleService;
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index(HttpServletRequest request, HttpServletResponse response) throws Exception {
// HibernateMatchRuleFactory factory =
// HibernateMatchRuleContext.getMatchRuleFactory();
return "index";
}
@RequestMapping(value = "/spring-application-browser", method = RequestMethod.GET)
public ModelAndView browserSpringApplication(HttpServletRequest request, HttpServletResponse response) { | // Path: src/main/java/com/avicit/bis/system/simple/service/SimpleService.java
// public interface SimpleService {
//
// public void selectSimple();
// }
//
// Path: src/main/java/com/avicit/framework/context/spring/SpringContextBeanFactory.java
// public class SpringContextBeanFactory {
//
// @SuppressWarnings("unchecked")
// public static <T> T getBean(String name) {
// try {
// return (T) SpringApplicationContextHolder
// .getWebApplicationContext().getBean(name);
// } catch (Exception e) {
// return (T) SpringDispatcherContextHolder.getWebApplicationContext()
// .getBean(name);
// }
// }
//
// public static <T> T getBean(Class<T> clazz) {
// try {
// return SpringApplicationContextHolder.getWebApplicationContext()
// .getBean(clazz);
// } catch (Exception e) {
// return SpringDispatcherContextHolder.getWebApplicationContext()
// .getBean(clazz);
// }
//
// }
//
// public static <T> T getBean(String name, Class<T> clazz) {
// try {
// return getBean(name);
// } catch (Exception e) {
// try {
// return getBean(clazz);
// } catch (Exception ex) {
// return null;
// }
// }
// }
//
// public static Map<String, BeanDefinition> getApplicationBeanDefinitions() {
// Map<String, BeanDefinition> map = new HashMap<String, BeanDefinition>();
// XmlWebApplicationContext context = (XmlWebApplicationContext) SpringApplicationContextHolder
// .getWebApplicationContext();
// ConfigurableListableBeanFactory factory = context.getBeanFactory();
// String[] names = factory.getBeanDefinitionNames();
// for (String name : names) {
// map.put(name, factory.getBeanDefinition(name));
// }
// return map;
// }
//
// public static Map<String, BeanDefinition> getDispatcherBeanDefinitions() {
// Map<String, BeanDefinition> map = new HashMap<String, BeanDefinition>();
// XmlWebApplicationContext context = (XmlWebApplicationContext) SpringDispatcherContextHolder
// .getWebApplicationContext();
// ConfigurableListableBeanFactory factory = context.getBeanFactory();
// String[] names = factory.getBeanDefinitionNames();
// for (String name : names) {
// map.put(name, factory.getBeanDefinition(name));
// }
// return map;
// }
//
// }
// Path: src/main/java/com/avicit/bis/system/simple/controller/SimpleController.java
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.avicit.bis.system.simple.service.SimpleService;
import com.avicit.framework.context.spring.SpringContextBeanFactory;
package com.avicit.bis.system.simple.controller;
@Controller
public class SimpleController {
protected static final Log logger = LogFactory.getLog(SimpleController.class);
@Autowired
protected SimpleService simpleService;
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index(HttpServletRequest request, HttpServletResponse response) throws Exception {
// HibernateMatchRuleFactory factory =
// HibernateMatchRuleContext.getMatchRuleFactory();
return "index";
}
@RequestMapping(value = "/spring-application-browser", method = RequestMethod.GET)
public ModelAndView browserSpringApplication(HttpServletRequest request, HttpServletResponse response) { | Map<String, BeanDefinition> map = SpringContextBeanFactory.getApplicationBeanDefinitions(); |
jacarrichan/bis | src/test/java/cn/javass/ssonline/spider/service/impl/UserServiceTest.java | // Path: src/main/java/com/avicit/bis/hr/user/model/UserModel.java
// @SuppressWarnings("serial")
// @Entity
// @Table(name = "tbl_user")
// @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
// public class UserModel extends BaseEntity {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "id", nullable = false)
// private int id;
//
//
// @Pattern(regexp = "[A-Za-z0-9]{5,20}", message = "{username.illegal}") //java validator验证(用户名字母数字组成,长度为5-10)
// private String username;
//
// @NotEmpty(message = "{email.illegal}")
// @Email(message = "{email.illegal}") //错误消息会自动到MessageSource中查找
// private String email;
//
// @Pattern(regexp = "[A-Za-z0-9]{5,20}", message = "{password.illegal}")
// private String password;
//
// @DateFormat( message="{register.date.error}")//自定义的验证器
// private Date registerDate;
//
// public int getId() {
// return id;
// }
// public void setId(int id) {
// this.id = id;
// }
// public String getUsername() {
// return username;
// }
// public void setUsername(String username) {
// this.username = username;
// }
// public String getEmail() {
// return email;
// }
// public void setEmail(String email) {
// this.email = email;
// }
// public String getPassword() {
// return password;
// }
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Date getRegisterDate() {
// return registerDate;
// }
//
// public void setRegisterDate(Date registerDate) {
// this.registerDate = registerDate;
// }
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + id;
// return result;
// }
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// UserModel other = (UserModel) obj;
// if (id != other.id)
// return false;
// return true;
// }
//
//
//
// }
//
// Path: src/main/java/com/avicit/bis/hr/user/service/UserService.java
// public interface UserService extends BaseService<UserModel, Integer> {
//
// Page<UserModel> query(int pn, int pageSize, UserQueryModel command);
// }
| import static junit.framework.Assert.assertEquals;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import com.avicit.bis.hr.user.model.UserModel;
import com.avicit.bis.hr.user.service.UserService; | package cn.javass.ssonline.spider.service.impl;
/**
*
* 该测试为集成测试,非单元测试
*
* User: Zhang Kaitao Date: 11-12-26 下午4:33 Version: 1.0
*/
// @Ignore
@ContextConfiguration(locations = { "classpath*:applicationContext.xml" })
@Transactional
@TransactionConfiguration(transactionManager = "txManager", defaultRollback = false)
public class UserServiceTest extends AbstractJUnit4SpringContextTests {
AtomicInteger counter = new AtomicInteger();
@Autowired | // Path: src/main/java/com/avicit/bis/hr/user/model/UserModel.java
// @SuppressWarnings("serial")
// @Entity
// @Table(name = "tbl_user")
// @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
// public class UserModel extends BaseEntity {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "id", nullable = false)
// private int id;
//
//
// @Pattern(regexp = "[A-Za-z0-9]{5,20}", message = "{username.illegal}") //java validator验证(用户名字母数字组成,长度为5-10)
// private String username;
//
// @NotEmpty(message = "{email.illegal}")
// @Email(message = "{email.illegal}") //错误消息会自动到MessageSource中查找
// private String email;
//
// @Pattern(regexp = "[A-Za-z0-9]{5,20}", message = "{password.illegal}")
// private String password;
//
// @DateFormat( message="{register.date.error}")//自定义的验证器
// private Date registerDate;
//
// public int getId() {
// return id;
// }
// public void setId(int id) {
// this.id = id;
// }
// public String getUsername() {
// return username;
// }
// public void setUsername(String username) {
// this.username = username;
// }
// public String getEmail() {
// return email;
// }
// public void setEmail(String email) {
// this.email = email;
// }
// public String getPassword() {
// return password;
// }
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Date getRegisterDate() {
// return registerDate;
// }
//
// public void setRegisterDate(Date registerDate) {
// this.registerDate = registerDate;
// }
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + id;
// return result;
// }
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// UserModel other = (UserModel) obj;
// if (id != other.id)
// return false;
// return true;
// }
//
//
//
// }
//
// Path: src/main/java/com/avicit/bis/hr/user/service/UserService.java
// public interface UserService extends BaseService<UserModel, Integer> {
//
// Page<UserModel> query(int pn, int pageSize, UserQueryModel command);
// }
// Path: src/test/java/cn/javass/ssonline/spider/service/impl/UserServiceTest.java
import static junit.framework.Assert.assertEquals;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import com.avicit.bis.hr.user.model.UserModel;
import com.avicit.bis.hr.user.service.UserService;
package cn.javass.ssonline.spider.service.impl;
/**
*
* 该测试为集成测试,非单元测试
*
* User: Zhang Kaitao Date: 11-12-26 下午4:33 Version: 1.0
*/
// @Ignore
@ContextConfiguration(locations = { "classpath*:applicationContext.xml" })
@Transactional
@TransactionConfiguration(transactionManager = "txManager", defaultRollback = false)
public class UserServiceTest extends AbstractJUnit4SpringContextTests {
AtomicInteger counter = new AtomicInteger();
@Autowired | private UserService userService; |
jacarrichan/bis | src/test/java/cn/javass/ssonline/spider/service/impl/UserServiceTest.java | // Path: src/main/java/com/avicit/bis/hr/user/model/UserModel.java
// @SuppressWarnings("serial")
// @Entity
// @Table(name = "tbl_user")
// @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
// public class UserModel extends BaseEntity {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "id", nullable = false)
// private int id;
//
//
// @Pattern(regexp = "[A-Za-z0-9]{5,20}", message = "{username.illegal}") //java validator验证(用户名字母数字组成,长度为5-10)
// private String username;
//
// @NotEmpty(message = "{email.illegal}")
// @Email(message = "{email.illegal}") //错误消息会自动到MessageSource中查找
// private String email;
//
// @Pattern(regexp = "[A-Za-z0-9]{5,20}", message = "{password.illegal}")
// private String password;
//
// @DateFormat( message="{register.date.error}")//自定义的验证器
// private Date registerDate;
//
// public int getId() {
// return id;
// }
// public void setId(int id) {
// this.id = id;
// }
// public String getUsername() {
// return username;
// }
// public void setUsername(String username) {
// this.username = username;
// }
// public String getEmail() {
// return email;
// }
// public void setEmail(String email) {
// this.email = email;
// }
// public String getPassword() {
// return password;
// }
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Date getRegisterDate() {
// return registerDate;
// }
//
// public void setRegisterDate(Date registerDate) {
// this.registerDate = registerDate;
// }
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + id;
// return result;
// }
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// UserModel other = (UserModel) obj;
// if (id != other.id)
// return false;
// return true;
// }
//
//
//
// }
//
// Path: src/main/java/com/avicit/bis/hr/user/service/UserService.java
// public interface UserService extends BaseService<UserModel, Integer> {
//
// Page<UserModel> query(int pn, int pageSize, UserQueryModel command);
// }
| import static junit.framework.Assert.assertEquals;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import com.avicit.bis.hr.user.model.UserModel;
import com.avicit.bis.hr.user.service.UserService; | package cn.javass.ssonline.spider.service.impl;
/**
*
* 该测试为集成测试,非单元测试
*
* User: Zhang Kaitao Date: 11-12-26 下午4:33 Version: 1.0
*/
// @Ignore
@ContextConfiguration(locations = { "classpath*:applicationContext.xml" })
@Transactional
@TransactionConfiguration(transactionManager = "txManager", defaultRollback = false)
public class UserServiceTest extends AbstractJUnit4SpringContextTests {
AtomicInteger counter = new AtomicInteger();
@Autowired
private UserService userService;
@Test
public void testCreate() {
int beforeDbCount = userService.countAll();
userService.save(genRandomUser());
int afterDbCount = userService.countAll();
assertEquals(beforeDbCount + 1, afterDbCount);
}
@Test
public void testUpdate() {
| // Path: src/main/java/com/avicit/bis/hr/user/model/UserModel.java
// @SuppressWarnings("serial")
// @Entity
// @Table(name = "tbl_user")
// @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
// public class UserModel extends BaseEntity {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "id", nullable = false)
// private int id;
//
//
// @Pattern(regexp = "[A-Za-z0-9]{5,20}", message = "{username.illegal}") //java validator验证(用户名字母数字组成,长度为5-10)
// private String username;
//
// @NotEmpty(message = "{email.illegal}")
// @Email(message = "{email.illegal}") //错误消息会自动到MessageSource中查找
// private String email;
//
// @Pattern(regexp = "[A-Za-z0-9]{5,20}", message = "{password.illegal}")
// private String password;
//
// @DateFormat( message="{register.date.error}")//自定义的验证器
// private Date registerDate;
//
// public int getId() {
// return id;
// }
// public void setId(int id) {
// this.id = id;
// }
// public String getUsername() {
// return username;
// }
// public void setUsername(String username) {
// this.username = username;
// }
// public String getEmail() {
// return email;
// }
// public void setEmail(String email) {
// this.email = email;
// }
// public String getPassword() {
// return password;
// }
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Date getRegisterDate() {
// return registerDate;
// }
//
// public void setRegisterDate(Date registerDate) {
// this.registerDate = registerDate;
// }
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + id;
// return result;
// }
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// UserModel other = (UserModel) obj;
// if (id != other.id)
// return false;
// return true;
// }
//
//
//
// }
//
// Path: src/main/java/com/avicit/bis/hr/user/service/UserService.java
// public interface UserService extends BaseService<UserModel, Integer> {
//
// Page<UserModel> query(int pn, int pageSize, UserQueryModel command);
// }
// Path: src/test/java/cn/javass/ssonline/spider/service/impl/UserServiceTest.java
import static junit.framework.Assert.assertEquals;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import com.avicit.bis.hr.user.model.UserModel;
import com.avicit.bis.hr.user.service.UserService;
package cn.javass.ssonline.spider.service.impl;
/**
*
* 该测试为集成测试,非单元测试
*
* User: Zhang Kaitao Date: 11-12-26 下午4:33 Version: 1.0
*/
// @Ignore
@ContextConfiguration(locations = { "classpath*:applicationContext.xml" })
@Transactional
@TransactionConfiguration(transactionManager = "txManager", defaultRollback = false)
public class UserServiceTest extends AbstractJUnit4SpringContextTests {
AtomicInteger counter = new AtomicInteger();
@Autowired
private UserService userService;
@Test
public void testCreate() {
int beforeDbCount = userService.countAll();
userService.save(genRandomUser());
int afterDbCount = userService.countAll();
assertEquals(beforeDbCount + 1, afterDbCount);
}
@Test
public void testUpdate() {
| UserModel user = userService.save(genRandomUser()); |
jacarrichan/bis | src/main/java/com/avicit/bis/system/role/service/RoleService.java | // Path: src/main/java/com/avicit/bis/system/role/entity/Role.java
// @Entity
// @Table(name="SYS_ROLE")
// public class Role extends BaseEntity{
//
// private static final long serialVersionUID = 1L;
// private Integer id;
// /**
// * 角色名称
// */
// private String name;
// /**
// * 角色代码
// */
// private String code;
// /**
// * 角色描述
// */
// private String description;
//
// /**
// * 该角色对应的资源菜单
// */
// private List<Resource> resources;
//
// /**
// * 该角色对应的用户集合
// */
// private List<User> users;
//
// private String roleLevel;
//
// public Role(){
//
// }
//
//
// @Id
// @GeneratedValue
// @Column(name="ID")
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// @Column(name="NAME")
// public String getName() {
// return name;
// }
//
//
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Column(name="CODE")
// public String getCode() {
// return code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// @Column(name="DESCRIPTION")
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// @ManyToMany(targetEntity=Resource.class,fetch=FetchType.LAZY)
// @JoinTable(name="SYS_ROLE_RESOURCE",joinColumns=@JoinColumn(name = "ROLE_ID"),inverseJoinColumns = @JoinColumn(name = "RESOURCE_ID"))
// @Fetch(FetchMode.SUBSELECT)
// public List<Resource> getResources() {
// return resources;
// }
//
// public void setResources(List<Resource> resources) {
// this.resources = resources;
// }
//
// @ManyToMany(targetEntity=User.class,fetch=FetchType.LAZY)
// @JoinTable(name="SYS_USER_ROLE",joinColumns=@JoinColumn(name = "ROLE_ID"),inverseJoinColumns = @JoinColumn(name = "USER_ID"))
// @Fetch(FetchMode.SUBSELECT)
// public List<User> getUsers() {
// return users;
// }
//
//
//
// public void setUsers(List<User> users) {
// this.users = users;
// }
//
// @Column(name="ROLE_LEVEL")
// public String getRoleLevel() {
// return roleLevel;
// }
//
// public void setRoleLevel(String roleLevel) {
// this.roleLevel = roleLevel;
// }
//
// @Override
// public String toString() {
// return this.code;
// }
//
//
// }
//
// Path: src/main/java/com/avicit/bis/system/role/vo/RoleVo.java
// public class RoleVo {
//
// private Integer id;
//
// private String name;
//
// private String code;
//
// private String roleLevel;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getCode() {
// return code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public String getRoleLevel() {
// return roleLevel;
// }
//
// public void setRoleLevel(String roleLevel) {
// this.roleLevel = roleLevel;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// private String description;
// }
| import java.util.List;
import com.avicit.bis.system.role.entity.Role;
import com.avicit.bis.system.role.vo.RoleVo; | package com.avicit.bis.system.role.service;
public interface RoleService {
public List<RoleVo> list();
| // Path: src/main/java/com/avicit/bis/system/role/entity/Role.java
// @Entity
// @Table(name="SYS_ROLE")
// public class Role extends BaseEntity{
//
// private static final long serialVersionUID = 1L;
// private Integer id;
// /**
// * 角色名称
// */
// private String name;
// /**
// * 角色代码
// */
// private String code;
// /**
// * 角色描述
// */
// private String description;
//
// /**
// * 该角色对应的资源菜单
// */
// private List<Resource> resources;
//
// /**
// * 该角色对应的用户集合
// */
// private List<User> users;
//
// private String roleLevel;
//
// public Role(){
//
// }
//
//
// @Id
// @GeneratedValue
// @Column(name="ID")
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// @Column(name="NAME")
// public String getName() {
// return name;
// }
//
//
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Column(name="CODE")
// public String getCode() {
// return code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// @Column(name="DESCRIPTION")
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// @ManyToMany(targetEntity=Resource.class,fetch=FetchType.LAZY)
// @JoinTable(name="SYS_ROLE_RESOURCE",joinColumns=@JoinColumn(name = "ROLE_ID"),inverseJoinColumns = @JoinColumn(name = "RESOURCE_ID"))
// @Fetch(FetchMode.SUBSELECT)
// public List<Resource> getResources() {
// return resources;
// }
//
// public void setResources(List<Resource> resources) {
// this.resources = resources;
// }
//
// @ManyToMany(targetEntity=User.class,fetch=FetchType.LAZY)
// @JoinTable(name="SYS_USER_ROLE",joinColumns=@JoinColumn(name = "ROLE_ID"),inverseJoinColumns = @JoinColumn(name = "USER_ID"))
// @Fetch(FetchMode.SUBSELECT)
// public List<User> getUsers() {
// return users;
// }
//
//
//
// public void setUsers(List<User> users) {
// this.users = users;
// }
//
// @Column(name="ROLE_LEVEL")
// public String getRoleLevel() {
// return roleLevel;
// }
//
// public void setRoleLevel(String roleLevel) {
// this.roleLevel = roleLevel;
// }
//
// @Override
// public String toString() {
// return this.code;
// }
//
//
// }
//
// Path: src/main/java/com/avicit/bis/system/role/vo/RoleVo.java
// public class RoleVo {
//
// private Integer id;
//
// private String name;
//
// private String code;
//
// private String roleLevel;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getCode() {
// return code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public String getRoleLevel() {
// return roleLevel;
// }
//
// public void setRoleLevel(String roleLevel) {
// this.roleLevel = roleLevel;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// private String description;
// }
// Path: src/main/java/com/avicit/bis/system/role/service/RoleService.java
import java.util.List;
import com.avicit.bis.system.role.entity.Role;
import com.avicit.bis.system.role.vo.RoleVo;
package com.avicit.bis.system.role.service;
public interface RoleService {
public List<RoleVo> list();
| public void update(Role role) throws Exception; |
jacarrichan/bis | src/main/java/com/avicit/framework/resolver/GlobalExceptionResolver.java | // Path: src/main/java/com/avicit/framework/util/WebUtils.java
// public class WebUtils extends org.springframework.web.util.WebUtils {
//
// private static Log logger = LogFactory.getLog(WebUtils.class);
//
// /**
// * 判断是否是异步的请求、AJAX请求
// *
// * @param request
// * @return boolean
// */
// public static boolean isAsynRequest(HttpServletRequest request) {
// if (request == null) {
// request = SpringDispatcherContextHolder.getRequest();
// }
// return (request.getHeader("x-requested-with") != null && request
// .getHeader("x-requested-with").equalsIgnoreCase(
// "XMLHttpRequest"));
// }
//
// public static void send(String text) {
// try {
// HttpServletResponse response = SpringDispatcherContextHolder
// .getResponse();
// response.setCharacterEncoding("utf-8");
// PrintWriter out = response.getWriter();
// out.write(text);
// out.close();
// } catch (Exception e) {
// logger.error("Output something to client error,error message:"
// + e.getMessage());
// e.printStackTrace();
// }
// }
//
// public static void sendFailure(String text) {
// send(JsonUtil.buildFailure(text));
// }
//
// public static void sendSuccess(String text) {
// send(JsonUtil.buildSuccess(text));
// }
//
// public static void sendPagination(List<?> list) {
// send(JsonUtil.buildPagination(list));
// }
//
// public static void sendArrayList(List<?> list) {
// send(JsonUtil.buildArrayList(list));
// }
// }
| import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import com.avicit.framework.util.WebUtils; | package com.avicit.framework.resolver;
@Component
public class GlobalExceptionResolver implements HandlerExceptionResolver {
private static Log logger = LogFactory.getLog(GlobalExceptionResolver.class);
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) { | // Path: src/main/java/com/avicit/framework/util/WebUtils.java
// public class WebUtils extends org.springframework.web.util.WebUtils {
//
// private static Log logger = LogFactory.getLog(WebUtils.class);
//
// /**
// * 判断是否是异步的请求、AJAX请求
// *
// * @param request
// * @return boolean
// */
// public static boolean isAsynRequest(HttpServletRequest request) {
// if (request == null) {
// request = SpringDispatcherContextHolder.getRequest();
// }
// return (request.getHeader("x-requested-with") != null && request
// .getHeader("x-requested-with").equalsIgnoreCase(
// "XMLHttpRequest"));
// }
//
// public static void send(String text) {
// try {
// HttpServletResponse response = SpringDispatcherContextHolder
// .getResponse();
// response.setCharacterEncoding("utf-8");
// PrintWriter out = response.getWriter();
// out.write(text);
// out.close();
// } catch (Exception e) {
// logger.error("Output something to client error,error message:"
// + e.getMessage());
// e.printStackTrace();
// }
// }
//
// public static void sendFailure(String text) {
// send(JsonUtil.buildFailure(text));
// }
//
// public static void sendSuccess(String text) {
// send(JsonUtil.buildSuccess(text));
// }
//
// public static void sendPagination(List<?> list) {
// send(JsonUtil.buildPagination(list));
// }
//
// public static void sendArrayList(List<?> list) {
// send(JsonUtil.buildArrayList(list));
// }
// }
// Path: src/main/java/com/avicit/framework/resolver/GlobalExceptionResolver.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import com.avicit.framework.util.WebUtils;
package com.avicit.framework.resolver;
@Component
public class GlobalExceptionResolver implements HandlerExceptionResolver {
private static Log logger = LogFactory.getLog(GlobalExceptionResolver.class);
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) { | logger.error("用户" + WebUtils.getSessionId(request) + "访问" |
jacarrichan/bis | src/main/java/com/avicit/bis/system/simple/service/impl/SimpleServiceImpl.java | // Path: src/main/java/com/avicit/bis/system/simple/dao/SimpleDao.java
// public interface SimpleDao<T,ID> extends HibernateDao<T,ID> {
//
//
// }
//
// Path: src/main/java/com/avicit/bis/system/simple/domain/Simple.java
// public class Simple {
//
// }
//
// Path: src/main/java/com/avicit/bis/system/simple/service/SimpleService.java
// public interface SimpleService {
//
// public void selectSimple();
// }
| import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.avicit.bis.system.simple.dao.SimpleDao;
import com.avicit.bis.system.simple.domain.Simple;
import com.avicit.bis.system.simple.service.SimpleService; | package com.avicit.bis.system.simple.service.impl;
@Service("simpleServiceImpl")
public class SimpleServiceImpl implements SimpleService{
private static final Log logger = LogFactory.getLog(SimpleServiceImpl.class);
@Autowired | // Path: src/main/java/com/avicit/bis/system/simple/dao/SimpleDao.java
// public interface SimpleDao<T,ID> extends HibernateDao<T,ID> {
//
//
// }
//
// Path: src/main/java/com/avicit/bis/system/simple/domain/Simple.java
// public class Simple {
//
// }
//
// Path: src/main/java/com/avicit/bis/system/simple/service/SimpleService.java
// public interface SimpleService {
//
// public void selectSimple();
// }
// Path: src/main/java/com/avicit/bis/system/simple/service/impl/SimpleServiceImpl.java
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.avicit.bis.system.simple.dao.SimpleDao;
import com.avicit.bis.system.simple.domain.Simple;
import com.avicit.bis.system.simple.service.SimpleService;
package com.avicit.bis.system.simple.service.impl;
@Service("simpleServiceImpl")
public class SimpleServiceImpl implements SimpleService{
private static final Log logger = LogFactory.getLog(SimpleServiceImpl.class);
@Autowired | private SimpleDao<Simple, Integer> simpleDao; |
jacarrichan/bis | src/main/java/com/avicit/bis/system/simple/service/impl/SimpleServiceImpl.java | // Path: src/main/java/com/avicit/bis/system/simple/dao/SimpleDao.java
// public interface SimpleDao<T,ID> extends HibernateDao<T,ID> {
//
//
// }
//
// Path: src/main/java/com/avicit/bis/system/simple/domain/Simple.java
// public class Simple {
//
// }
//
// Path: src/main/java/com/avicit/bis/system/simple/service/SimpleService.java
// public interface SimpleService {
//
// public void selectSimple();
// }
| import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.avicit.bis.system.simple.dao.SimpleDao;
import com.avicit.bis.system.simple.domain.Simple;
import com.avicit.bis.system.simple.service.SimpleService; | package com.avicit.bis.system.simple.service.impl;
@Service("simpleServiceImpl")
public class SimpleServiceImpl implements SimpleService{
private static final Log logger = LogFactory.getLog(SimpleServiceImpl.class);
@Autowired | // Path: src/main/java/com/avicit/bis/system/simple/dao/SimpleDao.java
// public interface SimpleDao<T,ID> extends HibernateDao<T,ID> {
//
//
// }
//
// Path: src/main/java/com/avicit/bis/system/simple/domain/Simple.java
// public class Simple {
//
// }
//
// Path: src/main/java/com/avicit/bis/system/simple/service/SimpleService.java
// public interface SimpleService {
//
// public void selectSimple();
// }
// Path: src/main/java/com/avicit/bis/system/simple/service/impl/SimpleServiceImpl.java
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.avicit.bis.system.simple.dao.SimpleDao;
import com.avicit.bis.system.simple.domain.Simple;
import com.avicit.bis.system.simple.service.SimpleService;
package com.avicit.bis.system.simple.service.impl;
@Service("simpleServiceImpl")
public class SimpleServiceImpl implements SimpleService{
private static final Log logger = LogFactory.getLog(SimpleServiceImpl.class);
@Autowired | private SimpleDao<Simple, Integer> simpleDao; |
jacarrichan/bis | src/main/java/com/avicit/bis/system/resource/controller/ResourceController.java | // Path: src/main/java/com/avicit/bis/system/resource/service/ResourceService.java
// public interface ResourceService {
//
// public List<ResourceNode> getRoot() throws Exception;
//
// public List<ResourceNode> getChildren(Integer id) throws Exception;
// }
//
// Path: src/main/java/com/avicit/bis/system/resource/vo/ResourceNode.java
// public class ResourceNode {
//
// private Integer id;
//
// private String text;
//
// private String iconCls;
//
// private String type;
//
// private String component;
//
// private boolean leaf;
//
// public boolean isLeaf() {
// return leaf;
// }
//
// public void setLeaf(boolean leaf) {
// this.leaf = leaf;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public String getIconCls() {
// return iconCls;
// }
//
// public void setIconCls(String iconCls) {
// this.iconCls = iconCls;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getComponent() {
// return component;
// }
//
// public void setComponent(String component) {
// this.component = component;
// }
//
//
// }
| import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.avicit.bis.system.resource.service.ResourceService;
import com.avicit.bis.system.resource.vo.ResourceNode; | package com.avicit.bis.system.resource.controller;
@Controller
@RequestMapping("/resource")
public class ResourceController {
@Autowired | // Path: src/main/java/com/avicit/bis/system/resource/service/ResourceService.java
// public interface ResourceService {
//
// public List<ResourceNode> getRoot() throws Exception;
//
// public List<ResourceNode> getChildren(Integer id) throws Exception;
// }
//
// Path: src/main/java/com/avicit/bis/system/resource/vo/ResourceNode.java
// public class ResourceNode {
//
// private Integer id;
//
// private String text;
//
// private String iconCls;
//
// private String type;
//
// private String component;
//
// private boolean leaf;
//
// public boolean isLeaf() {
// return leaf;
// }
//
// public void setLeaf(boolean leaf) {
// this.leaf = leaf;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public String getIconCls() {
// return iconCls;
// }
//
// public void setIconCls(String iconCls) {
// this.iconCls = iconCls;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getComponent() {
// return component;
// }
//
// public void setComponent(String component) {
// this.component = component;
// }
//
//
// }
// Path: src/main/java/com/avicit/bis/system/resource/controller/ResourceController.java
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.avicit.bis.system.resource.service.ResourceService;
import com.avicit.bis.system.resource.vo.ResourceNode;
package com.avicit.bis.system.resource.controller;
@Controller
@RequestMapping("/resource")
public class ResourceController {
@Autowired | private ResourceService resourceService; |
jacarrichan/bis | src/main/java/com/avicit/bis/system/resource/controller/ResourceController.java | // Path: src/main/java/com/avicit/bis/system/resource/service/ResourceService.java
// public interface ResourceService {
//
// public List<ResourceNode> getRoot() throws Exception;
//
// public List<ResourceNode> getChildren(Integer id) throws Exception;
// }
//
// Path: src/main/java/com/avicit/bis/system/resource/vo/ResourceNode.java
// public class ResourceNode {
//
// private Integer id;
//
// private String text;
//
// private String iconCls;
//
// private String type;
//
// private String component;
//
// private boolean leaf;
//
// public boolean isLeaf() {
// return leaf;
// }
//
// public void setLeaf(boolean leaf) {
// this.leaf = leaf;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public String getIconCls() {
// return iconCls;
// }
//
// public void setIconCls(String iconCls) {
// this.iconCls = iconCls;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getComponent() {
// return component;
// }
//
// public void setComponent(String component) {
// this.component = component;
// }
//
//
// }
| import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.avicit.bis.system.resource.service.ResourceService;
import com.avicit.bis.system.resource.vo.ResourceNode; | package com.avicit.bis.system.resource.controller;
@Controller
@RequestMapping("/resource")
public class ResourceController {
@Autowired
private ResourceService resourceService;
@RequestMapping(value="root",method=RequestMethod.GET) | // Path: src/main/java/com/avicit/bis/system/resource/service/ResourceService.java
// public interface ResourceService {
//
// public List<ResourceNode> getRoot() throws Exception;
//
// public List<ResourceNode> getChildren(Integer id) throws Exception;
// }
//
// Path: src/main/java/com/avicit/bis/system/resource/vo/ResourceNode.java
// public class ResourceNode {
//
// private Integer id;
//
// private String text;
//
// private String iconCls;
//
// private String type;
//
// private String component;
//
// private boolean leaf;
//
// public boolean isLeaf() {
// return leaf;
// }
//
// public void setLeaf(boolean leaf) {
// this.leaf = leaf;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public String getIconCls() {
// return iconCls;
// }
//
// public void setIconCls(String iconCls) {
// this.iconCls = iconCls;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getComponent() {
// return component;
// }
//
// public void setComponent(String component) {
// this.component = component;
// }
//
//
// }
// Path: src/main/java/com/avicit/bis/system/resource/controller/ResourceController.java
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.avicit.bis.system.resource.service.ResourceService;
import com.avicit.bis.system.resource.vo.ResourceNode;
package com.avicit.bis.system.resource.controller;
@Controller
@RequestMapping("/resource")
public class ResourceController {
@Autowired
private ResourceService resourceService;
@RequestMapping(value="root",method=RequestMethod.GET) | public @ResponseBody List<ResourceNode> root() throws Exception{ |
jacarrichan/bis | src/main/java/com/avicit/bis/system/data/service/impl/DataServiceImpl.java | // Path: src/main/java/com/avicit/bis/system/data/dao/DataDao.java
// public interface DataDao<T, ID> extends HibernateDao<T, ID>{
//
// }
//
// Path: src/main/java/com/avicit/bis/system/data/entity/Data.java
// @Entity
// @Table(name="SYS_DATA")
// public class Data extends BaseEntity{
//
// private static final long serialVersionUID = 1L;
//
// private Integer id;
//
// private String code;
//
// private String text;
//
// private String value;
//
// private Integer sort;
//
// private Integer parentId;
//
// private String description;
//
// @Id
// @GeneratedValue
// @Column(name="ID")
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
// @Column(name="CODE")
// public String getCode() {
// return code;
// }
// public void setCode(String code) {
// this.code = code;
// }
//
// @Column(name="TEXT")
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// @Column(name="VALUE")
// public String getValue() {
// return value;
// }
// public void setValue(String value) {
// this.value = value;
// }
//
// @Column(name="PARENT_ID")
// public Integer getParentId() {
// return parentId;
// }
// public void setParentId(Integer parentId) {
// this.parentId = parentId;
// }
//
// @Column(name="DESCRIPTION")
// public String getDescription() {
// return description;
// }
// public void setDescription(String description) {
// this.description = description;
// }
//
// @Column(name="SORT")
// public Integer getSort() {
// return sort;
// }
// public void setSort(Integer sort) {
// this.sort = sort;
// }
//
//
// }
//
// Path: src/main/java/com/avicit/bis/system/data/service/DataService.java
// public interface DataService {
//
//
// public List<Data> list();
// }
| import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.avicit.bis.system.data.dao.DataDao;
import com.avicit.bis.system.data.entity.Data;
import com.avicit.bis.system.data.service.DataService; | package com.avicit.bis.system.data.service.impl;
@Service("dataService")
public class DataServiceImpl implements DataService{
@Autowired | // Path: src/main/java/com/avicit/bis/system/data/dao/DataDao.java
// public interface DataDao<T, ID> extends HibernateDao<T, ID>{
//
// }
//
// Path: src/main/java/com/avicit/bis/system/data/entity/Data.java
// @Entity
// @Table(name="SYS_DATA")
// public class Data extends BaseEntity{
//
// private static final long serialVersionUID = 1L;
//
// private Integer id;
//
// private String code;
//
// private String text;
//
// private String value;
//
// private Integer sort;
//
// private Integer parentId;
//
// private String description;
//
// @Id
// @GeneratedValue
// @Column(name="ID")
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
// @Column(name="CODE")
// public String getCode() {
// return code;
// }
// public void setCode(String code) {
// this.code = code;
// }
//
// @Column(name="TEXT")
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// @Column(name="VALUE")
// public String getValue() {
// return value;
// }
// public void setValue(String value) {
// this.value = value;
// }
//
// @Column(name="PARENT_ID")
// public Integer getParentId() {
// return parentId;
// }
// public void setParentId(Integer parentId) {
// this.parentId = parentId;
// }
//
// @Column(name="DESCRIPTION")
// public String getDescription() {
// return description;
// }
// public void setDescription(String description) {
// this.description = description;
// }
//
// @Column(name="SORT")
// public Integer getSort() {
// return sort;
// }
// public void setSort(Integer sort) {
// this.sort = sort;
// }
//
//
// }
//
// Path: src/main/java/com/avicit/bis/system/data/service/DataService.java
// public interface DataService {
//
//
// public List<Data> list();
// }
// Path: src/main/java/com/avicit/bis/system/data/service/impl/DataServiceImpl.java
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.avicit.bis.system.data.dao.DataDao;
import com.avicit.bis.system.data.entity.Data;
import com.avicit.bis.system.data.service.DataService;
package com.avicit.bis.system.data.service.impl;
@Service("dataService")
public class DataServiceImpl implements DataService{
@Autowired | private DataDao<Data, Integer> dataDao; |
jacarrichan/bis | src/main/java/com/avicit/bis/system/data/service/impl/DataServiceImpl.java | // Path: src/main/java/com/avicit/bis/system/data/dao/DataDao.java
// public interface DataDao<T, ID> extends HibernateDao<T, ID>{
//
// }
//
// Path: src/main/java/com/avicit/bis/system/data/entity/Data.java
// @Entity
// @Table(name="SYS_DATA")
// public class Data extends BaseEntity{
//
// private static final long serialVersionUID = 1L;
//
// private Integer id;
//
// private String code;
//
// private String text;
//
// private String value;
//
// private Integer sort;
//
// private Integer parentId;
//
// private String description;
//
// @Id
// @GeneratedValue
// @Column(name="ID")
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
// @Column(name="CODE")
// public String getCode() {
// return code;
// }
// public void setCode(String code) {
// this.code = code;
// }
//
// @Column(name="TEXT")
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// @Column(name="VALUE")
// public String getValue() {
// return value;
// }
// public void setValue(String value) {
// this.value = value;
// }
//
// @Column(name="PARENT_ID")
// public Integer getParentId() {
// return parentId;
// }
// public void setParentId(Integer parentId) {
// this.parentId = parentId;
// }
//
// @Column(name="DESCRIPTION")
// public String getDescription() {
// return description;
// }
// public void setDescription(String description) {
// this.description = description;
// }
//
// @Column(name="SORT")
// public Integer getSort() {
// return sort;
// }
// public void setSort(Integer sort) {
// this.sort = sort;
// }
//
//
// }
//
// Path: src/main/java/com/avicit/bis/system/data/service/DataService.java
// public interface DataService {
//
//
// public List<Data> list();
// }
| import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.avicit.bis.system.data.dao.DataDao;
import com.avicit.bis.system.data.entity.Data;
import com.avicit.bis.system.data.service.DataService; | package com.avicit.bis.system.data.service.impl;
@Service("dataService")
public class DataServiceImpl implements DataService{
@Autowired | // Path: src/main/java/com/avicit/bis/system/data/dao/DataDao.java
// public interface DataDao<T, ID> extends HibernateDao<T, ID>{
//
// }
//
// Path: src/main/java/com/avicit/bis/system/data/entity/Data.java
// @Entity
// @Table(name="SYS_DATA")
// public class Data extends BaseEntity{
//
// private static final long serialVersionUID = 1L;
//
// private Integer id;
//
// private String code;
//
// private String text;
//
// private String value;
//
// private Integer sort;
//
// private Integer parentId;
//
// private String description;
//
// @Id
// @GeneratedValue
// @Column(name="ID")
// public Integer getId() {
// return id;
// }
// public void setId(Integer id) {
// this.id = id;
// }
// @Column(name="CODE")
// public String getCode() {
// return code;
// }
// public void setCode(String code) {
// this.code = code;
// }
//
// @Column(name="TEXT")
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// @Column(name="VALUE")
// public String getValue() {
// return value;
// }
// public void setValue(String value) {
// this.value = value;
// }
//
// @Column(name="PARENT_ID")
// public Integer getParentId() {
// return parentId;
// }
// public void setParentId(Integer parentId) {
// this.parentId = parentId;
// }
//
// @Column(name="DESCRIPTION")
// public String getDescription() {
// return description;
// }
// public void setDescription(String description) {
// this.description = description;
// }
//
// @Column(name="SORT")
// public Integer getSort() {
// return sort;
// }
// public void setSort(Integer sort) {
// this.sort = sort;
// }
//
//
// }
//
// Path: src/main/java/com/avicit/bis/system/data/service/DataService.java
// public interface DataService {
//
//
// public List<Data> list();
// }
// Path: src/main/java/com/avicit/bis/system/data/service/impl/DataServiceImpl.java
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.avicit.bis.system.data.dao.DataDao;
import com.avicit.bis.system.data.entity.Data;
import com.avicit.bis.system.data.service.DataService;
package com.avicit.bis.system.data.service.impl;
@Service("dataService")
public class DataServiceImpl implements DataService{
@Autowired | private DataDao<Data, Integer> dataDao; |
jacarrichan/bis | src/main/java/com/avicit/bis/system/resource/entity/Resource.java | // Path: src/main/java/com/avicit/framework/support/entity/BaseEntity.java
// public abstract class BaseEntity implements java.io.Serializable {
//
// private static final long serialVersionUID = 2035013017939483936L;
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this);
// }
//
// public <T,ID extends Serializable> HibernateDaoSupport<T,ID> getDAO() {
// String className = this.getClass().getSimpleName();
// String daoName = className.substring(0,1).toLowerCase() + className.substring(1, className.length()) + "Dao";
// return SpringContextBeanFactory.getBean(daoName);
// }
//
// @SuppressWarnings("unchecked")
// public <ID extends Serializable> ID save() {
// return (ID) this.getDAO().save(this);
// }
//
// public void delete() {
// this.getDAO().delete(this);
// }
//
// public void update() {
// this.getDAO().update(this);
// }
//
// // 创建日期
// protected Date createDate;
// // 更新日期
// protected Date modifyDate;
// // 创建人
// protected Integer createUserId;
// // 更新人
// protected Integer modifyUserId;
// // 版本号
// protected Integer version;
// // 是否删除
// protected String deleted = "N";
//
// /**
// * @return the createDate
// */
// @Column(name = "CREATE_DATE")
// public Date getCreateDate() {
// return createDate;
// }
//
// /**
// * @param createDate
// * the createDate to set
// */
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// /**
// * @return the modifyDate
// */
// @Column(name = "MODIFY_DATE")
// public Date getModifyDate() {
// return modifyDate;
// }
//
// /**
// * @param modifyDate
// * the modifyDate to set
// */
// public void setModifyDate(Date modifyDate) {
// this.modifyDate = modifyDate;
// }
//
// /**
// * @return the createUserId
// */
// @Column(name = "CREATE_USER_ID")
// public Integer getCreateUserId() {
// return createUserId;
// }
//
// /**
// * @param createUserId
// * the createUserId to set
// */
// public void setCreateUserId(Integer createUserId) {
// this.createUserId = createUserId;
// }
//
// /**
// * @return the modifyUserId
// */
// @Column(name = "MODIFY_USER_ID")
// public Integer getModifyUserId() {
// return modifyUserId;
// }
//
// /**
// * @param modifyUserId
// * the modifyUserId to set
// */
// public void setModifyUserId(Integer modifyUserId) {
// this.modifyUserId = modifyUserId;
// }
//
// /**
// * @return the version
// */
// @Version
// @Column(name = "VERSION")
// public Integer getVersion() {
// return version;
// }
//
// /**
// * @param version
// * the version to set
// */
// public void setVersion(Integer version) {
// this.version = version;
// }
//
// /**
// * @return the deleted
// */
// @Column(name = "DELETED")
// public String getDeleted() {
// return deleted;
// }
//
// /**
// * @param deleted
// * the deleted to set
// */
// public void setDeleted(String deleted) {
// this.deleted = deleted;
// }
//
// }
| import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.avicit.framework.support.entity.BaseEntity; | package com.avicit.bis.system.resource.entity;
@Entity
@Table(name="SYS_RESOURCE") | // Path: src/main/java/com/avicit/framework/support/entity/BaseEntity.java
// public abstract class BaseEntity implements java.io.Serializable {
//
// private static final long serialVersionUID = 2035013017939483936L;
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this);
// }
//
// public <T,ID extends Serializable> HibernateDaoSupport<T,ID> getDAO() {
// String className = this.getClass().getSimpleName();
// String daoName = className.substring(0,1).toLowerCase() + className.substring(1, className.length()) + "Dao";
// return SpringContextBeanFactory.getBean(daoName);
// }
//
// @SuppressWarnings("unchecked")
// public <ID extends Serializable> ID save() {
// return (ID) this.getDAO().save(this);
// }
//
// public void delete() {
// this.getDAO().delete(this);
// }
//
// public void update() {
// this.getDAO().update(this);
// }
//
// // 创建日期
// protected Date createDate;
// // 更新日期
// protected Date modifyDate;
// // 创建人
// protected Integer createUserId;
// // 更新人
// protected Integer modifyUserId;
// // 版本号
// protected Integer version;
// // 是否删除
// protected String deleted = "N";
//
// /**
// * @return the createDate
// */
// @Column(name = "CREATE_DATE")
// public Date getCreateDate() {
// return createDate;
// }
//
// /**
// * @param createDate
// * the createDate to set
// */
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// /**
// * @return the modifyDate
// */
// @Column(name = "MODIFY_DATE")
// public Date getModifyDate() {
// return modifyDate;
// }
//
// /**
// * @param modifyDate
// * the modifyDate to set
// */
// public void setModifyDate(Date modifyDate) {
// this.modifyDate = modifyDate;
// }
//
// /**
// * @return the createUserId
// */
// @Column(name = "CREATE_USER_ID")
// public Integer getCreateUserId() {
// return createUserId;
// }
//
// /**
// * @param createUserId
// * the createUserId to set
// */
// public void setCreateUserId(Integer createUserId) {
// this.createUserId = createUserId;
// }
//
// /**
// * @return the modifyUserId
// */
// @Column(name = "MODIFY_USER_ID")
// public Integer getModifyUserId() {
// return modifyUserId;
// }
//
// /**
// * @param modifyUserId
// * the modifyUserId to set
// */
// public void setModifyUserId(Integer modifyUserId) {
// this.modifyUserId = modifyUserId;
// }
//
// /**
// * @return the version
// */
// @Version
// @Column(name = "VERSION")
// public Integer getVersion() {
// return version;
// }
//
// /**
// * @param version
// * the version to set
// */
// public void setVersion(Integer version) {
// this.version = version;
// }
//
// /**
// * @return the deleted
// */
// @Column(name = "DELETED")
// public String getDeleted() {
// return deleted;
// }
//
// /**
// * @param deleted
// * the deleted to set
// */
// public void setDeleted(String deleted) {
// this.deleted = deleted;
// }
//
// }
// Path: src/main/java/com/avicit/bis/system/resource/entity/Resource.java
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.avicit.framework.support.entity.BaseEntity;
package com.avicit.bis.system.resource.entity;
@Entity
@Table(name="SYS_RESOURCE") | public class Resource extends BaseEntity{ |
jacarrichan/bis | src/main/java/com/avicit/framework/web/filter/GZIPFilter.java | // Path: src/main/java/com/avicit/framework/web/support/gzip/GZIPResponseWrapper.java
// public class GZIPResponseWrapper extends HttpServletResponseWrapper {
//
// protected HttpServletResponse origResponse = null;
// protected ServletOutputStream stream = null;
// protected PrintWriter writer = null;
//
// public GZIPResponseWrapper(HttpServletResponse response) {
// super(response);
// origResponse = response;
// }
//
// public ServletOutputStream createOutputStream() throws IOException {
// return (new GZIPResponseStream(origResponse));
// }
//
// public void finishResponse() {
// try {
// if (writer != null) {
// writer.close();
// }
// else {
// if (stream != null) {
// stream.close();
// }
// }
// }
// catch (IOException e) {
// }
// }
//
// @Override
// public void flushBuffer() throws IOException {
// stream.flush();
// }
//
// @Override
// public ServletOutputStream getOutputStream() throws IOException {
// if (writer != null) {
// throw new IllegalStateException("getWriter() has already been called!");
// }
//
// if (stream == null) stream = createOutputStream();
// return (stream);
// }
//
// @Override
// public PrintWriter getWriter() throws IOException {
// if (writer != null) {
// return (writer);
// }
//
// if (stream != null) {
// throw new IllegalStateException("getOutputStream() has already been called!");
// }
//
// stream = createOutputStream();
// writer = new PrintWriter(new OutputStreamWriter(stream, "UTF-8"));
// return (writer);
// }
//
// @Override
// public void setContentLength(int length) {
// }
// }
| import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.avicit.framework.web.support.gzip.GZIPResponseWrapper;
import java.io.IOException; | /*
* Copyright 2003 Jayson Falkner ([email protected])
* This code is from "Servlets and JavaServer pages; the J2EE Web Tier",
* http://www.jspbook.com. You may freely use the code both commercially
* and non-commercially. If you like the code, please pick up a copy of
* the book and help support the authors, development of more free code,
* and the JSP/Servlet/J2EE community.
*/
package com.avicit.framework.web.filter;
public class GZIPFilter implements Filter {
private static Logger log = LoggerFactory.getLogger(GZIPFilter.class);
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
if (req instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String ae = request.getHeader("accept-encoding");
if (ae != null && ae.indexOf("gzip") != -1) {
log.debug("GZIP supported, compressing."); | // Path: src/main/java/com/avicit/framework/web/support/gzip/GZIPResponseWrapper.java
// public class GZIPResponseWrapper extends HttpServletResponseWrapper {
//
// protected HttpServletResponse origResponse = null;
// protected ServletOutputStream stream = null;
// protected PrintWriter writer = null;
//
// public GZIPResponseWrapper(HttpServletResponse response) {
// super(response);
// origResponse = response;
// }
//
// public ServletOutputStream createOutputStream() throws IOException {
// return (new GZIPResponseStream(origResponse));
// }
//
// public void finishResponse() {
// try {
// if (writer != null) {
// writer.close();
// }
// else {
// if (stream != null) {
// stream.close();
// }
// }
// }
// catch (IOException e) {
// }
// }
//
// @Override
// public void flushBuffer() throws IOException {
// stream.flush();
// }
//
// @Override
// public ServletOutputStream getOutputStream() throws IOException {
// if (writer != null) {
// throw new IllegalStateException("getWriter() has already been called!");
// }
//
// if (stream == null) stream = createOutputStream();
// return (stream);
// }
//
// @Override
// public PrintWriter getWriter() throws IOException {
// if (writer != null) {
// return (writer);
// }
//
// if (stream != null) {
// throw new IllegalStateException("getOutputStream() has already been called!");
// }
//
// stream = createOutputStream();
// writer = new PrintWriter(new OutputStreamWriter(stream, "UTF-8"));
// return (writer);
// }
//
// @Override
// public void setContentLength(int length) {
// }
// }
// Path: src/main/java/com/avicit/framework/web/filter/GZIPFilter.java
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.avicit.framework.web.support.gzip.GZIPResponseWrapper;
import java.io.IOException;
/*
* Copyright 2003 Jayson Falkner ([email protected])
* This code is from "Servlets and JavaServer pages; the J2EE Web Tier",
* http://www.jspbook.com. You may freely use the code both commercially
* and non-commercially. If you like the code, please pick up a copy of
* the book and help support the authors, development of more free code,
* and the JSP/Servlet/J2EE community.
*/
package com.avicit.framework.web.filter;
public class GZIPFilter implements Filter {
private static Logger log = LoggerFactory.getLogger(GZIPFilter.class);
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
if (req instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String ae = request.getHeader("accept-encoding");
if (ae != null && ae.indexOf("gzip") != -1) {
log.debug("GZIP supported, compressing."); | GZIPResponseWrapper wrappedResponse = new GZIPResponseWrapper(response); |
jacarrichan/bis | src/main/java/com/avicit/framework/interceptor/dispatcher/HandlerDispatcherContextInterceptor.java | // Path: src/main/java/com/avicit/framework/context/spring/SpringDispatcherContextHolder.java
// public class SpringDispatcherContextHolder {
//
// protected static final Log logger = LogFactory
// .getLog(SpringDispatcherContextHolder.class);
//
// private static final ThreadLocal<HttpServletResponse> responseHolder = new NamedThreadLocal<HttpServletResponse>(
// "Response Holder");
//
// public static void initDispatcherContext(HttpServletResponse response) {
// if (response != null) {
// responseHolder.set(response);
// }
// }
//
// public static void resetDispatcherContext() {
// responseHolder.remove();
// }
//
// public static HttpServletRequest getRequest() {
// return ((ServletRequestAttributes) RequestContextHolder
// .getRequestAttributes()).getRequest();
// }
//
// public static HttpServletResponse getResponse() {
// return responseHolder.get();
// }
//
// public static HttpSession getSession() {
// return getRequest().getSession();
// }
//
// public static ServletContext getServletContext() {
// return getSession().getServletContext();
// }
//
// /**
// * 获取DispathcerSerlvet的WebApplicationContext,而非全局的
// * **/
// public static WebApplicationContext getWebApplicationContext() {
// return RequestContextUtils.getWebApplicationContext(getRequest());
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T getBean(String name) {
// return (T) getWebApplicationContext().getBean(name);
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T getBean(Class<?> clazz) {
// return (T)getWebApplicationContext().getBean(clazz);
// }
// }
//
// Path: src/main/java/com/avicit/framework/interceptor/AbstractHandlerPreparInterceptor.java
// public abstract class AbstractHandlerPreparInterceptor implements HandlerInterceptor{
//
// @Override
// public abstract boolean preHandle(HttpServletRequest request,
// HttpServletResponse response, Object handler);
//
// @Override
// public void postHandle(HttpServletRequest request,
// HttpServletResponse response, Object handler,
// ModelAndView modelAndView) throws Exception {
// }
//
// @Override
// public void afterCompletion(HttpServletRequest request,
// HttpServletResponse response, Object handler, Exception ex)
// throws Exception{
// }
//
// }
| import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.avicit.framework.context.spring.SpringDispatcherContextHolder;
import com.avicit.framework.interceptor.AbstractHandlerPreparInterceptor; | package com.avicit.framework.interceptor.dispatcher;
public class HandlerDispatcherContextInterceptor extends
AbstractHandlerPreparInterceptor {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) { | // Path: src/main/java/com/avicit/framework/context/spring/SpringDispatcherContextHolder.java
// public class SpringDispatcherContextHolder {
//
// protected static final Log logger = LogFactory
// .getLog(SpringDispatcherContextHolder.class);
//
// private static final ThreadLocal<HttpServletResponse> responseHolder = new NamedThreadLocal<HttpServletResponse>(
// "Response Holder");
//
// public static void initDispatcherContext(HttpServletResponse response) {
// if (response != null) {
// responseHolder.set(response);
// }
// }
//
// public static void resetDispatcherContext() {
// responseHolder.remove();
// }
//
// public static HttpServletRequest getRequest() {
// return ((ServletRequestAttributes) RequestContextHolder
// .getRequestAttributes()).getRequest();
// }
//
// public static HttpServletResponse getResponse() {
// return responseHolder.get();
// }
//
// public static HttpSession getSession() {
// return getRequest().getSession();
// }
//
// public static ServletContext getServletContext() {
// return getSession().getServletContext();
// }
//
// /**
// * 获取DispathcerSerlvet的WebApplicationContext,而非全局的
// * **/
// public static WebApplicationContext getWebApplicationContext() {
// return RequestContextUtils.getWebApplicationContext(getRequest());
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T getBean(String name) {
// return (T) getWebApplicationContext().getBean(name);
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T getBean(Class<?> clazz) {
// return (T)getWebApplicationContext().getBean(clazz);
// }
// }
//
// Path: src/main/java/com/avicit/framework/interceptor/AbstractHandlerPreparInterceptor.java
// public abstract class AbstractHandlerPreparInterceptor implements HandlerInterceptor{
//
// @Override
// public abstract boolean preHandle(HttpServletRequest request,
// HttpServletResponse response, Object handler);
//
// @Override
// public void postHandle(HttpServletRequest request,
// HttpServletResponse response, Object handler,
// ModelAndView modelAndView) throws Exception {
// }
//
// @Override
// public void afterCompletion(HttpServletRequest request,
// HttpServletResponse response, Object handler, Exception ex)
// throws Exception{
// }
//
// }
// Path: src/main/java/com/avicit/framework/interceptor/dispatcher/HandlerDispatcherContextInterceptor.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.avicit.framework.context.spring.SpringDispatcherContextHolder;
import com.avicit.framework.interceptor.AbstractHandlerPreparInterceptor;
package com.avicit.framework.interceptor.dispatcher;
public class HandlerDispatcherContextInterceptor extends
AbstractHandlerPreparInterceptor {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) { | SpringDispatcherContextHolder.initDispatcherContext(response); |
jacarrichan/bis | src/main/java/com/avicit/bis/hr/user/model/UserModel.java | // Path: src/main/java/com/avicit/framework/support/entity/BaseEntity.java
// public abstract class BaseEntity implements java.io.Serializable {
//
// private static final long serialVersionUID = 2035013017939483936L;
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this);
// }
//
// public <T,ID extends Serializable> HibernateDaoSupport<T,ID> getDAO() {
// String className = this.getClass().getSimpleName();
// String daoName = className.substring(0,1).toLowerCase() + className.substring(1, className.length()) + "Dao";
// return SpringContextBeanFactory.getBean(daoName);
// }
//
// @SuppressWarnings("unchecked")
// public <ID extends Serializable> ID save() {
// return (ID) this.getDAO().save(this);
// }
//
// public void delete() {
// this.getDAO().delete(this);
// }
//
// public void update() {
// this.getDAO().update(this);
// }
//
// // 创建日期
// protected Date createDate;
// // 更新日期
// protected Date modifyDate;
// // 创建人
// protected Integer createUserId;
// // 更新人
// protected Integer modifyUserId;
// // 版本号
// protected Integer version;
// // 是否删除
// protected String deleted = "N";
//
// /**
// * @return the createDate
// */
// @Column(name = "CREATE_DATE")
// public Date getCreateDate() {
// return createDate;
// }
//
// /**
// * @param createDate
// * the createDate to set
// */
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// /**
// * @return the modifyDate
// */
// @Column(name = "MODIFY_DATE")
// public Date getModifyDate() {
// return modifyDate;
// }
//
// /**
// * @param modifyDate
// * the modifyDate to set
// */
// public void setModifyDate(Date modifyDate) {
// this.modifyDate = modifyDate;
// }
//
// /**
// * @return the createUserId
// */
// @Column(name = "CREATE_USER_ID")
// public Integer getCreateUserId() {
// return createUserId;
// }
//
// /**
// * @param createUserId
// * the createUserId to set
// */
// public void setCreateUserId(Integer createUserId) {
// this.createUserId = createUserId;
// }
//
// /**
// * @return the modifyUserId
// */
// @Column(name = "MODIFY_USER_ID")
// public Integer getModifyUserId() {
// return modifyUserId;
// }
//
// /**
// * @param modifyUserId
// * the modifyUserId to set
// */
// public void setModifyUserId(Integer modifyUserId) {
// this.modifyUserId = modifyUserId;
// }
//
// /**
// * @return the version
// */
// @Version
// @Column(name = "VERSION")
// public Integer getVersion() {
// return version;
// }
//
// /**
// * @param version
// * the version to set
// */
// public void setVersion(Integer version) {
// this.version = version;
// }
//
// /**
// * @return the deleted
// */
// @Column(name = "DELETED")
// public String getDeleted() {
// return deleted;
// }
//
// /**
// * @param deleted
// * the deleted to set
// */
// public void setDeleted(String deleted) {
// this.deleted = deleted;
// }
//
// }
| import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Pattern;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import com.avicit.framework.support.entity.BaseEntity;
import com.avicit.framework.web.support.validator.DateFormat; | package com.avicit.bis.hr.user.model;
/**
* User: Zhang Kaitao
* Date: 12-1-4 下午3:12
* Version: 1.0
*/
@SuppressWarnings("serial")
@Entity
@Table(name = "tbl_user")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE) | // Path: src/main/java/com/avicit/framework/support/entity/BaseEntity.java
// public abstract class BaseEntity implements java.io.Serializable {
//
// private static final long serialVersionUID = 2035013017939483936L;
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this);
// }
//
// public <T,ID extends Serializable> HibernateDaoSupport<T,ID> getDAO() {
// String className = this.getClass().getSimpleName();
// String daoName = className.substring(0,1).toLowerCase() + className.substring(1, className.length()) + "Dao";
// return SpringContextBeanFactory.getBean(daoName);
// }
//
// @SuppressWarnings("unchecked")
// public <ID extends Serializable> ID save() {
// return (ID) this.getDAO().save(this);
// }
//
// public void delete() {
// this.getDAO().delete(this);
// }
//
// public void update() {
// this.getDAO().update(this);
// }
//
// // 创建日期
// protected Date createDate;
// // 更新日期
// protected Date modifyDate;
// // 创建人
// protected Integer createUserId;
// // 更新人
// protected Integer modifyUserId;
// // 版本号
// protected Integer version;
// // 是否删除
// protected String deleted = "N";
//
// /**
// * @return the createDate
// */
// @Column(name = "CREATE_DATE")
// public Date getCreateDate() {
// return createDate;
// }
//
// /**
// * @param createDate
// * the createDate to set
// */
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// /**
// * @return the modifyDate
// */
// @Column(name = "MODIFY_DATE")
// public Date getModifyDate() {
// return modifyDate;
// }
//
// /**
// * @param modifyDate
// * the modifyDate to set
// */
// public void setModifyDate(Date modifyDate) {
// this.modifyDate = modifyDate;
// }
//
// /**
// * @return the createUserId
// */
// @Column(name = "CREATE_USER_ID")
// public Integer getCreateUserId() {
// return createUserId;
// }
//
// /**
// * @param createUserId
// * the createUserId to set
// */
// public void setCreateUserId(Integer createUserId) {
// this.createUserId = createUserId;
// }
//
// /**
// * @return the modifyUserId
// */
// @Column(name = "MODIFY_USER_ID")
// public Integer getModifyUserId() {
// return modifyUserId;
// }
//
// /**
// * @param modifyUserId
// * the modifyUserId to set
// */
// public void setModifyUserId(Integer modifyUserId) {
// this.modifyUserId = modifyUserId;
// }
//
// /**
// * @return the version
// */
// @Version
// @Column(name = "VERSION")
// public Integer getVersion() {
// return version;
// }
//
// /**
// * @param version
// * the version to set
// */
// public void setVersion(Integer version) {
// this.version = version;
// }
//
// /**
// * @return the deleted
// */
// @Column(name = "DELETED")
// public String getDeleted() {
// return deleted;
// }
//
// /**
// * @param deleted
// * the deleted to set
// */
// public void setDeleted(String deleted) {
// this.deleted = deleted;
// }
//
// }
// Path: src/main/java/com/avicit/bis/hr/user/model/UserModel.java
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Pattern;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import com.avicit.framework.support.entity.BaseEntity;
import com.avicit.framework.web.support.validator.DateFormat;
package com.avicit.bis.hr.user.model;
/**
* User: Zhang Kaitao
* Date: 12-1-4 下午3:12
* Version: 1.0
*/
@SuppressWarnings("serial")
@Entity
@Table(name = "tbl_user")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE) | public class UserModel extends BaseEntity { |
jacarrichan/bis | src/main/java/com/avicit/framework/util/WebUtils.java | // Path: src/main/java/com/avicit/framework/context/spring/SpringDispatcherContextHolder.java
// public class SpringDispatcherContextHolder {
//
// protected static final Log logger = LogFactory
// .getLog(SpringDispatcherContextHolder.class);
//
// private static final ThreadLocal<HttpServletResponse> responseHolder = new NamedThreadLocal<HttpServletResponse>(
// "Response Holder");
//
// public static void initDispatcherContext(HttpServletResponse response) {
// if (response != null) {
// responseHolder.set(response);
// }
// }
//
// public static void resetDispatcherContext() {
// responseHolder.remove();
// }
//
// public static HttpServletRequest getRequest() {
// return ((ServletRequestAttributes) RequestContextHolder
// .getRequestAttributes()).getRequest();
// }
//
// public static HttpServletResponse getResponse() {
// return responseHolder.get();
// }
//
// public static HttpSession getSession() {
// return getRequest().getSession();
// }
//
// public static ServletContext getServletContext() {
// return getSession().getServletContext();
// }
//
// /**
// * 获取DispathcerSerlvet的WebApplicationContext,而非全局的
// * **/
// public static WebApplicationContext getWebApplicationContext() {
// return RequestContextUtils.getWebApplicationContext(getRequest());
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T getBean(String name) {
// return (T) getWebApplicationContext().getBean(name);
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T getBean(Class<?> clazz) {
// return (T)getWebApplicationContext().getBean(clazz);
// }
// }
| import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.avicit.framework.context.spring.SpringDispatcherContextHolder; | package com.avicit.framework.util;
public class WebUtils extends org.springframework.web.util.WebUtils {
private static Log logger = LogFactory.getLog(WebUtils.class);
/**
* 判断是否是异步的请求、AJAX请求
*
* @param request
* @return boolean
*/
public static boolean isAsynRequest(HttpServletRequest request) {
if (request == null) { | // Path: src/main/java/com/avicit/framework/context/spring/SpringDispatcherContextHolder.java
// public class SpringDispatcherContextHolder {
//
// protected static final Log logger = LogFactory
// .getLog(SpringDispatcherContextHolder.class);
//
// private static final ThreadLocal<HttpServletResponse> responseHolder = new NamedThreadLocal<HttpServletResponse>(
// "Response Holder");
//
// public static void initDispatcherContext(HttpServletResponse response) {
// if (response != null) {
// responseHolder.set(response);
// }
// }
//
// public static void resetDispatcherContext() {
// responseHolder.remove();
// }
//
// public static HttpServletRequest getRequest() {
// return ((ServletRequestAttributes) RequestContextHolder
// .getRequestAttributes()).getRequest();
// }
//
// public static HttpServletResponse getResponse() {
// return responseHolder.get();
// }
//
// public static HttpSession getSession() {
// return getRequest().getSession();
// }
//
// public static ServletContext getServletContext() {
// return getSession().getServletContext();
// }
//
// /**
// * 获取DispathcerSerlvet的WebApplicationContext,而非全局的
// * **/
// public static WebApplicationContext getWebApplicationContext() {
// return RequestContextUtils.getWebApplicationContext(getRequest());
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T getBean(String name) {
// return (T) getWebApplicationContext().getBean(name);
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T getBean(Class<?> clazz) {
// return (T)getWebApplicationContext().getBean(clazz);
// }
// }
// Path: src/main/java/com/avicit/framework/util/WebUtils.java
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.avicit.framework.context.spring.SpringDispatcherContextHolder;
package com.avicit.framework.util;
public class WebUtils extends org.springframework.web.util.WebUtils {
private static Log logger = LogFactory.getLog(WebUtils.class);
/**
* 判断是否是异步的请求、AJAX请求
*
* @param request
* @return boolean
*/
public static boolean isAsynRequest(HttpServletRequest request) {
if (request == null) { | request = SpringDispatcherContextHolder.getRequest(); |
jacarrichan/bis | src/main/java/com/avicit/framework/util/JsonUtil.java | // Path: src/main/java/com/avicit/framework/web/support/pagination/PaginationUtils.java
// public class PaginationUtils {
//
// private static final ThreadLocal<Pagination> paginationHolder = new NamedThreadLocal<Pagination>(
// "Pagination Holder");
//
// public static void setPagination(Pagination p){
// paginationHolder.set(p);
// }
//
// public static Pagination getPagination(){
// return paginationHolder.get();
// }
//
// public static int getStart(){
// return getPagination().getStart();
// }
//
// public static int getLimit(){
// return getPagination().getLimit();
// }
//
// public static String getSorter(){
// return getPagination().getSorter();
// }
//
// public static String getOrder(){
// return getPagination().getOrder();
// }
//
// public static void setTotal(int total){
// getPagination().setTotal(total);
// }
//
// public static void getTotal(){
// getPagination().getTotal();
// }
//
// public static boolean exist(){
// return getPagination() != null;
// }
// }
| import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.avicit.framework.web.support.pagination.PaginationUtils; | package com.avicit.framework.util;
public class JsonUtil {
public static String build(String flag, String text) {
return "{'" + flag + "' : true , '" + ResponseUtils.RESPONSE_TEXT_KEY
+ "' : '" + text + "'}";
}
public static String buildFailure(String text) {
return build(ResponseUtils.RESPONSE_FAILURE_KEY, text);
}
public static String buildSuccess(String text) {
return build(ResponseUtils.RESPONSE_SUCCESS_KEY, text);
}
public static String buildPagination(List<?> list) {
JSONObject json = new JSONObject();
json.element(ResponseUtils.RESPONSE_SUCCESS_KEY, true);
json.element(ResponseUtils.PAGINATION_TOTAL_PROPERTY_KEY, | // Path: src/main/java/com/avicit/framework/web/support/pagination/PaginationUtils.java
// public class PaginationUtils {
//
// private static final ThreadLocal<Pagination> paginationHolder = new NamedThreadLocal<Pagination>(
// "Pagination Holder");
//
// public static void setPagination(Pagination p){
// paginationHolder.set(p);
// }
//
// public static Pagination getPagination(){
// return paginationHolder.get();
// }
//
// public static int getStart(){
// return getPagination().getStart();
// }
//
// public static int getLimit(){
// return getPagination().getLimit();
// }
//
// public static String getSorter(){
// return getPagination().getSorter();
// }
//
// public static String getOrder(){
// return getPagination().getOrder();
// }
//
// public static void setTotal(int total){
// getPagination().setTotal(total);
// }
//
// public static void getTotal(){
// getPagination().getTotal();
// }
//
// public static boolean exist(){
// return getPagination() != null;
// }
// }
// Path: src/main/java/com/avicit/framework/util/JsonUtil.java
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.avicit.framework.web.support.pagination.PaginationUtils;
package com.avicit.framework.util;
public class JsonUtil {
public static String build(String flag, String text) {
return "{'" + flag + "' : true , '" + ResponseUtils.RESPONSE_TEXT_KEY
+ "' : '" + text + "'}";
}
public static String buildFailure(String text) {
return build(ResponseUtils.RESPONSE_FAILURE_KEY, text);
}
public static String buildSuccess(String text) {
return build(ResponseUtils.RESPONSE_SUCCESS_KEY, text);
}
public static String buildPagination(List<?> list) {
JSONObject json = new JSONObject();
json.element(ResponseUtils.RESPONSE_SUCCESS_KEY, true);
json.element(ResponseUtils.PAGINATION_TOTAL_PROPERTY_KEY, | PaginationUtils.getPagination().getTotal()); |
jacarrichan/bis | src/main/java/com/avicit/framework/support/service/BaseService.java | // Path: src/main/java/com/avicit/framework/web/support/pagination/Page.java
// public class Page<E> {
// private boolean hasPre;//是否首页
// private boolean hasNext;//是否尾页
// private List<E> items;//当前页包含的记录列表
// private int index;//当前页页码(起始为1)
// private IPageContext<E> context;
//
// public IPageContext<E> getContext() {
// return this.context;
// }
//
// public void setContext(IPageContext<E> context) {
// this.context = context;
// }
//
// public int getIndex() {
// return this.index;
// }
//
// public void setIndex(int index) {
// this.index = index;
// }
//
// public boolean isHasPre() {
// return this.hasPre;
// }
//
// public void setHasPre(boolean hasPre) {
// this.hasPre = hasPre;
// }
//
// public boolean isHasNext() {
// return this.hasNext;
// }
//
// public void setHasNext(boolean hasNext) {
// this.hasNext = hasNext;
// }
//
// public List<E> getItems() {
// return this.items == null ? Collections.<E>emptyList() : this.items;
// }
//
// public void setItems(List<E> items) {
// this.items = items;
// }
//
// }
| import java.util.List;
import com.avicit.framework.web.support.pagination.Page; | package com.avicit.framework.support.service;
public interface BaseService<M extends java.io.Serializable, PK extends java.io.Serializable> {
public M save(M model);
public void saveOrUpdate(M model);
public void update(M model);
public void merge(M model);
public void delete(PK id);
public void deleteObject(M model);
public M get(PK id);
public int countAll();
public List<M> listAll();
| // Path: src/main/java/com/avicit/framework/web/support/pagination/Page.java
// public class Page<E> {
// private boolean hasPre;//是否首页
// private boolean hasNext;//是否尾页
// private List<E> items;//当前页包含的记录列表
// private int index;//当前页页码(起始为1)
// private IPageContext<E> context;
//
// public IPageContext<E> getContext() {
// return this.context;
// }
//
// public void setContext(IPageContext<E> context) {
// this.context = context;
// }
//
// public int getIndex() {
// return this.index;
// }
//
// public void setIndex(int index) {
// this.index = index;
// }
//
// public boolean isHasPre() {
// return this.hasPre;
// }
//
// public void setHasPre(boolean hasPre) {
// this.hasPre = hasPre;
// }
//
// public boolean isHasNext() {
// return this.hasNext;
// }
//
// public void setHasNext(boolean hasNext) {
// this.hasNext = hasNext;
// }
//
// public List<E> getItems() {
// return this.items == null ? Collections.<E>emptyList() : this.items;
// }
//
// public void setItems(List<E> items) {
// this.items = items;
// }
//
// }
// Path: src/main/java/com/avicit/framework/support/service/BaseService.java
import java.util.List;
import com.avicit.framework.web.support.pagination.Page;
package com.avicit.framework.support.service;
public interface BaseService<M extends java.io.Serializable, PK extends java.io.Serializable> {
public M save(M model);
public void saveOrUpdate(M model);
public void update(M model);
public void merge(M model);
public void delete(PK id);
public void deleteObject(M model);
public M get(PK id);
public int countAll();
public List<M> listAll();
| public Page<M> listAll(int pn); |
jacarrichan/bis | src/main/java/com/avicit/framework/web/filter/ImageFilter.java | // Path: src/main/java/com/avicit/framework/web/support/image/ImageResponseWrapper.java
// public class ImageResponseWrapper extends HttpServletResponseWrapper {
//
// protected HttpServletResponse origResponse = null;
// protected ServletOutputStream stream = null;
// protected PrintWriter writer = null;
// protected String imageType = null;
//
// public ImageResponseWrapper(HttpServletResponse response, String imageType) {
// super(response);
// origResponse = response;
// this.imageType = imageType;
// }
//
// public ServletOutputStream createOutputStream() throws IOException {
// return (new ImageResponseStream(origResponse, imageType));
// }
//
// public void finishResponse() {
// try {
// if (writer != null) {
// writer.close();
// }
// else {
// if (stream != null) {
// stream.close();
// }
// }
// }
// catch (IOException e) {
// }
// }
//
// @Override
// public void flushBuffer() throws IOException {
// stream.flush();
// }
//
// @Override
// public ServletOutputStream getOutputStream() throws IOException {
// if (writer != null) {
// throw new IllegalStateException("getWriter() has already been called!");
// }
//
// if (stream == null) stream = createOutputStream();
// return (stream);
// }
//
// @Override
// public PrintWriter getWriter() throws IOException {
// if (writer != null) {
// return (writer);
// }
//
// if (stream != null) {
// throw new IllegalStateException("getOutputStream() has already been called!");
// }
//
// stream = createOutputStream();
// writer = new PrintWriter(new OutputStreamWriter(stream, "UTF-8"));
// return (writer);
// }
//
// @Override
// public void setContentLength(int length) {
// }
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.avicit.framework.web.support.image.ImageResponseWrapper;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*; | public void init(FilterConfig config) throws ServletException {
String dateStr = config.getInitParameter("filterDate");
if (dateStr != null) {
String[] dates = dateStr.split(",");
for (String date : dates) {
filterDate.add(date);
}
}
contentTypes.add("image/bmp");
imageTypes.put("image/bmp", "bmp");
contentTypes.add("image/gif");
imageTypes.put("image/gif", "gif");
contentTypes.add("image/jpeg");
imageTypes.put("image/jpeg", "jpeg");
contentTypes.add("image/png");
imageTypes.put("image/png", "png");
contentTypes.add("image/vnd.wap.wbmp");
imageTypes.put("image/vnd.wap.wbmp", "bmp");
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
ServletException {
HttpServletRequest request = (HttpServletRequest) req;
if (isImageRequest(request) && isFilter()) {
HttpServletResponse response = (HttpServletResponse) res; | // Path: src/main/java/com/avicit/framework/web/support/image/ImageResponseWrapper.java
// public class ImageResponseWrapper extends HttpServletResponseWrapper {
//
// protected HttpServletResponse origResponse = null;
// protected ServletOutputStream stream = null;
// protected PrintWriter writer = null;
// protected String imageType = null;
//
// public ImageResponseWrapper(HttpServletResponse response, String imageType) {
// super(response);
// origResponse = response;
// this.imageType = imageType;
// }
//
// public ServletOutputStream createOutputStream() throws IOException {
// return (new ImageResponseStream(origResponse, imageType));
// }
//
// public void finishResponse() {
// try {
// if (writer != null) {
// writer.close();
// }
// else {
// if (stream != null) {
// stream.close();
// }
// }
// }
// catch (IOException e) {
// }
// }
//
// @Override
// public void flushBuffer() throws IOException {
// stream.flush();
// }
//
// @Override
// public ServletOutputStream getOutputStream() throws IOException {
// if (writer != null) {
// throw new IllegalStateException("getWriter() has already been called!");
// }
//
// if (stream == null) stream = createOutputStream();
// return (stream);
// }
//
// @Override
// public PrintWriter getWriter() throws IOException {
// if (writer != null) {
// return (writer);
// }
//
// if (stream != null) {
// throw new IllegalStateException("getOutputStream() has already been called!");
// }
//
// stream = createOutputStream();
// writer = new PrintWriter(new OutputStreamWriter(stream, "UTF-8"));
// return (writer);
// }
//
// @Override
// public void setContentLength(int length) {
// }
// }
// Path: src/main/java/com/avicit/framework/web/filter/ImageFilter.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.avicit.framework.web.support.image.ImageResponseWrapper;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
public void init(FilterConfig config) throws ServletException {
String dateStr = config.getInitParameter("filterDate");
if (dateStr != null) {
String[] dates = dateStr.split(",");
for (String date : dates) {
filterDate.add(date);
}
}
contentTypes.add("image/bmp");
imageTypes.put("image/bmp", "bmp");
contentTypes.add("image/gif");
imageTypes.put("image/gif", "gif");
contentTypes.add("image/jpeg");
imageTypes.put("image/jpeg", "jpeg");
contentTypes.add("image/png");
imageTypes.put("image/png", "png");
contentTypes.add("image/vnd.wap.wbmp");
imageTypes.put("image/vnd.wap.wbmp", "bmp");
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
ServletException {
HttpServletRequest request = (HttpServletRequest) req;
if (isImageRequest(request) && isFilter()) {
HttpServletResponse response = (HttpServletResponse) res; | ImageResponseWrapper wrappedResponse = new ImageResponseWrapper(response, getImageType(request)); |
jacarrichan/bis | src/main/java/com/avicit/bis/system/data/entity/Data.java | // Path: src/main/java/com/avicit/framework/support/entity/BaseEntity.java
// public abstract class BaseEntity implements java.io.Serializable {
//
// private static final long serialVersionUID = 2035013017939483936L;
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this);
// }
//
// public <T,ID extends Serializable> HibernateDaoSupport<T,ID> getDAO() {
// String className = this.getClass().getSimpleName();
// String daoName = className.substring(0,1).toLowerCase() + className.substring(1, className.length()) + "Dao";
// return SpringContextBeanFactory.getBean(daoName);
// }
//
// @SuppressWarnings("unchecked")
// public <ID extends Serializable> ID save() {
// return (ID) this.getDAO().save(this);
// }
//
// public void delete() {
// this.getDAO().delete(this);
// }
//
// public void update() {
// this.getDAO().update(this);
// }
//
// // 创建日期
// protected Date createDate;
// // 更新日期
// protected Date modifyDate;
// // 创建人
// protected Integer createUserId;
// // 更新人
// protected Integer modifyUserId;
// // 版本号
// protected Integer version;
// // 是否删除
// protected String deleted = "N";
//
// /**
// * @return the createDate
// */
// @Column(name = "CREATE_DATE")
// public Date getCreateDate() {
// return createDate;
// }
//
// /**
// * @param createDate
// * the createDate to set
// */
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// /**
// * @return the modifyDate
// */
// @Column(name = "MODIFY_DATE")
// public Date getModifyDate() {
// return modifyDate;
// }
//
// /**
// * @param modifyDate
// * the modifyDate to set
// */
// public void setModifyDate(Date modifyDate) {
// this.modifyDate = modifyDate;
// }
//
// /**
// * @return the createUserId
// */
// @Column(name = "CREATE_USER_ID")
// public Integer getCreateUserId() {
// return createUserId;
// }
//
// /**
// * @param createUserId
// * the createUserId to set
// */
// public void setCreateUserId(Integer createUserId) {
// this.createUserId = createUserId;
// }
//
// /**
// * @return the modifyUserId
// */
// @Column(name = "MODIFY_USER_ID")
// public Integer getModifyUserId() {
// return modifyUserId;
// }
//
// /**
// * @param modifyUserId
// * the modifyUserId to set
// */
// public void setModifyUserId(Integer modifyUserId) {
// this.modifyUserId = modifyUserId;
// }
//
// /**
// * @return the version
// */
// @Version
// @Column(name = "VERSION")
// public Integer getVersion() {
// return version;
// }
//
// /**
// * @param version
// * the version to set
// */
// public void setVersion(Integer version) {
// this.version = version;
// }
//
// /**
// * @return the deleted
// */
// @Column(name = "DELETED")
// public String getDeleted() {
// return deleted;
// }
//
// /**
// * @param deleted
// * the deleted to set
// */
// public void setDeleted(String deleted) {
// this.deleted = deleted;
// }
//
// }
| import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import com.avicit.framework.support.entity.BaseEntity; | package com.avicit.bis.system.data.entity;
@Entity
@Table(name="SYS_DATA") | // Path: src/main/java/com/avicit/framework/support/entity/BaseEntity.java
// public abstract class BaseEntity implements java.io.Serializable {
//
// private static final long serialVersionUID = 2035013017939483936L;
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this);
// }
//
// public <T,ID extends Serializable> HibernateDaoSupport<T,ID> getDAO() {
// String className = this.getClass().getSimpleName();
// String daoName = className.substring(0,1).toLowerCase() + className.substring(1, className.length()) + "Dao";
// return SpringContextBeanFactory.getBean(daoName);
// }
//
// @SuppressWarnings("unchecked")
// public <ID extends Serializable> ID save() {
// return (ID) this.getDAO().save(this);
// }
//
// public void delete() {
// this.getDAO().delete(this);
// }
//
// public void update() {
// this.getDAO().update(this);
// }
//
// // 创建日期
// protected Date createDate;
// // 更新日期
// protected Date modifyDate;
// // 创建人
// protected Integer createUserId;
// // 更新人
// protected Integer modifyUserId;
// // 版本号
// protected Integer version;
// // 是否删除
// protected String deleted = "N";
//
// /**
// * @return the createDate
// */
// @Column(name = "CREATE_DATE")
// public Date getCreateDate() {
// return createDate;
// }
//
// /**
// * @param createDate
// * the createDate to set
// */
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// /**
// * @return the modifyDate
// */
// @Column(name = "MODIFY_DATE")
// public Date getModifyDate() {
// return modifyDate;
// }
//
// /**
// * @param modifyDate
// * the modifyDate to set
// */
// public void setModifyDate(Date modifyDate) {
// this.modifyDate = modifyDate;
// }
//
// /**
// * @return the createUserId
// */
// @Column(name = "CREATE_USER_ID")
// public Integer getCreateUserId() {
// return createUserId;
// }
//
// /**
// * @param createUserId
// * the createUserId to set
// */
// public void setCreateUserId(Integer createUserId) {
// this.createUserId = createUserId;
// }
//
// /**
// * @return the modifyUserId
// */
// @Column(name = "MODIFY_USER_ID")
// public Integer getModifyUserId() {
// return modifyUserId;
// }
//
// /**
// * @param modifyUserId
// * the modifyUserId to set
// */
// public void setModifyUserId(Integer modifyUserId) {
// this.modifyUserId = modifyUserId;
// }
//
// /**
// * @return the version
// */
// @Version
// @Column(name = "VERSION")
// public Integer getVersion() {
// return version;
// }
//
// /**
// * @param version
// * the version to set
// */
// public void setVersion(Integer version) {
// this.version = version;
// }
//
// /**
// * @return the deleted
// */
// @Column(name = "DELETED")
// public String getDeleted() {
// return deleted;
// }
//
// /**
// * @param deleted
// * the deleted to set
// */
// public void setDeleted(String deleted) {
// this.deleted = deleted;
// }
//
// }
// Path: src/main/java/com/avicit/bis/system/data/entity/Data.java
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import com.avicit.framework.support.entity.BaseEntity;
package com.avicit.bis.system.data.entity;
@Entity
@Table(name="SYS_DATA") | public class Data extends BaseEntity{ |
jacarrichan/bis | src/main/java/com/avicit/framework/web/support/pagination/PageUtil.java | // Path: src/main/java/com/avicit/framework/util/KeySynchronizer.java
// public class KeySynchronizer {
//
// private static final WeakHashMap<Object, Locker> LOCK_MAP = new WeakHashMap<Object, Locker>();
//
// private static class Locker {
// private Locker() {
//
// }
// }
//
//
// public static synchronized Object acquire(Object key) {
// Locker locker = LOCK_MAP.get(key);
// if(locker == null) {
// locker = new Locker();
// LOCK_MAP.put(key, locker);
// }
// return locker;
// }
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.avicit.framework.util.KeySynchronizer;
import javax.persistence.Id;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap; | package com.avicit.framework.web.support.pagination;
/**
* @author Zhang Kaitao
* @version 1.0, Sep 17, 2010
* @since 1.0
*/
public class PageUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(PageUtil.class);
/**
* 获取主键时缓存
*/
private static Map<Class<?>, Field> classPKMap = new WeakHashMap<Class<?>, Field>();
/**
* 不关心总记录数
* @param pageNumber
* @param pageSize
* @return
*/
public static int getPageStart(int pageNumber, int pageSize) {
return (pageNumber - 1) * pageSize;
}
/**
* 计算分页获取数据时游标的起始位置
*
* @param totalCount 所有记录总和
* @param pageNumber 页码,从1开始
* @return
*/
public static int getPageStart(int totalCount, int pageNumber, int pageSize) {
int start = (pageNumber - 1) * pageSize;
if (start >= totalCount) {
start = 0;
}
return start;
}
/**
* 构造分页对象
*
* @param totalCount 满足条件的所有记录总和
* @param pageNumber 本次分页的页码
* @param items
* @return
*/
public static <E> Page<E> getPage(int totalCount, int pageNumber, List<E> items, int pageSize) {
IPageContext<E> pageContext = new QuickPageContext<E>(totalCount, pageSize, items);
return pageContext.getPage(pageNumber);
}
public static Field getPkField(Class<?> cls) {
Field pkField = classPKMap.get(cls);
if(pkField == null) { | // Path: src/main/java/com/avicit/framework/util/KeySynchronizer.java
// public class KeySynchronizer {
//
// private static final WeakHashMap<Object, Locker> LOCK_MAP = new WeakHashMap<Object, Locker>();
//
// private static class Locker {
// private Locker() {
//
// }
// }
//
//
// public static synchronized Object acquire(Object key) {
// Locker locker = LOCK_MAP.get(key);
// if(locker == null) {
// locker = new Locker();
// LOCK_MAP.put(key, locker);
// }
// return locker;
// }
// }
// Path: src/main/java/com/avicit/framework/web/support/pagination/PageUtil.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.avicit.framework.util.KeySynchronizer;
import javax.persistence.Id;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
package com.avicit.framework.web.support.pagination;
/**
* @author Zhang Kaitao
* @version 1.0, Sep 17, 2010
* @since 1.0
*/
public class PageUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(PageUtil.class);
/**
* 获取主键时缓存
*/
private static Map<Class<?>, Field> classPKMap = new WeakHashMap<Class<?>, Field>();
/**
* 不关心总记录数
* @param pageNumber
* @param pageSize
* @return
*/
public static int getPageStart(int pageNumber, int pageSize) {
return (pageNumber - 1) * pageSize;
}
/**
* 计算分页获取数据时游标的起始位置
*
* @param totalCount 所有记录总和
* @param pageNumber 页码,从1开始
* @return
*/
public static int getPageStart(int totalCount, int pageNumber, int pageSize) {
int start = (pageNumber - 1) * pageSize;
if (start >= totalCount) {
start = 0;
}
return start;
}
/**
* 构造分页对象
*
* @param totalCount 满足条件的所有记录总和
* @param pageNumber 本次分页的页码
* @param items
* @return
*/
public static <E> Page<E> getPage(int totalCount, int pageNumber, List<E> items, int pageSize) {
IPageContext<E> pageContext = new QuickPageContext<E>(totalCount, pageSize, items);
return pageContext.getPage(pageNumber);
}
public static Field getPkField(Class<?> cls) {
Field pkField = classPKMap.get(cls);
if(pkField == null) { | synchronized (KeySynchronizer.acquire(cls)) { |
jacarrichan/bis | src/main/java/com/avicit/framework/interceptor/pagination/HandlerPaginationInterceptor.java | // Path: src/main/java/com/avicit/framework/interceptor/AbstractHandlerPreparInterceptor.java
// public abstract class AbstractHandlerPreparInterceptor implements HandlerInterceptor{
//
// @Override
// public abstract boolean preHandle(HttpServletRequest request,
// HttpServletResponse response, Object handler);
//
// @Override
// public void postHandle(HttpServletRequest request,
// HttpServletResponse response, Object handler,
// ModelAndView modelAndView) throws Exception {
// }
//
// @Override
// public void afterCompletion(HttpServletRequest request,
// HttpServletResponse response, Object handler, Exception ex)
// throws Exception{
// }
//
// }
//
// Path: src/main/java/com/avicit/framework/web/support/pagination/Pagination.java
// public class Pagination {
//
// private int start;
//
// private int limit;
//
// private String sorter;
//
// private String order = "DESC";
//
// private int total;
//
//
// public Pagination(int start,int limit){
// this.start = start;
// this.limit = limit;
// }
//
// public Pagination(int start,int limit,String sorter,String order){
// this.start = start;
// this.limit = limit;
// this.sorter = sorter;
// this.order = order;
// }
//
// public int getStart() {
// return start;
// }
//
// public void setStart(int start) {
// this.start = start;
// }
//
// public int getLimit() {
// return limit;
// }
//
// public void setLimit(int limit) {
// this.limit = limit;
// }
//
// public String getSorter() {
// return sorter;
// }
//
// public void setSorter(String sorter) {
// this.sorter = sorter;
// }
//
// public String getOrder() {
// return order;
// }
//
// public void setOrder(String order) {
// this.order = order;
// }
//
// public int getTotal() {
// return total;
// }
//
// public void setTotal(int total) {
// this.total = total;
// }
// }
//
// Path: src/main/java/com/avicit/framework/web/support/pagination/PaginationUtils.java
// public class PaginationUtils {
//
// private static final ThreadLocal<Pagination> paginationHolder = new NamedThreadLocal<Pagination>(
// "Pagination Holder");
//
// public static void setPagination(Pagination p){
// paginationHolder.set(p);
// }
//
// public static Pagination getPagination(){
// return paginationHolder.get();
// }
//
// public static int getStart(){
// return getPagination().getStart();
// }
//
// public static int getLimit(){
// return getPagination().getLimit();
// }
//
// public static String getSorter(){
// return getPagination().getSorter();
// }
//
// public static String getOrder(){
// return getPagination().getOrder();
// }
//
// public static void setTotal(int total){
// getPagination().setTotal(total);
// }
//
// public static void getTotal(){
// getPagination().getTotal();
// }
//
// public static boolean exist(){
// return getPagination() != null;
// }
// }
| import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.avicit.framework.interceptor.AbstractHandlerPreparInterceptor;
import com.avicit.framework.web.support.pagination.Pagination;
import com.avicit.framework.web.support.pagination.PaginationUtils; | package com.avicit.framework.interceptor.pagination;
public class HandlerPaginationInterceptor extends
AbstractHandlerPreparInterceptor {
public static final String PAGINATION_BEAN_ATTRIBUTE = "pagination_bean";
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) {
String startParam = request.getParameter("start");
String limitParam = request.getParameter("limit");
if (startParam != null) {
int start = 0;
int limit = 0;
boolean isPagination = true;
try {
start = Integer.valueOf(startParam);
limit = Integer.valueOf(limitParam);
} catch (Exception e) {
isPagination = false;
}
if (isPagination) { | // Path: src/main/java/com/avicit/framework/interceptor/AbstractHandlerPreparInterceptor.java
// public abstract class AbstractHandlerPreparInterceptor implements HandlerInterceptor{
//
// @Override
// public abstract boolean preHandle(HttpServletRequest request,
// HttpServletResponse response, Object handler);
//
// @Override
// public void postHandle(HttpServletRequest request,
// HttpServletResponse response, Object handler,
// ModelAndView modelAndView) throws Exception {
// }
//
// @Override
// public void afterCompletion(HttpServletRequest request,
// HttpServletResponse response, Object handler, Exception ex)
// throws Exception{
// }
//
// }
//
// Path: src/main/java/com/avicit/framework/web/support/pagination/Pagination.java
// public class Pagination {
//
// private int start;
//
// private int limit;
//
// private String sorter;
//
// private String order = "DESC";
//
// private int total;
//
//
// public Pagination(int start,int limit){
// this.start = start;
// this.limit = limit;
// }
//
// public Pagination(int start,int limit,String sorter,String order){
// this.start = start;
// this.limit = limit;
// this.sorter = sorter;
// this.order = order;
// }
//
// public int getStart() {
// return start;
// }
//
// public void setStart(int start) {
// this.start = start;
// }
//
// public int getLimit() {
// return limit;
// }
//
// public void setLimit(int limit) {
// this.limit = limit;
// }
//
// public String getSorter() {
// return sorter;
// }
//
// public void setSorter(String sorter) {
// this.sorter = sorter;
// }
//
// public String getOrder() {
// return order;
// }
//
// public void setOrder(String order) {
// this.order = order;
// }
//
// public int getTotal() {
// return total;
// }
//
// public void setTotal(int total) {
// this.total = total;
// }
// }
//
// Path: src/main/java/com/avicit/framework/web/support/pagination/PaginationUtils.java
// public class PaginationUtils {
//
// private static final ThreadLocal<Pagination> paginationHolder = new NamedThreadLocal<Pagination>(
// "Pagination Holder");
//
// public static void setPagination(Pagination p){
// paginationHolder.set(p);
// }
//
// public static Pagination getPagination(){
// return paginationHolder.get();
// }
//
// public static int getStart(){
// return getPagination().getStart();
// }
//
// public static int getLimit(){
// return getPagination().getLimit();
// }
//
// public static String getSorter(){
// return getPagination().getSorter();
// }
//
// public static String getOrder(){
// return getPagination().getOrder();
// }
//
// public static void setTotal(int total){
// getPagination().setTotal(total);
// }
//
// public static void getTotal(){
// getPagination().getTotal();
// }
//
// public static boolean exist(){
// return getPagination() != null;
// }
// }
// Path: src/main/java/com/avicit/framework/interceptor/pagination/HandlerPaginationInterceptor.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.avicit.framework.interceptor.AbstractHandlerPreparInterceptor;
import com.avicit.framework.web.support.pagination.Pagination;
import com.avicit.framework.web.support.pagination.PaginationUtils;
package com.avicit.framework.interceptor.pagination;
public class HandlerPaginationInterceptor extends
AbstractHandlerPreparInterceptor {
public static final String PAGINATION_BEAN_ATTRIBUTE = "pagination_bean";
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) {
String startParam = request.getParameter("start");
String limitParam = request.getParameter("limit");
if (startParam != null) {
int start = 0;
int limit = 0;
boolean isPagination = true;
try {
start = Integer.valueOf(startParam);
limit = Integer.valueOf(limitParam);
} catch (Exception e) {
isPagination = false;
}
if (isPagination) { | Pagination p = null; |
jacarrichan/bis | src/main/java/com/avicit/framework/interceptor/pagination/HandlerPaginationInterceptor.java | // Path: src/main/java/com/avicit/framework/interceptor/AbstractHandlerPreparInterceptor.java
// public abstract class AbstractHandlerPreparInterceptor implements HandlerInterceptor{
//
// @Override
// public abstract boolean preHandle(HttpServletRequest request,
// HttpServletResponse response, Object handler);
//
// @Override
// public void postHandle(HttpServletRequest request,
// HttpServletResponse response, Object handler,
// ModelAndView modelAndView) throws Exception {
// }
//
// @Override
// public void afterCompletion(HttpServletRequest request,
// HttpServletResponse response, Object handler, Exception ex)
// throws Exception{
// }
//
// }
//
// Path: src/main/java/com/avicit/framework/web/support/pagination/Pagination.java
// public class Pagination {
//
// private int start;
//
// private int limit;
//
// private String sorter;
//
// private String order = "DESC";
//
// private int total;
//
//
// public Pagination(int start,int limit){
// this.start = start;
// this.limit = limit;
// }
//
// public Pagination(int start,int limit,String sorter,String order){
// this.start = start;
// this.limit = limit;
// this.sorter = sorter;
// this.order = order;
// }
//
// public int getStart() {
// return start;
// }
//
// public void setStart(int start) {
// this.start = start;
// }
//
// public int getLimit() {
// return limit;
// }
//
// public void setLimit(int limit) {
// this.limit = limit;
// }
//
// public String getSorter() {
// return sorter;
// }
//
// public void setSorter(String sorter) {
// this.sorter = sorter;
// }
//
// public String getOrder() {
// return order;
// }
//
// public void setOrder(String order) {
// this.order = order;
// }
//
// public int getTotal() {
// return total;
// }
//
// public void setTotal(int total) {
// this.total = total;
// }
// }
//
// Path: src/main/java/com/avicit/framework/web/support/pagination/PaginationUtils.java
// public class PaginationUtils {
//
// private static final ThreadLocal<Pagination> paginationHolder = new NamedThreadLocal<Pagination>(
// "Pagination Holder");
//
// public static void setPagination(Pagination p){
// paginationHolder.set(p);
// }
//
// public static Pagination getPagination(){
// return paginationHolder.get();
// }
//
// public static int getStart(){
// return getPagination().getStart();
// }
//
// public static int getLimit(){
// return getPagination().getLimit();
// }
//
// public static String getSorter(){
// return getPagination().getSorter();
// }
//
// public static String getOrder(){
// return getPagination().getOrder();
// }
//
// public static void setTotal(int total){
// getPagination().setTotal(total);
// }
//
// public static void getTotal(){
// getPagination().getTotal();
// }
//
// public static boolean exist(){
// return getPagination() != null;
// }
// }
| import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.avicit.framework.interceptor.AbstractHandlerPreparInterceptor;
import com.avicit.framework.web.support.pagination.Pagination;
import com.avicit.framework.web.support.pagination.PaginationUtils; | public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) {
String startParam = request.getParameter("start");
String limitParam = request.getParameter("limit");
if (startParam != null) {
int start = 0;
int limit = 0;
boolean isPagination = true;
try {
start = Integer.valueOf(startParam);
limit = Integer.valueOf(limitParam);
} catch (Exception e) {
isPagination = false;
}
if (isPagination) {
Pagination p = null;
try {
JSONObject sort = JSONArray.fromObject(request
.getParameter("sort")).getJSONObject(0);
if (sort != null) {
p = new Pagination(start, limit,
sort.getString("property"),
sort.getString("direction"));
} else {
p = new Pagination(start, limit);
}
} catch (Exception e) {
p = new Pagination(start, limit);
} | // Path: src/main/java/com/avicit/framework/interceptor/AbstractHandlerPreparInterceptor.java
// public abstract class AbstractHandlerPreparInterceptor implements HandlerInterceptor{
//
// @Override
// public abstract boolean preHandle(HttpServletRequest request,
// HttpServletResponse response, Object handler);
//
// @Override
// public void postHandle(HttpServletRequest request,
// HttpServletResponse response, Object handler,
// ModelAndView modelAndView) throws Exception {
// }
//
// @Override
// public void afterCompletion(HttpServletRequest request,
// HttpServletResponse response, Object handler, Exception ex)
// throws Exception{
// }
//
// }
//
// Path: src/main/java/com/avicit/framework/web/support/pagination/Pagination.java
// public class Pagination {
//
// private int start;
//
// private int limit;
//
// private String sorter;
//
// private String order = "DESC";
//
// private int total;
//
//
// public Pagination(int start,int limit){
// this.start = start;
// this.limit = limit;
// }
//
// public Pagination(int start,int limit,String sorter,String order){
// this.start = start;
// this.limit = limit;
// this.sorter = sorter;
// this.order = order;
// }
//
// public int getStart() {
// return start;
// }
//
// public void setStart(int start) {
// this.start = start;
// }
//
// public int getLimit() {
// return limit;
// }
//
// public void setLimit(int limit) {
// this.limit = limit;
// }
//
// public String getSorter() {
// return sorter;
// }
//
// public void setSorter(String sorter) {
// this.sorter = sorter;
// }
//
// public String getOrder() {
// return order;
// }
//
// public void setOrder(String order) {
// this.order = order;
// }
//
// public int getTotal() {
// return total;
// }
//
// public void setTotal(int total) {
// this.total = total;
// }
// }
//
// Path: src/main/java/com/avicit/framework/web/support/pagination/PaginationUtils.java
// public class PaginationUtils {
//
// private static final ThreadLocal<Pagination> paginationHolder = new NamedThreadLocal<Pagination>(
// "Pagination Holder");
//
// public static void setPagination(Pagination p){
// paginationHolder.set(p);
// }
//
// public static Pagination getPagination(){
// return paginationHolder.get();
// }
//
// public static int getStart(){
// return getPagination().getStart();
// }
//
// public static int getLimit(){
// return getPagination().getLimit();
// }
//
// public static String getSorter(){
// return getPagination().getSorter();
// }
//
// public static String getOrder(){
// return getPagination().getOrder();
// }
//
// public static void setTotal(int total){
// getPagination().setTotal(total);
// }
//
// public static void getTotal(){
// getPagination().getTotal();
// }
//
// public static boolean exist(){
// return getPagination() != null;
// }
// }
// Path: src/main/java/com/avicit/framework/interceptor/pagination/HandlerPaginationInterceptor.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.avicit.framework.interceptor.AbstractHandlerPreparInterceptor;
import com.avicit.framework.web.support.pagination.Pagination;
import com.avicit.framework.web.support.pagination.PaginationUtils;
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) {
String startParam = request.getParameter("start");
String limitParam = request.getParameter("limit");
if (startParam != null) {
int start = 0;
int limit = 0;
boolean isPagination = true;
try {
start = Integer.valueOf(startParam);
limit = Integer.valueOf(limitParam);
} catch (Exception e) {
isPagination = false;
}
if (isPagination) {
Pagination p = null;
try {
JSONObject sort = JSONArray.fromObject(request
.getParameter("sort")).getJSONObject(0);
if (sort != null) {
p = new Pagination(start, limit,
sort.getString("property"),
sort.getString("direction"));
} else {
p = new Pagination(start, limit);
}
} catch (Exception e) {
p = new Pagination(start, limit);
} | PaginationUtils.setPagination(p); |
jacarrichan/bis | src/main/java/com/avicit/framework/util/ResponseUtils.java | // Path: src/main/java/com/avicit/framework/web/support/pagination/PaginationUtils.java
// public class PaginationUtils {
//
// private static final ThreadLocal<Pagination> paginationHolder = new NamedThreadLocal<Pagination>(
// "Pagination Holder");
//
// public static void setPagination(Pagination p){
// paginationHolder.set(p);
// }
//
// public static Pagination getPagination(){
// return paginationHolder.get();
// }
//
// public static int getStart(){
// return getPagination().getStart();
// }
//
// public static int getLimit(){
// return getPagination().getLimit();
// }
//
// public static String getSorter(){
// return getPagination().getSorter();
// }
//
// public static String getOrder(){
// return getPagination().getOrder();
// }
//
// public static void setTotal(int total){
// getPagination().setTotal(total);
// }
//
// public static void getTotal(){
// getPagination().getTotal();
// }
//
// public static boolean exist(){
// return getPagination() != null;
// }
// }
| import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.avicit.framework.web.support.pagination.PaginationUtils; | package com.avicit.framework.util;
public class ResponseUtils {
public static final String RESPONSE_SUCCESS_KEY = "success";
public static final String RESPONSE_FAILURE_KEY = "failure";
public static final String RESPONSE_TEXT_KEY = "text";
public static final String RESPONSE_EXTRA_KEY = "extra";
public static final String PAGINATION_ROOT_PROPERTY_KEY = "root";
public static final String PAGINATION_TOTAL_PROPERTY_KEY = "total";
/**
* 分页数据
* */
public static <T> Map<String, Object> sendPagination(List<T> T) {
Map<String, Object> map = getInstanceMap(); | // Path: src/main/java/com/avicit/framework/web/support/pagination/PaginationUtils.java
// public class PaginationUtils {
//
// private static final ThreadLocal<Pagination> paginationHolder = new NamedThreadLocal<Pagination>(
// "Pagination Holder");
//
// public static void setPagination(Pagination p){
// paginationHolder.set(p);
// }
//
// public static Pagination getPagination(){
// return paginationHolder.get();
// }
//
// public static int getStart(){
// return getPagination().getStart();
// }
//
// public static int getLimit(){
// return getPagination().getLimit();
// }
//
// public static String getSorter(){
// return getPagination().getSorter();
// }
//
// public static String getOrder(){
// return getPagination().getOrder();
// }
//
// public static void setTotal(int total){
// getPagination().setTotal(total);
// }
//
// public static void getTotal(){
// getPagination().getTotal();
// }
//
// public static boolean exist(){
// return getPagination() != null;
// }
// }
// Path: src/main/java/com/avicit/framework/util/ResponseUtils.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.avicit.framework.web.support.pagination.PaginationUtils;
package com.avicit.framework.util;
public class ResponseUtils {
public static final String RESPONSE_SUCCESS_KEY = "success";
public static final String RESPONSE_FAILURE_KEY = "failure";
public static final String RESPONSE_TEXT_KEY = "text";
public static final String RESPONSE_EXTRA_KEY = "extra";
public static final String PAGINATION_ROOT_PROPERTY_KEY = "root";
public static final String PAGINATION_TOTAL_PROPERTY_KEY = "total";
/**
* 分页数据
* */
public static <T> Map<String, Object> sendPagination(List<T> T) {
Map<String, Object> map = getInstanceMap(); | map.put(PAGINATION_TOTAL_PROPERTY_KEY, PaginationUtils.getPagination() |
jacarrichan/bis | src/main/java/com/avicit/framework/web/servlet/WebDispatcherServlet.java | // Path: src/main/java/com/avicit/framework/context/spring/SpringDispatcherContextHolder.java
// public class SpringDispatcherContextHolder {
//
// protected static final Log logger = LogFactory
// .getLog(SpringDispatcherContextHolder.class);
//
// private static final ThreadLocal<HttpServletResponse> responseHolder = new NamedThreadLocal<HttpServletResponse>(
// "Response Holder");
//
// public static void initDispatcherContext(HttpServletResponse response) {
// if (response != null) {
// responseHolder.set(response);
// }
// }
//
// public static void resetDispatcherContext() {
// responseHolder.remove();
// }
//
// public static HttpServletRequest getRequest() {
// return ((ServletRequestAttributes) RequestContextHolder
// .getRequestAttributes()).getRequest();
// }
//
// public static HttpServletResponse getResponse() {
// return responseHolder.get();
// }
//
// public static HttpSession getSession() {
// return getRequest().getSession();
// }
//
// public static ServletContext getServletContext() {
// return getSession().getServletContext();
// }
//
// /**
// * 获取DispathcerSerlvet的WebApplicationContext,而非全局的
// * **/
// public static WebApplicationContext getWebApplicationContext() {
// return RequestContextUtils.getWebApplicationContext(getRequest());
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T getBean(String name) {
// return (T) getWebApplicationContext().getBean(name);
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T getBean(Class<?> clazz) {
// return (T)getWebApplicationContext().getBean(clazz);
// }
// }
| import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.DispatcherServlet;
import com.avicit.framework.context.spring.SpringDispatcherContextHolder; | package com.avicit.framework.web.servlet;
@Deprecated
public class WebDispatcherServlet extends DispatcherServlet{
private static final long serialVersionUID = 1L;
@Override
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception { | // Path: src/main/java/com/avicit/framework/context/spring/SpringDispatcherContextHolder.java
// public class SpringDispatcherContextHolder {
//
// protected static final Log logger = LogFactory
// .getLog(SpringDispatcherContextHolder.class);
//
// private static final ThreadLocal<HttpServletResponse> responseHolder = new NamedThreadLocal<HttpServletResponse>(
// "Response Holder");
//
// public static void initDispatcherContext(HttpServletResponse response) {
// if (response != null) {
// responseHolder.set(response);
// }
// }
//
// public static void resetDispatcherContext() {
// responseHolder.remove();
// }
//
// public static HttpServletRequest getRequest() {
// return ((ServletRequestAttributes) RequestContextHolder
// .getRequestAttributes()).getRequest();
// }
//
// public static HttpServletResponse getResponse() {
// return responseHolder.get();
// }
//
// public static HttpSession getSession() {
// return getRequest().getSession();
// }
//
// public static ServletContext getServletContext() {
// return getSession().getServletContext();
// }
//
// /**
// * 获取DispathcerSerlvet的WebApplicationContext,而非全局的
// * **/
// public static WebApplicationContext getWebApplicationContext() {
// return RequestContextUtils.getWebApplicationContext(getRequest());
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T getBean(String name) {
// return (T) getWebApplicationContext().getBean(name);
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T getBean(Class<?> clazz) {
// return (T)getWebApplicationContext().getBean(clazz);
// }
// }
// Path: src/main/java/com/avicit/framework/web/servlet/WebDispatcherServlet.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.DispatcherServlet;
import com.avicit.framework.context.spring.SpringDispatcherContextHolder;
package com.avicit.framework.web.servlet;
@Deprecated
public class WebDispatcherServlet extends DispatcherServlet{
private static final long serialVersionUID = 1L;
@Override
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception { | SpringDispatcherContextHolder.initDispatcherContext(response); |
MCUpdater/MCUpdater | MCU-API/src/org/mcupdater/util/Archive.java | // Path: MCU-API/src/org/mcupdater/MCUApp.java
// public abstract class MCUApp {
//
// public Logger baseLogger;
//
// public abstract void setStatus(String string);
// //public abstract void setProgressBar(int i);
// public abstract void addProgressBar(String title, String parent);
// public abstract void log(String msg);
// public abstract boolean requestLogin();
// public abstract void addServer(ServerList entry);
// public abstract DownloadQueue submitNewQueue(String queueName, String parent, Collection<Downloadable> files, File basePath, File cachePath);
// public abstract DownloadQueue submitAssetsQueue(String queueName, String parent, MinecraftVersion version);
// }
| import java.io.BufferedInputStream;
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.nio.file.Path;
import java.util.Iterator;
import java.util.List;
import java.util.jar.*;
import java.util.logging.Level;
import java.util.zip.*;
import org.apache.commons.io.FileUtils;
import org.mcupdater.MCUApp; | entry = zis.getNextEntry();
continue;
}
if (entryName.contains("aux.class")) {
entryName = "mojangDerpyClass1.class";
}
File outFile = destination.toPath().resolve(entryName).toFile();
outFile.getParentFile().mkdirs();
MCUpdater.apiLogger.finest(" Extract: " + outFile.getPath());
FileOutputStream fos = new FileOutputStream(outFile);
int len;
byte[] buf = new byte[1024];
while((len = zis.read(buf, 0, 1024)) > -1) {
fos.write(buf, 0, len);
}
fos.close();
}
zis.closeEntry();
entry = zis.getNextEntry();
}
zis.close();
} catch (FileNotFoundException fnf) {
MCUpdater.apiLogger.log(Level.SEVERE, "File not found", fnf);
} catch (IOException ioe) {
MCUpdater.apiLogger.log(Level.SEVERE, "I/O error", ioe);
}
}
| // Path: MCU-API/src/org/mcupdater/MCUApp.java
// public abstract class MCUApp {
//
// public Logger baseLogger;
//
// public abstract void setStatus(String string);
// //public abstract void setProgressBar(int i);
// public abstract void addProgressBar(String title, String parent);
// public abstract void log(String msg);
// public abstract boolean requestLogin();
// public abstract void addServer(ServerList entry);
// public abstract DownloadQueue submitNewQueue(String queueName, String parent, Collection<Downloadable> files, File basePath, File cachePath);
// public abstract DownloadQueue submitAssetsQueue(String queueName, String parent, MinecraftVersion version);
// }
// Path: MCU-API/src/org/mcupdater/util/Archive.java
import java.io.BufferedInputStream;
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.nio.file.Path;
import java.util.Iterator;
import java.util.List;
import java.util.jar.*;
import java.util.logging.Level;
import java.util.zip.*;
import org.apache.commons.io.FileUtils;
import org.mcupdater.MCUApp;
entry = zis.getNextEntry();
continue;
}
if (entryName.contains("aux.class")) {
entryName = "mojangDerpyClass1.class";
}
File outFile = destination.toPath().resolve(entryName).toFile();
outFile.getParentFile().mkdirs();
MCUpdater.apiLogger.finest(" Extract: " + outFile.getPath());
FileOutputStream fos = new FileOutputStream(outFile);
int len;
byte[] buf = new byte[1024];
while((len = zis.read(buf, 0, 1024)) > -1) {
fos.write(buf, 0, len);
}
fos.close();
}
zis.closeEntry();
entry = zis.getNextEntry();
}
zis.close();
} catch (FileNotFoundException fnf) {
MCUpdater.apiLogger.log(Level.SEVERE, "File not found", fnf);
} catch (IOException ioe) {
MCUpdater.apiLogger.log(Level.SEVERE, "I/O error", ioe);
}
}
| public static void createZip(File archive, List<File> files, Path mCFolder, MCUApp parent) throws IOException |
MCUpdater/MCUpdater | MCU-Launcher/src/org/mcupdater/MinecraftFrame.java | // Path: MCU-Launcher/src/net/minecraft/Launcher.java
// public class Launcher extends Applet implements AppletStub {
//
// /**
// *
// */
// private static final long serialVersionUID = 6604634479463399020L;
// private final Map<String, String> params;
// private Applet mcApplet;
// private boolean active;
// private URLClassLoader classLoader;
//
// public Launcher(File instance, File lwjgl, String username, String sessionid, String host, String port, boolean doConnect) {
// params = new HashMap<String, String>();
// params.put("username", username);
// params.put("sessionid", sessionid);
// params.put("stand-alone", "true");
// if (doConnect) {
// params.put("server", host);
// params.put("port", port);
// }
// params.put("fullscreen","false"); //Required param for vanilla. Forge handles the absence gracefully.
// URL[] urls = new URL[4];
// urls[0] = pathToUrl(new File(new File(instance,"bin"), "minecraft.jar"));
// urls[1] = pathToUrl(new File(lwjgl, "lwjgl.jar"));
// urls[2] = pathToUrl(new File(lwjgl, "lwjgl_util.jar"));
// urls[3] = pathToUrl(new File(lwjgl, "jinput.jar"));
// classLoader = new URLClassLoader(urls, Launcher.class.getClassLoader());
// try {
// Class<?> minecraft = classLoader.loadClass("net.minecraft.client.Minecraft");
// Field pathField = findPathField(minecraft);
// if (pathField == null) {
// System.err.println("Unable to find a matching field. Aborting launch.");
// System.exit(-1);
// }
// pathField.setAccessible(true);
// pathField.set(null, instance);
// mcApplet = (Applet)classLoader.loadClass("net.minecraft.client.MinecraftApplet").newInstance();
// this.add(mcApplet, "Center");
// } catch (InstantiationException e) {
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// }
// }
//
// public void replace(Applet applet) {
// this.mcApplet = applet;
//
// applet.setStub(this);
// applet.setSize(getWidth(), getHeight());
//
// this.setLayout(new BorderLayout());
// this.add(applet, "Center");
//
// applet.init();
// active = true;
// applet.start();
// validate();
// }
//
// private Field findPathField(Class<?> minecraft) {
// Field[] fields = minecraft.getDeclaredFields();
//
// for (int i=0; i<fields.length; i++) {
// Field current = fields[i];
// if (current.getType() != File.class || (current.getModifiers() != (Modifier.PRIVATE + Modifier.STATIC))) {continue;}
// return current;
// }
// return null;
// }
//
// private URL pathToUrl(File path) {
// try {
// return path.toURI().toURL();
// } catch (MalformedURLException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// @Override
// public void appletResize(int width, int height) {
// mcApplet.resize(width, height);
// }
//
// @Override
// public void resize(int width, int height) {
// mcApplet.resize(width, height);
// }
//
// @Override
// public void resize(Dimension dim) {
// mcApplet.resize(dim);
// }
//
// @Override
// public String getParameter(String name) {
// String value = params.get(name);
// if (value != null) {
// return value;
// }
// try {
// return super.getParameter(name);
// } catch (Exception e) {}
// return null;
// }
//
// @Override
// public boolean isActive() {
// return this.active;
// }
//
// @Override
// public void init() {
// if (mcApplet != null) {
// mcApplet.setStub(this);
// mcApplet.setSize(getWidth(),getHeight());
// this.setLayout(new BorderLayout());
// this.add(mcApplet, "Center");
// mcApplet.init();
// }
// }
//
// @Override
// public void start() {
// mcApplet.start();
// active = true;
// }
//
// @Override
// public void stop() {
// mcApplet.stop();
// active = false;
// }
//
// @Override
// public URL getCodeBase() {
// return mcApplet.getCodeBase();
// }
//
// @Override
// public URL getDocumentBase()
// {
// try {
// return new URL("http://www.minecraft.net/game");
// } catch (MalformedURLException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// @Override
// public void setVisible(boolean flag) {
// super.setVisible(flag);
// mcApplet.setVisible(flag);
// }
// }
| import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import javax.swing.ImageIcon;
import net.minecraft.Launcher; | package org.mcupdater;
public class MinecraftFrame extends Frame implements WindowListener {
/**
*
*/
private static final long serialVersionUID = -2949740978305392280L;
| // Path: MCU-Launcher/src/net/minecraft/Launcher.java
// public class Launcher extends Applet implements AppletStub {
//
// /**
// *
// */
// private static final long serialVersionUID = 6604634479463399020L;
// private final Map<String, String> params;
// private Applet mcApplet;
// private boolean active;
// private URLClassLoader classLoader;
//
// public Launcher(File instance, File lwjgl, String username, String sessionid, String host, String port, boolean doConnect) {
// params = new HashMap<String, String>();
// params.put("username", username);
// params.put("sessionid", sessionid);
// params.put("stand-alone", "true");
// if (doConnect) {
// params.put("server", host);
// params.put("port", port);
// }
// params.put("fullscreen","false"); //Required param for vanilla. Forge handles the absence gracefully.
// URL[] urls = new URL[4];
// urls[0] = pathToUrl(new File(new File(instance,"bin"), "minecraft.jar"));
// urls[1] = pathToUrl(new File(lwjgl, "lwjgl.jar"));
// urls[2] = pathToUrl(new File(lwjgl, "lwjgl_util.jar"));
// urls[3] = pathToUrl(new File(lwjgl, "jinput.jar"));
// classLoader = new URLClassLoader(urls, Launcher.class.getClassLoader());
// try {
// Class<?> minecraft = classLoader.loadClass("net.minecraft.client.Minecraft");
// Field pathField = findPathField(minecraft);
// if (pathField == null) {
// System.err.println("Unable to find a matching field. Aborting launch.");
// System.exit(-1);
// }
// pathField.setAccessible(true);
// pathField.set(null, instance);
// mcApplet = (Applet)classLoader.loadClass("net.minecraft.client.MinecraftApplet").newInstance();
// this.add(mcApplet, "Center");
// } catch (InstantiationException e) {
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// }
// }
//
// public void replace(Applet applet) {
// this.mcApplet = applet;
//
// applet.setStub(this);
// applet.setSize(getWidth(), getHeight());
//
// this.setLayout(new BorderLayout());
// this.add(applet, "Center");
//
// applet.init();
// active = true;
// applet.start();
// validate();
// }
//
// private Field findPathField(Class<?> minecraft) {
// Field[] fields = minecraft.getDeclaredFields();
//
// for (int i=0; i<fields.length; i++) {
// Field current = fields[i];
// if (current.getType() != File.class || (current.getModifiers() != (Modifier.PRIVATE + Modifier.STATIC))) {continue;}
// return current;
// }
// return null;
// }
//
// private URL pathToUrl(File path) {
// try {
// return path.toURI().toURL();
// } catch (MalformedURLException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// @Override
// public void appletResize(int width, int height) {
// mcApplet.resize(width, height);
// }
//
// @Override
// public void resize(int width, int height) {
// mcApplet.resize(width, height);
// }
//
// @Override
// public void resize(Dimension dim) {
// mcApplet.resize(dim);
// }
//
// @Override
// public String getParameter(String name) {
// String value = params.get(name);
// if (value != null) {
// return value;
// }
// try {
// return super.getParameter(name);
// } catch (Exception e) {}
// return null;
// }
//
// @Override
// public boolean isActive() {
// return this.active;
// }
//
// @Override
// public void init() {
// if (mcApplet != null) {
// mcApplet.setStub(this);
// mcApplet.setSize(getWidth(),getHeight());
// this.setLayout(new BorderLayout());
// this.add(mcApplet, "Center");
// mcApplet.init();
// }
// }
//
// @Override
// public void start() {
// mcApplet.start();
// active = true;
// }
//
// @Override
// public void stop() {
// mcApplet.stop();
// active = false;
// }
//
// @Override
// public URL getCodeBase() {
// return mcApplet.getCodeBase();
// }
//
// @Override
// public URL getDocumentBase()
// {
// try {
// return new URL("http://www.minecraft.net/game");
// } catch (MalformedURLException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// @Override
// public void setVisible(boolean flag) {
// super.setVisible(flag);
// mcApplet.setVisible(flag);
// }
// }
// Path: MCU-Launcher/src/org/mcupdater/MinecraftFrame.java
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import javax.swing.ImageIcon;
import net.minecraft.Launcher;
package org.mcupdater;
public class MinecraftFrame extends Frame implements WindowListener {
/**
*
*/
private static final long serialVersionUID = -2949740978305392280L;
| private Launcher applet = null; |
MCUpdater/MCUpdater | MCU-API/src/org/mcupdater/util/ModDownload.java | // Path: MCU-API/src/org/mcupdater/Version.java
// public class Version {
// public static final int MAJOR_VERSION;
// public static final int MINOR_VERSION;
// public static final int BUILD_VERSION;
// public static final String BUILD_BRANCH;
// public static final String BUILD_LABEL;
// static {
// Properties prop = new Properties();
// try {
// prop.load(Version.class.getResourceAsStream("/version.properties"));
// } catch (IOException e) {
// }
// MAJOR_VERSION = Integer.valueOf(prop.getProperty("major","0"));
// MINOR_VERSION = Integer.valueOf(prop.getProperty("minor","0"));
// BUILD_VERSION = Integer.valueOf(prop.getProperty("build_version","0"));
// BUILD_BRANCH = prop.getProperty("git_branch","unknown");
// if( BUILD_BRANCH.equals("unknown") || BUILD_BRANCH.equals("master") ) {
// BUILD_LABEL = "";
// } else {
// BUILD_LABEL = " ("+BUILD_BRANCH+")";
// }
// }
//
// public static final String API_VERSION = MAJOR_VERSION + "." + MINOR_VERSION;
// public static final String VERSION = "v"+MAJOR_VERSION+"."+MINOR_VERSION+"."+BUILD_VERSION;
//
// public static boolean isVersionOld(String packVersion) {
// if( packVersion == null ) return false; // can't check anything if they don't tell us
// String parts[] = packVersion.split("\\.");
// try {
// int mcuParts[] = { MAJOR_VERSION, MINOR_VERSION, BUILD_VERSION };
// for( int q = 0; q < mcuParts.length && q < parts.length; ++q ) {
// int packPart = Integer.valueOf(parts[q]);
// if( packPart > mcuParts[q] ) return true;
// if( packPart < mcuParts[q] ) return false; // Since we check major, then minor, then build, if the required value < current value, we can stop checking.
// }
// return false;
// } catch( NumberFormatException e ) {
// log("Got non-numerical pack format version '"+packVersion+"'");
// } catch( ArrayIndexOutOfBoundsException e ) {
// log("Got malformed pack format version '"+packVersion+"'");
// }
// return false;
// }
//
// public static boolean requestedFeatureLevel(String packVersion, String featureLevelVersion) {
// String packParts[] = packVersion.split("\\.");
// String featureParts[] = featureLevelVersion.split("\\.");
// try {
// for (int q = 0; q < featureParts.length; ++q ) {
// if (Integer.valueOf(packParts[q]) > Integer.valueOf(featureParts[q])) return true;
// if (Integer.valueOf(packParts[q]) < Integer.valueOf(featureParts[q])) return false;
// }
// return true;
// } catch( NumberFormatException e ) {
// log("Got non-numerical pack format version '"+packVersion+"'");
// } catch( ArrayIndexOutOfBoundsException e ) {
// log("Got malformed pack format version '"+packVersion+"'");
// }
// return false;
// }
//
// public static boolean isMasterBranch() {
// return BUILD_BRANCH.equals("master");
// }
// public static boolean isDevBranch() {
// return BUILD_BRANCH.equals("develop");
// }
//
// // for error logging support
// public static void setApp( MCUApp app ) {
// _app = app;
// }
// private static MCUApp _app;
// private static void log(String msg) {
// if( _app != null ) {
// _app.log(msg);
// } else {
// System.out.println(msg);
// }
// }
// }
| import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTML.Tag;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.mcupdater.Version; | }
public ModDownload(URL url, File destination, ModDownload referer, String MD5) throws Exception {
logger = Logger.getLogger("ModDownload");
logger.setParent(MCUpdater.apiLogger);
this.url = url;
this.expectedMD5 = MD5;
logger.fine("URL: " + url.toString());
//this.remoteFilename = url.getFile().substring(url.getFile().lastIndexOf('/')+1);
// TODO: check for md5 in download cache first
if( MD5 != null ) {
final File cacheFile = DownloadCache.getFile(MD5);
if( cacheFile.exists() ) {
cacheHit = true;
logger.fine(" Cache hit - "+MD5);
this.destFile = destination;
FileUtils.copyFile(cacheFile, this.destFile);
return;
} else {
logger.fine(" Cache miss - "+MD5);
}
}
if (url.getProtocol().equals("file")){
this.destFile = destination;
FileUtils.copyURLToFile(url, this.destFile);
return;
}
isOptifined = url.getHost().endsWith("optifined.net");
isMediafire = url.getHost().toLowerCase().contains("mediafire");
HttpURLConnection connection = (HttpURLConnection)url.openConnection(); | // Path: MCU-API/src/org/mcupdater/Version.java
// public class Version {
// public static final int MAJOR_VERSION;
// public static final int MINOR_VERSION;
// public static final int BUILD_VERSION;
// public static final String BUILD_BRANCH;
// public static final String BUILD_LABEL;
// static {
// Properties prop = new Properties();
// try {
// prop.load(Version.class.getResourceAsStream("/version.properties"));
// } catch (IOException e) {
// }
// MAJOR_VERSION = Integer.valueOf(prop.getProperty("major","0"));
// MINOR_VERSION = Integer.valueOf(prop.getProperty("minor","0"));
// BUILD_VERSION = Integer.valueOf(prop.getProperty("build_version","0"));
// BUILD_BRANCH = prop.getProperty("git_branch","unknown");
// if( BUILD_BRANCH.equals("unknown") || BUILD_BRANCH.equals("master") ) {
// BUILD_LABEL = "";
// } else {
// BUILD_LABEL = " ("+BUILD_BRANCH+")";
// }
// }
//
// public static final String API_VERSION = MAJOR_VERSION + "." + MINOR_VERSION;
// public static final String VERSION = "v"+MAJOR_VERSION+"."+MINOR_VERSION+"."+BUILD_VERSION;
//
// public static boolean isVersionOld(String packVersion) {
// if( packVersion == null ) return false; // can't check anything if they don't tell us
// String parts[] = packVersion.split("\\.");
// try {
// int mcuParts[] = { MAJOR_VERSION, MINOR_VERSION, BUILD_VERSION };
// for( int q = 0; q < mcuParts.length && q < parts.length; ++q ) {
// int packPart = Integer.valueOf(parts[q]);
// if( packPart > mcuParts[q] ) return true;
// if( packPart < mcuParts[q] ) return false; // Since we check major, then minor, then build, if the required value < current value, we can stop checking.
// }
// return false;
// } catch( NumberFormatException e ) {
// log("Got non-numerical pack format version '"+packVersion+"'");
// } catch( ArrayIndexOutOfBoundsException e ) {
// log("Got malformed pack format version '"+packVersion+"'");
// }
// return false;
// }
//
// public static boolean requestedFeatureLevel(String packVersion, String featureLevelVersion) {
// String packParts[] = packVersion.split("\\.");
// String featureParts[] = featureLevelVersion.split("\\.");
// try {
// for (int q = 0; q < featureParts.length; ++q ) {
// if (Integer.valueOf(packParts[q]) > Integer.valueOf(featureParts[q])) return true;
// if (Integer.valueOf(packParts[q]) < Integer.valueOf(featureParts[q])) return false;
// }
// return true;
// } catch( NumberFormatException e ) {
// log("Got non-numerical pack format version '"+packVersion+"'");
// } catch( ArrayIndexOutOfBoundsException e ) {
// log("Got malformed pack format version '"+packVersion+"'");
// }
// return false;
// }
//
// public static boolean isMasterBranch() {
// return BUILD_BRANCH.equals("master");
// }
// public static boolean isDevBranch() {
// return BUILD_BRANCH.equals("develop");
// }
//
// // for error logging support
// public static void setApp( MCUApp app ) {
// _app = app;
// }
// private static MCUApp _app;
// private static void log(String msg) {
// if( _app != null ) {
// _app.log(msg);
// } else {
// System.out.println(msg);
// }
// }
// }
// Path: MCU-API/src/org/mcupdater/util/ModDownload.java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTML.Tag;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.mcupdater.Version;
}
public ModDownload(URL url, File destination, ModDownload referer, String MD5) throws Exception {
logger = Logger.getLogger("ModDownload");
logger.setParent(MCUpdater.apiLogger);
this.url = url;
this.expectedMD5 = MD5;
logger.fine("URL: " + url.toString());
//this.remoteFilename = url.getFile().substring(url.getFile().lastIndexOf('/')+1);
// TODO: check for md5 in download cache first
if( MD5 != null ) {
final File cacheFile = DownloadCache.getFile(MD5);
if( cacheFile.exists() ) {
cacheHit = true;
logger.fine(" Cache hit - "+MD5);
this.destFile = destination;
FileUtils.copyFile(cacheFile, this.destFile);
return;
} else {
logger.fine(" Cache miss - "+MD5);
}
}
if (url.getProtocol().equals("file")){
this.destFile = destination;
FileUtils.copyURLToFile(url, this.destFile);
return;
}
isOptifined = url.getHost().endsWith("optifined.net");
isMediafire = url.getHost().toLowerCase().contains("mediafire");
HttpURLConnection connection = (HttpURLConnection)url.openConnection(); | connection.setRequestProperty("User-Agent", "MCUpdater/" + Version.VERSION); |
MCUpdater/MCUpdater | MCU-EndUser/src/org/mcupdater/ConsoleHandler.java | // Path: MCU-EndUser/src/org/mcupdater/MCUConsole.java
// public enum LineStyle {
// NORMAL(new RGB(255,255,255)),
// WARNING(new RGB(255,255,0)),
// ERROR(new RGB(255,0,0));
//
// private RGB color;
//
// LineStyle(RGB color) {
// this.setColor(color);
// }
//
// public RGB getColor() {
// return color;
// }
//
// private void setColor(RGB color) {
// this.color = color;
// }
// }
| import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import org.mcupdater.MCUConsole.LineStyle; | package org.mcupdater;
public class ConsoleHandler extends Handler {
private MCUConsole console;
private final SimpleDateFormat sdFormat = new SimpleDateFormat("[HH:mm:ss.SSS] ");
public ConsoleHandler(MCUConsole console) {
this.console = console;
}
@Override
public void publish(final LogRecord record) {
if (this.isLoggable(record)){
final Calendar recordDate = Calendar.getInstance();
recordDate.setTimeInMillis(record.getMillis()); | // Path: MCU-EndUser/src/org/mcupdater/MCUConsole.java
// public enum LineStyle {
// NORMAL(new RGB(255,255,255)),
// WARNING(new RGB(255,255,0)),
// ERROR(new RGB(255,0,0));
//
// private RGB color;
//
// LineStyle(RGB color) {
// this.setColor(color);
// }
//
// public RGB getColor() {
// return color;
// }
//
// private void setColor(RGB color) {
// this.color = color;
// }
// }
// Path: MCU-EndUser/src/org/mcupdater/ConsoleHandler.java
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import org.mcupdater.MCUConsole.LineStyle;
package org.mcupdater;
public class ConsoleHandler extends Handler {
private MCUConsole console;
private final SimpleDateFormat sdFormat = new SimpleDateFormat("[HH:mm:ss.SSS] ");
public ConsoleHandler(MCUConsole console) {
this.console = console;
}
@Override
public void publish(final LogRecord record) {
if (this.isLoggable(record)){
final Calendar recordDate = Calendar.getInstance();
recordDate.setTimeInMillis(record.getMillis()); | LineStyle a = LineStyle.NORMAL; |
MCUpdater/MCUpdater | MCU-EndUser/src/org/mcupdater/MCUModules.java | // Path: MCU-API/src/org/mcupdater/model/Module.java
// public class Module extends GenericModule {
// private List<ConfigFile> configs = new ArrayList<ConfigFile>();
// private List<GenericModule> submodules = new ArrayList<GenericModule>();
//
// public Module(String name, String id, List<PrioritizedURL> url, String depends, boolean required, boolean inJar, int jarOrder, boolean keepMeta, boolean extract, boolean inRoot, boolean isDefault, boolean coreMod, String md5, List<ConfigFile> configs, String side, String path, HashMap<String, String> meta, boolean isLibrary, boolean litemod, String launchArgs, String jreArgs, List<GenericModule> submodules){
// super(name,id,url,depends,required,inJar,jarOrder,keepMeta,extract,inRoot,isDefault,coreMod,md5,side,path,meta,isLibrary,litemod,launchArgs,jreArgs);
// if(configs != null)
// {
// this.configs = configs;
// } else {
// this.configs = new ArrayList<ConfigFile>();
// }
// this.submodules.addAll(submodules);
// }
//
// @Deprecated
// public Module(String name, String id, List<PrioritizedURL> url, String depends, boolean required, boolean inJar, int jarOrder, boolean keepMeta, boolean extract, boolean inRoot, boolean isDefault, boolean coreMod, String md5, List<ConfigFile> configs, String side, String path, HashMap<String, String> meta){
// this(name,id,url,depends,required,inJar,jarOrder,keepMeta,extract,inRoot,isDefault,coreMod,md5,configs,side,path,meta,false,false,null,null,null);
// }
//
// @Deprecated
// public Module(String name, String id, String url, String depends, boolean required, boolean inJar, boolean extract, boolean inRoot, boolean isDefault, boolean coreMod, String md5, List<ConfigFile> configs)
// {
// this(name, id, makeList(url), depends, required, inJar, 0, true, extract, inRoot, isDefault, coreMod, md5, configs, null, null, null);
// }
//
// private static List<PrioritizedURL> makeList(String url) {
// List<PrioritizedURL> urls = new ArrayList<PrioritizedURL>();
// urls.add(new PrioritizedURL(url, 0));
// return urls;
// }
//
// public List<ConfigFile> getConfigs()
// {
// return configs;
// }
//
// public void setConfigs(List<ConfigFile> configs)
// {
// this.configs = configs;
// }
//
// public boolean hasConfigs() {
// return (this.configs.size() > 0);
// }
//
// public boolean hasSubmodules() {
// return (this.submodules.size() > 0);
// }
//
// public List<GenericModule> getSubmodules() {
// return this.submodules;
// }
//
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.mcupdater.model.Module; | package org.mcupdater;
public class MCUModules extends Composite {
private Composite container;
private RowLayout rlContainer = new RowLayout(SWT.VERTICAL);
private ScrolledComposite scroller;
private List<ModuleCheckbox> modules = new ArrayList<ModuleCheckbox>();
public MCUModules(Composite parent) {
super(parent, SWT.NONE);
this.setLayout(new FillLayout());
scroller = new ScrolledComposite(this, SWT.V_SCROLL);
scroller.setExpandHorizontal(true);
scroller.setExpandVertical(true);
container = new Composite(scroller, SWT.NONE);
scroller.setContent(container);
container.setLayout(rlContainer);
}
| // Path: MCU-API/src/org/mcupdater/model/Module.java
// public class Module extends GenericModule {
// private List<ConfigFile> configs = new ArrayList<ConfigFile>();
// private List<GenericModule> submodules = new ArrayList<GenericModule>();
//
// public Module(String name, String id, List<PrioritizedURL> url, String depends, boolean required, boolean inJar, int jarOrder, boolean keepMeta, boolean extract, boolean inRoot, boolean isDefault, boolean coreMod, String md5, List<ConfigFile> configs, String side, String path, HashMap<String, String> meta, boolean isLibrary, boolean litemod, String launchArgs, String jreArgs, List<GenericModule> submodules){
// super(name,id,url,depends,required,inJar,jarOrder,keepMeta,extract,inRoot,isDefault,coreMod,md5,side,path,meta,isLibrary,litemod,launchArgs,jreArgs);
// if(configs != null)
// {
// this.configs = configs;
// } else {
// this.configs = new ArrayList<ConfigFile>();
// }
// this.submodules.addAll(submodules);
// }
//
// @Deprecated
// public Module(String name, String id, List<PrioritizedURL> url, String depends, boolean required, boolean inJar, int jarOrder, boolean keepMeta, boolean extract, boolean inRoot, boolean isDefault, boolean coreMod, String md5, List<ConfigFile> configs, String side, String path, HashMap<String, String> meta){
// this(name,id,url,depends,required,inJar,jarOrder,keepMeta,extract,inRoot,isDefault,coreMod,md5,configs,side,path,meta,false,false,null,null,null);
// }
//
// @Deprecated
// public Module(String name, String id, String url, String depends, boolean required, boolean inJar, boolean extract, boolean inRoot, boolean isDefault, boolean coreMod, String md5, List<ConfigFile> configs)
// {
// this(name, id, makeList(url), depends, required, inJar, 0, true, extract, inRoot, isDefault, coreMod, md5, configs, null, null, null);
// }
//
// private static List<PrioritizedURL> makeList(String url) {
// List<PrioritizedURL> urls = new ArrayList<PrioritizedURL>();
// urls.add(new PrioritizedURL(url, 0));
// return urls;
// }
//
// public List<ConfigFile> getConfigs()
// {
// return configs;
// }
//
// public void setConfigs(List<ConfigFile> configs)
// {
// this.configs = configs;
// }
//
// public boolean hasConfigs() {
// return (this.configs.size() > 0);
// }
//
// public boolean hasSubmodules() {
// return (this.submodules.size() > 0);
// }
//
// public List<GenericModule> getSubmodules() {
// return this.submodules;
// }
//
// }
// Path: MCU-EndUser/src/org/mcupdater/MCUModules.java
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.mcupdater.model.Module;
package org.mcupdater;
public class MCUModules extends Composite {
private Composite container;
private RowLayout rlContainer = new RowLayout(SWT.VERTICAL);
private ScrolledComposite scroller;
private List<ModuleCheckbox> modules = new ArrayList<ModuleCheckbox>();
public MCUModules(Composite parent) {
super(parent, SWT.NONE);
this.setLayout(new FillLayout());
scroller = new ScrolledComposite(this, SWT.V_SCROLL);
scroller.setExpandHorizontal(true);
scroller.setExpandVertical(true);
container = new Composite(scroller, SWT.NONE);
scroller.setContent(container);
container.setLayout(rlContainer);
}
| public void reload(List<Module> modList, Map<String, Boolean> optionalSelections) { |
MCUpdater/MCUpdater | MCU-EndUser/src/org/mcupdater/ModuleCheckbox.java | // Path: MCU-API/src/org/mcupdater/model/Module.java
// public class Module extends GenericModule {
// private List<ConfigFile> configs = new ArrayList<ConfigFile>();
// private List<GenericModule> submodules = new ArrayList<GenericModule>();
//
// public Module(String name, String id, List<PrioritizedURL> url, String depends, boolean required, boolean inJar, int jarOrder, boolean keepMeta, boolean extract, boolean inRoot, boolean isDefault, boolean coreMod, String md5, List<ConfigFile> configs, String side, String path, HashMap<String, String> meta, boolean isLibrary, boolean litemod, String launchArgs, String jreArgs, List<GenericModule> submodules){
// super(name,id,url,depends,required,inJar,jarOrder,keepMeta,extract,inRoot,isDefault,coreMod,md5,side,path,meta,isLibrary,litemod,launchArgs,jreArgs);
// if(configs != null)
// {
// this.configs = configs;
// } else {
// this.configs = new ArrayList<ConfigFile>();
// }
// this.submodules.addAll(submodules);
// }
//
// @Deprecated
// public Module(String name, String id, List<PrioritizedURL> url, String depends, boolean required, boolean inJar, int jarOrder, boolean keepMeta, boolean extract, boolean inRoot, boolean isDefault, boolean coreMod, String md5, List<ConfigFile> configs, String side, String path, HashMap<String, String> meta){
// this(name,id,url,depends,required,inJar,jarOrder,keepMeta,extract,inRoot,isDefault,coreMod,md5,configs,side,path,meta,false,false,null,null,null);
// }
//
// @Deprecated
// public Module(String name, String id, String url, String depends, boolean required, boolean inJar, boolean extract, boolean inRoot, boolean isDefault, boolean coreMod, String md5, List<ConfigFile> configs)
// {
// this(name, id, makeList(url), depends, required, inJar, 0, true, extract, inRoot, isDefault, coreMod, md5, configs, null, null, null);
// }
//
// private static List<PrioritizedURL> makeList(String url) {
// List<PrioritizedURL> urls = new ArrayList<PrioritizedURL>();
// urls.add(new PrioritizedURL(url, 0));
// return urls;
// }
//
// public List<ConfigFile> getConfigs()
// {
// return configs;
// }
//
// public void setConfigs(List<ConfigFile> configs)
// {
// this.configs = configs;
// }
//
// public boolean hasConfigs() {
// return (this.configs.size() > 0);
// }
//
// public boolean hasSubmodules() {
// return (this.submodules.size() > 0);
// }
//
// public List<GenericModule> getSubmodules() {
// return this.submodules;
// }
//
// }
| import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.mcupdater.model.Module; | package org.mcupdater;
public class ModuleCheckbox extends Composite {
private Button chk; | // Path: MCU-API/src/org/mcupdater/model/Module.java
// public class Module extends GenericModule {
// private List<ConfigFile> configs = new ArrayList<ConfigFile>();
// private List<GenericModule> submodules = new ArrayList<GenericModule>();
//
// public Module(String name, String id, List<PrioritizedURL> url, String depends, boolean required, boolean inJar, int jarOrder, boolean keepMeta, boolean extract, boolean inRoot, boolean isDefault, boolean coreMod, String md5, List<ConfigFile> configs, String side, String path, HashMap<String, String> meta, boolean isLibrary, boolean litemod, String launchArgs, String jreArgs, List<GenericModule> submodules){
// super(name,id,url,depends,required,inJar,jarOrder,keepMeta,extract,inRoot,isDefault,coreMod,md5,side,path,meta,isLibrary,litemod,launchArgs,jreArgs);
// if(configs != null)
// {
// this.configs = configs;
// } else {
// this.configs = new ArrayList<ConfigFile>();
// }
// this.submodules.addAll(submodules);
// }
//
// @Deprecated
// public Module(String name, String id, List<PrioritizedURL> url, String depends, boolean required, boolean inJar, int jarOrder, boolean keepMeta, boolean extract, boolean inRoot, boolean isDefault, boolean coreMod, String md5, List<ConfigFile> configs, String side, String path, HashMap<String, String> meta){
// this(name,id,url,depends,required,inJar,jarOrder,keepMeta,extract,inRoot,isDefault,coreMod,md5,configs,side,path,meta,false,false,null,null,null);
// }
//
// @Deprecated
// public Module(String name, String id, String url, String depends, boolean required, boolean inJar, boolean extract, boolean inRoot, boolean isDefault, boolean coreMod, String md5, List<ConfigFile> configs)
// {
// this(name, id, makeList(url), depends, required, inJar, 0, true, extract, inRoot, isDefault, coreMod, md5, configs, null, null, null);
// }
//
// private static List<PrioritizedURL> makeList(String url) {
// List<PrioritizedURL> urls = new ArrayList<PrioritizedURL>();
// urls.add(new PrioritizedURL(url, 0));
// return urls;
// }
//
// public List<ConfigFile> getConfigs()
// {
// return configs;
// }
//
// public void setConfigs(List<ConfigFile> configs)
// {
// this.configs = configs;
// }
//
// public boolean hasConfigs() {
// return (this.configs.size() > 0);
// }
//
// public boolean hasSubmodules() {
// return (this.submodules.size() > 0);
// }
//
// public List<GenericModule> getSubmodules() {
// return this.submodules;
// }
//
// }
// Path: MCU-EndUser/src/org/mcupdater/ModuleCheckbox.java
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.mcupdater.model.Module;
package org.mcupdater;
public class ModuleCheckbox extends Composite {
private Button chk; | private Module data; |
USC-NSL/PUMA | src/nsl/stg/core/UIStateManager.java | // Path: src/nsl/stg/tests/Util.java
// public class Util {
// public static void log(Object obj) {
// long ts = System.currentTimeMillis();
// System.out.println(ts + ": " + obj);
// System.out.flush();
// }
//
// public static void err(Object obj) {
// System.err.println(obj.toString());
// }
//
// public static void log2File(Object obj) {
// if (handle != null) {
// handle.println(obj);
// }
// }
//
// private static PrintWriter handle;
// private static String fileName;
//
// public static void openFile(String fn, boolean append) {
// try {
// fileName = fn;
// handle = new PrintWriter(new BufferedWriter(new FileWriter(fileName, append)));
// } catch (IOException e) {
// fileName = null;
// handle = null;
// }
// }
//
// public static void closeFile(String fn) {
// if (fileName != null && fileName.equals(fn)) {
// handle.close();
// }
// }
// }
| import java.util.ArrayList;
import java.util.List;
import nsl.stg.tests.Util; | package nsl.stg.core;
public class UIStateManager {
private final double SIMILARITY_THRESHOLD = 0.95;
// private final double SIMILARITY_THRESHOLD = 0.9999;
private List<UIState> slist;
// reference to self
private static UIStateManager self;
private UIStateManager() {
/* hide constructor */
slist = new ArrayList<UIState>();
}
public static UIStateManager getInstance() {
if (self == null) {
self = new UIStateManager();
}
return self;
}
public void addState(UIState s) {
if (getState(s) == null) { | // Path: src/nsl/stg/tests/Util.java
// public class Util {
// public static void log(Object obj) {
// long ts = System.currentTimeMillis();
// System.out.println(ts + ": " + obj);
// System.out.flush();
// }
//
// public static void err(Object obj) {
// System.err.println(obj.toString());
// }
//
// public static void log2File(Object obj) {
// if (handle != null) {
// handle.println(obj);
// }
// }
//
// private static PrintWriter handle;
// private static String fileName;
//
// public static void openFile(String fn, boolean append) {
// try {
// fileName = fn;
// handle = new PrintWriter(new BufferedWriter(new FileWriter(fileName, append)));
// } catch (IOException e) {
// fileName = null;
// handle = null;
// }
// }
//
// public static void closeFile(String fn) {
// if (fileName != null && fileName.equals(fn)) {
// handle.close();
// }
// }
// }
// Path: src/nsl/stg/core/UIStateManager.java
import java.util.ArrayList;
import java.util.List;
import nsl.stg.tests.Util;
package nsl.stg.core;
public class UIStateManager {
private final double SIMILARITY_THRESHOLD = 0.95;
// private final double SIMILARITY_THRESHOLD = 0.9999;
private List<UIState> slist;
// reference to self
private static UIStateManager self;
private UIStateManager() {
/* hide constructor */
slist = new ArrayList<UIState>();
}
public static UIStateManager getInstance() {
if (self == null) {
self = new UIStateManager();
}
return self;
}
public void addState(UIState s) {
if (getState(s) == null) { | Util.log("New UIState: " + s.dumpShort()); |
USC-NSL/PUMA | src/nsl/stg/core/ExplorationState.java | // Path: src/nsl/stg/tests/Util.java
// public class Util {
// public static void log(Object obj) {
// long ts = System.currentTimeMillis();
// System.out.println(ts + ": " + obj);
// System.out.flush();
// }
//
// public static void err(Object obj) {
// System.err.println(obj.toString());
// }
//
// public static void log2File(Object obj) {
// if (handle != null) {
// handle.println(obj);
// }
// }
//
// private static PrintWriter handle;
// private static String fileName;
//
// public static void openFile(String fn, boolean append) {
// try {
// fileName = fn;
// handle = new PrintWriter(new BufferedWriter(new FileWriter(fileName, append)));
// } catch (IOException e) {
// fileName = null;
// handle = null;
// }
// }
//
// public static void closeFile(String fn) {
// if (fileName != null && fileName.equals(fn)) {
// handle.close();
// }
// }
// }
| import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import nsl.stg.tests.Util; | package nsl.stg.core;
public class ExplorationState {
public static final ExplorationState DUMMY_3RD_PARTY_STATE = new ExplorationState(UIState.DUMMY_3RD_PARTY_STATE, UIState.DUMMY_3RD_PARTY_STATE.computeFeatureHash());
private UIState clusterRef;
private String hashId;
private Map<Integer, ExplorationState> reachables;
public ExplorationState(UIState ref, String featureHash) {
this.clusterRef = ref;
this.hashId = featureHash;
this.reachables = new Hashtable<Integer, ExplorationState>();
}
public void addReachableState(int clickId, ExplorationState target) {
if (reachables.containsKey(clickId)) { | // Path: src/nsl/stg/tests/Util.java
// public class Util {
// public static void log(Object obj) {
// long ts = System.currentTimeMillis();
// System.out.println(ts + ": " + obj);
// System.out.flush();
// }
//
// public static void err(Object obj) {
// System.err.println(obj.toString());
// }
//
// public static void log2File(Object obj) {
// if (handle != null) {
// handle.println(obj);
// }
// }
//
// private static PrintWriter handle;
// private static String fileName;
//
// public static void openFile(String fn, boolean append) {
// try {
// fileName = fn;
// handle = new PrintWriter(new BufferedWriter(new FileWriter(fileName, append)));
// } catch (IOException e) {
// fileName = null;
// handle = null;
// }
// }
//
// public static void closeFile(String fn) {
// if (fileName != null && fileName.equals(fn)) {
// handle.close();
// }
// }
// }
// Path: src/nsl/stg/core/ExplorationState.java
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import nsl.stg.tests.Util;
package nsl.stg.core;
public class ExplorationState {
public static final ExplorationState DUMMY_3RD_PARTY_STATE = new ExplorationState(UIState.DUMMY_3RD_PARTY_STATE, UIState.DUMMY_3RD_PARTY_STATE.computeFeatureHash());
private UIState clusterRef;
private String hashId;
private Map<Integer, ExplorationState> reachables;
public ExplorationState(UIState ref, String featureHash) {
this.clusterRef = ref;
this.hashId = featureHash;
this.reachables = new Hashtable<Integer, ExplorationState>();
}
public void addReachableState(int clickId, ExplorationState target) {
if (reachables.containsKey(clickId)) { | Util.log("FAILED to link " + dumpShort() + " @" + clickId + " --> " + target.dumpShort()); |
USC-NSL/PUMA | src/nsl/stg/core/AccessibilityEventProcessor.java | // Path: src/nsl/stg/tests/Util.java
// public class Util {
// public static void log(Object obj) {
// long ts = System.currentTimeMillis();
// System.out.println(ts + ": " + obj);
// System.out.flush();
// }
//
// public static void err(Object obj) {
// System.err.println(obj.toString());
// }
//
// public static void log2File(Object obj) {
// if (handle != null) {
// handle.println(obj);
// }
// }
//
// private static PrintWriter handle;
// private static String fileName;
//
// public static void openFile(String fn, boolean append) {
// try {
// fileName = fn;
// handle = new PrintWriter(new BufferedWriter(new FileWriter(fileName, append)));
// } catch (IOException e) {
// fileName = null;
// handle = null;
// }
// }
//
// public static void closeFile(String fn) {
// if (fileName != null && fileName.equals(fn)) {
// handle.close();
// }
// }
// }
| import java.util.ArrayList;
import nsl.stg.tests.Util;
import android.graphics.Rect;
import android.os.SystemClock;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.ListView; | package nsl.stg.core;
public class AccessibilityEventProcessor {
private static final ArrayList<AccessibilityEvent> mEventQueue = new ArrayList<AccessibilityEvent>();
private static final Object mLock = new Object();
private static AccessibilityEvent currEvent;
// private static long mLastEventTimeMillis;
private static boolean mWaitingForEventDelivery = false;
private static void dump(AccessibilityEvent event) {
AccessibilityNodeInfo source = event.getSource();
if (source == null) { | // Path: src/nsl/stg/tests/Util.java
// public class Util {
// public static void log(Object obj) {
// long ts = System.currentTimeMillis();
// System.out.println(ts + ": " + obj);
// System.out.flush();
// }
//
// public static void err(Object obj) {
// System.err.println(obj.toString());
// }
//
// public static void log2File(Object obj) {
// if (handle != null) {
// handle.println(obj);
// }
// }
//
// private static PrintWriter handle;
// private static String fileName;
//
// public static void openFile(String fn, boolean append) {
// try {
// fileName = fn;
// handle = new PrintWriter(new BufferedWriter(new FileWriter(fileName, append)));
// } catch (IOException e) {
// fileName = null;
// handle = null;
// }
// }
//
// public static void closeFile(String fn) {
// if (fileName != null && fileName.equals(fn)) {
// handle.close();
// }
// }
// }
// Path: src/nsl/stg/core/AccessibilityEventProcessor.java
import java.util.ArrayList;
import nsl.stg.tests.Util;
import android.graphics.Rect;
import android.os.SystemClock;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.ListView;
package nsl.stg.core;
public class AccessibilityEventProcessor {
private static final ArrayList<AccessibilityEvent> mEventQueue = new ArrayList<AccessibilityEvent>();
private static final Object mLock = new Object();
private static AccessibilityEvent currEvent;
// private static long mLastEventTimeMillis;
private static boolean mWaitingForEventDelivery = false;
private static void dump(AccessibilityEvent event) {
AccessibilityNodeInfo source = event.getSource();
if (source == null) { | Util.err("event source: NULL"); |
USC-NSL/PUMA | src/nsl/stg/core/ExplorationStateManager.java | // Path: src/nsl/stg/tests/Util.java
// public class Util {
// public static void log(Object obj) {
// long ts = System.currentTimeMillis();
// System.out.println(ts + ": " + obj);
// System.out.flush();
// }
//
// public static void err(Object obj) {
// System.err.println(obj.toString());
// }
//
// public static void log2File(Object obj) {
// if (handle != null) {
// handle.println(obj);
// }
// }
//
// private static PrintWriter handle;
// private static String fileName;
//
// public static void openFile(String fn, boolean append) {
// try {
// fileName = fn;
// handle = new PrintWriter(new BufferedWriter(new FileWriter(fileName, append)));
// } catch (IOException e) {
// fileName = null;
// handle = null;
// }
// }
//
// public static void closeFile(String fn) {
// if (fileName != null && fileName.equals(fn)) {
// handle.close();
// }
// }
// }
| import java.util.ArrayList;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Set;
import java.util.Stack;
import nsl.stg.tests.Util; | package nsl.stg.core;
public class ExplorationStateManager {
private static ExplorationStateManager self;
private static List<ExplorationState> states; // keep some implicit ordering
private ExplorationStateManager() {
/* hide constructor */
states = new ArrayList<ExplorationState>();
}
public static ExplorationStateManager getInstance() {
if (self == null) {
self = new ExplorationStateManager();
}
return self;
}
// Not very efficient: Linear traversal
private ExplorationState find_state(ExplorationState state) {
ExplorationState ret = null;
for (Iterator<ExplorationState> iter = states.iterator(); iter.hasNext();) {
ExplorationState tmpState = iter.next();
if (tmpState.equals(state)) {
ret = tmpState;
break;
}
}
return ret;
}
public void addState(ExplorationState fromState, int clickId, ExplorationState toState) {
ExplorationState myFromState = fromState;
ExplorationState myToState = toState;
if (states.contains(fromState)) {
myFromState = find_state(fromState);
} else {
states.add(fromState);
}
if (states.contains(toState)) {
myToState = find_state(toState);
} else {
states.add(toState);
}
// Util.log("Adding " + fromState.dumpShort() + " @" + clickId + " --> " + toState.dumpShort());
// Util.log("Before:\n" + myState.toString());
myFromState.addReachableState(clickId, myToState);
// Util.log("After:\n" + myState.toString());
}
public boolean containsState(ExplorationState targetState) {
return (find_state(targetState) != null);
}
public List<UIAction> copmuteShortestPath(ExplorationState fromState, ExplorationState toState) {
List<UIAction> ret = new ArrayList<UIAction>();
if (fromState.equals(toState)) {
return ret;
}
Stack<UIAction> S = new Stack<UIAction>();
if (states.contains(fromState)) {
ExplorationState actualFromState = find_state(fromState);
// BFS
Queue<ExplorationState> Q = new LinkedList<ExplorationState>();
Set<ExplorationState> visited = new HashSet<ExplorationState>();
Map<ExplorationState, UIAction> map = new Hashtable<ExplorationState, UIAction>();
boolean done = false;
Q.add(actualFromState);
while (!Q.isEmpty() && !done) {
ExplorationState state = Q.remove();
if (states.contains(state)) {
state = find_state(state);
}
// Util.log("Procesing " + state.dumpShort());
if (state.equals(toState)) {
// backtrack to compute path
ExplorationState parent = state;
UIAction action;
while (!parent.equals(fromState)) {
action = map.get(parent);
// Util.log("Adding " + action);
S.push(action);
parent = action.getState();
}
done = true;
} else {
visited.add(state);
Map<Integer, ExplorationState> children = state.getReachables();
// Util.log("Children " + children);
for (Iterator<Entry<Integer, ExplorationState>> iter = children.entrySet().iterator(); iter.hasNext();) {
Entry<Integer, ExplorationState> entry = iter.next();
ExplorationState child = entry.getValue();
if (!visited.contains(child)) {
// Util.log("Adding to Q: " + child.dumpShort());
Q.add(child);
int clickId = entry.getKey();
map.put(child, new UIAction(state, clickId));
// Util.log(state.dumpShort() + " @" + clickId + " --> " + child.dumpShort());
}
}
}
} | // Path: src/nsl/stg/tests/Util.java
// public class Util {
// public static void log(Object obj) {
// long ts = System.currentTimeMillis();
// System.out.println(ts + ": " + obj);
// System.out.flush();
// }
//
// public static void err(Object obj) {
// System.err.println(obj.toString());
// }
//
// public static void log2File(Object obj) {
// if (handle != null) {
// handle.println(obj);
// }
// }
//
// private static PrintWriter handle;
// private static String fileName;
//
// public static void openFile(String fn, boolean append) {
// try {
// fileName = fn;
// handle = new PrintWriter(new BufferedWriter(new FileWriter(fileName, append)));
// } catch (IOException e) {
// fileName = null;
// handle = null;
// }
// }
//
// public static void closeFile(String fn) {
// if (fileName != null && fileName.equals(fn)) {
// handle.close();
// }
// }
// }
// Path: src/nsl/stg/core/ExplorationStateManager.java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Set;
import java.util.Stack;
import nsl.stg.tests.Util;
package nsl.stg.core;
public class ExplorationStateManager {
private static ExplorationStateManager self;
private static List<ExplorationState> states; // keep some implicit ordering
private ExplorationStateManager() {
/* hide constructor */
states = new ArrayList<ExplorationState>();
}
public static ExplorationStateManager getInstance() {
if (self == null) {
self = new ExplorationStateManager();
}
return self;
}
// Not very efficient: Linear traversal
private ExplorationState find_state(ExplorationState state) {
ExplorationState ret = null;
for (Iterator<ExplorationState> iter = states.iterator(); iter.hasNext();) {
ExplorationState tmpState = iter.next();
if (tmpState.equals(state)) {
ret = tmpState;
break;
}
}
return ret;
}
public void addState(ExplorationState fromState, int clickId, ExplorationState toState) {
ExplorationState myFromState = fromState;
ExplorationState myToState = toState;
if (states.contains(fromState)) {
myFromState = find_state(fromState);
} else {
states.add(fromState);
}
if (states.contains(toState)) {
myToState = find_state(toState);
} else {
states.add(toState);
}
// Util.log("Adding " + fromState.dumpShort() + " @" + clickId + " --> " + toState.dumpShort());
// Util.log("Before:\n" + myState.toString());
myFromState.addReachableState(clickId, myToState);
// Util.log("After:\n" + myState.toString());
}
public boolean containsState(ExplorationState targetState) {
return (find_state(targetState) != null);
}
public List<UIAction> copmuteShortestPath(ExplorationState fromState, ExplorationState toState) {
List<UIAction> ret = new ArrayList<UIAction>();
if (fromState.equals(toState)) {
return ret;
}
Stack<UIAction> S = new Stack<UIAction>();
if (states.contains(fromState)) {
ExplorationState actualFromState = find_state(fromState);
// BFS
Queue<ExplorationState> Q = new LinkedList<ExplorationState>();
Set<ExplorationState> visited = new HashSet<ExplorationState>();
Map<ExplorationState, UIAction> map = new Hashtable<ExplorationState, UIAction>();
boolean done = false;
Q.add(actualFromState);
while (!Q.isEmpty() && !done) {
ExplorationState state = Q.remove();
if (states.contains(state)) {
state = find_state(state);
}
// Util.log("Procesing " + state.dumpShort());
if (state.equals(toState)) {
// backtrack to compute path
ExplorationState parent = state;
UIAction action;
while (!parent.equals(fromState)) {
action = map.get(parent);
// Util.log("Adding " + action);
S.push(action);
parent = action.getState();
}
done = true;
} else {
visited.add(state);
Map<Integer, ExplorationState> children = state.getReachables();
// Util.log("Children " + children);
for (Iterator<Entry<Integer, ExplorationState>> iter = children.entrySet().iterator(); iter.hasNext();) {
Entry<Integer, ExplorationState> entry = iter.next();
ExplorationState child = entry.getValue();
if (!visited.contains(child)) {
// Util.log("Adding to Q: " + child.dumpShort());
Q.add(child);
int clickId = entry.getKey();
map.put(child, new UIAction(state, clickId));
// Util.log(state.dumpShort() + " @" + clickId + " --> " + child.dumpShort());
}
}
}
} | Util.log("|Q|=" + Q.size() + ", done=" + done); |
USC-NSL/PUMA | src/nsl/stg/core/MyAccessibilityNodeInfoSuite.java | // Path: src/nsl/stg/tests/Util.java
// public class Util {
// public static void log(Object obj) {
// long ts = System.currentTimeMillis();
// System.out.println(ts + ": " + obj);
// System.out.flush();
// }
//
// public static void err(Object obj) {
// System.err.println(obj.toString());
// }
//
// public static void log2File(Object obj) {
// if (handle != null) {
// handle.println(obj);
// }
// }
//
// private static PrintWriter handle;
// private static String fileName;
//
// public static void openFile(String fn, boolean append) {
// try {
// fileName = fn;
// handle = new PrintWriter(new BufferedWriter(new FileWriter(fileName, append)));
// } catch (IOException e) {
// fileName = null;
// handle = null;
// }
// }
//
// public static void closeFile(String fn) {
// if (fileName != null && fileName.equals(fn)) {
// handle.close();
// }
// }
// }
| import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import nsl.stg.tests.Util;
import android.graphics.Rect;
import android.view.accessibility.AccessibilityNodeInfo; | package nsl.stg.core;
public class MyAccessibilityNodeInfoSuite {
// Rebuild the tree with MyAccessibilityNodeInfo class
public static MyAccessibilityNodeInfo rebuildTree(AccessibilityNodeInfo root) {
MyAccessibilityNodeInfo newRoot = new MyAccessibilityNodeInfo(root);
for (int i = 0; i < root.getChildCount(); i++) {
AccessibilityNodeInfo child = root.getChild(i);
MyAccessibilityNodeInfo newChild = MyAccessibilityNodeInfoSuite.rebuildTree(child);
newRoot.addChild(newChild);
}
return newRoot;
}
// Dump tree info
public static void dumpTree(MyAccessibilityNodeInfo root, int level) {
AccessibilityNodeInfo content = root.getOriginal();
String s = "";
for (int i = 0; i < level; i++) {
s += " ";
}
| // Path: src/nsl/stg/tests/Util.java
// public class Util {
// public static void log(Object obj) {
// long ts = System.currentTimeMillis();
// System.out.println(ts + ": " + obj);
// System.out.flush();
// }
//
// public static void err(Object obj) {
// System.err.println(obj.toString());
// }
//
// public static void log2File(Object obj) {
// if (handle != null) {
// handle.println(obj);
// }
// }
//
// private static PrintWriter handle;
// private static String fileName;
//
// public static void openFile(String fn, boolean append) {
// try {
// fileName = fn;
// handle = new PrintWriter(new BufferedWriter(new FileWriter(fileName, append)));
// } catch (IOException e) {
// fileName = null;
// handle = null;
// }
// }
//
// public static void closeFile(String fn) {
// if (fileName != null && fileName.equals(fn)) {
// handle.close();
// }
// }
// }
// Path: src/nsl/stg/core/MyAccessibilityNodeInfoSuite.java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import nsl.stg.tests.Util;
import android.graphics.Rect;
import android.view.accessibility.AccessibilityNodeInfo;
package nsl.stg.core;
public class MyAccessibilityNodeInfoSuite {
// Rebuild the tree with MyAccessibilityNodeInfo class
public static MyAccessibilityNodeInfo rebuildTree(AccessibilityNodeInfo root) {
MyAccessibilityNodeInfo newRoot = new MyAccessibilityNodeInfo(root);
for (int i = 0; i < root.getChildCount(); i++) {
AccessibilityNodeInfo child = root.getChild(i);
MyAccessibilityNodeInfo newChild = MyAccessibilityNodeInfoSuite.rebuildTree(child);
newRoot.addChild(newChild);
}
return newRoot;
}
// Dump tree info
public static void dumpTree(MyAccessibilityNodeInfo root, int level) {
AccessibilityNodeInfo content = root.getOriginal();
String s = "";
for (int i = 0; i < level; i++) {
s += " ";
}
| Util.log(s + content.getClassName() + "," + content.getText() + "," + root.needScroll() + "," + root.getScrollBound()); |
Adyen/adyen-hybris | adyenv6core/src/com/adyen/v6/actions/order/AdyenCancelOrRefundAction.java | // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java
// public static final String PAYMENT_PROVIDER = "Adyen";
| import de.hybris.platform.core.model.order.OrderModel;
import de.hybris.platform.orderprocessing.model.OrderProcessModel;
import de.hybris.platform.payment.PaymentService;
import de.hybris.platform.payment.model.PaymentTransactionEntryModel;
import de.hybris.platform.payment.model.PaymentTransactionModel;
import de.hybris.platform.processengine.action.AbstractProceduralAction;
import org.apache.log4j.Logger;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_PROVIDER; | /*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
*
* Adyen Hybris Extension
*
* Copyright (c) 2017 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
package com.adyen.v6.actions.order;
/**
* Sends cancellation to adyen transactions
*/
public class AdyenCancelOrRefundAction extends AbstractProceduralAction<OrderProcessModel> {
private static final Logger LOG = Logger.getLogger(AdyenCancelOrRefundAction.class);
private PaymentService paymentService;
@Override
public void executeAction(final OrderProcessModel process) throws Exception {
final OrderModel order = process.getOrder();
LOG.info("Cancelling order: " + order.getCode());
for (PaymentTransactionModel transactionModel : order.getPaymentTransactions()) { | // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java
// public static final String PAYMENT_PROVIDER = "Adyen";
// Path: adyenv6core/src/com/adyen/v6/actions/order/AdyenCancelOrRefundAction.java
import de.hybris.platform.core.model.order.OrderModel;
import de.hybris.platform.orderprocessing.model.OrderProcessModel;
import de.hybris.platform.payment.PaymentService;
import de.hybris.platform.payment.model.PaymentTransactionEntryModel;
import de.hybris.platform.payment.model.PaymentTransactionModel;
import de.hybris.platform.processengine.action.AbstractProceduralAction;
import org.apache.log4j.Logger;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_PROVIDER;
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
*
* Adyen Hybris Extension
*
* Copyright (c) 2017 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
package com.adyen.v6.actions.order;
/**
* Sends cancellation to adyen transactions
*/
public class AdyenCancelOrRefundAction extends AbstractProceduralAction<OrderProcessModel> {
private static final Logger LOG = Logger.getLogger(AdyenCancelOrRefundAction.class);
private PaymentService paymentService;
@Override
public void executeAction(final OrderProcessModel process) throws Exception {
final OrderModel order = process.getOrder();
LOG.info("Cancelling order: " + order.getCode());
for (PaymentTransactionModel transactionModel : order.getPaymentTransactions()) { | if (!PAYMENT_PROVIDER.equals(transactionModel.getPaymentProvider())) { |
Adyen/adyen-hybris | adyenv6b2ccheckoutaddon/src/com/adyen/v6/jalo/Adyenv6b2ccheckoutaddonManager.java | // Path: adyenv6b2ccheckoutaddon/src/com/adyen/v6/constants/Adyenv6b2ccheckoutaddonConstants.java
// public final class Adyenv6b2ccheckoutaddonConstants extends GeneratedAdyenv6b2ccheckoutaddonConstants
// {
// public static final String EXTENSIONNAME = "adyenv6b2ccheckoutaddon";
//
// private Adyenv6b2ccheckoutaddonConstants()
// {
// //empty to avoid instantiating this constant class
// }
//
// // implement here constants used by this extension
// }
| import de.hybris.platform.core.Registry;
import de.hybris.platform.util.JspContext;
import java.util.Map;
import org.apache.log4j.Logger;
import com.adyen.v6.constants.Adyenv6b2ccheckoutaddonConstants; | /*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 SAP SE or an SAP affiliate company.
* All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package com.adyen.v6.jalo;
/**
* This is the extension manager of the Adyenv6b2ccheckoutaddon extension.
*/
public class Adyenv6b2ccheckoutaddonManager extends GeneratedAdyenv6b2ccheckoutaddonManager
{
/** Edit the local|project.properties to change logging behavior (properties 'log4j.*'). */
private static final Logger LOG = Logger.getLogger(Adyenv6b2ccheckoutaddonManager.class.getName());
/*
* Some important tips for development:
*
* Do NEVER use the default constructor of manager's or items. => If you want to do something whenever the manger is
* created use the init() or destroy() methods described below
*
* Do NEVER use STATIC fields in your manager or items! => If you want to cache anything in a "static" way, use an
* instance variable in your manager, the manager is created only once in the lifetime of a "deployment" or tenant.
*/
/**
* Get the valid instance of this manager.
*
* @return the current instance of this manager
*/
public static Adyenv6b2ccheckoutaddonManager getInstance()
{
return (Adyenv6b2ccheckoutaddonManager) Registry.getCurrentTenant().getJaloConnection().getExtensionManager().getExtension( | // Path: adyenv6b2ccheckoutaddon/src/com/adyen/v6/constants/Adyenv6b2ccheckoutaddonConstants.java
// public final class Adyenv6b2ccheckoutaddonConstants extends GeneratedAdyenv6b2ccheckoutaddonConstants
// {
// public static final String EXTENSIONNAME = "adyenv6b2ccheckoutaddon";
//
// private Adyenv6b2ccheckoutaddonConstants()
// {
// //empty to avoid instantiating this constant class
// }
//
// // implement here constants used by this extension
// }
// Path: adyenv6b2ccheckoutaddon/src/com/adyen/v6/jalo/Adyenv6b2ccheckoutaddonManager.java
import de.hybris.platform.core.Registry;
import de.hybris.platform.util.JspContext;
import java.util.Map;
import org.apache.log4j.Logger;
import com.adyen.v6.constants.Adyenv6b2ccheckoutaddonConstants;
/*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 SAP SE or an SAP affiliate company.
* All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package com.adyen.v6.jalo;
/**
* This is the extension manager of the Adyenv6b2ccheckoutaddon extension.
*/
public class Adyenv6b2ccheckoutaddonManager extends GeneratedAdyenv6b2ccheckoutaddonManager
{
/** Edit the local|project.properties to change logging behavior (properties 'log4j.*'). */
private static final Logger LOG = Logger.getLogger(Adyenv6b2ccheckoutaddonManager.class.getName());
/*
* Some important tips for development:
*
* Do NEVER use the default constructor of manager's or items. => If you want to do something whenever the manger is
* created use the init() or destroy() methods described below
*
* Do NEVER use STATIC fields in your manager or items! => If you want to cache anything in a "static" way, use an
* instance variable in your manager, the manager is created only once in the lifetime of a "deployment" or tenant.
*/
/**
* Get the valid instance of this manager.
*
* @return the current instance of this manager
*/
public static Adyenv6b2ccheckoutaddonManager getInstance()
{
return (Adyenv6b2ccheckoutaddonManager) Registry.getCurrentTenant().getJaloConnection().getExtensionManager().getExtension( | Adyenv6b2ccheckoutaddonConstants.EXTENSIONNAME); |
Adyen/adyen-hybris | adyenv6core/src/com/adyen/v6/actions/order/AdyenCheckCaptureAction.java | // Path: adyenv6core/src/com/adyen/v6/actions/AbstractWaitableAction.java
// abstract public class AbstractWaitableAction<T extends BusinessProcessModel> extends AbstractAction<T> {
// public enum Transition {
// OK, NOK, WAIT;
//
// public static Set<String> getStringValues() {
// Set<String> res = new HashSet<>();
// for (final Transition transitions : Transition.values()) {
// res.add(transitions.toString());
// }
// return res;
// }
// }
//
// @Override
// public Set<String> getTransitions() {
// return Transition.getStringValues();
// }
// }
//
// Path: adyenv6core/src/com/adyen/v6/service/AdyenTransactionService.java
// public interface AdyenTransactionService {
// /**
// * Get TX entry by type and status
// */
// static PaymentTransactionEntryModel getTransactionEntry(PaymentTransactionModel paymentTransactionModel, PaymentTransactionType paymentTransactionType, TransactionStatus transactionStatus) {
// PaymentTransactionEntryModel result = paymentTransactionModel.getEntries().stream()
// .filter(
// entry -> paymentTransactionType.equals(entry.getType())
// && transactionStatus.name().equals(entry.getTransactionStatus())
// )
// .findFirst()
// .orElse(null);
//
// return result;
// }
//
// /**
// * Get TX entry by type, status and details
// */
// static PaymentTransactionEntryModel getTransactionEntry(PaymentTransactionModel paymentTransactionModel,
// PaymentTransactionType paymentTransactionType,
// TransactionStatus transactionStatus,
// TransactionStatusDetails transactionStatusDetails) {
// PaymentTransactionEntryModel result = paymentTransactionModel.getEntries().stream()
// .filter(
// entry -> paymentTransactionType.equals(entry.getType())
// && transactionStatus.name().equals(entry.getTransactionStatus())
// && transactionStatusDetails.name().equals(entry.getTransactionStatusDetails())
// )
// .findFirst()
// .orElse(null);
//
// return result;
// }
//
// /**
// * Creates a PaymentTransactionEntryModel with type=CAPTURE from NotificationItemModel
// */
// PaymentTransactionEntryModel createCapturedTransactionFromNotification(PaymentTransactionModel paymentTransaction, NotificationItemModel notificationItemModel);
//
// /**
// * Creates a PaymentTransactionEntryModel with type=REFUND_FOLLOW_ON from NotificationItemModel
// */
// PaymentTransactionEntryModel createRefundedTransactionFromNotification(PaymentTransactionModel paymentTransaction, NotificationItemModel notificationItemModel);
//
// /**
// * Stores the authorization transactions for an order
// */
// PaymentTransactionModel authorizeOrderModel(AbstractOrderModel abstractOrderModel, String merchantTransactionCode, String pspReference);
//
// /**
// * Store failed authorization transaction entry
// */
// PaymentTransactionModel storeFailedAuthorizationFromNotification(NotificationItemModel notificationItemModel, AbstractOrderModel abstractOrderModel);
//
// /**
// * Creates a PaymentTransactionEntryModel with type=CANCEL
// */
// PaymentTransactionEntryModel createCancellationTransaction(PaymentTransactionModel paymentTransaction, String merchantCode, String pspReference);
//
// /**
// * Creates a PaymentTransactionModel
// */
// PaymentTransactionModel createPaymentTransactionFromResultCode(AbstractOrderModel abstractOrderModel, String merchantTransactionCode, String pspReference, PaymentsResponse.ResultCodeEnum resultCodeEnum);
//
// /**
// * Stores the authorization transactions for an order
// */
// PaymentTransactionModel authorizeOrderModel(AbstractOrderModel abstractOrderModel, String merchantTransactionCode, String pspReference, BigDecimal paymentAmount);
// }
| import org.apache.log4j.Logger;
import java.math.BigDecimal;
import java.util.Set;
import com.adyen.v6.actions.AbstractWaitableAction;
import com.adyen.v6.service.AdyenTransactionService;
import de.hybris.platform.core.enums.OrderStatus;
import de.hybris.platform.core.model.order.OrderModel;
import de.hybris.platform.orderprocessing.model.OrderProcessModel;
import de.hybris.platform.payment.dto.TransactionStatus;
import de.hybris.platform.payment.dto.TransactionStatusDetails;
import de.hybris.platform.payment.enums.PaymentTransactionType;
import de.hybris.platform.payment.model.PaymentTransactionEntryModel;
import de.hybris.platform.payment.model.PaymentTransactionModel; | /*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
*
* Adyen Hybris Extension
*
* Copyright (c) 2017 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
package com.adyen.v6.actions.order;
/**
* Check if order is captured
*/
public class AdyenCheckCaptureAction extends AbstractWaitableAction<OrderProcessModel> {
private static final Logger LOG = Logger.getLogger(AdyenCheckCaptureAction.class);
@Override
public Set<String> getTransitions() {
return Transition.getStringValues();
}
@Override
public String execute(final OrderProcessModel process) {
LOG.debug("Process: " + process.getCode() + " in step " + getClass().getSimpleName());
final OrderModel order = process.getOrder();
if (order.getPaymentInfo().getAdyenPaymentMethod() == null) {
LOG.debug("Not Adyen Payment");
return Transition.OK.toString();
}
/*
TakePaymentAction will move the order to PAYMENT_CAPTURED state
Revert it back to PAYMENT_NOT_CAPTURED
*/
order.setStatus(OrderStatus.PAYMENT_NOT_CAPTURED);
modelService.save(order);
BigDecimal remainingAmount = new BigDecimal(order.getTotalPrice());
for (final PaymentTransactionModel paymentTransactionModel : order.getPaymentTransactions()) { | // Path: adyenv6core/src/com/adyen/v6/actions/AbstractWaitableAction.java
// abstract public class AbstractWaitableAction<T extends BusinessProcessModel> extends AbstractAction<T> {
// public enum Transition {
// OK, NOK, WAIT;
//
// public static Set<String> getStringValues() {
// Set<String> res = new HashSet<>();
// for (final Transition transitions : Transition.values()) {
// res.add(transitions.toString());
// }
// return res;
// }
// }
//
// @Override
// public Set<String> getTransitions() {
// return Transition.getStringValues();
// }
// }
//
// Path: adyenv6core/src/com/adyen/v6/service/AdyenTransactionService.java
// public interface AdyenTransactionService {
// /**
// * Get TX entry by type and status
// */
// static PaymentTransactionEntryModel getTransactionEntry(PaymentTransactionModel paymentTransactionModel, PaymentTransactionType paymentTransactionType, TransactionStatus transactionStatus) {
// PaymentTransactionEntryModel result = paymentTransactionModel.getEntries().stream()
// .filter(
// entry -> paymentTransactionType.equals(entry.getType())
// && transactionStatus.name().equals(entry.getTransactionStatus())
// )
// .findFirst()
// .orElse(null);
//
// return result;
// }
//
// /**
// * Get TX entry by type, status and details
// */
// static PaymentTransactionEntryModel getTransactionEntry(PaymentTransactionModel paymentTransactionModel,
// PaymentTransactionType paymentTransactionType,
// TransactionStatus transactionStatus,
// TransactionStatusDetails transactionStatusDetails) {
// PaymentTransactionEntryModel result = paymentTransactionModel.getEntries().stream()
// .filter(
// entry -> paymentTransactionType.equals(entry.getType())
// && transactionStatus.name().equals(entry.getTransactionStatus())
// && transactionStatusDetails.name().equals(entry.getTransactionStatusDetails())
// )
// .findFirst()
// .orElse(null);
//
// return result;
// }
//
// /**
// * Creates a PaymentTransactionEntryModel with type=CAPTURE from NotificationItemModel
// */
// PaymentTransactionEntryModel createCapturedTransactionFromNotification(PaymentTransactionModel paymentTransaction, NotificationItemModel notificationItemModel);
//
// /**
// * Creates a PaymentTransactionEntryModel with type=REFUND_FOLLOW_ON from NotificationItemModel
// */
// PaymentTransactionEntryModel createRefundedTransactionFromNotification(PaymentTransactionModel paymentTransaction, NotificationItemModel notificationItemModel);
//
// /**
// * Stores the authorization transactions for an order
// */
// PaymentTransactionModel authorizeOrderModel(AbstractOrderModel abstractOrderModel, String merchantTransactionCode, String pspReference);
//
// /**
// * Store failed authorization transaction entry
// */
// PaymentTransactionModel storeFailedAuthorizationFromNotification(NotificationItemModel notificationItemModel, AbstractOrderModel abstractOrderModel);
//
// /**
// * Creates a PaymentTransactionEntryModel with type=CANCEL
// */
// PaymentTransactionEntryModel createCancellationTransaction(PaymentTransactionModel paymentTransaction, String merchantCode, String pspReference);
//
// /**
// * Creates a PaymentTransactionModel
// */
// PaymentTransactionModel createPaymentTransactionFromResultCode(AbstractOrderModel abstractOrderModel, String merchantTransactionCode, String pspReference, PaymentsResponse.ResultCodeEnum resultCodeEnum);
//
// /**
// * Stores the authorization transactions for an order
// */
// PaymentTransactionModel authorizeOrderModel(AbstractOrderModel abstractOrderModel, String merchantTransactionCode, String pspReference, BigDecimal paymentAmount);
// }
// Path: adyenv6core/src/com/adyen/v6/actions/order/AdyenCheckCaptureAction.java
import org.apache.log4j.Logger;
import java.math.BigDecimal;
import java.util.Set;
import com.adyen.v6.actions.AbstractWaitableAction;
import com.adyen.v6.service.AdyenTransactionService;
import de.hybris.platform.core.enums.OrderStatus;
import de.hybris.platform.core.model.order.OrderModel;
import de.hybris.platform.orderprocessing.model.OrderProcessModel;
import de.hybris.platform.payment.dto.TransactionStatus;
import de.hybris.platform.payment.dto.TransactionStatusDetails;
import de.hybris.platform.payment.enums.PaymentTransactionType;
import de.hybris.platform.payment.model.PaymentTransactionEntryModel;
import de.hybris.platform.payment.model.PaymentTransactionModel;
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
*
* Adyen Hybris Extension
*
* Copyright (c) 2017 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
package com.adyen.v6.actions.order;
/**
* Check if order is captured
*/
public class AdyenCheckCaptureAction extends AbstractWaitableAction<OrderProcessModel> {
private static final Logger LOG = Logger.getLogger(AdyenCheckCaptureAction.class);
@Override
public Set<String> getTransitions() {
return Transition.getStringValues();
}
@Override
public String execute(final OrderProcessModel process) {
LOG.debug("Process: " + process.getCode() + " in step " + getClass().getSimpleName());
final OrderModel order = process.getOrder();
if (order.getPaymentInfo().getAdyenPaymentMethod() == null) {
LOG.debug("Not Adyen Payment");
return Transition.OK.toString();
}
/*
TakePaymentAction will move the order to PAYMENT_CAPTURED state
Revert it back to PAYMENT_NOT_CAPTURED
*/
order.setStatus(OrderStatus.PAYMENT_NOT_CAPTURED);
modelService.save(order);
BigDecimal remainingAmount = new BigDecimal(order.getTotalPrice());
for (final PaymentTransactionModel paymentTransactionModel : order.getPaymentTransactions()) { | boolean isRejected = AdyenTransactionService.getTransactionEntry( |
Adyen/adyen-hybris | adyenv6ordermanagement/src/com/adyen/v6/jalo/Adyenv6ordermanagementManager.java | // Path: adyenv6ordermanagement/src/com/adyen/v6/constants/Adyenv6ordermanagementConstants.java
// @SuppressWarnings("PMD")
// public class Adyenv6ordermanagementConstants extends GeneratedAdyenv6ordermanagementConstants
// {
// public static final String EXTENSIONNAME = "adyenv6ordermanagement";
//
// private Adyenv6ordermanagementConstants()
// {
// //empty
// }
//
//
// }
| import com.adyen.v6.constants.Adyenv6ordermanagementConstants;
import org.apache.log4j.Logger;
import de.hybris.platform.jalo.JaloSession;
import de.hybris.platform.jalo.extension.ExtensionManager; | /*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 SAP SE or an SAP affiliate company.
* All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*
*/
package com.adyen.v6.jalo;
@SuppressWarnings("PMD")
public class Adyenv6ordermanagementManager extends GeneratedAdyenv6ordermanagementManager
{
@SuppressWarnings("unused")
private static Logger log = Logger.getLogger( Adyenv6ordermanagementManager.class.getName() );
public static final Adyenv6ordermanagementManager getInstance()
{
ExtensionManager em = JaloSession.getCurrentSession().getExtensionManager(); | // Path: adyenv6ordermanagement/src/com/adyen/v6/constants/Adyenv6ordermanagementConstants.java
// @SuppressWarnings("PMD")
// public class Adyenv6ordermanagementConstants extends GeneratedAdyenv6ordermanagementConstants
// {
// public static final String EXTENSIONNAME = "adyenv6ordermanagement";
//
// private Adyenv6ordermanagementConstants()
// {
// //empty
// }
//
//
// }
// Path: adyenv6ordermanagement/src/com/adyen/v6/jalo/Adyenv6ordermanagementManager.java
import com.adyen.v6.constants.Adyenv6ordermanagementConstants;
import org.apache.log4j.Logger;
import de.hybris.platform.jalo.JaloSession;
import de.hybris.platform.jalo.extension.ExtensionManager;
/*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 SAP SE or an SAP affiliate company.
* All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*
*/
package com.adyen.v6.jalo;
@SuppressWarnings("PMD")
public class Adyenv6ordermanagementManager extends GeneratedAdyenv6ordermanagementManager
{
@SuppressWarnings("unused")
private static Logger log = Logger.getLogger( Adyenv6ordermanagementManager.class.getName() );
public static final Adyenv6ordermanagementManager getInstance()
{
ExtensionManager em = JaloSession.getCurrentSession().getExtensionManager(); | return (Adyenv6ordermanagementManager) em.getExtension(Adyenv6ordermanagementConstants.EXTENSIONNAME); |
Adyen/adyen-hybris | adyenv6core/src/com/adyen/v6/repository/PaymentTransactionRepository.java | // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java
// public static final String PAYMENT_PROVIDER = "Adyen";
| import de.hybris.platform.payment.model.PaymentTransactionEntryModel;
import de.hybris.platform.payment.model.PaymentTransactionModel;
import de.hybris.platform.servicelayer.search.FlexibleSearchQuery;
import org.apache.log4j.Logger;
import java.util.HashMap;
import java.util.Map;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_PROVIDER; | /*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
*
* Adyen Hybris Extension
*
* Copyright (c) 2017 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
package com.adyen.v6.repository;
/**
* Repository class for PaymentTransactions
*/
public class PaymentTransactionRepository extends AbstractRepository {
private static final Logger LOG = Logger.getLogger(PaymentTransactionRepository.class);
public PaymentTransactionModel getTransactionModel(String pspReference) {
final Map queryParams = new HashMap(); | // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java
// public static final String PAYMENT_PROVIDER = "Adyen";
// Path: adyenv6core/src/com/adyen/v6/repository/PaymentTransactionRepository.java
import de.hybris.platform.payment.model.PaymentTransactionEntryModel;
import de.hybris.platform.payment.model.PaymentTransactionModel;
import de.hybris.platform.servicelayer.search.FlexibleSearchQuery;
import org.apache.log4j.Logger;
import java.util.HashMap;
import java.util.Map;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_PROVIDER;
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
*
* Adyen Hybris Extension
*
* Copyright (c) 2017 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
package com.adyen.v6.repository;
/**
* Repository class for PaymentTransactions
*/
public class PaymentTransactionRepository extends AbstractRepository {
private static final Logger LOG = Logger.getLogger(PaymentTransactionRepository.class);
public PaymentTransactionModel getTransactionModel(String pspReference) {
final Map queryParams = new HashMap(); | queryParams.put("paymentProvider", PAYMENT_PROVIDER); |
Adyen/adyen-hybris | adyenv6core/src/com/adyen/v6/forms/AdyenPaymentForm.java | // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java
// final public static String PAYMENT_METHOD_CC = "adyen_cc";
//
// Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java
// final public static String PAYMENT_METHOD_ONECLICK = "adyen_oneclick_";
//
// Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java
// final public static String PAYMENT_METHOD_PAYPAL = "paypal";
| import java.text.SimpleDateFormat;
import java.util.Date;
import javax.validation.constraints.NotNull;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import com.adyen.util.Util;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_CC;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_ONECLICK;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_PAYPAL; |
public Date getDob() {
Date dateOfBirth = null;
if (dob != null) {
try {
// make sure the input format is yyyy-MM-dd
if (dob.matches("\\d{4}-\\d{2}-\\d{2}")) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
dateOfBirth = format.parse(dob);
}
} catch (Exception e) {
LOG.error(e);
}
}
return dateOfBirth;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getSocialSecurityNumber() {
return socialSecurityNumber;
}
public void setSocialSecurityNumber(String socialSecurityNumber) {
this.socialSecurityNumber = socialSecurityNumber;
}
public boolean isCC() { | // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java
// final public static String PAYMENT_METHOD_CC = "adyen_cc";
//
// Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java
// final public static String PAYMENT_METHOD_ONECLICK = "adyen_oneclick_";
//
// Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java
// final public static String PAYMENT_METHOD_PAYPAL = "paypal";
// Path: adyenv6core/src/com/adyen/v6/forms/AdyenPaymentForm.java
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.validation.constraints.NotNull;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import com.adyen.util.Util;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_CC;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_ONECLICK;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_PAYPAL;
public Date getDob() {
Date dateOfBirth = null;
if (dob != null) {
try {
// make sure the input format is yyyy-MM-dd
if (dob.matches("\\d{4}-\\d{2}-\\d{2}")) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
dateOfBirth = format.parse(dob);
}
} catch (Exception e) {
LOG.error(e);
}
}
return dateOfBirth;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getSocialSecurityNumber() {
return socialSecurityNumber;
}
public void setSocialSecurityNumber(String socialSecurityNumber) {
this.socialSecurityNumber = socialSecurityNumber;
}
public boolean isCC() { | return PAYMENT_METHOD_CC.equals(paymentMethod); |
Adyen/adyen-hybris | adyenv6core/src/com/adyen/v6/forms/AdyenPaymentForm.java | // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java
// final public static String PAYMENT_METHOD_CC = "adyen_cc";
//
// Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java
// final public static String PAYMENT_METHOD_ONECLICK = "adyen_oneclick_";
//
// Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java
// final public static String PAYMENT_METHOD_PAYPAL = "paypal";
| import java.text.SimpleDateFormat;
import java.util.Date;
import javax.validation.constraints.NotNull;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import com.adyen.util.Util;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_CC;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_ONECLICK;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_PAYPAL; | // make sure the input format is yyyy-MM-dd
if (dob.matches("\\d{4}-\\d{2}-\\d{2}")) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
dateOfBirth = format.parse(dob);
}
} catch (Exception e) {
LOG.error(e);
}
}
return dateOfBirth;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getSocialSecurityNumber() {
return socialSecurityNumber;
}
public void setSocialSecurityNumber(String socialSecurityNumber) {
this.socialSecurityNumber = socialSecurityNumber;
}
public boolean isCC() {
return PAYMENT_METHOD_CC.equals(paymentMethod);
}
public boolean isOneClick() { | // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java
// final public static String PAYMENT_METHOD_CC = "adyen_cc";
//
// Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java
// final public static String PAYMENT_METHOD_ONECLICK = "adyen_oneclick_";
//
// Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java
// final public static String PAYMENT_METHOD_PAYPAL = "paypal";
// Path: adyenv6core/src/com/adyen/v6/forms/AdyenPaymentForm.java
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.validation.constraints.NotNull;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import com.adyen.util.Util;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_CC;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_ONECLICK;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_PAYPAL;
// make sure the input format is yyyy-MM-dd
if (dob.matches("\\d{4}-\\d{2}-\\d{2}")) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
dateOfBirth = format.parse(dob);
}
} catch (Exception e) {
LOG.error(e);
}
}
return dateOfBirth;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getSocialSecurityNumber() {
return socialSecurityNumber;
}
public void setSocialSecurityNumber(String socialSecurityNumber) {
this.socialSecurityNumber = socialSecurityNumber;
}
public boolean isCC() {
return PAYMENT_METHOD_CC.equals(paymentMethod);
}
public boolean isOneClick() { | return PAYMENT_METHOD_ONECLICK.indexOf(paymentMethod) == 0; |
Adyen/adyen-hybris | adyenv6core/src/com/adyen/v6/forms/AdyenPaymentForm.java | // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java
// final public static String PAYMENT_METHOD_CC = "adyen_cc";
//
// Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java
// final public static String PAYMENT_METHOD_ONECLICK = "adyen_oneclick_";
//
// Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java
// final public static String PAYMENT_METHOD_PAYPAL = "paypal";
| import java.text.SimpleDateFormat;
import java.util.Date;
import javax.validation.constraints.NotNull;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import com.adyen.util.Util;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_CC;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_ONECLICK;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_PAYPAL; |
public void setCardBrand(String cardBrand) {
this.cardBrand = cardBrand;
}
public int getInstallments() {
return installments;
}
public void setInstallments(int installments) {
this.installments = installments;
}
public String getTerminalId() {
return terminalId;
}
public void setTerminalId(String terminalId) {
this.terminalId = terminalId;
}
public String getCardType() {
return cardType;
}
public void setCardType(String cardType) {
this.cardType = cardType;
}
public boolean usesComponent() { | // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java
// final public static String PAYMENT_METHOD_CC = "adyen_cc";
//
// Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java
// final public static String PAYMENT_METHOD_ONECLICK = "adyen_oneclick_";
//
// Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java
// final public static String PAYMENT_METHOD_PAYPAL = "paypal";
// Path: adyenv6core/src/com/adyen/v6/forms/AdyenPaymentForm.java
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.validation.constraints.NotNull;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import com.adyen.util.Util;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_CC;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_ONECLICK;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_PAYPAL;
public void setCardBrand(String cardBrand) {
this.cardBrand = cardBrand;
}
public int getInstallments() {
return installments;
}
public void setInstallments(int installments) {
this.installments = installments;
}
public String getTerminalId() {
return terminalId;
}
public void setTerminalId(String terminalId) {
this.terminalId = terminalId;
}
public String getCardType() {
return cardType;
}
public void setCardType(String cardType) {
this.cardType = cardType;
}
public boolean usesComponent() { | return PAYMENT_METHOD_PAYPAL.equals(paymentMethod); |
Adyen/adyen-hybris | adyenv6backoffice/src/com/adyen/v6/jalo/Adyenv6backofficeManager.java | // Path: adyenv6backoffice/src/com/adyen/v6/constants/Adyenv6backofficeConstants.java
// public final class Adyenv6backofficeConstants extends GeneratedAdyenv6backofficeConstants
// {
// public static final String EXTENSIONNAME = "adyenv6backoffice";
//
// private Adyenv6backofficeConstants()
// {
// //empty to avoid instantiating this constant class
// }
//
// // implement here constants used by this extension
// }
| import de.hybris.platform.core.Registry;
import de.hybris.platform.util.JspContext;
import java.util.Map;
import org.apache.log4j.Logger;
import com.adyen.v6.constants.Adyenv6backofficeConstants; | /*
* [y] hybris Platform
*
* Copyright (c) 2000-2015 hybris AG
* All rights reserved.
*
* This software is the confidential and proprietary information of hybris
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with hybris.
*/
package com.adyen.v6.jalo;
/**
* This is the extension manager of the Ybackoffice extension.
*/
public class Adyenv6backofficeManager extends GeneratedAdyenv6backofficeManager
{
/** Edit the local|project.properties to change logging behavior (properties 'log4j.*'). */
private static final Logger LOG = Logger.getLogger(Adyenv6backofficeManager.class.getName());
/*
* Some important tips for development:
*
* Do NEVER use the default constructor of manager's or items. => If you want to do something whenever the manger is
* created use the init() or destroy() methods described below
*
* Do NEVER use STATIC fields in your manager or items! => If you want to cache anything in a "static" way, use an
* instance variable in your manager, the manager is created only once in the lifetime of a "deployment" or tenant.
*/
/**
* Get the valid instance of this manager.
*
* @return the current instance of this manager
*/
public static Adyenv6backofficeManager getInstance()
{
return (Adyenv6backofficeManager) Registry.getCurrentTenant().getJaloConnection().getExtensionManager() | // Path: adyenv6backoffice/src/com/adyen/v6/constants/Adyenv6backofficeConstants.java
// public final class Adyenv6backofficeConstants extends GeneratedAdyenv6backofficeConstants
// {
// public static final String EXTENSIONNAME = "adyenv6backoffice";
//
// private Adyenv6backofficeConstants()
// {
// //empty to avoid instantiating this constant class
// }
//
// // implement here constants used by this extension
// }
// Path: adyenv6backoffice/src/com/adyen/v6/jalo/Adyenv6backofficeManager.java
import de.hybris.platform.core.Registry;
import de.hybris.platform.util.JspContext;
import java.util.Map;
import org.apache.log4j.Logger;
import com.adyen.v6.constants.Adyenv6backofficeConstants;
/*
* [y] hybris Platform
*
* Copyright (c) 2000-2015 hybris AG
* All rights reserved.
*
* This software is the confidential and proprietary information of hybris
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with hybris.
*/
package com.adyen.v6.jalo;
/**
* This is the extension manager of the Ybackoffice extension.
*/
public class Adyenv6backofficeManager extends GeneratedAdyenv6backofficeManager
{
/** Edit the local|project.properties to change logging behavior (properties 'log4j.*'). */
private static final Logger LOG = Logger.getLogger(Adyenv6backofficeManager.class.getName());
/*
* Some important tips for development:
*
* Do NEVER use the default constructor of manager's or items. => If you want to do something whenever the manger is
* created use the init() or destroy() methods described below
*
* Do NEVER use STATIC fields in your manager or items! => If you want to cache anything in a "static" way, use an
* instance variable in your manager, the manager is created only once in the lifetime of a "deployment" or tenant.
*/
/**
* Get the valid instance of this manager.
*
* @return the current instance of this manager
*/
public static Adyenv6backofficeManager getInstance()
{
return (Adyenv6backofficeManager) Registry.getCurrentTenant().getJaloConnection().getExtensionManager() | .getExtension(Adyenv6backofficeConstants.EXTENSIONNAME); |
Adyen/adyen-hybris | adyenv6core/src/com/adyen/v6/service/DefaultAdyenTransactionService.java | // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java
// public static final String PAYMENT_PROVIDER = "Adyen";
| import de.hybris.platform.servicelayer.model.ModelService;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_PROVIDER;
import com.adyen.model.checkout.PaymentsResponse;
import com.adyen.v6.model.NotificationItemModel;
import de.hybris.platform.core.model.c2l.CurrencyModel;
import de.hybris.platform.core.model.order.AbstractOrderModel;
import de.hybris.platform.payment.dto.TransactionStatus;
import de.hybris.platform.payment.dto.TransactionStatusDetails;
import de.hybris.platform.payment.enums.PaymentTransactionType;
import de.hybris.platform.payment.model.PaymentTransactionEntryModel;
import de.hybris.platform.payment.model.PaymentTransactionModel;
import de.hybris.platform.servicelayer.i18n.CommonI18NService; | transactionEntryModel.setRequestId(paymentTransaction.getRequestId());
transactionEntryModel.setRequestToken(merchantCode);
transactionEntryModel.setCode(code);
transactionEntryModel.setTime(DateTime.now().toDate());
transactionEntryModel.setTransactionStatus(TransactionStatus.ACCEPTED.name());
transactionEntryModel.setTransactionStatusDetails(TransactionStatusDetails.SUCCESFULL.name());
transactionEntryModel.setAmount(BigDecimal.valueOf(abstractOrderModel.getTotalPrice()));
transactionEntryModel.setCurrency(abstractOrderModel.getCurrency());
return transactionEntryModel;
}
private PaymentTransactionEntryModel createAuthorizationPaymentTransactionEntryModel(
final PaymentTransactionModel paymentTransaction,
final String merchantCode,
final AbstractOrderModel abstractOrderModel,
final BigDecimal paymentAmount) {
final PaymentTransactionEntryModel transactionEntryModel = createAuthorizationPaymentTransactionEntryModel(paymentTransaction, merchantCode, abstractOrderModel);
transactionEntryModel.setAmount(paymentAmount);
return transactionEntryModel;
}
private PaymentTransactionModel createPaymentTransaction(
final String merchantCode,
final String pspReference,
final AbstractOrderModel abstractOrderModel) {
final PaymentTransactionModel paymentTransactionModel = modelService.create(PaymentTransactionModel.class);
paymentTransactionModel.setCode(pspReference);
paymentTransactionModel.setRequestId(pspReference);
paymentTransactionModel.setRequestToken(merchantCode); | // Path: adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java
// public static final String PAYMENT_PROVIDER = "Adyen";
// Path: adyenv6core/src/com/adyen/v6/service/DefaultAdyenTransactionService.java
import de.hybris.platform.servicelayer.model.ModelService;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_PROVIDER;
import com.adyen.model.checkout.PaymentsResponse;
import com.adyen.v6.model.NotificationItemModel;
import de.hybris.platform.core.model.c2l.CurrencyModel;
import de.hybris.platform.core.model.order.AbstractOrderModel;
import de.hybris.platform.payment.dto.TransactionStatus;
import de.hybris.platform.payment.dto.TransactionStatusDetails;
import de.hybris.platform.payment.enums.PaymentTransactionType;
import de.hybris.platform.payment.model.PaymentTransactionEntryModel;
import de.hybris.platform.payment.model.PaymentTransactionModel;
import de.hybris.platform.servicelayer.i18n.CommonI18NService;
transactionEntryModel.setRequestId(paymentTransaction.getRequestId());
transactionEntryModel.setRequestToken(merchantCode);
transactionEntryModel.setCode(code);
transactionEntryModel.setTime(DateTime.now().toDate());
transactionEntryModel.setTransactionStatus(TransactionStatus.ACCEPTED.name());
transactionEntryModel.setTransactionStatusDetails(TransactionStatusDetails.SUCCESFULL.name());
transactionEntryModel.setAmount(BigDecimal.valueOf(abstractOrderModel.getTotalPrice()));
transactionEntryModel.setCurrency(abstractOrderModel.getCurrency());
return transactionEntryModel;
}
private PaymentTransactionEntryModel createAuthorizationPaymentTransactionEntryModel(
final PaymentTransactionModel paymentTransaction,
final String merchantCode,
final AbstractOrderModel abstractOrderModel,
final BigDecimal paymentAmount) {
final PaymentTransactionEntryModel transactionEntryModel = createAuthorizationPaymentTransactionEntryModel(paymentTransaction, merchantCode, abstractOrderModel);
transactionEntryModel.setAmount(paymentAmount);
return transactionEntryModel;
}
private PaymentTransactionModel createPaymentTransaction(
final String merchantCode,
final String pspReference,
final AbstractOrderModel abstractOrderModel) {
final PaymentTransactionModel paymentTransactionModel = modelService.create(PaymentTransactionModel.class);
paymentTransactionModel.setCode(pspReference);
paymentTransactionModel.setRequestId(pspReference);
paymentTransactionModel.setRequestToken(merchantCode); | paymentTransactionModel.setPaymentProvider(PAYMENT_PROVIDER); |
Adyen/adyen-hybris | adyenv6core/testsrc/com/adyen/v6/service/AdyenNotificationServiceTest.java | // Path: adyenv6core/src/com/adyen/v6/repository/OrderRepository.java
// public class OrderRepository extends AbstractRepository {
// private static final Logger LOG = Logger.getLogger(OrderRepository.class);
//
// public OrderModel getOrderModel(String code) {
// final Map queryParams = new HashMap();
// queryParams.put("code", code);
//
// //Adding "{versionID} IS NULL" to get the original order regardless of modification history
// final FlexibleSearchQuery selectOrderQuery = new FlexibleSearchQuery(
// "SELECT {pk} FROM {" + OrderModel._TYPECODE + "}"
// + " WHERE {" + OrderModel.CODE + "} = ?code"
// + " AND {versionID} IS NULL",
// queryParams
// );
//
// LOG.debug("Finding order with code: " + code);
//
// return (OrderModel) getOneOrNull(selectOrderQuery);
// }
// }
//
// Path: adyenv6core/src/com/adyen/v6/repository/PaymentTransactionRepository.java
// public class PaymentTransactionRepository extends AbstractRepository {
// private static final Logger LOG = Logger.getLogger(PaymentTransactionRepository.class);
//
// public PaymentTransactionModel getTransactionModel(String pspReference) {
// final Map queryParams = new HashMap();
// queryParams.put("paymentProvider", PAYMENT_PROVIDER);
// queryParams.put("requestId", pspReference);
// final FlexibleSearchQuery selectOrderQuery = new FlexibleSearchQuery(
// "SELECT {pk} FROM {" + PaymentTransactionModel._TYPECODE + "}"
// + " WHERE {" + PaymentTransactionModel.PAYMENTPROVIDER + "} = ?paymentProvider"
// + " AND {" + PaymentTransactionEntryModel.REQUESTID + "} = ?requestId"
// //Adding "{versionID} IS NULL" to get the original order regardless of modification history
// + " AND {versionID} IS NULL",
// queryParams
// );
//
// LOG.debug("Finding transaction with PSP reference: " + pspReference);
//
// return (PaymentTransactionModel) getOneOrNull(selectOrderQuery);
// }
// }
| import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import com.adyen.v6.model.NotificationItemModel;
import com.adyen.v6.repository.OrderRepository;
import com.adyen.v6.repository.PaymentTransactionRepository;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.core.model.order.OrderModel;
import de.hybris.platform.orderprocessing.model.OrderProcessModel;
import de.hybris.platform.payment.model.PaymentTransactionEntryModel;
import de.hybris.platform.payment.model.PaymentTransactionModel;
import de.hybris.platform.processengine.BusinessProcessService;
import de.hybris.platform.returns.model.ReturnProcessModel;
import de.hybris.platform.returns.model.ReturnRequestModel;
import de.hybris.platform.servicelayer.model.ModelService;
import static com.adyen.model.notification.NotificationRequestItem.EVENT_CODE_AUTHORISATION;
import static com.adyen.model.notification.NotificationRequestItem.EVENT_CODE_CAPTURE;
import static com.adyen.model.notification.NotificationRequestItem.EVENT_CODE_REFUND;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | /*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
*
* Adyen Hybris Extension
*
* Copyright (c) 2017 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
package com.adyen.v6.service;
@UnitTest
@RunWith(MockitoJUnitRunner.class)
public class AdyenNotificationServiceTest {
@Mock
private ModelService modelServiceMock;
@Mock
private AdyenTransactionService adyenTransactionServiceMock;
@Mock | // Path: adyenv6core/src/com/adyen/v6/repository/OrderRepository.java
// public class OrderRepository extends AbstractRepository {
// private static final Logger LOG = Logger.getLogger(OrderRepository.class);
//
// public OrderModel getOrderModel(String code) {
// final Map queryParams = new HashMap();
// queryParams.put("code", code);
//
// //Adding "{versionID} IS NULL" to get the original order regardless of modification history
// final FlexibleSearchQuery selectOrderQuery = new FlexibleSearchQuery(
// "SELECT {pk} FROM {" + OrderModel._TYPECODE + "}"
// + " WHERE {" + OrderModel.CODE + "} = ?code"
// + " AND {versionID} IS NULL",
// queryParams
// );
//
// LOG.debug("Finding order with code: " + code);
//
// return (OrderModel) getOneOrNull(selectOrderQuery);
// }
// }
//
// Path: adyenv6core/src/com/adyen/v6/repository/PaymentTransactionRepository.java
// public class PaymentTransactionRepository extends AbstractRepository {
// private static final Logger LOG = Logger.getLogger(PaymentTransactionRepository.class);
//
// public PaymentTransactionModel getTransactionModel(String pspReference) {
// final Map queryParams = new HashMap();
// queryParams.put("paymentProvider", PAYMENT_PROVIDER);
// queryParams.put("requestId", pspReference);
// final FlexibleSearchQuery selectOrderQuery = new FlexibleSearchQuery(
// "SELECT {pk} FROM {" + PaymentTransactionModel._TYPECODE + "}"
// + " WHERE {" + PaymentTransactionModel.PAYMENTPROVIDER + "} = ?paymentProvider"
// + " AND {" + PaymentTransactionEntryModel.REQUESTID + "} = ?requestId"
// //Adding "{versionID} IS NULL" to get the original order regardless of modification history
// + " AND {versionID} IS NULL",
// queryParams
// );
//
// LOG.debug("Finding transaction with PSP reference: " + pspReference);
//
// return (PaymentTransactionModel) getOneOrNull(selectOrderQuery);
// }
// }
// Path: adyenv6core/testsrc/com/adyen/v6/service/AdyenNotificationServiceTest.java
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import com.adyen.v6.model.NotificationItemModel;
import com.adyen.v6.repository.OrderRepository;
import com.adyen.v6.repository.PaymentTransactionRepository;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.core.model.order.OrderModel;
import de.hybris.platform.orderprocessing.model.OrderProcessModel;
import de.hybris.platform.payment.model.PaymentTransactionEntryModel;
import de.hybris.platform.payment.model.PaymentTransactionModel;
import de.hybris.platform.processengine.BusinessProcessService;
import de.hybris.platform.returns.model.ReturnProcessModel;
import de.hybris.platform.returns.model.ReturnRequestModel;
import de.hybris.platform.servicelayer.model.ModelService;
import static com.adyen.model.notification.NotificationRequestItem.EVENT_CODE_AUTHORISATION;
import static com.adyen.model.notification.NotificationRequestItem.EVENT_CODE_CAPTURE;
import static com.adyen.model.notification.NotificationRequestItem.EVENT_CODE_REFUND;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
*
* Adyen Hybris Extension
*
* Copyright (c) 2017 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
package com.adyen.v6.service;
@UnitTest
@RunWith(MockitoJUnitRunner.class)
public class AdyenNotificationServiceTest {
@Mock
private ModelService modelServiceMock;
@Mock
private AdyenTransactionService adyenTransactionServiceMock;
@Mock | private OrderRepository orderRepositoryMock; |
Adyen/adyen-hybris | adyenv6core/testsrc/com/adyen/v6/service/AdyenNotificationServiceTest.java | // Path: adyenv6core/src/com/adyen/v6/repository/OrderRepository.java
// public class OrderRepository extends AbstractRepository {
// private static final Logger LOG = Logger.getLogger(OrderRepository.class);
//
// public OrderModel getOrderModel(String code) {
// final Map queryParams = new HashMap();
// queryParams.put("code", code);
//
// //Adding "{versionID} IS NULL" to get the original order regardless of modification history
// final FlexibleSearchQuery selectOrderQuery = new FlexibleSearchQuery(
// "SELECT {pk} FROM {" + OrderModel._TYPECODE + "}"
// + " WHERE {" + OrderModel.CODE + "} = ?code"
// + " AND {versionID} IS NULL",
// queryParams
// );
//
// LOG.debug("Finding order with code: " + code);
//
// return (OrderModel) getOneOrNull(selectOrderQuery);
// }
// }
//
// Path: adyenv6core/src/com/adyen/v6/repository/PaymentTransactionRepository.java
// public class PaymentTransactionRepository extends AbstractRepository {
// private static final Logger LOG = Logger.getLogger(PaymentTransactionRepository.class);
//
// public PaymentTransactionModel getTransactionModel(String pspReference) {
// final Map queryParams = new HashMap();
// queryParams.put("paymentProvider", PAYMENT_PROVIDER);
// queryParams.put("requestId", pspReference);
// final FlexibleSearchQuery selectOrderQuery = new FlexibleSearchQuery(
// "SELECT {pk} FROM {" + PaymentTransactionModel._TYPECODE + "}"
// + " WHERE {" + PaymentTransactionModel.PAYMENTPROVIDER + "} = ?paymentProvider"
// + " AND {" + PaymentTransactionEntryModel.REQUESTID + "} = ?requestId"
// //Adding "{versionID} IS NULL" to get the original order regardless of modification history
// + " AND {versionID} IS NULL",
// queryParams
// );
//
// LOG.debug("Finding transaction with PSP reference: " + pspReference);
//
// return (PaymentTransactionModel) getOneOrNull(selectOrderQuery);
// }
// }
| import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import com.adyen.v6.model.NotificationItemModel;
import com.adyen.v6.repository.OrderRepository;
import com.adyen.v6.repository.PaymentTransactionRepository;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.core.model.order.OrderModel;
import de.hybris.platform.orderprocessing.model.OrderProcessModel;
import de.hybris.platform.payment.model.PaymentTransactionEntryModel;
import de.hybris.platform.payment.model.PaymentTransactionModel;
import de.hybris.platform.processengine.BusinessProcessService;
import de.hybris.platform.returns.model.ReturnProcessModel;
import de.hybris.platform.returns.model.ReturnRequestModel;
import de.hybris.platform.servicelayer.model.ModelService;
import static com.adyen.model.notification.NotificationRequestItem.EVENT_CODE_AUTHORISATION;
import static com.adyen.model.notification.NotificationRequestItem.EVENT_CODE_CAPTURE;
import static com.adyen.model.notification.NotificationRequestItem.EVENT_CODE_REFUND;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | /*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
*
* Adyen Hybris Extension
*
* Copyright (c) 2017 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
package com.adyen.v6.service;
@UnitTest
@RunWith(MockitoJUnitRunner.class)
public class AdyenNotificationServiceTest {
@Mock
private ModelService modelServiceMock;
@Mock
private AdyenTransactionService adyenTransactionServiceMock;
@Mock
private OrderRepository orderRepositoryMock;
@Mock | // Path: adyenv6core/src/com/adyen/v6/repository/OrderRepository.java
// public class OrderRepository extends AbstractRepository {
// private static final Logger LOG = Logger.getLogger(OrderRepository.class);
//
// public OrderModel getOrderModel(String code) {
// final Map queryParams = new HashMap();
// queryParams.put("code", code);
//
// //Adding "{versionID} IS NULL" to get the original order regardless of modification history
// final FlexibleSearchQuery selectOrderQuery = new FlexibleSearchQuery(
// "SELECT {pk} FROM {" + OrderModel._TYPECODE + "}"
// + " WHERE {" + OrderModel.CODE + "} = ?code"
// + " AND {versionID} IS NULL",
// queryParams
// );
//
// LOG.debug("Finding order with code: " + code);
//
// return (OrderModel) getOneOrNull(selectOrderQuery);
// }
// }
//
// Path: adyenv6core/src/com/adyen/v6/repository/PaymentTransactionRepository.java
// public class PaymentTransactionRepository extends AbstractRepository {
// private static final Logger LOG = Logger.getLogger(PaymentTransactionRepository.class);
//
// public PaymentTransactionModel getTransactionModel(String pspReference) {
// final Map queryParams = new HashMap();
// queryParams.put("paymentProvider", PAYMENT_PROVIDER);
// queryParams.put("requestId", pspReference);
// final FlexibleSearchQuery selectOrderQuery = new FlexibleSearchQuery(
// "SELECT {pk} FROM {" + PaymentTransactionModel._TYPECODE + "}"
// + " WHERE {" + PaymentTransactionModel.PAYMENTPROVIDER + "} = ?paymentProvider"
// + " AND {" + PaymentTransactionEntryModel.REQUESTID + "} = ?requestId"
// //Adding "{versionID} IS NULL" to get the original order regardless of modification history
// + " AND {versionID} IS NULL",
// queryParams
// );
//
// LOG.debug("Finding transaction with PSP reference: " + pspReference);
//
// return (PaymentTransactionModel) getOneOrNull(selectOrderQuery);
// }
// }
// Path: adyenv6core/testsrc/com/adyen/v6/service/AdyenNotificationServiceTest.java
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import com.adyen.v6.model.NotificationItemModel;
import com.adyen.v6.repository.OrderRepository;
import com.adyen.v6.repository.PaymentTransactionRepository;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.core.model.order.OrderModel;
import de.hybris.platform.orderprocessing.model.OrderProcessModel;
import de.hybris.platform.payment.model.PaymentTransactionEntryModel;
import de.hybris.platform.payment.model.PaymentTransactionModel;
import de.hybris.platform.processengine.BusinessProcessService;
import de.hybris.platform.returns.model.ReturnProcessModel;
import de.hybris.platform.returns.model.ReturnRequestModel;
import de.hybris.platform.servicelayer.model.ModelService;
import static com.adyen.model.notification.NotificationRequestItem.EVENT_CODE_AUTHORISATION;
import static com.adyen.model.notification.NotificationRequestItem.EVENT_CODE_CAPTURE;
import static com.adyen.model.notification.NotificationRequestItem.EVENT_CODE_REFUND;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
*
* Adyen Hybris Extension
*
* Copyright (c) 2017 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
package com.adyen.v6.service;
@UnitTest
@RunWith(MockitoJUnitRunner.class)
public class AdyenNotificationServiceTest {
@Mock
private ModelService modelServiceMock;
@Mock
private AdyenTransactionService adyenTransactionServiceMock;
@Mock
private OrderRepository orderRepositoryMock;
@Mock | private PaymentTransactionRepository paymentTransactionRepositoryMock; |
Adyen/adyen-hybris | adyenv6notification/web/src/com/adyen/v6/controllers/AdyenNotificationController.java | // Path: adyenv6notification/src/com/adyen/v6/security/AdyenNotificationAuthenticationProvider.java
// @Component
// public class AdyenNotificationAuthenticationProvider {
// @Resource(name = "baseStoreService")
// private BaseStoreService baseStoreService;
//
// @Resource(name = "baseSiteService")
// private BaseSiteService baseSiteService;
//
// private static final Logger LOG = Logger.getLogger(AdyenNotificationAuthenticationProvider.class);
//
// public boolean authenticateBasic(final HttpServletRequest request, String baseSiteId) {
// final String authorization = request.getHeader("Authorization");
// if (authorization != null && authorization.startsWith("Basic")) {
// String base64Credentials = authorization.substring("Basic".length()).trim();
// String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
// final String[] values = credentials.split(":", 2);
// return tryToAuthenticate(values[0], values[1], baseSiteId);
// }
// return false;
// }
//
// private boolean tryToAuthenticate(String name, String password, String baseSiteId) {
//
// LOG.debug("Trying to authenticate for baseSiteId " + baseSiteId);
// final BaseSiteModel requestedBaseSite = getBaseSiteService().getBaseSiteForUID(baseSiteId);
// if (requestedBaseSite != null) {
// final BaseSiteModel currentBaseSite = getBaseSiteService().getCurrentBaseSite();
//
// if (! requestedBaseSite.equals(currentBaseSite)) {
// getBaseSiteService().setCurrentBaseSite(requestedBaseSite, true);
// }
// }
// BaseStoreModel baseStore = baseStoreService.getCurrentBaseStore();
//
// if (baseStore == null) {
// return false;
// }
//
// String notificationUsername = baseStore.getAdyenNotificationUsername();
// String notificationPassword = baseStore.getAdyenNotificationPassword();
//
// Assert.notNull(notificationUsername);
// Assert.notNull(notificationPassword);
//
// if (notificationUsername.isEmpty() || notificationPassword.isEmpty()) {
// return false;
// }
//
// if (notificationUsername.equals(name) && notificationPassword.equals(password)) {
// return true;
// }
//
// return false;
// }
//
// public BaseStoreService getBaseStoreService() {
// return baseStoreService;
// }
//
// protected BaseSiteService getBaseSiteService() {
// return baseSiteService;
// }
//
// public void setBaseStoreService(BaseStoreService baseStoreService) {
// this.baseStoreService = baseStoreService;
// }
// }
//
// Path: adyenv6core/src/com/adyen/v6/service/AdyenNotificationService.java
// public interface AdyenNotificationService {
//
// /**
// * Process NotificationItemModel
// * Handles multiple eventCodes
// */
// void processNotification(NotificationItemModel notificationItemModel);
//
// /**
// * Parse HTTP request body and save NotificationItemModels
// */
// void saveNotifications(String requestString);
//
// /**
// * Create NotificationItemModel from NotificationRequestItem
// */
// NotificationItemModel createFromNotificationRequest(NotificationRequestItem notificationRequestItem);
//
// /**
// * Save NotificationItemModel from NotificationRequestItem
// */
// void saveFromNotificationRequest(NotificationRequestItem notificationRequestItem);
//
// /**
// * Process notification with eventCode=CAPTURED
// */
// PaymentTransactionEntryModel processCapturedEvent(NotificationItemModel notificationItemModel, PaymentTransactionModel paymentTransactionModel);
//
// /**
// * Process notification with eventCode=AUTHORISED
// */
// PaymentTransactionModel processAuthorisationEvent(NotificationItemModel notificationItemModel);
//
// /**
// * Process notification with eventCode=CANCEL_OR_REFUND
// */
// PaymentTransactionEntryModel processCancelEvent(NotificationItemModel notificationItemModel, PaymentTransactionModel paymentTransactionModel);
//
// /**
// * Process notification with eventCode=REFUND
// */
// PaymentTransactionEntryModel processRefundEvent(NotificationItemModel notificationItem);
//
// /**
// * Process notification with eventCode=OFFER_CLOSED
// * @return
// */
// PaymentTransactionModel processOfferClosedEvent(NotificationItemModel notificationItem);
//
// }
| import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.adyen.v6.security.AdyenNotificationAuthenticationProvider;
import com.adyen.v6.service.AdyenNotificationService; | /*
* [y] hybris Platform
*
* Copyright (c) 2017 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package com.adyen.v6.controllers;
@Controller
@RequestMapping(value = "/adyen/v6/notification/{baseSiteId}")
public class AdyenNotificationController {
private static final Logger LOG = Logger.getLogger(AdyenNotificationController.class);
@Resource(name = "adyenNotificationAuthenticationProvider") | // Path: adyenv6notification/src/com/adyen/v6/security/AdyenNotificationAuthenticationProvider.java
// @Component
// public class AdyenNotificationAuthenticationProvider {
// @Resource(name = "baseStoreService")
// private BaseStoreService baseStoreService;
//
// @Resource(name = "baseSiteService")
// private BaseSiteService baseSiteService;
//
// private static final Logger LOG = Logger.getLogger(AdyenNotificationAuthenticationProvider.class);
//
// public boolean authenticateBasic(final HttpServletRequest request, String baseSiteId) {
// final String authorization = request.getHeader("Authorization");
// if (authorization != null && authorization.startsWith("Basic")) {
// String base64Credentials = authorization.substring("Basic".length()).trim();
// String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
// final String[] values = credentials.split(":", 2);
// return tryToAuthenticate(values[0], values[1], baseSiteId);
// }
// return false;
// }
//
// private boolean tryToAuthenticate(String name, String password, String baseSiteId) {
//
// LOG.debug("Trying to authenticate for baseSiteId " + baseSiteId);
// final BaseSiteModel requestedBaseSite = getBaseSiteService().getBaseSiteForUID(baseSiteId);
// if (requestedBaseSite != null) {
// final BaseSiteModel currentBaseSite = getBaseSiteService().getCurrentBaseSite();
//
// if (! requestedBaseSite.equals(currentBaseSite)) {
// getBaseSiteService().setCurrentBaseSite(requestedBaseSite, true);
// }
// }
// BaseStoreModel baseStore = baseStoreService.getCurrentBaseStore();
//
// if (baseStore == null) {
// return false;
// }
//
// String notificationUsername = baseStore.getAdyenNotificationUsername();
// String notificationPassword = baseStore.getAdyenNotificationPassword();
//
// Assert.notNull(notificationUsername);
// Assert.notNull(notificationPassword);
//
// if (notificationUsername.isEmpty() || notificationPassword.isEmpty()) {
// return false;
// }
//
// if (notificationUsername.equals(name) && notificationPassword.equals(password)) {
// return true;
// }
//
// return false;
// }
//
// public BaseStoreService getBaseStoreService() {
// return baseStoreService;
// }
//
// protected BaseSiteService getBaseSiteService() {
// return baseSiteService;
// }
//
// public void setBaseStoreService(BaseStoreService baseStoreService) {
// this.baseStoreService = baseStoreService;
// }
// }
//
// Path: adyenv6core/src/com/adyen/v6/service/AdyenNotificationService.java
// public interface AdyenNotificationService {
//
// /**
// * Process NotificationItemModel
// * Handles multiple eventCodes
// */
// void processNotification(NotificationItemModel notificationItemModel);
//
// /**
// * Parse HTTP request body and save NotificationItemModels
// */
// void saveNotifications(String requestString);
//
// /**
// * Create NotificationItemModel from NotificationRequestItem
// */
// NotificationItemModel createFromNotificationRequest(NotificationRequestItem notificationRequestItem);
//
// /**
// * Save NotificationItemModel from NotificationRequestItem
// */
// void saveFromNotificationRequest(NotificationRequestItem notificationRequestItem);
//
// /**
// * Process notification with eventCode=CAPTURED
// */
// PaymentTransactionEntryModel processCapturedEvent(NotificationItemModel notificationItemModel, PaymentTransactionModel paymentTransactionModel);
//
// /**
// * Process notification with eventCode=AUTHORISED
// */
// PaymentTransactionModel processAuthorisationEvent(NotificationItemModel notificationItemModel);
//
// /**
// * Process notification with eventCode=CANCEL_OR_REFUND
// */
// PaymentTransactionEntryModel processCancelEvent(NotificationItemModel notificationItemModel, PaymentTransactionModel paymentTransactionModel);
//
// /**
// * Process notification with eventCode=REFUND
// */
// PaymentTransactionEntryModel processRefundEvent(NotificationItemModel notificationItem);
//
// /**
// * Process notification with eventCode=OFFER_CLOSED
// * @return
// */
// PaymentTransactionModel processOfferClosedEvent(NotificationItemModel notificationItem);
//
// }
// Path: adyenv6notification/web/src/com/adyen/v6/controllers/AdyenNotificationController.java
import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.adyen.v6.security.AdyenNotificationAuthenticationProvider;
import com.adyen.v6.service.AdyenNotificationService;
/*
* [y] hybris Platform
*
* Copyright (c) 2017 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package com.adyen.v6.controllers;
@Controller
@RequestMapping(value = "/adyen/v6/notification/{baseSiteId}")
public class AdyenNotificationController {
private static final Logger LOG = Logger.getLogger(AdyenNotificationController.class);
@Resource(name = "adyenNotificationAuthenticationProvider") | private AdyenNotificationAuthenticationProvider adyenNotificationAuthenticationProvider; |
Adyen/adyen-hybris | adyenv6notification/web/src/com/adyen/v6/controllers/AdyenNotificationController.java | // Path: adyenv6notification/src/com/adyen/v6/security/AdyenNotificationAuthenticationProvider.java
// @Component
// public class AdyenNotificationAuthenticationProvider {
// @Resource(name = "baseStoreService")
// private BaseStoreService baseStoreService;
//
// @Resource(name = "baseSiteService")
// private BaseSiteService baseSiteService;
//
// private static final Logger LOG = Logger.getLogger(AdyenNotificationAuthenticationProvider.class);
//
// public boolean authenticateBasic(final HttpServletRequest request, String baseSiteId) {
// final String authorization = request.getHeader("Authorization");
// if (authorization != null && authorization.startsWith("Basic")) {
// String base64Credentials = authorization.substring("Basic".length()).trim();
// String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
// final String[] values = credentials.split(":", 2);
// return tryToAuthenticate(values[0], values[1], baseSiteId);
// }
// return false;
// }
//
// private boolean tryToAuthenticate(String name, String password, String baseSiteId) {
//
// LOG.debug("Trying to authenticate for baseSiteId " + baseSiteId);
// final BaseSiteModel requestedBaseSite = getBaseSiteService().getBaseSiteForUID(baseSiteId);
// if (requestedBaseSite != null) {
// final BaseSiteModel currentBaseSite = getBaseSiteService().getCurrentBaseSite();
//
// if (! requestedBaseSite.equals(currentBaseSite)) {
// getBaseSiteService().setCurrentBaseSite(requestedBaseSite, true);
// }
// }
// BaseStoreModel baseStore = baseStoreService.getCurrentBaseStore();
//
// if (baseStore == null) {
// return false;
// }
//
// String notificationUsername = baseStore.getAdyenNotificationUsername();
// String notificationPassword = baseStore.getAdyenNotificationPassword();
//
// Assert.notNull(notificationUsername);
// Assert.notNull(notificationPassword);
//
// if (notificationUsername.isEmpty() || notificationPassword.isEmpty()) {
// return false;
// }
//
// if (notificationUsername.equals(name) && notificationPassword.equals(password)) {
// return true;
// }
//
// return false;
// }
//
// public BaseStoreService getBaseStoreService() {
// return baseStoreService;
// }
//
// protected BaseSiteService getBaseSiteService() {
// return baseSiteService;
// }
//
// public void setBaseStoreService(BaseStoreService baseStoreService) {
// this.baseStoreService = baseStoreService;
// }
// }
//
// Path: adyenv6core/src/com/adyen/v6/service/AdyenNotificationService.java
// public interface AdyenNotificationService {
//
// /**
// * Process NotificationItemModel
// * Handles multiple eventCodes
// */
// void processNotification(NotificationItemModel notificationItemModel);
//
// /**
// * Parse HTTP request body and save NotificationItemModels
// */
// void saveNotifications(String requestString);
//
// /**
// * Create NotificationItemModel from NotificationRequestItem
// */
// NotificationItemModel createFromNotificationRequest(NotificationRequestItem notificationRequestItem);
//
// /**
// * Save NotificationItemModel from NotificationRequestItem
// */
// void saveFromNotificationRequest(NotificationRequestItem notificationRequestItem);
//
// /**
// * Process notification with eventCode=CAPTURED
// */
// PaymentTransactionEntryModel processCapturedEvent(NotificationItemModel notificationItemModel, PaymentTransactionModel paymentTransactionModel);
//
// /**
// * Process notification with eventCode=AUTHORISED
// */
// PaymentTransactionModel processAuthorisationEvent(NotificationItemModel notificationItemModel);
//
// /**
// * Process notification with eventCode=CANCEL_OR_REFUND
// */
// PaymentTransactionEntryModel processCancelEvent(NotificationItemModel notificationItemModel, PaymentTransactionModel paymentTransactionModel);
//
// /**
// * Process notification with eventCode=REFUND
// */
// PaymentTransactionEntryModel processRefundEvent(NotificationItemModel notificationItem);
//
// /**
// * Process notification with eventCode=OFFER_CLOSED
// * @return
// */
// PaymentTransactionModel processOfferClosedEvent(NotificationItemModel notificationItem);
//
// }
| import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.adyen.v6.security.AdyenNotificationAuthenticationProvider;
import com.adyen.v6.service.AdyenNotificationService; | /*
* [y] hybris Platform
*
* Copyright (c) 2017 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package com.adyen.v6.controllers;
@Controller
@RequestMapping(value = "/adyen/v6/notification/{baseSiteId}")
public class AdyenNotificationController {
private static final Logger LOG = Logger.getLogger(AdyenNotificationController.class);
@Resource(name = "adyenNotificationAuthenticationProvider")
private AdyenNotificationAuthenticationProvider adyenNotificationAuthenticationProvider;
@Resource(name = "adyenNotificationService") | // Path: adyenv6notification/src/com/adyen/v6/security/AdyenNotificationAuthenticationProvider.java
// @Component
// public class AdyenNotificationAuthenticationProvider {
// @Resource(name = "baseStoreService")
// private BaseStoreService baseStoreService;
//
// @Resource(name = "baseSiteService")
// private BaseSiteService baseSiteService;
//
// private static final Logger LOG = Logger.getLogger(AdyenNotificationAuthenticationProvider.class);
//
// public boolean authenticateBasic(final HttpServletRequest request, String baseSiteId) {
// final String authorization = request.getHeader("Authorization");
// if (authorization != null && authorization.startsWith("Basic")) {
// String base64Credentials = authorization.substring("Basic".length()).trim();
// String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
// final String[] values = credentials.split(":", 2);
// return tryToAuthenticate(values[0], values[1], baseSiteId);
// }
// return false;
// }
//
// private boolean tryToAuthenticate(String name, String password, String baseSiteId) {
//
// LOG.debug("Trying to authenticate for baseSiteId " + baseSiteId);
// final BaseSiteModel requestedBaseSite = getBaseSiteService().getBaseSiteForUID(baseSiteId);
// if (requestedBaseSite != null) {
// final BaseSiteModel currentBaseSite = getBaseSiteService().getCurrentBaseSite();
//
// if (! requestedBaseSite.equals(currentBaseSite)) {
// getBaseSiteService().setCurrentBaseSite(requestedBaseSite, true);
// }
// }
// BaseStoreModel baseStore = baseStoreService.getCurrentBaseStore();
//
// if (baseStore == null) {
// return false;
// }
//
// String notificationUsername = baseStore.getAdyenNotificationUsername();
// String notificationPassword = baseStore.getAdyenNotificationPassword();
//
// Assert.notNull(notificationUsername);
// Assert.notNull(notificationPassword);
//
// if (notificationUsername.isEmpty() || notificationPassword.isEmpty()) {
// return false;
// }
//
// if (notificationUsername.equals(name) && notificationPassword.equals(password)) {
// return true;
// }
//
// return false;
// }
//
// public BaseStoreService getBaseStoreService() {
// return baseStoreService;
// }
//
// protected BaseSiteService getBaseSiteService() {
// return baseSiteService;
// }
//
// public void setBaseStoreService(BaseStoreService baseStoreService) {
// this.baseStoreService = baseStoreService;
// }
// }
//
// Path: adyenv6core/src/com/adyen/v6/service/AdyenNotificationService.java
// public interface AdyenNotificationService {
//
// /**
// * Process NotificationItemModel
// * Handles multiple eventCodes
// */
// void processNotification(NotificationItemModel notificationItemModel);
//
// /**
// * Parse HTTP request body and save NotificationItemModels
// */
// void saveNotifications(String requestString);
//
// /**
// * Create NotificationItemModel from NotificationRequestItem
// */
// NotificationItemModel createFromNotificationRequest(NotificationRequestItem notificationRequestItem);
//
// /**
// * Save NotificationItemModel from NotificationRequestItem
// */
// void saveFromNotificationRequest(NotificationRequestItem notificationRequestItem);
//
// /**
// * Process notification with eventCode=CAPTURED
// */
// PaymentTransactionEntryModel processCapturedEvent(NotificationItemModel notificationItemModel, PaymentTransactionModel paymentTransactionModel);
//
// /**
// * Process notification with eventCode=AUTHORISED
// */
// PaymentTransactionModel processAuthorisationEvent(NotificationItemModel notificationItemModel);
//
// /**
// * Process notification with eventCode=CANCEL_OR_REFUND
// */
// PaymentTransactionEntryModel processCancelEvent(NotificationItemModel notificationItemModel, PaymentTransactionModel paymentTransactionModel);
//
// /**
// * Process notification with eventCode=REFUND
// */
// PaymentTransactionEntryModel processRefundEvent(NotificationItemModel notificationItem);
//
// /**
// * Process notification with eventCode=OFFER_CLOSED
// * @return
// */
// PaymentTransactionModel processOfferClosedEvent(NotificationItemModel notificationItem);
//
// }
// Path: adyenv6notification/web/src/com/adyen/v6/controllers/AdyenNotificationController.java
import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.adyen.v6.security.AdyenNotificationAuthenticationProvider;
import com.adyen.v6.service.AdyenNotificationService;
/*
* [y] hybris Platform
*
* Copyright (c) 2017 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package com.adyen.v6.controllers;
@Controller
@RequestMapping(value = "/adyen/v6/notification/{baseSiteId}")
public class AdyenNotificationController {
private static final Logger LOG = Logger.getLogger(AdyenNotificationController.class);
@Resource(name = "adyenNotificationAuthenticationProvider")
private AdyenNotificationAuthenticationProvider adyenNotificationAuthenticationProvider;
@Resource(name = "adyenNotificationService") | private AdyenNotificationService adyenNotificationService; |