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 |
|---|---|---|---|---|---|---|
DevOps-TangoMe/BucketSyncer | src/main/java/com/tango/BucketSyncer/DeleteMaster.java | // Path: src/main/java/com/tango/BucketSyncer/KeyJobs/KeyJob.java
// public abstract class KeyJob implements Runnable {
// protected final ObjectSummary summary;
// protected final Object notifyLock;
// protected final MirrorContext context;
//
//
// public KeyJob(ObjectSummary summary,
// Object notifyLock,
// MirrorContext context) {
// this.summary = summary;
// this.notifyLock = notifyLock;
// this.context = context;
// }
//
// @Override
// public String toString() {
// return summary.toString();
// }
//
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/KeyListers/KeyLister.java
// @Slf4j
// public abstract class KeyLister implements Runnable {
// protected MirrorContext context;
// protected Integer maxQueueCapacity;
// protected String bucket;
// protected String prefix;
//
// protected final AtomicBoolean done = new AtomicBoolean(false);
//
// public boolean isDone() {
// return done.get();
// }
//
// public KeyLister(String bucket,
// String prefix,
// MirrorContext context,
// Integer maxQueueCapacity) {
// this.bucket = bucket;
// this.prefix = prefix;
// this.context = context;
// this.maxQueueCapacity = maxQueueCapacity;
// }
//
// public abstract List<ObjectSummary> getNextBatch();
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/ObjectSummary.java
// public interface ObjectSummary {
// public String getKey();
//
// public long getSize();
//
// public Date getLastModified();
//
// public String getETag();
// }
| import com.tango.BucketSyncer.KeyJobs.KeyJob;
import com.tango.BucketSyncer.KeyListers.KeyLister;
import com.tango.BucketSyncer.ObjectSummaries.ObjectSummary;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor; | /**
* Copyright 2013 Jonathan Cobb
* Copyright 2014 TangoMe Inc.
*
* 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.tango.BucketSyncer;
@Slf4j
public class DeleteMaster extends KeyMaster {
public DeleteMaster(Object sourceClient, Object destClient, MirrorContext context, BlockingQueue<Runnable> workQueue, ThreadPoolExecutor executorService) {
super(sourceClient, destClient, context, workQueue, executorService);
}
protected String getPrefix(MirrorOptions options) {
return options.hasDestPrefix() ? options.getDestPrefix() : options.getPrefix();
}
protected String getBucket(MirrorOptions options) {
return options.getDestinationBucket();
}
| // Path: src/main/java/com/tango/BucketSyncer/KeyJobs/KeyJob.java
// public abstract class KeyJob implements Runnable {
// protected final ObjectSummary summary;
// protected final Object notifyLock;
// protected final MirrorContext context;
//
//
// public KeyJob(ObjectSummary summary,
// Object notifyLock,
// MirrorContext context) {
// this.summary = summary;
// this.notifyLock = notifyLock;
// this.context = context;
// }
//
// @Override
// public String toString() {
// return summary.toString();
// }
//
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/KeyListers/KeyLister.java
// @Slf4j
// public abstract class KeyLister implements Runnable {
// protected MirrorContext context;
// protected Integer maxQueueCapacity;
// protected String bucket;
// protected String prefix;
//
// protected final AtomicBoolean done = new AtomicBoolean(false);
//
// public boolean isDone() {
// return done.get();
// }
//
// public KeyLister(String bucket,
// String prefix,
// MirrorContext context,
// Integer maxQueueCapacity) {
// this.bucket = bucket;
// this.prefix = prefix;
// this.context = context;
// this.maxQueueCapacity = maxQueueCapacity;
// }
//
// public abstract List<ObjectSummary> getNextBatch();
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/ObjectSummary.java
// public interface ObjectSummary {
// public String getKey();
//
// public long getSize();
//
// public Date getLastModified();
//
// public String getETag();
// }
// Path: src/main/java/com/tango/BucketSyncer/DeleteMaster.java
import com.tango.BucketSyncer.KeyJobs.KeyJob;
import com.tango.BucketSyncer.KeyListers.KeyLister;
import com.tango.BucketSyncer.ObjectSummaries.ObjectSummary;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
/**
* Copyright 2013 Jonathan Cobb
* Copyright 2014 TangoMe Inc.
*
* 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.tango.BucketSyncer;
@Slf4j
public class DeleteMaster extends KeyMaster {
public DeleteMaster(Object sourceClient, Object destClient, MirrorContext context, BlockingQueue<Runnable> workQueue, ThreadPoolExecutor executorService) {
super(sourceClient, destClient, context, workQueue, executorService);
}
protected String getPrefix(MirrorOptions options) {
return options.hasDestPrefix() ? options.getDestPrefix() : options.getPrefix();
}
protected String getBucket(MirrorOptions options) {
return options.getDestinationBucket();
}
| protected KeyLister getKeyLister(MirrorOptions options) { |
DevOps-TangoMe/BucketSyncer | src/main/java/com/tango/BucketSyncer/DeleteMaster.java | // Path: src/main/java/com/tango/BucketSyncer/KeyJobs/KeyJob.java
// public abstract class KeyJob implements Runnable {
// protected final ObjectSummary summary;
// protected final Object notifyLock;
// protected final MirrorContext context;
//
//
// public KeyJob(ObjectSummary summary,
// Object notifyLock,
// MirrorContext context) {
// this.summary = summary;
// this.notifyLock = notifyLock;
// this.context = context;
// }
//
// @Override
// public String toString() {
// return summary.toString();
// }
//
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/KeyListers/KeyLister.java
// @Slf4j
// public abstract class KeyLister implements Runnable {
// protected MirrorContext context;
// protected Integer maxQueueCapacity;
// protected String bucket;
// protected String prefix;
//
// protected final AtomicBoolean done = new AtomicBoolean(false);
//
// public boolean isDone() {
// return done.get();
// }
//
// public KeyLister(String bucket,
// String prefix,
// MirrorContext context,
// Integer maxQueueCapacity) {
// this.bucket = bucket;
// this.prefix = prefix;
// this.context = context;
// this.maxQueueCapacity = maxQueueCapacity;
// }
//
// public abstract List<ObjectSummary> getNextBatch();
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/ObjectSummary.java
// public interface ObjectSummary {
// public String getKey();
//
// public long getSize();
//
// public Date getLastModified();
//
// public String getETag();
// }
| import com.tango.BucketSyncer.KeyJobs.KeyJob;
import com.tango.BucketSyncer.KeyListers.KeyLister;
import com.tango.BucketSyncer.ObjectSummaries.ObjectSummary;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor; | log.error("Classname for KEY_LISTER {} is not found: {}", className, e);
}
Constructor<?> constructor = null;
try {
constructor = clazz.getConstructor(Object.class,
String.class,
String.class,
MirrorContext.class,
Integer.class);
} catch (NoSuchMethodException e) {
log.error("Failed to find corresponding KEY_LISTER constructor: ", e);
}
try {
return (KeyLister) constructor
.newInstance(destClient,
getBucket(options),
getPrefix(options),
context,
MirrorMaster.getMaxQueueCapacity(options));
} catch (InstantiationException e) {
log.error("Failed to instantiate KEY_LISTER: ", e);
} catch (IllegalAccessException e) {
log.error("Failed to access KEY_LISTER: ", e);
} catch (InvocationTargetException e) {
log.error("Failed to invocate KEY_LISTER: ", e);
}
return null;
}
| // Path: src/main/java/com/tango/BucketSyncer/KeyJobs/KeyJob.java
// public abstract class KeyJob implements Runnable {
// protected final ObjectSummary summary;
// protected final Object notifyLock;
// protected final MirrorContext context;
//
//
// public KeyJob(ObjectSummary summary,
// Object notifyLock,
// MirrorContext context) {
// this.summary = summary;
// this.notifyLock = notifyLock;
// this.context = context;
// }
//
// @Override
// public String toString() {
// return summary.toString();
// }
//
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/KeyListers/KeyLister.java
// @Slf4j
// public abstract class KeyLister implements Runnable {
// protected MirrorContext context;
// protected Integer maxQueueCapacity;
// protected String bucket;
// protected String prefix;
//
// protected final AtomicBoolean done = new AtomicBoolean(false);
//
// public boolean isDone() {
// return done.get();
// }
//
// public KeyLister(String bucket,
// String prefix,
// MirrorContext context,
// Integer maxQueueCapacity) {
// this.bucket = bucket;
// this.prefix = prefix;
// this.context = context;
// this.maxQueueCapacity = maxQueueCapacity;
// }
//
// public abstract List<ObjectSummary> getNextBatch();
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/ObjectSummary.java
// public interface ObjectSummary {
// public String getKey();
//
// public long getSize();
//
// public Date getLastModified();
//
// public String getETag();
// }
// Path: src/main/java/com/tango/BucketSyncer/DeleteMaster.java
import com.tango.BucketSyncer.KeyJobs.KeyJob;
import com.tango.BucketSyncer.KeyListers.KeyLister;
import com.tango.BucketSyncer.ObjectSummaries.ObjectSummary;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
log.error("Classname for KEY_LISTER {} is not found: {}", className, e);
}
Constructor<?> constructor = null;
try {
constructor = clazz.getConstructor(Object.class,
String.class,
String.class,
MirrorContext.class,
Integer.class);
} catch (NoSuchMethodException e) {
log.error("Failed to find corresponding KEY_LISTER constructor: ", e);
}
try {
return (KeyLister) constructor
.newInstance(destClient,
getBucket(options),
getPrefix(options),
context,
MirrorMaster.getMaxQueueCapacity(options));
} catch (InstantiationException e) {
log.error("Failed to instantiate KEY_LISTER: ", e);
} catch (IllegalAccessException e) {
log.error("Failed to access KEY_LISTER: ", e);
} catch (InvocationTargetException e) {
log.error("Failed to invocate KEY_LISTER: ", e);
}
return null;
}
| protected KeyJob getTask(ObjectSummary summary) { |
DevOps-TangoMe/BucketSyncer | src/main/java/com/tango/BucketSyncer/DeleteMaster.java | // Path: src/main/java/com/tango/BucketSyncer/KeyJobs/KeyJob.java
// public abstract class KeyJob implements Runnable {
// protected final ObjectSummary summary;
// protected final Object notifyLock;
// protected final MirrorContext context;
//
//
// public KeyJob(ObjectSummary summary,
// Object notifyLock,
// MirrorContext context) {
// this.summary = summary;
// this.notifyLock = notifyLock;
// this.context = context;
// }
//
// @Override
// public String toString() {
// return summary.toString();
// }
//
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/KeyListers/KeyLister.java
// @Slf4j
// public abstract class KeyLister implements Runnable {
// protected MirrorContext context;
// protected Integer maxQueueCapacity;
// protected String bucket;
// protected String prefix;
//
// protected final AtomicBoolean done = new AtomicBoolean(false);
//
// public boolean isDone() {
// return done.get();
// }
//
// public KeyLister(String bucket,
// String prefix,
// MirrorContext context,
// Integer maxQueueCapacity) {
// this.bucket = bucket;
// this.prefix = prefix;
// this.context = context;
// this.maxQueueCapacity = maxQueueCapacity;
// }
//
// public abstract List<ObjectSummary> getNextBatch();
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/ObjectSummary.java
// public interface ObjectSummary {
// public String getKey();
//
// public long getSize();
//
// public Date getLastModified();
//
// public String getETag();
// }
| import com.tango.BucketSyncer.KeyJobs.KeyJob;
import com.tango.BucketSyncer.KeyListers.KeyLister;
import com.tango.BucketSyncer.ObjectSummaries.ObjectSummary;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor; | log.error("Classname for KEY_LISTER {} is not found: {}", className, e);
}
Constructor<?> constructor = null;
try {
constructor = clazz.getConstructor(Object.class,
String.class,
String.class,
MirrorContext.class,
Integer.class);
} catch (NoSuchMethodException e) {
log.error("Failed to find corresponding KEY_LISTER constructor: ", e);
}
try {
return (KeyLister) constructor
.newInstance(destClient,
getBucket(options),
getPrefix(options),
context,
MirrorMaster.getMaxQueueCapacity(options));
} catch (InstantiationException e) {
log.error("Failed to instantiate KEY_LISTER: ", e);
} catch (IllegalAccessException e) {
log.error("Failed to access KEY_LISTER: ", e);
} catch (InvocationTargetException e) {
log.error("Failed to invocate KEY_LISTER: ", e);
}
return null;
}
| // Path: src/main/java/com/tango/BucketSyncer/KeyJobs/KeyJob.java
// public abstract class KeyJob implements Runnable {
// protected final ObjectSummary summary;
// protected final Object notifyLock;
// protected final MirrorContext context;
//
//
// public KeyJob(ObjectSummary summary,
// Object notifyLock,
// MirrorContext context) {
// this.summary = summary;
// this.notifyLock = notifyLock;
// this.context = context;
// }
//
// @Override
// public String toString() {
// return summary.toString();
// }
//
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/KeyListers/KeyLister.java
// @Slf4j
// public abstract class KeyLister implements Runnable {
// protected MirrorContext context;
// protected Integer maxQueueCapacity;
// protected String bucket;
// protected String prefix;
//
// protected final AtomicBoolean done = new AtomicBoolean(false);
//
// public boolean isDone() {
// return done.get();
// }
//
// public KeyLister(String bucket,
// String prefix,
// MirrorContext context,
// Integer maxQueueCapacity) {
// this.bucket = bucket;
// this.prefix = prefix;
// this.context = context;
// this.maxQueueCapacity = maxQueueCapacity;
// }
//
// public abstract List<ObjectSummary> getNextBatch();
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/ObjectSummary.java
// public interface ObjectSummary {
// public String getKey();
//
// public long getSize();
//
// public Date getLastModified();
//
// public String getETag();
// }
// Path: src/main/java/com/tango/BucketSyncer/DeleteMaster.java
import com.tango.BucketSyncer.KeyJobs.KeyJob;
import com.tango.BucketSyncer.KeyListers.KeyLister;
import com.tango.BucketSyncer.ObjectSummaries.ObjectSummary;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
log.error("Classname for KEY_LISTER {} is not found: {}", className, e);
}
Constructor<?> constructor = null;
try {
constructor = clazz.getConstructor(Object.class,
String.class,
String.class,
MirrorContext.class,
Integer.class);
} catch (NoSuchMethodException e) {
log.error("Failed to find corresponding KEY_LISTER constructor: ", e);
}
try {
return (KeyLister) constructor
.newInstance(destClient,
getBucket(options),
getPrefix(options),
context,
MirrorMaster.getMaxQueueCapacity(options));
} catch (InstantiationException e) {
log.error("Failed to instantiate KEY_LISTER: ", e);
} catch (IllegalAccessException e) {
log.error("Failed to access KEY_LISTER: ", e);
} catch (InvocationTargetException e) {
log.error("Failed to invocate KEY_LISTER: ", e);
}
return null;
}
| protected KeyJob getTask(ObjectSummary summary) { |
DevOps-TangoMe/BucketSyncer | src/main/java/com/tango/BucketSyncer/KeyListers/S3KeyLister.java | // Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/ObjectSummary.java
// public interface ObjectSummary {
// public String getKey();
//
// public long getSize();
//
// public Date getLastModified();
//
// public String getETag();
// }
//
// Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/S3_ObjectSummary.java
// public class S3_ObjectSummary implements ObjectSummary {
// S3ObjectSummary s3ObjectSummary;
//
// public S3_ObjectSummary(S3ObjectSummary s3ObjectSummary) {
// this.s3ObjectSummary = s3ObjectSummary;
// }
//
// @Override
// public String getKey() {
// return s3ObjectSummary.getKey();
// }
//
// @Override
// public long getSize() {
// return s3ObjectSummary.getSize();
// }
//
// @Override
// public Date getLastModified() {
// return s3ObjectSummary.getLastModified();
// }
//
// @Override
// public String getETag() {
// return s3ObjectSummary.getETag();
// }
// }
| import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import com.tango.BucketSyncer.*;
import com.tango.BucketSyncer.ObjectSummaries.ObjectSummary;
import com.tango.BucketSyncer.ObjectSummaries.S3_ObjectSummary;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import java.util.ArrayList;
import java.util.List; | }
if (Sleep.sleep(50)) {
log.info("s3GetNextBatch: interrupted while waiting for next try");
break;
}
}
if(next != null){
return next;
}else {
throw new IllegalStateException(String.format("Too many errors trying to list objects (maxRetries= %d)", maxRetries));
}
}
private int getSize() {
synchronized (summaries) {
return summaries.size();
}
}
private List<S3ObjectSummary> getNextBatchOfS3ObjectSummary() {
List<S3ObjectSummary> copy;
synchronized (summaries) {
copy = new ArrayList<S3ObjectSummary>(summaries);
summaries.clear();
}
return copy;
}
| // Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/ObjectSummary.java
// public interface ObjectSummary {
// public String getKey();
//
// public long getSize();
//
// public Date getLastModified();
//
// public String getETag();
// }
//
// Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/S3_ObjectSummary.java
// public class S3_ObjectSummary implements ObjectSummary {
// S3ObjectSummary s3ObjectSummary;
//
// public S3_ObjectSummary(S3ObjectSummary s3ObjectSummary) {
// this.s3ObjectSummary = s3ObjectSummary;
// }
//
// @Override
// public String getKey() {
// return s3ObjectSummary.getKey();
// }
//
// @Override
// public long getSize() {
// return s3ObjectSummary.getSize();
// }
//
// @Override
// public Date getLastModified() {
// return s3ObjectSummary.getLastModified();
// }
//
// @Override
// public String getETag() {
// return s3ObjectSummary.getETag();
// }
// }
// Path: src/main/java/com/tango/BucketSyncer/KeyListers/S3KeyLister.java
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import com.tango.BucketSyncer.*;
import com.tango.BucketSyncer.ObjectSummaries.ObjectSummary;
import com.tango.BucketSyncer.ObjectSummaries.S3_ObjectSummary;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import java.util.ArrayList;
import java.util.List;
}
if (Sleep.sleep(50)) {
log.info("s3GetNextBatch: interrupted while waiting for next try");
break;
}
}
if(next != null){
return next;
}else {
throw new IllegalStateException(String.format("Too many errors trying to list objects (maxRetries= %d)", maxRetries));
}
}
private int getSize() {
synchronized (summaries) {
return summaries.size();
}
}
private List<S3ObjectSummary> getNextBatchOfS3ObjectSummary() {
List<S3ObjectSummary> copy;
synchronized (summaries) {
copy = new ArrayList<S3ObjectSummary>(summaries);
summaries.clear();
}
return copy;
}
| public List<ObjectSummary> getNextBatch() { |
DevOps-TangoMe/BucketSyncer | src/main/java/com/tango/BucketSyncer/KeyListers/S3KeyLister.java | // Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/ObjectSummary.java
// public interface ObjectSummary {
// public String getKey();
//
// public long getSize();
//
// public Date getLastModified();
//
// public String getETag();
// }
//
// Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/S3_ObjectSummary.java
// public class S3_ObjectSummary implements ObjectSummary {
// S3ObjectSummary s3ObjectSummary;
//
// public S3_ObjectSummary(S3ObjectSummary s3ObjectSummary) {
// this.s3ObjectSummary = s3ObjectSummary;
// }
//
// @Override
// public String getKey() {
// return s3ObjectSummary.getKey();
// }
//
// @Override
// public long getSize() {
// return s3ObjectSummary.getSize();
// }
//
// @Override
// public Date getLastModified() {
// return s3ObjectSummary.getLastModified();
// }
//
// @Override
// public String getETag() {
// return s3ObjectSummary.getETag();
// }
// }
| import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import com.tango.BucketSyncer.*;
import com.tango.BucketSyncer.ObjectSummaries.ObjectSummary;
import com.tango.BucketSyncer.ObjectSummaries.S3_ObjectSummary;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import java.util.ArrayList;
import java.util.List; | if(next != null){
return next;
}else {
throw new IllegalStateException(String.format("Too many errors trying to list objects (maxRetries= %d)", maxRetries));
}
}
private int getSize() {
synchronized (summaries) {
return summaries.size();
}
}
private List<S3ObjectSummary> getNextBatchOfS3ObjectSummary() {
List<S3ObjectSummary> copy;
synchronized (summaries) {
copy = new ArrayList<S3ObjectSummary>(summaries);
summaries.clear();
}
return copy;
}
public List<ObjectSummary> getNextBatch() {
List<S3ObjectSummary> s3ObjectSummaries = getNextBatchOfS3ObjectSummary();
List<ObjectSummary> objectSummaries = new ArrayList<ObjectSummary>(s3ObjectSummaries.size());
for (S3ObjectSummary s3ObjectSummary : s3ObjectSummaries) { | // Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/ObjectSummary.java
// public interface ObjectSummary {
// public String getKey();
//
// public long getSize();
//
// public Date getLastModified();
//
// public String getETag();
// }
//
// Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/S3_ObjectSummary.java
// public class S3_ObjectSummary implements ObjectSummary {
// S3ObjectSummary s3ObjectSummary;
//
// public S3_ObjectSummary(S3ObjectSummary s3ObjectSummary) {
// this.s3ObjectSummary = s3ObjectSummary;
// }
//
// @Override
// public String getKey() {
// return s3ObjectSummary.getKey();
// }
//
// @Override
// public long getSize() {
// return s3ObjectSummary.getSize();
// }
//
// @Override
// public Date getLastModified() {
// return s3ObjectSummary.getLastModified();
// }
//
// @Override
// public String getETag() {
// return s3ObjectSummary.getETag();
// }
// }
// Path: src/main/java/com/tango/BucketSyncer/KeyListers/S3KeyLister.java
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import com.tango.BucketSyncer.*;
import com.tango.BucketSyncer.ObjectSummaries.ObjectSummary;
import com.tango.BucketSyncer.ObjectSummaries.S3_ObjectSummary;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import java.util.ArrayList;
import java.util.List;
if(next != null){
return next;
}else {
throw new IllegalStateException(String.format("Too many errors trying to list objects (maxRetries= %d)", maxRetries));
}
}
private int getSize() {
synchronized (summaries) {
return summaries.size();
}
}
private List<S3ObjectSummary> getNextBatchOfS3ObjectSummary() {
List<S3ObjectSummary> copy;
synchronized (summaries) {
copy = new ArrayList<S3ObjectSummary>(summaries);
summaries.clear();
}
return copy;
}
public List<ObjectSummary> getNextBatch() {
List<S3ObjectSummary> s3ObjectSummaries = getNextBatchOfS3ObjectSummary();
List<ObjectSummary> objectSummaries = new ArrayList<ObjectSummary>(s3ObjectSummaries.size());
for (S3ObjectSummary s3ObjectSummary : s3ObjectSummaries) { | objectSummaries.add(new S3_ObjectSummary(s3ObjectSummary)); |
DevOps-TangoMe/BucketSyncer | src/main/java/com/tango/BucketSyncer/MirrorMain.java | // Path: src/main/java/com/tango/BucketSyncer/StorageClients/StorageClient.java
// public interface StorageClient {
//
// Object getClient(MirrorOptions options);
// }
| import com.google.api.client.repackaged.com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;
import com.tango.BucketSyncer.StorageClients.StorageClient;
import lombok.Cleanup;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.kohsuke.args4j.CmdLineParser;
import java.io.*; | options.setAWSSecretKey(line.substring(line.indexOf("=") + 1).trim());
} else if (!options.getHasProxy() && line.trim().startsWith("proxy_host")) {
options.setProxyHost(line.substring(line.indexOf("=") + 1).trim());
} else if (!options.getHasProxy() && line.trim().startsWith("proxy_port")){
options.setProxyPort(Integer.parseInt(line.substring(line.indexOf("=") + 1).trim()));
}
}
}
if (!options.hasAwsKeys()) {
throw new IllegalStateException("ENV vars not defined: " + MirrorOptions.AWS_ACCESS_KEY + " and/or " + MirrorOptions.AWS_SECRET_KEY);
}
options.initDerivedFields();
}
protected Object getSourceClient(MirrorOptions options) {
String name = options.getSrcStore().toString().toUpperCase();
String clientName = String.format("%s%s", name, MirrorConstants.CLIENT);
String packageName = this.getClass().getPackage().getName();
String className = String.format("%s.%s.%s", packageName, MirrorConstants.STORAGE_CLIENT,clientName);
Class<?> clazz = null;
try {
clazz = Class.forName(className);
} catch (ClassNotFoundException e) {
log.error("Classname for SourceClient {} is not found. It is possible that this storage client has not been implemented as SourceClient: {}", className, e);
Throwables.propagate(e);
} | // Path: src/main/java/com/tango/BucketSyncer/StorageClients/StorageClient.java
// public interface StorageClient {
//
// Object getClient(MirrorOptions options);
// }
// Path: src/main/java/com/tango/BucketSyncer/MirrorMain.java
import com.google.api.client.repackaged.com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;
import com.tango.BucketSyncer.StorageClients.StorageClient;
import lombok.Cleanup;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.kohsuke.args4j.CmdLineParser;
import java.io.*;
options.setAWSSecretKey(line.substring(line.indexOf("=") + 1).trim());
} else if (!options.getHasProxy() && line.trim().startsWith("proxy_host")) {
options.setProxyHost(line.substring(line.indexOf("=") + 1).trim());
} else if (!options.getHasProxy() && line.trim().startsWith("proxy_port")){
options.setProxyPort(Integer.parseInt(line.substring(line.indexOf("=") + 1).trim()));
}
}
}
if (!options.hasAwsKeys()) {
throw new IllegalStateException("ENV vars not defined: " + MirrorOptions.AWS_ACCESS_KEY + " and/or " + MirrorOptions.AWS_SECRET_KEY);
}
options.initDerivedFields();
}
protected Object getSourceClient(MirrorOptions options) {
String name = options.getSrcStore().toString().toUpperCase();
String clientName = String.format("%s%s", name, MirrorConstants.CLIENT);
String packageName = this.getClass().getPackage().getName();
String className = String.format("%s.%s.%s", packageName, MirrorConstants.STORAGE_CLIENT,clientName);
Class<?> clazz = null;
try {
clazz = Class.forName(className);
} catch (ClassNotFoundException e) {
log.error("Classname for SourceClient {} is not found. It is possible that this storage client has not been implemented as SourceClient: {}", className, e);
Throwables.propagate(e);
} | StorageClient client = null; |
DevOps-TangoMe/BucketSyncer | src/main/java/com/tango/BucketSyncer/CopyMaster.java | // Path: src/main/java/com/tango/BucketSyncer/KeyJobs/KeyJob.java
// public abstract class KeyJob implements Runnable {
// protected final ObjectSummary summary;
// protected final Object notifyLock;
// protected final MirrorContext context;
//
//
// public KeyJob(ObjectSummary summary,
// Object notifyLock,
// MirrorContext context) {
// this.summary = summary;
// this.notifyLock = notifyLock;
// this.context = context;
// }
//
// @Override
// public String toString() {
// return summary.toString();
// }
//
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/KeyListers/KeyLister.java
// @Slf4j
// public abstract class KeyLister implements Runnable {
// protected MirrorContext context;
// protected Integer maxQueueCapacity;
// protected String bucket;
// protected String prefix;
//
// protected final AtomicBoolean done = new AtomicBoolean(false);
//
// public boolean isDone() {
// return done.get();
// }
//
// public KeyLister(String bucket,
// String prefix,
// MirrorContext context,
// Integer maxQueueCapacity) {
// this.bucket = bucket;
// this.prefix = prefix;
// this.context = context;
// this.maxQueueCapacity = maxQueueCapacity;
// }
//
// public abstract List<ObjectSummary> getNextBatch();
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/ObjectSummary.java
// public interface ObjectSummary {
// public String getKey();
//
// public long getSize();
//
// public Date getLastModified();
//
// public String getETag();
// }
| import com.tango.BucketSyncer.KeyJobs.KeyJob;
import com.tango.BucketSyncer.KeyListers.KeyLister;
import com.tango.BucketSyncer.ObjectSummaries.ObjectSummary;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor; | /**
* Copyright 2013 Jonathan Cobb
* Copyright 2014 TangoMe Inc.
*
* 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.tango.BucketSyncer;
@Slf4j
public class CopyMaster extends KeyMaster {
public CopyMaster(Object sourceClient, Object destClient, BlockingQueue<Runnable> workQueue, ThreadPoolExecutor executorService, MirrorContext context) {
super(sourceClient, destClient, context, workQueue, executorService);
}
protected String getPrefix(MirrorOptions options) {
return options.getPrefix();
}
protected String getBucket(MirrorOptions options) {
return options.getSourceBucket();
}
| // Path: src/main/java/com/tango/BucketSyncer/KeyJobs/KeyJob.java
// public abstract class KeyJob implements Runnable {
// protected final ObjectSummary summary;
// protected final Object notifyLock;
// protected final MirrorContext context;
//
//
// public KeyJob(ObjectSummary summary,
// Object notifyLock,
// MirrorContext context) {
// this.summary = summary;
// this.notifyLock = notifyLock;
// this.context = context;
// }
//
// @Override
// public String toString() {
// return summary.toString();
// }
//
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/KeyListers/KeyLister.java
// @Slf4j
// public abstract class KeyLister implements Runnable {
// protected MirrorContext context;
// protected Integer maxQueueCapacity;
// protected String bucket;
// protected String prefix;
//
// protected final AtomicBoolean done = new AtomicBoolean(false);
//
// public boolean isDone() {
// return done.get();
// }
//
// public KeyLister(String bucket,
// String prefix,
// MirrorContext context,
// Integer maxQueueCapacity) {
// this.bucket = bucket;
// this.prefix = prefix;
// this.context = context;
// this.maxQueueCapacity = maxQueueCapacity;
// }
//
// public abstract List<ObjectSummary> getNextBatch();
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/ObjectSummary.java
// public interface ObjectSummary {
// public String getKey();
//
// public long getSize();
//
// public Date getLastModified();
//
// public String getETag();
// }
// Path: src/main/java/com/tango/BucketSyncer/CopyMaster.java
import com.tango.BucketSyncer.KeyJobs.KeyJob;
import com.tango.BucketSyncer.KeyListers.KeyLister;
import com.tango.BucketSyncer.ObjectSummaries.ObjectSummary;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
/**
* Copyright 2013 Jonathan Cobb
* Copyright 2014 TangoMe Inc.
*
* 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.tango.BucketSyncer;
@Slf4j
public class CopyMaster extends KeyMaster {
public CopyMaster(Object sourceClient, Object destClient, BlockingQueue<Runnable> workQueue, ThreadPoolExecutor executorService, MirrorContext context) {
super(sourceClient, destClient, context, workQueue, executorService);
}
protected String getPrefix(MirrorOptions options) {
return options.getPrefix();
}
protected String getBucket(MirrorOptions options) {
return options.getSourceBucket();
}
| protected KeyLister getKeyLister(MirrorOptions options) { |
DevOps-TangoMe/BucketSyncer | src/main/java/com/tango/BucketSyncer/CopyMaster.java | // Path: src/main/java/com/tango/BucketSyncer/KeyJobs/KeyJob.java
// public abstract class KeyJob implements Runnable {
// protected final ObjectSummary summary;
// protected final Object notifyLock;
// protected final MirrorContext context;
//
//
// public KeyJob(ObjectSummary summary,
// Object notifyLock,
// MirrorContext context) {
// this.summary = summary;
// this.notifyLock = notifyLock;
// this.context = context;
// }
//
// @Override
// public String toString() {
// return summary.toString();
// }
//
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/KeyListers/KeyLister.java
// @Slf4j
// public abstract class KeyLister implements Runnable {
// protected MirrorContext context;
// protected Integer maxQueueCapacity;
// protected String bucket;
// protected String prefix;
//
// protected final AtomicBoolean done = new AtomicBoolean(false);
//
// public boolean isDone() {
// return done.get();
// }
//
// public KeyLister(String bucket,
// String prefix,
// MirrorContext context,
// Integer maxQueueCapacity) {
// this.bucket = bucket;
// this.prefix = prefix;
// this.context = context;
// this.maxQueueCapacity = maxQueueCapacity;
// }
//
// public abstract List<ObjectSummary> getNextBatch();
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/ObjectSummary.java
// public interface ObjectSummary {
// public String getKey();
//
// public long getSize();
//
// public Date getLastModified();
//
// public String getETag();
// }
| import com.tango.BucketSyncer.KeyJobs.KeyJob;
import com.tango.BucketSyncer.KeyListers.KeyLister;
import com.tango.BucketSyncer.ObjectSummaries.ObjectSummary;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor; | clazz = (Class<? extends KeyLister>) Class.forName(className);
} catch (ClassNotFoundException e) {
log.error("Classname for KEY_LISTER {} is not found: {}", className, e);
}
Constructor<?> constructor = null;
try {
constructor = clazz.getConstructor(Object.class,
String.class,
String.class,
MirrorContext.class,
Integer.class);
} catch (NoSuchMethodException e) {
log.error("Failed to find corresponding KEY_LISTER constructor: ", e);
}
try {
return (KeyLister) constructor.newInstance(sourceClient, getBucket(options),
getPrefix(options),
context,
MirrorMaster.getMaxQueueCapacity(options));
} catch (InstantiationException e) {
log.error("Failed to instantiate KEY_LISTER: ", e);
} catch (IllegalAccessException e) {
log.error("Failed to access KEY_LISTER: ", e);
} catch (InvocationTargetException e) {
log.error("Failed to invocate KEY_LISTER: ", e);
}
return null;
}
| // Path: src/main/java/com/tango/BucketSyncer/KeyJobs/KeyJob.java
// public abstract class KeyJob implements Runnable {
// protected final ObjectSummary summary;
// protected final Object notifyLock;
// protected final MirrorContext context;
//
//
// public KeyJob(ObjectSummary summary,
// Object notifyLock,
// MirrorContext context) {
// this.summary = summary;
// this.notifyLock = notifyLock;
// this.context = context;
// }
//
// @Override
// public String toString() {
// return summary.toString();
// }
//
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/KeyListers/KeyLister.java
// @Slf4j
// public abstract class KeyLister implements Runnable {
// protected MirrorContext context;
// protected Integer maxQueueCapacity;
// protected String bucket;
// protected String prefix;
//
// protected final AtomicBoolean done = new AtomicBoolean(false);
//
// public boolean isDone() {
// return done.get();
// }
//
// public KeyLister(String bucket,
// String prefix,
// MirrorContext context,
// Integer maxQueueCapacity) {
// this.bucket = bucket;
// this.prefix = prefix;
// this.context = context;
// this.maxQueueCapacity = maxQueueCapacity;
// }
//
// public abstract List<ObjectSummary> getNextBatch();
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/ObjectSummary.java
// public interface ObjectSummary {
// public String getKey();
//
// public long getSize();
//
// public Date getLastModified();
//
// public String getETag();
// }
// Path: src/main/java/com/tango/BucketSyncer/CopyMaster.java
import com.tango.BucketSyncer.KeyJobs.KeyJob;
import com.tango.BucketSyncer.KeyListers.KeyLister;
import com.tango.BucketSyncer.ObjectSummaries.ObjectSummary;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
clazz = (Class<? extends KeyLister>) Class.forName(className);
} catch (ClassNotFoundException e) {
log.error("Classname for KEY_LISTER {} is not found: {}", className, e);
}
Constructor<?> constructor = null;
try {
constructor = clazz.getConstructor(Object.class,
String.class,
String.class,
MirrorContext.class,
Integer.class);
} catch (NoSuchMethodException e) {
log.error("Failed to find corresponding KEY_LISTER constructor: ", e);
}
try {
return (KeyLister) constructor.newInstance(sourceClient, getBucket(options),
getPrefix(options),
context,
MirrorMaster.getMaxQueueCapacity(options));
} catch (InstantiationException e) {
log.error("Failed to instantiate KEY_LISTER: ", e);
} catch (IllegalAccessException e) {
log.error("Failed to access KEY_LISTER: ", e);
} catch (InvocationTargetException e) {
log.error("Failed to invocate KEY_LISTER: ", e);
}
return null;
}
| protected KeyJob getTask(ObjectSummary summary) { |
DevOps-TangoMe/BucketSyncer | src/main/java/com/tango/BucketSyncer/CopyMaster.java | // Path: src/main/java/com/tango/BucketSyncer/KeyJobs/KeyJob.java
// public abstract class KeyJob implements Runnable {
// protected final ObjectSummary summary;
// protected final Object notifyLock;
// protected final MirrorContext context;
//
//
// public KeyJob(ObjectSummary summary,
// Object notifyLock,
// MirrorContext context) {
// this.summary = summary;
// this.notifyLock = notifyLock;
// this.context = context;
// }
//
// @Override
// public String toString() {
// return summary.toString();
// }
//
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/KeyListers/KeyLister.java
// @Slf4j
// public abstract class KeyLister implements Runnable {
// protected MirrorContext context;
// protected Integer maxQueueCapacity;
// protected String bucket;
// protected String prefix;
//
// protected final AtomicBoolean done = new AtomicBoolean(false);
//
// public boolean isDone() {
// return done.get();
// }
//
// public KeyLister(String bucket,
// String prefix,
// MirrorContext context,
// Integer maxQueueCapacity) {
// this.bucket = bucket;
// this.prefix = prefix;
// this.context = context;
// this.maxQueueCapacity = maxQueueCapacity;
// }
//
// public abstract List<ObjectSummary> getNextBatch();
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/ObjectSummary.java
// public interface ObjectSummary {
// public String getKey();
//
// public long getSize();
//
// public Date getLastModified();
//
// public String getETag();
// }
| import com.tango.BucketSyncer.KeyJobs.KeyJob;
import com.tango.BucketSyncer.KeyListers.KeyLister;
import com.tango.BucketSyncer.ObjectSummaries.ObjectSummary;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor; | clazz = (Class<? extends KeyLister>) Class.forName(className);
} catch (ClassNotFoundException e) {
log.error("Classname for KEY_LISTER {} is not found: {}", className, e);
}
Constructor<?> constructor = null;
try {
constructor = clazz.getConstructor(Object.class,
String.class,
String.class,
MirrorContext.class,
Integer.class);
} catch (NoSuchMethodException e) {
log.error("Failed to find corresponding KEY_LISTER constructor: ", e);
}
try {
return (KeyLister) constructor.newInstance(sourceClient, getBucket(options),
getPrefix(options),
context,
MirrorMaster.getMaxQueueCapacity(options));
} catch (InstantiationException e) {
log.error("Failed to instantiate KEY_LISTER: ", e);
} catch (IllegalAccessException e) {
log.error("Failed to access KEY_LISTER: ", e);
} catch (InvocationTargetException e) {
log.error("Failed to invocate KEY_LISTER: ", e);
}
return null;
}
| // Path: src/main/java/com/tango/BucketSyncer/KeyJobs/KeyJob.java
// public abstract class KeyJob implements Runnable {
// protected final ObjectSummary summary;
// protected final Object notifyLock;
// protected final MirrorContext context;
//
//
// public KeyJob(ObjectSummary summary,
// Object notifyLock,
// MirrorContext context) {
// this.summary = summary;
// this.notifyLock = notifyLock;
// this.context = context;
// }
//
// @Override
// public String toString() {
// return summary.toString();
// }
//
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/KeyListers/KeyLister.java
// @Slf4j
// public abstract class KeyLister implements Runnable {
// protected MirrorContext context;
// protected Integer maxQueueCapacity;
// protected String bucket;
// protected String prefix;
//
// protected final AtomicBoolean done = new AtomicBoolean(false);
//
// public boolean isDone() {
// return done.get();
// }
//
// public KeyLister(String bucket,
// String prefix,
// MirrorContext context,
// Integer maxQueueCapacity) {
// this.bucket = bucket;
// this.prefix = prefix;
// this.context = context;
// this.maxQueueCapacity = maxQueueCapacity;
// }
//
// public abstract List<ObjectSummary> getNextBatch();
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/ObjectSummary.java
// public interface ObjectSummary {
// public String getKey();
//
// public long getSize();
//
// public Date getLastModified();
//
// public String getETag();
// }
// Path: src/main/java/com/tango/BucketSyncer/CopyMaster.java
import com.tango.BucketSyncer.KeyJobs.KeyJob;
import com.tango.BucketSyncer.KeyListers.KeyLister;
import com.tango.BucketSyncer.ObjectSummaries.ObjectSummary;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
clazz = (Class<? extends KeyLister>) Class.forName(className);
} catch (ClassNotFoundException e) {
log.error("Classname for KEY_LISTER {} is not found: {}", className, e);
}
Constructor<?> constructor = null;
try {
constructor = clazz.getConstructor(Object.class,
String.class,
String.class,
MirrorContext.class,
Integer.class);
} catch (NoSuchMethodException e) {
log.error("Failed to find corresponding KEY_LISTER constructor: ", e);
}
try {
return (KeyLister) constructor.newInstance(sourceClient, getBucket(options),
getPrefix(options),
context,
MirrorMaster.getMaxQueueCapacity(options));
} catch (InstantiationException e) {
log.error("Failed to instantiate KEY_LISTER: ", e);
} catch (IllegalAccessException e) {
log.error("Failed to access KEY_LISTER: ", e);
} catch (InvocationTargetException e) {
log.error("Failed to invocate KEY_LISTER: ", e);
}
return null;
}
| protected KeyJob getTask(ObjectSummary summary) { |
DevOps-TangoMe/BucketSyncer | src/main/java/com/tango/BucketSyncer/KeyJobs/S32GCSKeyCopyJob.java | // Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/ObjectSummary.java
// public interface ObjectSummary {
// public String getKey();
//
// public long getSize();
//
// public Date getLastModified();
//
// public String getETag();
// }
| import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import org.apache.http.HttpStatus;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.s3.model.*;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.googleapis.media.MediaHttpUploader;
import com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener;
import com.google.api.client.http.InputStreamContent;
import com.google.api.services.storage.Storage;
import com.google.api.services.storage.model.StorageObject;
import com.google.common.base.Stopwatch;
import com.google.common.collect.ImmutableMap;
import com.tango.BucketSyncer.*;
import com.tango.BucketSyncer.ObjectSummaries.ObjectSummary;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse; | /**
* Copyright 2013 Jonathan Cobb
* Copyright 2014 TangoMe Inc.
*
* 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.tango.BucketSyncer.KeyJobs;
@Slf4j
public class S32GCSKeyCopyJob extends S32GCSKeyJob {
protected String keydest;
public S32GCSKeyCopyJob(Object sourceClient,
Object destClient,
MirrorContext context, | // Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/ObjectSummary.java
// public interface ObjectSummary {
// public String getKey();
//
// public long getSize();
//
// public Date getLastModified();
//
// public String getETag();
// }
// Path: src/main/java/com/tango/BucketSyncer/KeyJobs/S32GCSKeyCopyJob.java
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import org.apache.http.HttpStatus;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.s3.model.*;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.googleapis.media.MediaHttpUploader;
import com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener;
import com.google.api.client.http.InputStreamContent;
import com.google.api.services.storage.Storage;
import com.google.api.services.storage.model.StorageObject;
import com.google.common.base.Stopwatch;
import com.google.common.collect.ImmutableMap;
import com.tango.BucketSyncer.*;
import com.tango.BucketSyncer.ObjectSummaries.ObjectSummary;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
/**
* Copyright 2013 Jonathan Cobb
* Copyright 2014 TangoMe Inc.
*
* 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.tango.BucketSyncer.KeyJobs;
@Slf4j
public class S32GCSKeyCopyJob extends S32GCSKeyJob {
protected String keydest;
public S32GCSKeyCopyJob(Object sourceClient,
Object destClient,
MirrorContext context, | ObjectSummary summary, |
DevOps-TangoMe/BucketSyncer | src/main/java/com/tango/BucketSyncer/KeyMaster.java | // Path: src/main/java/com/tango/BucketSyncer/KeyJobs/KeyJob.java
// public abstract class KeyJob implements Runnable {
// protected final ObjectSummary summary;
// protected final Object notifyLock;
// protected final MirrorContext context;
//
//
// public KeyJob(ObjectSummary summary,
// Object notifyLock,
// MirrorContext context) {
// this.summary = summary;
// this.notifyLock = notifyLock;
// this.context = context;
// }
//
// @Override
// public String toString() {
// return summary.toString();
// }
//
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/KeyListers/KeyLister.java
// @Slf4j
// public abstract class KeyLister implements Runnable {
// protected MirrorContext context;
// protected Integer maxQueueCapacity;
// protected String bucket;
// protected String prefix;
//
// protected final AtomicBoolean done = new AtomicBoolean(false);
//
// public boolean isDone() {
// return done.get();
// }
//
// public KeyLister(String bucket,
// String prefix,
// MirrorContext context,
// Integer maxQueueCapacity) {
// this.bucket = bucket;
// this.prefix = prefix;
// this.context = context;
// this.maxQueueCapacity = maxQueueCapacity;
// }
//
// public abstract List<ObjectSummary> getNextBatch();
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/ObjectSummary.java
// public interface ObjectSummary {
// public String getKey();
//
// public long getSize();
//
// public Date getLastModified();
//
// public String getETag();
// }
| import com.tango.BucketSyncer.KeyJobs.KeyJob;
import com.tango.BucketSyncer.KeyListers.KeyLister;
import com.tango.BucketSyncer.ObjectSummaries.ObjectSummary;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; | /**
* Copyright 2013 Jonathan Cobb
* Copyright 2014 TangoMe Inc.
*
* 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.tango.BucketSyncer;
@Slf4j
public abstract class KeyMaster implements Runnable {
public static final int STOP_TIMEOUT_SECONDS = 10;
private static final long STOP_TIMEOUT = TimeUnit.SECONDS.toMillis(STOP_TIMEOUT_SECONDS);
protected Object sourceClient;
protected Object destClient;
protected MirrorContext context;
private AtomicBoolean done = new AtomicBoolean(false);
public boolean isDone() {
return done.get();
}
private BlockingQueue<Runnable> workQueue;
private ThreadPoolExecutor executorService;
protected final Object notifyLock = new Object();
private Thread thread;
public KeyMaster(Object sourceClient,
Object destClient,
MirrorContext context,
BlockingQueue<Runnable> workQueue,
ThreadPoolExecutor executorService) {
this.sourceClient = sourceClient;
this.destClient = destClient;
this.context = context;
this.workQueue = workQueue;
this.executorService = executorService;
}
| // Path: src/main/java/com/tango/BucketSyncer/KeyJobs/KeyJob.java
// public abstract class KeyJob implements Runnable {
// protected final ObjectSummary summary;
// protected final Object notifyLock;
// protected final MirrorContext context;
//
//
// public KeyJob(ObjectSummary summary,
// Object notifyLock,
// MirrorContext context) {
// this.summary = summary;
// this.notifyLock = notifyLock;
// this.context = context;
// }
//
// @Override
// public String toString() {
// return summary.toString();
// }
//
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/KeyListers/KeyLister.java
// @Slf4j
// public abstract class KeyLister implements Runnable {
// protected MirrorContext context;
// protected Integer maxQueueCapacity;
// protected String bucket;
// protected String prefix;
//
// protected final AtomicBoolean done = new AtomicBoolean(false);
//
// public boolean isDone() {
// return done.get();
// }
//
// public KeyLister(String bucket,
// String prefix,
// MirrorContext context,
// Integer maxQueueCapacity) {
// this.bucket = bucket;
// this.prefix = prefix;
// this.context = context;
// this.maxQueueCapacity = maxQueueCapacity;
// }
//
// public abstract List<ObjectSummary> getNextBatch();
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/ObjectSummary.java
// public interface ObjectSummary {
// public String getKey();
//
// public long getSize();
//
// public Date getLastModified();
//
// public String getETag();
// }
// Path: src/main/java/com/tango/BucketSyncer/KeyMaster.java
import com.tango.BucketSyncer.KeyJobs.KeyJob;
import com.tango.BucketSyncer.KeyListers.KeyLister;
import com.tango.BucketSyncer.ObjectSummaries.ObjectSummary;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Copyright 2013 Jonathan Cobb
* Copyright 2014 TangoMe Inc.
*
* 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.tango.BucketSyncer;
@Slf4j
public abstract class KeyMaster implements Runnable {
public static final int STOP_TIMEOUT_SECONDS = 10;
private static final long STOP_TIMEOUT = TimeUnit.SECONDS.toMillis(STOP_TIMEOUT_SECONDS);
protected Object sourceClient;
protected Object destClient;
protected MirrorContext context;
private AtomicBoolean done = new AtomicBoolean(false);
public boolean isDone() {
return done.get();
}
private BlockingQueue<Runnable> workQueue;
private ThreadPoolExecutor executorService;
protected final Object notifyLock = new Object();
private Thread thread;
public KeyMaster(Object sourceClient,
Object destClient,
MirrorContext context,
BlockingQueue<Runnable> workQueue,
ThreadPoolExecutor executorService) {
this.sourceClient = sourceClient;
this.destClient = destClient;
this.context = context;
this.workQueue = workQueue;
this.executorService = executorService;
}
| protected abstract KeyLister getKeyLister(MirrorOptions options); |
DevOps-TangoMe/BucketSyncer | src/main/java/com/tango/BucketSyncer/KeyMaster.java | // Path: src/main/java/com/tango/BucketSyncer/KeyJobs/KeyJob.java
// public abstract class KeyJob implements Runnable {
// protected final ObjectSummary summary;
// protected final Object notifyLock;
// protected final MirrorContext context;
//
//
// public KeyJob(ObjectSummary summary,
// Object notifyLock,
// MirrorContext context) {
// this.summary = summary;
// this.notifyLock = notifyLock;
// this.context = context;
// }
//
// @Override
// public String toString() {
// return summary.toString();
// }
//
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/KeyListers/KeyLister.java
// @Slf4j
// public abstract class KeyLister implements Runnable {
// protected MirrorContext context;
// protected Integer maxQueueCapacity;
// protected String bucket;
// protected String prefix;
//
// protected final AtomicBoolean done = new AtomicBoolean(false);
//
// public boolean isDone() {
// return done.get();
// }
//
// public KeyLister(String bucket,
// String prefix,
// MirrorContext context,
// Integer maxQueueCapacity) {
// this.bucket = bucket;
// this.prefix = prefix;
// this.context = context;
// this.maxQueueCapacity = maxQueueCapacity;
// }
//
// public abstract List<ObjectSummary> getNextBatch();
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/ObjectSummary.java
// public interface ObjectSummary {
// public String getKey();
//
// public long getSize();
//
// public Date getLastModified();
//
// public String getETag();
// }
| import com.tango.BucketSyncer.KeyJobs.KeyJob;
import com.tango.BucketSyncer.KeyListers.KeyLister;
import com.tango.BucketSyncer.ObjectSummaries.ObjectSummary;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; | /**
* Copyright 2013 Jonathan Cobb
* Copyright 2014 TangoMe Inc.
*
* 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.tango.BucketSyncer;
@Slf4j
public abstract class KeyMaster implements Runnable {
public static final int STOP_TIMEOUT_SECONDS = 10;
private static final long STOP_TIMEOUT = TimeUnit.SECONDS.toMillis(STOP_TIMEOUT_SECONDS);
protected Object sourceClient;
protected Object destClient;
protected MirrorContext context;
private AtomicBoolean done = new AtomicBoolean(false);
public boolean isDone() {
return done.get();
}
private BlockingQueue<Runnable> workQueue;
private ThreadPoolExecutor executorService;
protected final Object notifyLock = new Object();
private Thread thread;
public KeyMaster(Object sourceClient,
Object destClient,
MirrorContext context,
BlockingQueue<Runnable> workQueue,
ThreadPoolExecutor executorService) {
this.sourceClient = sourceClient;
this.destClient = destClient;
this.context = context;
this.workQueue = workQueue;
this.executorService = executorService;
}
protected abstract KeyLister getKeyLister(MirrorOptions options);
| // Path: src/main/java/com/tango/BucketSyncer/KeyJobs/KeyJob.java
// public abstract class KeyJob implements Runnable {
// protected final ObjectSummary summary;
// protected final Object notifyLock;
// protected final MirrorContext context;
//
//
// public KeyJob(ObjectSummary summary,
// Object notifyLock,
// MirrorContext context) {
// this.summary = summary;
// this.notifyLock = notifyLock;
// this.context = context;
// }
//
// @Override
// public String toString() {
// return summary.toString();
// }
//
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/KeyListers/KeyLister.java
// @Slf4j
// public abstract class KeyLister implements Runnable {
// protected MirrorContext context;
// protected Integer maxQueueCapacity;
// protected String bucket;
// protected String prefix;
//
// protected final AtomicBoolean done = new AtomicBoolean(false);
//
// public boolean isDone() {
// return done.get();
// }
//
// public KeyLister(String bucket,
// String prefix,
// MirrorContext context,
// Integer maxQueueCapacity) {
// this.bucket = bucket;
// this.prefix = prefix;
// this.context = context;
// this.maxQueueCapacity = maxQueueCapacity;
// }
//
// public abstract List<ObjectSummary> getNextBatch();
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/ObjectSummary.java
// public interface ObjectSummary {
// public String getKey();
//
// public long getSize();
//
// public Date getLastModified();
//
// public String getETag();
// }
// Path: src/main/java/com/tango/BucketSyncer/KeyMaster.java
import com.tango.BucketSyncer.KeyJobs.KeyJob;
import com.tango.BucketSyncer.KeyListers.KeyLister;
import com.tango.BucketSyncer.ObjectSummaries.ObjectSummary;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Copyright 2013 Jonathan Cobb
* Copyright 2014 TangoMe Inc.
*
* 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.tango.BucketSyncer;
@Slf4j
public abstract class KeyMaster implements Runnable {
public static final int STOP_TIMEOUT_SECONDS = 10;
private static final long STOP_TIMEOUT = TimeUnit.SECONDS.toMillis(STOP_TIMEOUT_SECONDS);
protected Object sourceClient;
protected Object destClient;
protected MirrorContext context;
private AtomicBoolean done = new AtomicBoolean(false);
public boolean isDone() {
return done.get();
}
private BlockingQueue<Runnable> workQueue;
private ThreadPoolExecutor executorService;
protected final Object notifyLock = new Object();
private Thread thread;
public KeyMaster(Object sourceClient,
Object destClient,
MirrorContext context,
BlockingQueue<Runnable> workQueue,
ThreadPoolExecutor executorService) {
this.sourceClient = sourceClient;
this.destClient = destClient;
this.context = context;
this.workQueue = workQueue;
this.executorService = executorService;
}
protected abstract KeyLister getKeyLister(MirrorOptions options);
| protected abstract KeyJob getTask(ObjectSummary summary); |
DevOps-TangoMe/BucketSyncer | src/main/java/com/tango/BucketSyncer/KeyMaster.java | // Path: src/main/java/com/tango/BucketSyncer/KeyJobs/KeyJob.java
// public abstract class KeyJob implements Runnable {
// protected final ObjectSummary summary;
// protected final Object notifyLock;
// protected final MirrorContext context;
//
//
// public KeyJob(ObjectSummary summary,
// Object notifyLock,
// MirrorContext context) {
// this.summary = summary;
// this.notifyLock = notifyLock;
// this.context = context;
// }
//
// @Override
// public String toString() {
// return summary.toString();
// }
//
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/KeyListers/KeyLister.java
// @Slf4j
// public abstract class KeyLister implements Runnable {
// protected MirrorContext context;
// protected Integer maxQueueCapacity;
// protected String bucket;
// protected String prefix;
//
// protected final AtomicBoolean done = new AtomicBoolean(false);
//
// public boolean isDone() {
// return done.get();
// }
//
// public KeyLister(String bucket,
// String prefix,
// MirrorContext context,
// Integer maxQueueCapacity) {
// this.bucket = bucket;
// this.prefix = prefix;
// this.context = context;
// this.maxQueueCapacity = maxQueueCapacity;
// }
//
// public abstract List<ObjectSummary> getNextBatch();
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/ObjectSummary.java
// public interface ObjectSummary {
// public String getKey();
//
// public long getSize();
//
// public Date getLastModified();
//
// public String getETag();
// }
| import com.tango.BucketSyncer.KeyJobs.KeyJob;
import com.tango.BucketSyncer.KeyListers.KeyLister;
import com.tango.BucketSyncer.ObjectSummaries.ObjectSummary;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; | /**
* Copyright 2013 Jonathan Cobb
* Copyright 2014 TangoMe Inc.
*
* 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.tango.BucketSyncer;
@Slf4j
public abstract class KeyMaster implements Runnable {
public static final int STOP_TIMEOUT_SECONDS = 10;
private static final long STOP_TIMEOUT = TimeUnit.SECONDS.toMillis(STOP_TIMEOUT_SECONDS);
protected Object sourceClient;
protected Object destClient;
protected MirrorContext context;
private AtomicBoolean done = new AtomicBoolean(false);
public boolean isDone() {
return done.get();
}
private BlockingQueue<Runnable> workQueue;
private ThreadPoolExecutor executorService;
protected final Object notifyLock = new Object();
private Thread thread;
public KeyMaster(Object sourceClient,
Object destClient,
MirrorContext context,
BlockingQueue<Runnable> workQueue,
ThreadPoolExecutor executorService) {
this.sourceClient = sourceClient;
this.destClient = destClient;
this.context = context;
this.workQueue = workQueue;
this.executorService = executorService;
}
protected abstract KeyLister getKeyLister(MirrorOptions options);
| // Path: src/main/java/com/tango/BucketSyncer/KeyJobs/KeyJob.java
// public abstract class KeyJob implements Runnable {
// protected final ObjectSummary summary;
// protected final Object notifyLock;
// protected final MirrorContext context;
//
//
// public KeyJob(ObjectSummary summary,
// Object notifyLock,
// MirrorContext context) {
// this.summary = summary;
// this.notifyLock = notifyLock;
// this.context = context;
// }
//
// @Override
// public String toString() {
// return summary.toString();
// }
//
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/KeyListers/KeyLister.java
// @Slf4j
// public abstract class KeyLister implements Runnable {
// protected MirrorContext context;
// protected Integer maxQueueCapacity;
// protected String bucket;
// protected String prefix;
//
// protected final AtomicBoolean done = new AtomicBoolean(false);
//
// public boolean isDone() {
// return done.get();
// }
//
// public KeyLister(String bucket,
// String prefix,
// MirrorContext context,
// Integer maxQueueCapacity) {
// this.bucket = bucket;
// this.prefix = prefix;
// this.context = context;
// this.maxQueueCapacity = maxQueueCapacity;
// }
//
// public abstract List<ObjectSummary> getNextBatch();
//
// }
//
// Path: src/main/java/com/tango/BucketSyncer/ObjectSummaries/ObjectSummary.java
// public interface ObjectSummary {
// public String getKey();
//
// public long getSize();
//
// public Date getLastModified();
//
// public String getETag();
// }
// Path: src/main/java/com/tango/BucketSyncer/KeyMaster.java
import com.tango.BucketSyncer.KeyJobs.KeyJob;
import com.tango.BucketSyncer.KeyListers.KeyLister;
import com.tango.BucketSyncer.ObjectSummaries.ObjectSummary;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Copyright 2013 Jonathan Cobb
* Copyright 2014 TangoMe Inc.
*
* 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.tango.BucketSyncer;
@Slf4j
public abstract class KeyMaster implements Runnable {
public static final int STOP_TIMEOUT_SECONDS = 10;
private static final long STOP_TIMEOUT = TimeUnit.SECONDS.toMillis(STOP_TIMEOUT_SECONDS);
protected Object sourceClient;
protected Object destClient;
protected MirrorContext context;
private AtomicBoolean done = new AtomicBoolean(false);
public boolean isDone() {
return done.get();
}
private BlockingQueue<Runnable> workQueue;
private ThreadPoolExecutor executorService;
protected final Object notifyLock = new Object();
private Thread thread;
public KeyMaster(Object sourceClient,
Object destClient,
MirrorContext context,
BlockingQueue<Runnable> workQueue,
ThreadPoolExecutor executorService) {
this.sourceClient = sourceClient;
this.destClient = destClient;
this.context = context;
this.workQueue = workQueue;
this.executorService = executorService;
}
protected abstract KeyLister getKeyLister(MirrorOptions options);
| protected abstract KeyJob getTask(ObjectSummary summary); |
nodebox/nodebox | src/main/java/nodebox/Log.java | // Path: src/main/java/nodebox/util/AppDirs.java
// public class AppDirs {
//
// static final PlatformAppDirs platform;
// static final String separator = System.getProperty("file.separator");
// static final String homeDir = System.getProperty("user.home");
// static final String appName = "NodeBox";
//
// static {
// String os = System.getProperty("os.name").toLowerCase();
// if (os.startsWith("mac os")) {
// platform = new MacOsAppDirs();
// } else if (os.startsWith("windows")) {
// platform = new WindowsAppDirs();
// } else {
// platform = new LinuxAppDirs();
// }
// }
//
// interface PlatformAppDirs {
// File getUserDataDir();
//
// File getUserLogDir();
// }
//
// static class MacOsAppDirs implements PlatformAppDirs {
//
// @Override
// public File getUserDataDir() {
// return new File(homeDir + "/Library/Application Support/" + appName);
// }
//
// @Override
// public File getUserLogDir() {
// return new File(homeDir + "/Library/Logs/" + appName);
// }
// }
//
// static class WindowsAppDirs implements PlatformAppDirs {
//
// @Override
// public File getUserDataDir() {
// return new File(System.getenv("APPDATA") + separator + appName);
// }
//
//
// @Override
// public File getUserLogDir() {
// return new File(getUserDataDir(), "Logs");
// }
// }
//
// static class LinuxAppDirs implements PlatformAppDirs {
//
// @Override
// public File getUserDataDir() {
// String path = getEnv("XDG_DATA_HOME", homeDir + "/.local/share");
// return new File(path, appName);
// }
//
// public boolean ensureUserDataDir() {
// return getUserDataDir().mkdirs();
// }
//
// @Override
// public File getUserLogDir() {
// return new File(getUserDataDir(), "logs");
// }
//
// private String getEnv(String key, String defaultValue) {
// String value = System.getenv(key);
// if (value != null) {
// return value;
// } else {
// return defaultValue;
// }
// }
//
// }
//
// public static File getUserDataDir() {
// return platform.getUserDataDir();
// }
//
// public static File getUserLogDir() {
// return platform.getUserLogDir();
// }
//
// public static boolean ensureUserDataDir() {
// return platform.getUserDataDir().mkdirs();
// }
//
// public static boolean ensureUserLogDir() {
// return platform.getUserLogDir().mkdirs();
// }
//
// }
| import nodebox.util.AppDirs;
import java.io.File;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.logging.SimpleFormatter; | package nodebox;
public class Log {
private static final Logger LOGGER = java.util.logging.Logger.getGlobal();
static {
try {
// Initialize logging directory | // Path: src/main/java/nodebox/util/AppDirs.java
// public class AppDirs {
//
// static final PlatformAppDirs platform;
// static final String separator = System.getProperty("file.separator");
// static final String homeDir = System.getProperty("user.home");
// static final String appName = "NodeBox";
//
// static {
// String os = System.getProperty("os.name").toLowerCase();
// if (os.startsWith("mac os")) {
// platform = new MacOsAppDirs();
// } else if (os.startsWith("windows")) {
// platform = new WindowsAppDirs();
// } else {
// platform = new LinuxAppDirs();
// }
// }
//
// interface PlatformAppDirs {
// File getUserDataDir();
//
// File getUserLogDir();
// }
//
// static class MacOsAppDirs implements PlatformAppDirs {
//
// @Override
// public File getUserDataDir() {
// return new File(homeDir + "/Library/Application Support/" + appName);
// }
//
// @Override
// public File getUserLogDir() {
// return new File(homeDir + "/Library/Logs/" + appName);
// }
// }
//
// static class WindowsAppDirs implements PlatformAppDirs {
//
// @Override
// public File getUserDataDir() {
// return new File(System.getenv("APPDATA") + separator + appName);
// }
//
//
// @Override
// public File getUserLogDir() {
// return new File(getUserDataDir(), "Logs");
// }
// }
//
// static class LinuxAppDirs implements PlatformAppDirs {
//
// @Override
// public File getUserDataDir() {
// String path = getEnv("XDG_DATA_HOME", homeDir + "/.local/share");
// return new File(path, appName);
// }
//
// public boolean ensureUserDataDir() {
// return getUserDataDir().mkdirs();
// }
//
// @Override
// public File getUserLogDir() {
// return new File(getUserDataDir(), "logs");
// }
//
// private String getEnv(String key, String defaultValue) {
// String value = System.getenv(key);
// if (value != null) {
// return value;
// } else {
// return defaultValue;
// }
// }
//
// }
//
// public static File getUserDataDir() {
// return platform.getUserDataDir();
// }
//
// public static File getUserLogDir() {
// return platform.getUserLogDir();
// }
//
// public static boolean ensureUserDataDir() {
// return platform.getUserDataDir().mkdirs();
// }
//
// public static boolean ensureUserLogDir() {
// return platform.getUserLogDir().mkdirs();
// }
//
// }
// Path: src/main/java/nodebox/Log.java
import nodebox.util.AppDirs;
import java.io.File;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.logging.SimpleFormatter;
package nodebox;
public class Log {
private static final Logger LOGGER = java.util.logging.Logger.getGlobal();
static {
try {
// Initialize logging directory | AppDirs.ensureUserLogDir(); |
nodebox/nodebox | src/main/java/nodebox/client/devicehandler/AudioInputDeviceHandler.java | // Path: src/main/java/nodebox/client/MinimInputApplet.java
// public class MinimInputApplet extends PApplet {
// private Minim minim;
// private AudioInput input;
// private BeatDetect beat;
//
// public void setup() {
// minim = new Minim(this);
// input = minim.getLineIn();
// beat = new BeatDetect(input.bufferSize(), input.sampleRate());
// input.setVolume(0);
// input.setGain(-64);
// }
//
// public AudioInput getInput() {
// if (input == null) return null;
// return input;
// }
//
// public BeatDetect getBeatDetect() {
// return beat;
// }
//
// public void draw() {
// beat.detect(input.mix);
// }
//
// @Override
// public void stop() {
// if (input != null)
// input.close();
// input = null;
// if (minim != null)
// minim.stop();
// }
// }
//
// Path: src/main/java/nodebox/node/Device.java
// public class Device {
// public static final String TYPE_OSC = "osc";
// public static final String TYPE_AUDIOPLAYER = "audioplayer";
// public static final String TYPE_AUDIOINPUT = "audioinput";
//
// public static final String TIMELINE_SYNC = "sync_with_timeline";
//
// public static final ImmutableList<String> deviceTypes = ImmutableList.of(TYPE_OSC, TYPE_AUDIOPLAYER, TYPE_AUDIOINPUT);
//
// private final String name;
// private final String type;
// private final ImmutableMap<String, String> properties;
//
// private static final Pattern OSC_PROPERTY_NAMES_PATTERN = Pattern.compile("^(port|sync_with_timeline)$");
// private static final Pattern AUDIOPLAYER_PROPERTY_NAMES_PATTERN = Pattern.compile("^(filename|sync_with_timeline|loop)$");
// private static final Pattern AUDIOINPUT_PROPERTY_NAMES_PATTERN = Pattern.compile("^(sync_with_timeline)$");
//
// private final transient int hashCode;
//
// private static final Map<String, Pattern> validPropertyNames;
//
// static {
// ImmutableMap.Builder<String, Pattern> builder = new ImmutableMap.Builder<String, Pattern>();
// builder.put(TYPE_OSC, OSC_PROPERTY_NAMES_PATTERN);
// builder.put(TYPE_AUDIOPLAYER, AUDIOPLAYER_PROPERTY_NAMES_PATTERN);
// builder.put(TYPE_AUDIOINPUT, AUDIOINPUT_PROPERTY_NAMES_PATTERN);
// validPropertyNames = builder.build();
// }
//
// public static Device oscDevice(String name, long port, boolean syncWithTimeline) {
// return new Device(name, TYPE_OSC, ImmutableMap.<String, String>of("port", String.valueOf(port), TIMELINE_SYNC, String.valueOf(syncWithTimeline)));
// }
//
// public static Device deviceForType(String name, String type) {
// checkNotNull(type, "Type cannot be null.");
// checkArgument(deviceTypes.contains(type), "%s is not a valid device type.", type);
// // If the type is not found in the default values, get() returns null, which is what we need for custom types.
// return new Device(name, type, ImmutableMap.<String, String>of());
// }
//
// private Device(final String name, final String type, final ImmutableMap<String, String> properties) {
// this.name = name;
// this.type = type;
// this.properties = properties;
// this.hashCode = Objects.hashCode(name, type, properties);
// }
//
// public String getName() {
// return name;
// }
//
// public String getType() {
// return type;
// }
//
// public boolean hasProperty(String name) {
// return properties.containsKey(name);
// }
//
// public String getProperty(String name) {
// return properties.get(name);
// }
//
// public Map<String, String> getProperties() {
// return properties;
// }
//
// public String getProperty(String name, String defaultValue) {
// if (hasProperty(name)) {
// return properties.get(name);
// } else {
// return defaultValue;
// }
// }
//
// public Device withProperty(String name, String value) {
// checkArgument(isValidProperty(name), "Property name '%s' is not valid.", name);
// Map<String, String> b = new HashMap<String, String>();
// b.putAll(properties);
// b.put(name, value);
// return new Device(this.name, this.type, ImmutableMap.copyOf(b));
// }
//
// private boolean isValidProperty(String name) {
// checkNotNull(name);
// if (!validPropertyNames.containsKey(getType())) return false;
// return validPropertyNames.get(getType()).matcher(name).matches();
// }
//
// //// Object overrides ////
//
// @Override
// public int hashCode() {
// return hashCode;
// }
//
// @Override
// public boolean equals(Object o) {
// if (!(o instanceof Device)) return false;
// final Device other = (Device) o;
// return Objects.equal(name, other.name)
// && Objects.equal(type, other.type)
// && Objects.equal(properties, other.properties);
// }
//
// @Override
// public String toString() {
// return String.format("<Device %s (%s)>", name, type);
// }
//
// }
| import nodebox.client.MinimInputApplet;
import nodebox.node.Device;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Map; | package nodebox.client.devicehandler;
public class AudioInputDeviceHandler implements DeviceHandler {
private String name;
private boolean syncWithTimeline;
private JFrame frame = null;
| // Path: src/main/java/nodebox/client/MinimInputApplet.java
// public class MinimInputApplet extends PApplet {
// private Minim minim;
// private AudioInput input;
// private BeatDetect beat;
//
// public void setup() {
// minim = new Minim(this);
// input = minim.getLineIn();
// beat = new BeatDetect(input.bufferSize(), input.sampleRate());
// input.setVolume(0);
// input.setGain(-64);
// }
//
// public AudioInput getInput() {
// if (input == null) return null;
// return input;
// }
//
// public BeatDetect getBeatDetect() {
// return beat;
// }
//
// public void draw() {
// beat.detect(input.mix);
// }
//
// @Override
// public void stop() {
// if (input != null)
// input.close();
// input = null;
// if (minim != null)
// minim.stop();
// }
// }
//
// Path: src/main/java/nodebox/node/Device.java
// public class Device {
// public static final String TYPE_OSC = "osc";
// public static final String TYPE_AUDIOPLAYER = "audioplayer";
// public static final String TYPE_AUDIOINPUT = "audioinput";
//
// public static final String TIMELINE_SYNC = "sync_with_timeline";
//
// public static final ImmutableList<String> deviceTypes = ImmutableList.of(TYPE_OSC, TYPE_AUDIOPLAYER, TYPE_AUDIOINPUT);
//
// private final String name;
// private final String type;
// private final ImmutableMap<String, String> properties;
//
// private static final Pattern OSC_PROPERTY_NAMES_PATTERN = Pattern.compile("^(port|sync_with_timeline)$");
// private static final Pattern AUDIOPLAYER_PROPERTY_NAMES_PATTERN = Pattern.compile("^(filename|sync_with_timeline|loop)$");
// private static final Pattern AUDIOINPUT_PROPERTY_NAMES_PATTERN = Pattern.compile("^(sync_with_timeline)$");
//
// private final transient int hashCode;
//
// private static final Map<String, Pattern> validPropertyNames;
//
// static {
// ImmutableMap.Builder<String, Pattern> builder = new ImmutableMap.Builder<String, Pattern>();
// builder.put(TYPE_OSC, OSC_PROPERTY_NAMES_PATTERN);
// builder.put(TYPE_AUDIOPLAYER, AUDIOPLAYER_PROPERTY_NAMES_PATTERN);
// builder.put(TYPE_AUDIOINPUT, AUDIOINPUT_PROPERTY_NAMES_PATTERN);
// validPropertyNames = builder.build();
// }
//
// public static Device oscDevice(String name, long port, boolean syncWithTimeline) {
// return new Device(name, TYPE_OSC, ImmutableMap.<String, String>of("port", String.valueOf(port), TIMELINE_SYNC, String.valueOf(syncWithTimeline)));
// }
//
// public static Device deviceForType(String name, String type) {
// checkNotNull(type, "Type cannot be null.");
// checkArgument(deviceTypes.contains(type), "%s is not a valid device type.", type);
// // If the type is not found in the default values, get() returns null, which is what we need for custom types.
// return new Device(name, type, ImmutableMap.<String, String>of());
// }
//
// private Device(final String name, final String type, final ImmutableMap<String, String> properties) {
// this.name = name;
// this.type = type;
// this.properties = properties;
// this.hashCode = Objects.hashCode(name, type, properties);
// }
//
// public String getName() {
// return name;
// }
//
// public String getType() {
// return type;
// }
//
// public boolean hasProperty(String name) {
// return properties.containsKey(name);
// }
//
// public String getProperty(String name) {
// return properties.get(name);
// }
//
// public Map<String, String> getProperties() {
// return properties;
// }
//
// public String getProperty(String name, String defaultValue) {
// if (hasProperty(name)) {
// return properties.get(name);
// } else {
// return defaultValue;
// }
// }
//
// public Device withProperty(String name, String value) {
// checkArgument(isValidProperty(name), "Property name '%s' is not valid.", name);
// Map<String, String> b = new HashMap<String, String>();
// b.putAll(properties);
// b.put(name, value);
// return new Device(this.name, this.type, ImmutableMap.copyOf(b));
// }
//
// private boolean isValidProperty(String name) {
// checkNotNull(name);
// if (!validPropertyNames.containsKey(getType())) return false;
// return validPropertyNames.get(getType()).matcher(name).matches();
// }
//
// //// Object overrides ////
//
// @Override
// public int hashCode() {
// return hashCode;
// }
//
// @Override
// public boolean equals(Object o) {
// if (!(o instanceof Device)) return false;
// final Device other = (Device) o;
// return Objects.equal(name, other.name)
// && Objects.equal(type, other.type)
// && Objects.equal(properties, other.properties);
// }
//
// @Override
// public String toString() {
// return String.format("<Device %s (%s)>", name, type);
// }
//
// }
// Path: src/main/java/nodebox/client/devicehandler/AudioInputDeviceHandler.java
import nodebox.client.MinimInputApplet;
import nodebox.node.Device;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Map;
package nodebox.client.devicehandler;
public class AudioInputDeviceHandler implements DeviceHandler {
private String name;
private boolean syncWithTimeline;
private JFrame frame = null;
| private MinimInputApplet applet = null; |
nodebox/nodebox | src/main/java/nodebox/client/PortView.java | // Path: src/main/java/nodebox/Log.java
// public class Log {
// private static final Logger LOGGER = java.util.logging.Logger.getGlobal();
//
// static {
// try {
// // Initialize logging directory
// AppDirs.ensureUserLogDir();
// File logDir = AppDirs.getUserLogDir();
//
// // Initialize file logging
// FileHandler handler = new FileHandler(logDir.getAbsolutePath() + "/nodebox-%u.log");
// handler.setFormatter(new SimpleFormatter());
// LOGGER.addHandler(handler);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// public static void info(String message) {
// LOGGER.log(Level.INFO, message);
// }
//
// public static void warn(String message) {
// LOGGER.log(Level.WARNING, message);
// }
//
// public static void warn(String message, Throwable t) {
// LOGGER.log(Level.WARNING, message, t);
// }
//
// public static void error(String message) {
// LOGGER.log(Level.SEVERE, message);
// }
//
// public static void error(String message, Throwable t) {
// LOGGER.log(Level.SEVERE, message, t);
// }
//
// }
| import nodebox.Log;
import nodebox.client.port.*;
import nodebox.node.Node;
import nodebox.node.Port;
import nodebox.ui.PaneView;
import nodebox.ui.Theme;
import javax.swing.*;
import java.awt.*;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map; | rowConstraints.weightx = 1.0;
PortRow portRow = new PortRow(getDocument(), portName, control);
portRow.setEnabled(p.isEnabled());
controlPanel.add(portRow, rowConstraints);
rowIndex++;
}
if (rowIndex == 0) {
JLabel noPorts = new JLabel("No ports");
noPorts.setFont(Theme.SMALL_BOLD_FONT);
noPorts.setForeground(Theme.TEXT_NORMAL_COLOR);
controlPanel.add(noPorts);
}
JLabel filler = new JLabel();
GridBagConstraints fillerConstraints = new GridBagConstraints();
fillerConstraints.gridx = 0;
fillerConstraints.gridy = rowIndex;
fillerConstraints.fill = GridBagConstraints.BOTH;
fillerConstraints.weighty = 1.0;
fillerConstraints.gridwidth = GridBagConstraints.REMAINDER;
controlPanel.add(filler, fillerConstraints);
revalidate();
}
@SuppressWarnings("unchecked")
private PortControl constructControl(Class controlClass, String activeNodePath, Port p) {
try {
Constructor constructor = controlClass.getConstructor(String.class, Port.class);
return (PortControl) constructor.newInstance(activeNodePath, p);
} catch (Exception e) { | // Path: src/main/java/nodebox/Log.java
// public class Log {
// private static final Logger LOGGER = java.util.logging.Logger.getGlobal();
//
// static {
// try {
// // Initialize logging directory
// AppDirs.ensureUserLogDir();
// File logDir = AppDirs.getUserLogDir();
//
// // Initialize file logging
// FileHandler handler = new FileHandler(logDir.getAbsolutePath() + "/nodebox-%u.log");
// handler.setFormatter(new SimpleFormatter());
// LOGGER.addHandler(handler);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// public static void info(String message) {
// LOGGER.log(Level.INFO, message);
// }
//
// public static void warn(String message) {
// LOGGER.log(Level.WARNING, message);
// }
//
// public static void warn(String message, Throwable t) {
// LOGGER.log(Level.WARNING, message, t);
// }
//
// public static void error(String message) {
// LOGGER.log(Level.SEVERE, message);
// }
//
// public static void error(String message, Throwable t) {
// LOGGER.log(Level.SEVERE, message, t);
// }
//
// }
// Path: src/main/java/nodebox/client/PortView.java
import nodebox.Log;
import nodebox.client.port.*;
import nodebox.node.Node;
import nodebox.node.Port;
import nodebox.ui.PaneView;
import nodebox.ui.Theme;
import javax.swing.*;
import java.awt.*;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
rowConstraints.weightx = 1.0;
PortRow portRow = new PortRow(getDocument(), portName, control);
portRow.setEnabled(p.isEnabled());
controlPanel.add(portRow, rowConstraints);
rowIndex++;
}
if (rowIndex == 0) {
JLabel noPorts = new JLabel("No ports");
noPorts.setFont(Theme.SMALL_BOLD_FONT);
noPorts.setForeground(Theme.TEXT_NORMAL_COLOR);
controlPanel.add(noPorts);
}
JLabel filler = new JLabel();
GridBagConstraints fillerConstraints = new GridBagConstraints();
fillerConstraints.gridx = 0;
fillerConstraints.gridy = rowIndex;
fillerConstraints.fill = GridBagConstraints.BOTH;
fillerConstraints.weighty = 1.0;
fillerConstraints.gridwidth = GridBagConstraints.REMAINDER;
controlPanel.add(filler, fillerConstraints);
revalidate();
}
@SuppressWarnings("unchecked")
private PortControl constructControl(Class controlClass, String activeNodePath, Port p) {
try {
Constructor constructor = controlClass.getConstructor(String.class, Port.class);
return (PortControl) constructor.newInstance(activeNodePath, p);
} catch (Exception e) { | Log.error("Cannot construct control", e); |
nodebox/nodebox | src/main/java/nodebox/movie/Movie.java | // Path: src/main/java/nodebox/Log.java
// public class Log {
// private static final Logger LOGGER = java.util.logging.Logger.getGlobal();
//
// static {
// try {
// // Initialize logging directory
// AppDirs.ensureUserLogDir();
// File logDir = AppDirs.getUserLogDir();
//
// // Initialize file logging
// FileHandler handler = new FileHandler(logDir.getAbsolutePath() + "/nodebox-%u.log");
// handler.setFormatter(new SimpleFormatter());
// LOGGER.addHandler(handler);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// public static void info(String message) {
// LOGGER.log(Level.INFO, message);
// }
//
// public static void warn(String message) {
// LOGGER.log(Level.WARNING, message);
// }
//
// public static void warn(String message, Throwable t) {
// LOGGER.log(Level.WARNING, message, t);
// }
//
// public static void error(String message) {
// LOGGER.log(Level.SEVERE, message);
// }
//
// public static void error(String message, Throwable t) {
// LOGGER.log(Level.SEVERE, message, t);
// }
//
// }
| import nodebox.Log;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.Random; | package nodebox.movie;
public class Movie {
private static final File FFMPEG_BINARY;
private static final String TEMPORARY_FILE_PREFIX = "sme";
public static final ArrayList<VideoFormat> VIDEO_FORMATS;
public static final VideoFormat DEFAULT_FORMAT = MP4VideoFormat.HighFormat;
static {
String osName = System.getProperty("os.name").split("\\s")[0];
// If we provide a binary for this system, use it. Otherwise, see if a default "ffmpeg" binary exists.
String binaryName = "ffmpeg";
if (osName.equals("Windows"))
binaryName = "ffmpeg.exe";
File packagedBinary = nodebox.util.FileUtils.getApplicationFile(String.format("bin/%s", binaryName));
if (packagedBinary.exists()) {
FFMPEG_BINARY = packagedBinary;
} else { | // Path: src/main/java/nodebox/Log.java
// public class Log {
// private static final Logger LOGGER = java.util.logging.Logger.getGlobal();
//
// static {
// try {
// // Initialize logging directory
// AppDirs.ensureUserLogDir();
// File logDir = AppDirs.getUserLogDir();
//
// // Initialize file logging
// FileHandler handler = new FileHandler(logDir.getAbsolutePath() + "/nodebox-%u.log");
// handler.setFormatter(new SimpleFormatter());
// LOGGER.addHandler(handler);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// public static void info(String message) {
// LOGGER.log(Level.INFO, message);
// }
//
// public static void warn(String message) {
// LOGGER.log(Level.WARNING, message);
// }
//
// public static void warn(String message, Throwable t) {
// LOGGER.log(Level.WARNING, message, t);
// }
//
// public static void error(String message) {
// LOGGER.log(Level.SEVERE, message);
// }
//
// public static void error(String message, Throwable t) {
// LOGGER.log(Level.SEVERE, message, t);
// }
//
// }
// Path: src/main/java/nodebox/movie/Movie.java
import nodebox.Log;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
package nodebox.movie;
public class Movie {
private static final File FFMPEG_BINARY;
private static final String TEMPORARY_FILE_PREFIX = "sme";
public static final ArrayList<VideoFormat> VIDEO_FORMATS;
public static final VideoFormat DEFAULT_FORMAT = MP4VideoFormat.HighFormat;
static {
String osName = System.getProperty("os.name").split("\\s")[0];
// If we provide a binary for this system, use it. Otherwise, see if a default "ffmpeg" binary exists.
String binaryName = "ffmpeg";
if (osName.equals("Windows"))
binaryName = "ffmpeg.exe";
File packagedBinary = nodebox.util.FileUtils.getApplicationFile(String.format("bin/%s", binaryName));
if (packagedBinary.exists()) {
FFMPEG_BINARY = packagedBinary;
} else { | Log.warn(String.format("Could not find packaged ffmpeg %s", packagedBinary)); |
nodebox/nodebox | src/test/java/nodebox/function/StringFunctionsTest.java | // Path: src/main/java/nodebox/function/StringFunctions.java
// public static List<String> makeStrings(String s, String separator) {
// if (s == null) {
// return ImmutableList.of();
// }
// if (separator == null || separator.isEmpty()) {
// return ImmutableList.copyOf(Splitter.fixedLength(1).split(s));
// }
// return ImmutableList.copyOf(Splitter.on(separator).split(s));
// }
| import org.junit.Test;
import static junit.framework.TestCase.*;
import static nodebox.function.StringFunctions.makeStrings;
import static nodebox.util.Assertions.assertResultsEqual; | package nodebox.function;
public class StringFunctionsTest {
@Test
public void testMakeStrings() { | // Path: src/main/java/nodebox/function/StringFunctions.java
// public static List<String> makeStrings(String s, String separator) {
// if (s == null) {
// return ImmutableList.of();
// }
// if (separator == null || separator.isEmpty()) {
// return ImmutableList.copyOf(Splitter.fixedLength(1).split(s));
// }
// return ImmutableList.copyOf(Splitter.on(separator).split(s));
// }
// Path: src/test/java/nodebox/function/StringFunctionsTest.java
import org.junit.Test;
import static junit.framework.TestCase.*;
import static nodebox.function.StringFunctions.makeStrings;
import static nodebox.util.Assertions.assertResultsEqual;
package nodebox.function;
public class StringFunctionsTest {
@Test
public void testMakeStrings() { | assertResultsEqual(makeStrings("a;b", ";"), "a", "b"); |
nodebox/nodebox | src/main/java/nodebox/client/ExportDialog.java | // Path: src/main/java/nodebox/ui/ExportFormat.java
// public final class ExportFormat {
//
// public static final ExportFormat PDF = new ExportFormat("PDF", "pdf");
// public static final ExportFormat PNG = new ExportFormat("PNG", "png");
// public static final ExportFormat SVG = new ExportFormat("SVG", "svg");
// public static final ExportFormat CSV = new ExportFormat("CSV", "csv");
//
// private static final Map<String, ExportFormat> FORMAT_MAP;
//
// static {
// FORMAT_MAP = new HashMap<>();
// FORMAT_MAP.put("PDF", PDF);
// FORMAT_MAP.put("PNG", PNG);
// FORMAT_MAP.put("SVG", SVG);
// FORMAT_MAP.put("CSV", CSV);
// }
//
// public static ExportFormat of(String name) {
// return FORMAT_MAP.get(name.toUpperCase(Locale.US));
// }
//
// private final String label;
// private final String extension;
//
// public ExportFormat(String label, String extension) {
// this.label = label;
// this.extension = extension;
// }
//
// public String getLabel() {
// return label;
// }
//
// public String getExtension() {
// return extension;
// }
//
// public File ensureFileExtension(File file) {
// return new File(ensureFileExtension(file.getPath()));
// }
//
// public String ensureFileExtension(String file) {
// if (file.toLowerCase(Locale.US).endsWith("." + getExtension()))
// return file;
// return file + "." + getExtension();
// }
//
// }
| import com.google.common.collect.ImmutableMap;
import nodebox.ui.ExportFormat;
import nodebox.ui.Theme;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Map; | getRootPane().setDefaultButton(nextButton);
formatBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
boolean visible = e.getItem().toString().equals("CSV");
delimiterPanel.setVisible(visible);
quotesPanel.setVisible(visible);
mainPanel.validate();
ExportDialog.this.pack();
}
}
});
}
private void doCancel() {
setVisible(false);
}
private void doNext() {
dialogSuccessful = true;
setVisible(false);
}
public boolean isDialogSuccessful() {
return dialogSuccessful;
}
| // Path: src/main/java/nodebox/ui/ExportFormat.java
// public final class ExportFormat {
//
// public static final ExportFormat PDF = new ExportFormat("PDF", "pdf");
// public static final ExportFormat PNG = new ExportFormat("PNG", "png");
// public static final ExportFormat SVG = new ExportFormat("SVG", "svg");
// public static final ExportFormat CSV = new ExportFormat("CSV", "csv");
//
// private static final Map<String, ExportFormat> FORMAT_MAP;
//
// static {
// FORMAT_MAP = new HashMap<>();
// FORMAT_MAP.put("PDF", PDF);
// FORMAT_MAP.put("PNG", PNG);
// FORMAT_MAP.put("SVG", SVG);
// FORMAT_MAP.put("CSV", CSV);
// }
//
// public static ExportFormat of(String name) {
// return FORMAT_MAP.get(name.toUpperCase(Locale.US));
// }
//
// private final String label;
// private final String extension;
//
// public ExportFormat(String label, String extension) {
// this.label = label;
// this.extension = extension;
// }
//
// public String getLabel() {
// return label;
// }
//
// public String getExtension() {
// return extension;
// }
//
// public File ensureFileExtension(File file) {
// return new File(ensureFileExtension(file.getPath()));
// }
//
// public String ensureFileExtension(String file) {
// if (file.toLowerCase(Locale.US).endsWith("." + getExtension()))
// return file;
// return file + "." + getExtension();
// }
//
// }
// Path: src/main/java/nodebox/client/ExportDialog.java
import com.google.common.collect.ImmutableMap;
import nodebox.ui.ExportFormat;
import nodebox.ui.Theme;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Map;
getRootPane().setDefaultButton(nextButton);
formatBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
boolean visible = e.getItem().toString().equals("CSV");
delimiterPanel.setVisible(visible);
quotesPanel.setVisible(visible);
mainPanel.validate();
ExportDialog.this.pack();
}
}
});
}
private void doCancel() {
setVisible(false);
}
private void doNext() {
dialogSuccessful = true;
setVisible(false);
}
public boolean isDialogSuccessful() {
return dialogSuccessful;
}
| public ExportFormat getFormat() { |
nodebox/nodebox | src/main/java/nodebox/client/Console.java | // Path: src/main/java/nodebox/Log.java
// public class Log {
// private static final Logger LOGGER = java.util.logging.Logger.getGlobal();
//
// static {
// try {
// // Initialize logging directory
// AppDirs.ensureUserLogDir();
// File logDir = AppDirs.getUserLogDir();
//
// // Initialize file logging
// FileHandler handler = new FileHandler(logDir.getAbsolutePath() + "/nodebox-%u.log");
// handler.setFormatter(new SimpleFormatter());
// LOGGER.addHandler(handler);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// public static void info(String message) {
// LOGGER.log(Level.INFO, message);
// }
//
// public static void warn(String message) {
// LOGGER.log(Level.WARNING, message);
// }
//
// public static void warn(String message, Throwable t) {
// LOGGER.log(Level.WARNING, message, t);
// }
//
// public static void error(String message) {
// LOGGER.log(Level.SEVERE, message);
// }
//
// public static void error(String message, Throwable t) {
// LOGGER.log(Level.SEVERE, message, t);
// }
//
// }
| import nodebox.Log;
import nodebox.ui.Theme;
import org.python.util.PythonInterpreter;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import static com.google.common.base.Preconditions.checkNotNull; | }
});
messagesDocument = consoleMessages.getDocument();
JScrollPane messagesScroll = new JScrollPane(consoleMessages, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
messagesScroll.setBorder(BorderFactory.createEmptyBorder());
consolePrompt = new JTextField();
consolePrompt.setFont(Theme.EDITOR_FONT);
Keymap defaultKeymap = JTextComponent.getKeymap(JTextComponent.DEFAULT_KEYMAP);
Keymap keymap = JTextComponent.addKeymap(null, defaultKeymap);
keymap.addActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), new EnterAction());
keymap.addActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), new HistoryUpAction());
keymap.addActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), new HistoryDownAction());
consolePrompt.setKeymap(keymap);
consolePrompt.setBorder(new PromptBorder());
setLayout(new BorderLayout());
add(messagesScroll, BorderLayout.CENTER);
add(consolePrompt, BorderLayout.SOUTH);
interpreter = new PythonInterpreter();
consolePrompt.requestFocus();
addFocusListener(this);
addWindowListener(this);
}
private void addMessage(String s, AttributeSet attributes) {
try {
messagesDocument.insertString(messagesDocument.getLength(), s, attributes);
} catch (BadLocationException e) { | // Path: src/main/java/nodebox/Log.java
// public class Log {
// private static final Logger LOGGER = java.util.logging.Logger.getGlobal();
//
// static {
// try {
// // Initialize logging directory
// AppDirs.ensureUserLogDir();
// File logDir = AppDirs.getUserLogDir();
//
// // Initialize file logging
// FileHandler handler = new FileHandler(logDir.getAbsolutePath() + "/nodebox-%u.log");
// handler.setFormatter(new SimpleFormatter());
// LOGGER.addHandler(handler);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// public static void info(String message) {
// LOGGER.log(Level.INFO, message);
// }
//
// public static void warn(String message) {
// LOGGER.log(Level.WARNING, message);
// }
//
// public static void warn(String message, Throwable t) {
// LOGGER.log(Level.WARNING, message, t);
// }
//
// public static void error(String message) {
// LOGGER.log(Level.SEVERE, message);
// }
//
// public static void error(String message, Throwable t) {
// LOGGER.log(Level.SEVERE, message, t);
// }
//
// }
// Path: src/main/java/nodebox/client/Console.java
import nodebox.Log;
import nodebox.ui.Theme;
import org.python.util.PythonInterpreter;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import static com.google.common.base.Preconditions.checkNotNull;
}
});
messagesDocument = consoleMessages.getDocument();
JScrollPane messagesScroll = new JScrollPane(consoleMessages, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
messagesScroll.setBorder(BorderFactory.createEmptyBorder());
consolePrompt = new JTextField();
consolePrompt.setFont(Theme.EDITOR_FONT);
Keymap defaultKeymap = JTextComponent.getKeymap(JTextComponent.DEFAULT_KEYMAP);
Keymap keymap = JTextComponent.addKeymap(null, defaultKeymap);
keymap.addActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), new EnterAction());
keymap.addActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), new HistoryUpAction());
keymap.addActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), new HistoryDownAction());
consolePrompt.setKeymap(keymap);
consolePrompt.setBorder(new PromptBorder());
setLayout(new BorderLayout());
add(messagesScroll, BorderLayout.CENTER);
add(consolePrompt, BorderLayout.SOUTH);
interpreter = new PythonInterpreter();
consolePrompt.requestFocus();
addFocusListener(this);
addWindowListener(this);
}
private void addMessage(String s, AttributeSet attributes) {
try {
messagesDocument.insertString(messagesDocument.getLength(), s, attributes);
} catch (BadLocationException e) { | Log.warn("addMessage: bad location (" + s + ")", e); |
nodebox/nodebox | src/main/java/nodebox/versioncheck/Updater.java | // Path: src/main/java/nodebox/Log.java
// public class Log {
// private static final Logger LOGGER = java.util.logging.Logger.getGlobal();
//
// static {
// try {
// // Initialize logging directory
// AppDirs.ensureUserLogDir();
// File logDir = AppDirs.getUserLogDir();
//
// // Initialize file logging
// FileHandler handler = new FileHandler(logDir.getAbsolutePath() + "/nodebox-%u.log");
// handler.setFormatter(new SimpleFormatter());
// LOGGER.addHandler(handler);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// public static void info(String message) {
// LOGGER.log(Level.INFO, message);
// }
//
// public static void warn(String message) {
// LOGGER.log(Level.WARNING, message);
// }
//
// public static void warn(String message, Throwable t) {
// LOGGER.log(Level.WARNING, message, t);
// }
//
// public static void error(String message) {
// LOGGER.log(Level.SEVERE, message);
// }
//
// public static void error(String message, Throwable t) {
// LOGGER.log(Level.SEVERE, message, t);
// }
//
// }
| import nodebox.Log;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences; | public void checkerFoundValidUpdate(UpdateChecker checker, Appcast appcast) {
// Delegate method.
if (delegate != null)
if (delegate.checkerFoundValidUpdate(checker, appcast))
return;
UpdateAlert alert = new UpdateAlert(this, appcast);
alert.setLocationRelativeTo(null);
alert.setVisible(true);
}
public void checkerDetectedLatestVersion(UpdateChecker checker, Appcast appcast) {
// Delegate method.
if (delegate != null)
if (delegate.checkerDetectedLatestVersion(checker, appcast))
return;
// Show a message that you're using the latest version if you've explicitly checked for updates.
if (!checker.isSilent()) {
JOptionPane.showMessageDialog(null, "<html><b>You're up to date!</b><br>\n" + host.getName() + " " + host.getVersion() + " is the latest version available.", "", JOptionPane.INFORMATION_MESSAGE, getHostIcon());
}
}
public void checkerEncounteredError(UpdateChecker checker, Throwable t) {
hideUpdateCheckDialog();
// Delegate method.
if (delegate != null)
if (delegate.checkerEncounteredError(checker, t))
return;
if (checker.isSilent()) { | // Path: src/main/java/nodebox/Log.java
// public class Log {
// private static final Logger LOGGER = java.util.logging.Logger.getGlobal();
//
// static {
// try {
// // Initialize logging directory
// AppDirs.ensureUserLogDir();
// File logDir = AppDirs.getUserLogDir();
//
// // Initialize file logging
// FileHandler handler = new FileHandler(logDir.getAbsolutePath() + "/nodebox-%u.log");
// handler.setFormatter(new SimpleFormatter());
// LOGGER.addHandler(handler);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// public static void info(String message) {
// LOGGER.log(Level.INFO, message);
// }
//
// public static void warn(String message) {
// LOGGER.log(Level.WARNING, message);
// }
//
// public static void warn(String message, Throwable t) {
// LOGGER.log(Level.WARNING, message, t);
// }
//
// public static void error(String message) {
// LOGGER.log(Level.SEVERE, message);
// }
//
// public static void error(String message, Throwable t) {
// LOGGER.log(Level.SEVERE, message, t);
// }
//
// }
// Path: src/main/java/nodebox/versioncheck/Updater.java
import nodebox.Log;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
public void checkerFoundValidUpdate(UpdateChecker checker, Appcast appcast) {
// Delegate method.
if (delegate != null)
if (delegate.checkerFoundValidUpdate(checker, appcast))
return;
UpdateAlert alert = new UpdateAlert(this, appcast);
alert.setLocationRelativeTo(null);
alert.setVisible(true);
}
public void checkerDetectedLatestVersion(UpdateChecker checker, Appcast appcast) {
// Delegate method.
if (delegate != null)
if (delegate.checkerDetectedLatestVersion(checker, appcast))
return;
// Show a message that you're using the latest version if you've explicitly checked for updates.
if (!checker.isSilent()) {
JOptionPane.showMessageDialog(null, "<html><b>You're up to date!</b><br>\n" + host.getName() + " " + host.getVersion() + " is the latest version available.", "", JOptionPane.INFORMATION_MESSAGE, getHostIcon());
}
}
public void checkerEncounteredError(UpdateChecker checker, Throwable t) {
hideUpdateCheckDialog();
// Delegate method.
if (delegate != null)
if (delegate.checkerEncounteredError(checker, t))
return;
if (checker.isSilent()) { | Log.warn("Update checker encountered error.", t); |
killbill/killbill-meter-plugin | src/test/java/org/killbill/billing/plugin/meter/timeline/persistent/TestReplayer.java | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/sources/SourceSamplesForTimestamp.java
// @SuppressWarnings("unchecked")
// public class SourceSamplesForTimestamp {
//
// private static final String KEY_SOURCE = "H";
// private static final String KEY_CATEGORY = "V";
// private static final String KEY_TIMESTAMP = "T";
// private static final String KEY_SAMPLES = "S";
//
// private final Integer sourceId;
// private final String category;
// private final DateTime timestamp;
// // A map from sample id to sample value for that timestamp
// private final Map<Integer, ScalarSample> samples;
//
// public SourceSamplesForTimestamp(final int sourceId, final String category, final DateTime timestamp) {
// this(sourceId, category, timestamp, new HashMap<Integer, ScalarSample>());
// }
//
// @JsonCreator
// public SourceSamplesForTimestamp(@JsonProperty(KEY_SOURCE) final Integer sourceId, @JsonProperty(KEY_CATEGORY) final String category,
// @JsonProperty(KEY_TIMESTAMP) final DateTime timestamp, @JsonProperty(KEY_SAMPLES) final Map<Integer, ScalarSample> samples) {
// this.sourceId = sourceId;
// this.category = category;
// this.timestamp = timestamp;
// this.samples = samples;
// }
//
// public int getSourceId() {
// return sourceId;
// }
//
// public String getCategory() {
// return category;
// }
//
// public DateTime getTimestamp() {
// return timestamp;
// }
//
// public Map<Integer, ScalarSample> getSamples() {
// return samples;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("SourceSamplesForTimestamp");
// sb.append("{category='").append(category).append('\'');
// sb.append(", sourceId=").append(sourceId);
// sb.append(", timestamp=").append(timestamp);
// sb.append(", samples=").append(samples);
// sb.append('}');
//
// return sb.toString();
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// final SourceSamplesForTimestamp that = (SourceSamplesForTimestamp) o;
//
// if (category != null ? !category.equals(that.category) : that.category != null) {
// return false;
// }
// if (samples != null ? !samples.equals(that.samples) : that.samples != null) {
// return false;
// }
// if (sourceId != null ? !sourceId.equals(that.sourceId) : that.sourceId != null) {
// return false;
// }
// if (timestamp != null ? !timestamp.equals(that.timestamp) : that.timestamp != null) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = sourceId != null ? sourceId.hashCode() : 0;
// result = 31 * result + (category != null ? category.hashCode() : 0);
// result = 31 * result + (timestamp != null ? timestamp.hashCode() : 0);
// result = 31 * result + (samples != null ? samples.hashCode() : 0);
// return result;
// }
//
// @JsonValue
// public Map<String, Object> toMap() {
// return ImmutableMap.of(KEY_SOURCE, sourceId, KEY_CATEGORY, category, KEY_TIMESTAMP, timestamp, KEY_SAMPLES, samples);
// }
// }
| import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.killbill.billing.plugin.meter.MeterTestSuiteNoDB;
import org.killbill.billing.plugin.meter.timeline.sources.SourceSamplesForTimestamp;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists; | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline.persistent;
public class TestReplayer extends MeterTestSuiteNoDB {
private static final File basePath = new File(System.getProperty("java.io.tmpdir"), "TestReplayer-" + System.currentTimeMillis());
private static final class MockReplayer extends Replayer {
private final List<File> expectedFiles;
private int seen = 0;
public MockReplayer(final String path, final List<File> expectedFiles) {
super(path);
this.expectedFiles = expectedFiles;
}
@Override | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/sources/SourceSamplesForTimestamp.java
// @SuppressWarnings("unchecked")
// public class SourceSamplesForTimestamp {
//
// private static final String KEY_SOURCE = "H";
// private static final String KEY_CATEGORY = "V";
// private static final String KEY_TIMESTAMP = "T";
// private static final String KEY_SAMPLES = "S";
//
// private final Integer sourceId;
// private final String category;
// private final DateTime timestamp;
// // A map from sample id to sample value for that timestamp
// private final Map<Integer, ScalarSample> samples;
//
// public SourceSamplesForTimestamp(final int sourceId, final String category, final DateTime timestamp) {
// this(sourceId, category, timestamp, new HashMap<Integer, ScalarSample>());
// }
//
// @JsonCreator
// public SourceSamplesForTimestamp(@JsonProperty(KEY_SOURCE) final Integer sourceId, @JsonProperty(KEY_CATEGORY) final String category,
// @JsonProperty(KEY_TIMESTAMP) final DateTime timestamp, @JsonProperty(KEY_SAMPLES) final Map<Integer, ScalarSample> samples) {
// this.sourceId = sourceId;
// this.category = category;
// this.timestamp = timestamp;
// this.samples = samples;
// }
//
// public int getSourceId() {
// return sourceId;
// }
//
// public String getCategory() {
// return category;
// }
//
// public DateTime getTimestamp() {
// return timestamp;
// }
//
// public Map<Integer, ScalarSample> getSamples() {
// return samples;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("SourceSamplesForTimestamp");
// sb.append("{category='").append(category).append('\'');
// sb.append(", sourceId=").append(sourceId);
// sb.append(", timestamp=").append(timestamp);
// sb.append(", samples=").append(samples);
// sb.append('}');
//
// return sb.toString();
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// final SourceSamplesForTimestamp that = (SourceSamplesForTimestamp) o;
//
// if (category != null ? !category.equals(that.category) : that.category != null) {
// return false;
// }
// if (samples != null ? !samples.equals(that.samples) : that.samples != null) {
// return false;
// }
// if (sourceId != null ? !sourceId.equals(that.sourceId) : that.sourceId != null) {
// return false;
// }
// if (timestamp != null ? !timestamp.equals(that.timestamp) : that.timestamp != null) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = sourceId != null ? sourceId.hashCode() : 0;
// result = 31 * result + (category != null ? category.hashCode() : 0);
// result = 31 * result + (timestamp != null ? timestamp.hashCode() : 0);
// result = 31 * result + (samples != null ? samples.hashCode() : 0);
// return result;
// }
//
// @JsonValue
// public Map<String, Object> toMap() {
// return ImmutableMap.of(KEY_SOURCE, sourceId, KEY_CATEGORY, category, KEY_TIMESTAMP, timestamp, KEY_SAMPLES, samples);
// }
// }
// Path: src/test/java/org/killbill/billing/plugin/meter/timeline/persistent/TestReplayer.java
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.killbill.billing.plugin.meter.MeterTestSuiteNoDB;
import org.killbill.billing.plugin.meter.timeline.sources.SourceSamplesForTimestamp;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
/*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline.persistent;
public class TestReplayer extends MeterTestSuiteNoDB {
private static final File basePath = new File(System.getProperty("java.io.tmpdir"), "TestReplayer-" + System.currentTimeMillis());
private static final class MockReplayer extends Replayer {
private final List<File> expectedFiles;
private int seen = 0;
public MockReplayer(final String path, final List<File> expectedFiles) {
super(path);
this.expectedFiles = expectedFiles;
}
@Override | public void read(final File file, final Function<SourceSamplesForTimestamp, Void> fn) throws IOException { |
killbill/killbill-meter-plugin | src/main/java/org/killbill/billing/plugin/meter/timeline/persistent/FileBackedBuffer.java | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/sources/SourceSamplesForTimestamp.java
// @SuppressWarnings("unchecked")
// public class SourceSamplesForTimestamp {
//
// private static final String KEY_SOURCE = "H";
// private static final String KEY_CATEGORY = "V";
// private static final String KEY_TIMESTAMP = "T";
// private static final String KEY_SAMPLES = "S";
//
// private final Integer sourceId;
// private final String category;
// private final DateTime timestamp;
// // A map from sample id to sample value for that timestamp
// private final Map<Integer, ScalarSample> samples;
//
// public SourceSamplesForTimestamp(final int sourceId, final String category, final DateTime timestamp) {
// this(sourceId, category, timestamp, new HashMap<Integer, ScalarSample>());
// }
//
// @JsonCreator
// public SourceSamplesForTimestamp(@JsonProperty(KEY_SOURCE) final Integer sourceId, @JsonProperty(KEY_CATEGORY) final String category,
// @JsonProperty(KEY_TIMESTAMP) final DateTime timestamp, @JsonProperty(KEY_SAMPLES) final Map<Integer, ScalarSample> samples) {
// this.sourceId = sourceId;
// this.category = category;
// this.timestamp = timestamp;
// this.samples = samples;
// }
//
// public int getSourceId() {
// return sourceId;
// }
//
// public String getCategory() {
// return category;
// }
//
// public DateTime getTimestamp() {
// return timestamp;
// }
//
// public Map<Integer, ScalarSample> getSamples() {
// return samples;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("SourceSamplesForTimestamp");
// sb.append("{category='").append(category).append('\'');
// sb.append(", sourceId=").append(sourceId);
// sb.append(", timestamp=").append(timestamp);
// sb.append(", samples=").append(samples);
// sb.append('}');
//
// return sb.toString();
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// final SourceSamplesForTimestamp that = (SourceSamplesForTimestamp) o;
//
// if (category != null ? !category.equals(that.category) : that.category != null) {
// return false;
// }
// if (samples != null ? !samples.equals(that.samples) : that.samples != null) {
// return false;
// }
// if (sourceId != null ? !sourceId.equals(that.sourceId) : that.sourceId != null) {
// return false;
// }
// if (timestamp != null ? !timestamp.equals(that.timestamp) : that.timestamp != null) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = sourceId != null ? sourceId.hashCode() : 0;
// result = 31 * result + (category != null ? category.hashCode() : 0);
// result = 31 * result + (timestamp != null ? timestamp.hashCode() : 0);
// result = 31 * result + (samples != null ? samples.hashCode() : 0);
// return result;
// }
//
// @JsonValue
// public Map<String, Object> toMap() {
// return ImmutableMap.of(KEY_SOURCE, sourceId, KEY_CATEGORY, category, KEY_TIMESTAMP, timestamp, KEY_SAMPLES, samples);
// }
// }
| import com.fasterxml.util.membuf.MemBuffersForBytes;
import com.fasterxml.util.membuf.StreamyBytesMemBuffer;
import com.google.common.annotations.VisibleForTesting;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicLong;
import org.killbill.billing.plugin.meter.timeline.sources.SourceSamplesForTimestamp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.smile.SmileFactory;
import com.fasterxml.jackson.dataformat.smile.SmileGenerator;
import com.fasterxml.jackson.datatype.joda.JodaModule; |
private final String basePath;
private final String prefix;
private final boolean deleteFilesOnClose;
private final AtomicLong samplesforTimestampWritten = new AtomicLong();
private final Object recyclingMonitor = new Object();
private final StreamyBytesMemBuffer inputBuffer;
private StreamyBytesPersistentOutputStream out = null;
private SmileGenerator smileGenerator;
public FileBackedBuffer(final String basePath, final String prefix, final int segmentsSize, final int maxNbSegments) throws IOException {
this(basePath, prefix, true, segmentsSize, maxNbSegments);
}
public FileBackedBuffer(final String basePath, final String prefix, final boolean deleteFilesOnClose, final int segmentsSize, final int maxNbSegments) throws IOException {
this.basePath = basePath;
this.prefix = prefix;
this.deleteFilesOnClose = deleteFilesOnClose;
smileObjectMapper = new ObjectMapper(smileFactory);
smileObjectMapper.registerModule(new JodaModule());
smileObjectMapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
final MemBuffersForBytes bufs = new MemBuffersForBytes(segmentsSize, 1, maxNbSegments);
inputBuffer = bufs.createStreamyBuffer(1, maxNbSegments);
recycle();
}
| // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/sources/SourceSamplesForTimestamp.java
// @SuppressWarnings("unchecked")
// public class SourceSamplesForTimestamp {
//
// private static final String KEY_SOURCE = "H";
// private static final String KEY_CATEGORY = "V";
// private static final String KEY_TIMESTAMP = "T";
// private static final String KEY_SAMPLES = "S";
//
// private final Integer sourceId;
// private final String category;
// private final DateTime timestamp;
// // A map from sample id to sample value for that timestamp
// private final Map<Integer, ScalarSample> samples;
//
// public SourceSamplesForTimestamp(final int sourceId, final String category, final DateTime timestamp) {
// this(sourceId, category, timestamp, new HashMap<Integer, ScalarSample>());
// }
//
// @JsonCreator
// public SourceSamplesForTimestamp(@JsonProperty(KEY_SOURCE) final Integer sourceId, @JsonProperty(KEY_CATEGORY) final String category,
// @JsonProperty(KEY_TIMESTAMP) final DateTime timestamp, @JsonProperty(KEY_SAMPLES) final Map<Integer, ScalarSample> samples) {
// this.sourceId = sourceId;
// this.category = category;
// this.timestamp = timestamp;
// this.samples = samples;
// }
//
// public int getSourceId() {
// return sourceId;
// }
//
// public String getCategory() {
// return category;
// }
//
// public DateTime getTimestamp() {
// return timestamp;
// }
//
// public Map<Integer, ScalarSample> getSamples() {
// return samples;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("SourceSamplesForTimestamp");
// sb.append("{category='").append(category).append('\'');
// sb.append(", sourceId=").append(sourceId);
// sb.append(", timestamp=").append(timestamp);
// sb.append(", samples=").append(samples);
// sb.append('}');
//
// return sb.toString();
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// final SourceSamplesForTimestamp that = (SourceSamplesForTimestamp) o;
//
// if (category != null ? !category.equals(that.category) : that.category != null) {
// return false;
// }
// if (samples != null ? !samples.equals(that.samples) : that.samples != null) {
// return false;
// }
// if (sourceId != null ? !sourceId.equals(that.sourceId) : that.sourceId != null) {
// return false;
// }
// if (timestamp != null ? !timestamp.equals(that.timestamp) : that.timestamp != null) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = sourceId != null ? sourceId.hashCode() : 0;
// result = 31 * result + (category != null ? category.hashCode() : 0);
// result = 31 * result + (timestamp != null ? timestamp.hashCode() : 0);
// result = 31 * result + (samples != null ? samples.hashCode() : 0);
// return result;
// }
//
// @JsonValue
// public Map<String, Object> toMap() {
// return ImmutableMap.of(KEY_SOURCE, sourceId, KEY_CATEGORY, category, KEY_TIMESTAMP, timestamp, KEY_SAMPLES, samples);
// }
// }
// Path: src/main/java/org/killbill/billing/plugin/meter/timeline/persistent/FileBackedBuffer.java
import com.fasterxml.util.membuf.MemBuffersForBytes;
import com.fasterxml.util.membuf.StreamyBytesMemBuffer;
import com.google.common.annotations.VisibleForTesting;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicLong;
import org.killbill.billing.plugin.meter.timeline.sources.SourceSamplesForTimestamp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.smile.SmileFactory;
import com.fasterxml.jackson.dataformat.smile.SmileGenerator;
import com.fasterxml.jackson.datatype.joda.JodaModule;
private final String basePath;
private final String prefix;
private final boolean deleteFilesOnClose;
private final AtomicLong samplesforTimestampWritten = new AtomicLong();
private final Object recyclingMonitor = new Object();
private final StreamyBytesMemBuffer inputBuffer;
private StreamyBytesPersistentOutputStream out = null;
private SmileGenerator smileGenerator;
public FileBackedBuffer(final String basePath, final String prefix, final int segmentsSize, final int maxNbSegments) throws IOException {
this(basePath, prefix, true, segmentsSize, maxNbSegments);
}
public FileBackedBuffer(final String basePath, final String prefix, final boolean deleteFilesOnClose, final int segmentsSize, final int maxNbSegments) throws IOException {
this.basePath = basePath;
this.prefix = prefix;
this.deleteFilesOnClose = deleteFilesOnClose;
smileObjectMapper = new ObjectMapper(smileFactory);
smileObjectMapper.registerModule(new JodaModule());
smileObjectMapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
final MemBuffersForBytes bufs = new MemBuffersForBytes(segmentsSize, 1, maxNbSegments);
inputBuffer = bufs.createStreamyBuffer(1, maxNbSegments);
recycle();
}
| public boolean append(final SourceSamplesForTimestamp sourceSamplesForTimestamp) { |
killbill/killbill-meter-plugin | src/main/java/org/killbill/billing/plugin/meter/timeline/consumer/CSVConsumer.java | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/codec/SampleCoder.java
// public interface SampleCoder {
//
// public byte[] compressSamples(final List<ScalarSample> samples);
//
// public List<ScalarSample> decompressSamples(final byte[] sampleBytes) throws IOException;
//
// /**
// * This method writes the binary encoding of the sample to the outputStream. This encoding
// * is the form saved in the db and scanned when read from the db.
// *
// * @param outputStream the stream to which bytes should be written
// * @param sample the sample to be written
// */
// public void encodeSample(final DataOutputStream outputStream, final SampleBase sample);
//
// /**
// * Output the scalar value into the output stream
// *
// * @param outputStream the stream to which bytes should be written
// * @param value the sample value, interpreted according to the opcode
// */
// public void encodeScalarValue(final DataOutputStream outputStream, final SampleOpcode opcode, final Object value);
//
// /**
// * This routine returns a ScalarSample that may have a smaller representation than the
// * ScalarSample argument. In particular, if tries hard to choose the most compact
// * representation of double-precision values.
// *
// * @param sample A ScalarSample to be compressed
// * @return Either the same ScalarSample is that input, for for some cases of opcode DOUBLE,
// * a more compact ScalarSample which when processed returns a double value.
// */
// public ScalarSample compressSample(final ScalarSample sample);
//
// public Object decodeScalarValue(final DataInputStream inputStream, final SampleOpcode opcode) throws IOException;
//
// public double getMaxFractionError();
//
// public byte[] combineSampleBytes(final List<byte[]> sampleBytesList);
//
// public void scan(final TimelineChunk chunk, final SampleProcessor processor) throws IOException;
//
// public void scan(final byte[] samples, final byte[] times, final int sampleCount, final SampleProcessor processor) throws IOException;
// }
| import java.io.IOException;
import javax.annotation.Nullable;
import org.joda.time.DateTime;
import org.killbill.billing.plugin.meter.timeline.chunks.TimelineChunk;
import org.killbill.billing.plugin.meter.timeline.codec.SampleCoder; | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline.consumer;
public class CSVConsumer {
private CSVConsumer() {}
| // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/codec/SampleCoder.java
// public interface SampleCoder {
//
// public byte[] compressSamples(final List<ScalarSample> samples);
//
// public List<ScalarSample> decompressSamples(final byte[] sampleBytes) throws IOException;
//
// /**
// * This method writes the binary encoding of the sample to the outputStream. This encoding
// * is the form saved in the db and scanned when read from the db.
// *
// * @param outputStream the stream to which bytes should be written
// * @param sample the sample to be written
// */
// public void encodeSample(final DataOutputStream outputStream, final SampleBase sample);
//
// /**
// * Output the scalar value into the output stream
// *
// * @param outputStream the stream to which bytes should be written
// * @param value the sample value, interpreted according to the opcode
// */
// public void encodeScalarValue(final DataOutputStream outputStream, final SampleOpcode opcode, final Object value);
//
// /**
// * This routine returns a ScalarSample that may have a smaller representation than the
// * ScalarSample argument. In particular, if tries hard to choose the most compact
// * representation of double-precision values.
// *
// * @param sample A ScalarSample to be compressed
// * @return Either the same ScalarSample is that input, for for some cases of opcode DOUBLE,
// * a more compact ScalarSample which when processed returns a double value.
// */
// public ScalarSample compressSample(final ScalarSample sample);
//
// public Object decodeScalarValue(final DataInputStream inputStream, final SampleOpcode opcode) throws IOException;
//
// public double getMaxFractionError();
//
// public byte[] combineSampleBytes(final List<byte[]> sampleBytesList);
//
// public void scan(final TimelineChunk chunk, final SampleProcessor processor) throws IOException;
//
// public void scan(final byte[] samples, final byte[] times, final int sampleCount, final SampleProcessor processor) throws IOException;
// }
// Path: src/main/java/org/killbill/billing/plugin/meter/timeline/consumer/CSVConsumer.java
import java.io.IOException;
import javax.annotation.Nullable;
import org.joda.time.DateTime;
import org.killbill.billing.plugin.meter.timeline.chunks.TimelineChunk;
import org.killbill.billing.plugin.meter.timeline.codec.SampleCoder;
/*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline.consumer;
public class CSVConsumer {
private CSVConsumer() {}
| public static String getSamplesAsCSV(final SampleCoder sampleCoder, final TimelineChunk chunk) throws IOException { |
killbill/killbill-meter-plugin | src/main/java/org/killbill/billing/plugin/meter/api/user/JsonSamplesOutputer.java | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/codec/SampleCoder.java
// public interface SampleCoder {
//
// public byte[] compressSamples(final List<ScalarSample> samples);
//
// public List<ScalarSample> decompressSamples(final byte[] sampleBytes) throws IOException;
//
// /**
// * This method writes the binary encoding of the sample to the outputStream. This encoding
// * is the form saved in the db and scanned when read from the db.
// *
// * @param outputStream the stream to which bytes should be written
// * @param sample the sample to be written
// */
// public void encodeSample(final DataOutputStream outputStream, final SampleBase sample);
//
// /**
// * Output the scalar value into the output stream
// *
// * @param outputStream the stream to which bytes should be written
// * @param value the sample value, interpreted according to the opcode
// */
// public void encodeScalarValue(final DataOutputStream outputStream, final SampleOpcode opcode, final Object value);
//
// /**
// * This routine returns a ScalarSample that may have a smaller representation than the
// * ScalarSample argument. In particular, if tries hard to choose the most compact
// * representation of double-precision values.
// *
// * @param sample A ScalarSample to be compressed
// * @return Either the same ScalarSample is that input, for for some cases of opcode DOUBLE,
// * a more compact ScalarSample which when processed returns a double value.
// */
// public ScalarSample compressSample(final ScalarSample sample);
//
// public Object decodeScalarValue(final DataInputStream inputStream, final SampleOpcode opcode) throws IOException;
//
// public double getMaxFractionError();
//
// public byte[] combineSampleBytes(final List<byte[]> sampleBytesList);
//
// public void scan(final TimelineChunk chunk, final SampleProcessor processor) throws IOException;
//
// public void scan(final byte[] samples, final byte[] times, final int sampleCount, final SampleProcessor processor) throws IOException;
// }
//
// Path: src/main/java/org/killbill/billing/plugin/meter/timeline/persistent/TimelineDao.java
// public interface TimelineDao {
//
// // Sources table
//
// Integer getSourceId(String source, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// String getSource(Integer sourceId, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// BiMap<Integer, String> getSources(TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// int getOrAddSource(String source, CallContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// // Event categories table
//
// Integer getEventCategoryId(String eventCategory, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// String getEventCategory(Integer eventCategoryId, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// BiMap<Integer, String> getEventCategories(TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// int getOrAddEventCategory(String eventCategory, CallContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// // Metrics table
//
// Integer getMetricId(int eventCategory, String metric, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// CategoryRecordIdAndMetric getCategoryIdAndMetric(Integer metricId, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// BiMap<Integer, CategoryRecordIdAndMetric> getMetrics(TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// int getOrAddMetric(Integer eventCategoryId, String metric, CallContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// // Timelines tables
//
// Long insertTimelineChunk(TimelineChunk timelineChunk, CallContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// void getSamplesBySourceIdsAndMetricIds(List<Integer> sourceIds,
// @Nullable List<Integer> metricIds,
// DateTime startTime,
// DateTime endTime,
// TimelineChunkConsumer chunkConsumer,
// TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// Integer insertLastStartTimes(StartTimes startTimes, CallContext context);
//
// StartTimes getLastStartTimes(TenantContext context);
//
// void deleteLastStartTimes(CallContext context);
//
// void bulkInsertTimelineChunks(List<TimelineChunk> timelineChunkList, CallContext context);
//
// void test(TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
// }
| import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nullable;
import org.joda.time.DateTime;
import org.killbill.billing.plugin.meter.timeline.TimelineEventHandler;
import org.killbill.billing.plugin.meter.timeline.chunks.TimelineChunk;
import org.killbill.billing.plugin.meter.timeline.codec.DefaultSampleCoder;
import org.killbill.billing.plugin.meter.timeline.codec.SampleCoder;
import org.killbill.billing.plugin.meter.timeline.consumer.TimelineChunkConsumer;
import org.killbill.billing.plugin.meter.timeline.persistent.TimelineDao;
import org.killbill.billing.util.callcontext.TenantContext;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper; | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.api.user;
public abstract class JsonSamplesOutputer {
protected static final ObjectMapper objectMapper = new ObjectMapper();
protected final TimelineEventHandler timelineEventHandler; | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/codec/SampleCoder.java
// public interface SampleCoder {
//
// public byte[] compressSamples(final List<ScalarSample> samples);
//
// public List<ScalarSample> decompressSamples(final byte[] sampleBytes) throws IOException;
//
// /**
// * This method writes the binary encoding of the sample to the outputStream. This encoding
// * is the form saved in the db and scanned when read from the db.
// *
// * @param outputStream the stream to which bytes should be written
// * @param sample the sample to be written
// */
// public void encodeSample(final DataOutputStream outputStream, final SampleBase sample);
//
// /**
// * Output the scalar value into the output stream
// *
// * @param outputStream the stream to which bytes should be written
// * @param value the sample value, interpreted according to the opcode
// */
// public void encodeScalarValue(final DataOutputStream outputStream, final SampleOpcode opcode, final Object value);
//
// /**
// * This routine returns a ScalarSample that may have a smaller representation than the
// * ScalarSample argument. In particular, if tries hard to choose the most compact
// * representation of double-precision values.
// *
// * @param sample A ScalarSample to be compressed
// * @return Either the same ScalarSample is that input, for for some cases of opcode DOUBLE,
// * a more compact ScalarSample which when processed returns a double value.
// */
// public ScalarSample compressSample(final ScalarSample sample);
//
// public Object decodeScalarValue(final DataInputStream inputStream, final SampleOpcode opcode) throws IOException;
//
// public double getMaxFractionError();
//
// public byte[] combineSampleBytes(final List<byte[]> sampleBytesList);
//
// public void scan(final TimelineChunk chunk, final SampleProcessor processor) throws IOException;
//
// public void scan(final byte[] samples, final byte[] times, final int sampleCount, final SampleProcessor processor) throws IOException;
// }
//
// Path: src/main/java/org/killbill/billing/plugin/meter/timeline/persistent/TimelineDao.java
// public interface TimelineDao {
//
// // Sources table
//
// Integer getSourceId(String source, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// String getSource(Integer sourceId, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// BiMap<Integer, String> getSources(TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// int getOrAddSource(String source, CallContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// // Event categories table
//
// Integer getEventCategoryId(String eventCategory, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// String getEventCategory(Integer eventCategoryId, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// BiMap<Integer, String> getEventCategories(TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// int getOrAddEventCategory(String eventCategory, CallContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// // Metrics table
//
// Integer getMetricId(int eventCategory, String metric, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// CategoryRecordIdAndMetric getCategoryIdAndMetric(Integer metricId, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// BiMap<Integer, CategoryRecordIdAndMetric> getMetrics(TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// int getOrAddMetric(Integer eventCategoryId, String metric, CallContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// // Timelines tables
//
// Long insertTimelineChunk(TimelineChunk timelineChunk, CallContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// void getSamplesBySourceIdsAndMetricIds(List<Integer> sourceIds,
// @Nullable List<Integer> metricIds,
// DateTime startTime,
// DateTime endTime,
// TimelineChunkConsumer chunkConsumer,
// TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// Integer insertLastStartTimes(StartTimes startTimes, CallContext context);
//
// StartTimes getLastStartTimes(TenantContext context);
//
// void deleteLastStartTimes(CallContext context);
//
// void bulkInsertTimelineChunks(List<TimelineChunk> timelineChunkList, CallContext context);
//
// void test(TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
// }
// Path: src/main/java/org/killbill/billing/plugin/meter/api/user/JsonSamplesOutputer.java
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nullable;
import org.joda.time.DateTime;
import org.killbill.billing.plugin.meter.timeline.TimelineEventHandler;
import org.killbill.billing.plugin.meter.timeline.chunks.TimelineChunk;
import org.killbill.billing.plugin.meter.timeline.codec.DefaultSampleCoder;
import org.killbill.billing.plugin.meter.timeline.codec.SampleCoder;
import org.killbill.billing.plugin.meter.timeline.consumer.TimelineChunkConsumer;
import org.killbill.billing.plugin.meter.timeline.persistent.TimelineDao;
import org.killbill.billing.util.callcontext.TenantContext;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
/*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.api.user;
public abstract class JsonSamplesOutputer {
protected static final ObjectMapper objectMapper = new ObjectMapper();
protected final TimelineEventHandler timelineEventHandler; | protected final TimelineDao timelineDao; |
killbill/killbill-meter-plugin | src/main/java/org/killbill/billing/plugin/meter/api/user/JsonSamplesOutputer.java | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/codec/SampleCoder.java
// public interface SampleCoder {
//
// public byte[] compressSamples(final List<ScalarSample> samples);
//
// public List<ScalarSample> decompressSamples(final byte[] sampleBytes) throws IOException;
//
// /**
// * This method writes the binary encoding of the sample to the outputStream. This encoding
// * is the form saved in the db and scanned when read from the db.
// *
// * @param outputStream the stream to which bytes should be written
// * @param sample the sample to be written
// */
// public void encodeSample(final DataOutputStream outputStream, final SampleBase sample);
//
// /**
// * Output the scalar value into the output stream
// *
// * @param outputStream the stream to which bytes should be written
// * @param value the sample value, interpreted according to the opcode
// */
// public void encodeScalarValue(final DataOutputStream outputStream, final SampleOpcode opcode, final Object value);
//
// /**
// * This routine returns a ScalarSample that may have a smaller representation than the
// * ScalarSample argument. In particular, if tries hard to choose the most compact
// * representation of double-precision values.
// *
// * @param sample A ScalarSample to be compressed
// * @return Either the same ScalarSample is that input, for for some cases of opcode DOUBLE,
// * a more compact ScalarSample which when processed returns a double value.
// */
// public ScalarSample compressSample(final ScalarSample sample);
//
// public Object decodeScalarValue(final DataInputStream inputStream, final SampleOpcode opcode) throws IOException;
//
// public double getMaxFractionError();
//
// public byte[] combineSampleBytes(final List<byte[]> sampleBytesList);
//
// public void scan(final TimelineChunk chunk, final SampleProcessor processor) throws IOException;
//
// public void scan(final byte[] samples, final byte[] times, final int sampleCount, final SampleProcessor processor) throws IOException;
// }
//
// Path: src/main/java/org/killbill/billing/plugin/meter/timeline/persistent/TimelineDao.java
// public interface TimelineDao {
//
// // Sources table
//
// Integer getSourceId(String source, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// String getSource(Integer sourceId, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// BiMap<Integer, String> getSources(TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// int getOrAddSource(String source, CallContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// // Event categories table
//
// Integer getEventCategoryId(String eventCategory, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// String getEventCategory(Integer eventCategoryId, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// BiMap<Integer, String> getEventCategories(TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// int getOrAddEventCategory(String eventCategory, CallContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// // Metrics table
//
// Integer getMetricId(int eventCategory, String metric, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// CategoryRecordIdAndMetric getCategoryIdAndMetric(Integer metricId, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// BiMap<Integer, CategoryRecordIdAndMetric> getMetrics(TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// int getOrAddMetric(Integer eventCategoryId, String metric, CallContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// // Timelines tables
//
// Long insertTimelineChunk(TimelineChunk timelineChunk, CallContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// void getSamplesBySourceIdsAndMetricIds(List<Integer> sourceIds,
// @Nullable List<Integer> metricIds,
// DateTime startTime,
// DateTime endTime,
// TimelineChunkConsumer chunkConsumer,
// TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// Integer insertLastStartTimes(StartTimes startTimes, CallContext context);
//
// StartTimes getLastStartTimes(TenantContext context);
//
// void deleteLastStartTimes(CallContext context);
//
// void bulkInsertTimelineChunks(List<TimelineChunk> timelineChunkList, CallContext context);
//
// void test(TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
// }
| import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nullable;
import org.joda.time.DateTime;
import org.killbill.billing.plugin.meter.timeline.TimelineEventHandler;
import org.killbill.billing.plugin.meter.timeline.chunks.TimelineChunk;
import org.killbill.billing.plugin.meter.timeline.codec.DefaultSampleCoder;
import org.killbill.billing.plugin.meter.timeline.codec.SampleCoder;
import org.killbill.billing.plugin.meter.timeline.consumer.TimelineChunkConsumer;
import org.killbill.billing.plugin.meter.timeline.persistent.TimelineDao;
import org.killbill.billing.util.callcontext.TenantContext;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper; | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.api.user;
public abstract class JsonSamplesOutputer {
protected static final ObjectMapper objectMapper = new ObjectMapper();
protected final TimelineEventHandler timelineEventHandler;
protected final TimelineDao timelineDao; | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/codec/SampleCoder.java
// public interface SampleCoder {
//
// public byte[] compressSamples(final List<ScalarSample> samples);
//
// public List<ScalarSample> decompressSamples(final byte[] sampleBytes) throws IOException;
//
// /**
// * This method writes the binary encoding of the sample to the outputStream. This encoding
// * is the form saved in the db and scanned when read from the db.
// *
// * @param outputStream the stream to which bytes should be written
// * @param sample the sample to be written
// */
// public void encodeSample(final DataOutputStream outputStream, final SampleBase sample);
//
// /**
// * Output the scalar value into the output stream
// *
// * @param outputStream the stream to which bytes should be written
// * @param value the sample value, interpreted according to the opcode
// */
// public void encodeScalarValue(final DataOutputStream outputStream, final SampleOpcode opcode, final Object value);
//
// /**
// * This routine returns a ScalarSample that may have a smaller representation than the
// * ScalarSample argument. In particular, if tries hard to choose the most compact
// * representation of double-precision values.
// *
// * @param sample A ScalarSample to be compressed
// * @return Either the same ScalarSample is that input, for for some cases of opcode DOUBLE,
// * a more compact ScalarSample which when processed returns a double value.
// */
// public ScalarSample compressSample(final ScalarSample sample);
//
// public Object decodeScalarValue(final DataInputStream inputStream, final SampleOpcode opcode) throws IOException;
//
// public double getMaxFractionError();
//
// public byte[] combineSampleBytes(final List<byte[]> sampleBytesList);
//
// public void scan(final TimelineChunk chunk, final SampleProcessor processor) throws IOException;
//
// public void scan(final byte[] samples, final byte[] times, final int sampleCount, final SampleProcessor processor) throws IOException;
// }
//
// Path: src/main/java/org/killbill/billing/plugin/meter/timeline/persistent/TimelineDao.java
// public interface TimelineDao {
//
// // Sources table
//
// Integer getSourceId(String source, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// String getSource(Integer sourceId, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// BiMap<Integer, String> getSources(TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// int getOrAddSource(String source, CallContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// // Event categories table
//
// Integer getEventCategoryId(String eventCategory, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// String getEventCategory(Integer eventCategoryId, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// BiMap<Integer, String> getEventCategories(TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// int getOrAddEventCategory(String eventCategory, CallContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// // Metrics table
//
// Integer getMetricId(int eventCategory, String metric, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// CategoryRecordIdAndMetric getCategoryIdAndMetric(Integer metricId, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// BiMap<Integer, CategoryRecordIdAndMetric> getMetrics(TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// int getOrAddMetric(Integer eventCategoryId, String metric, CallContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// // Timelines tables
//
// Long insertTimelineChunk(TimelineChunk timelineChunk, CallContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// void getSamplesBySourceIdsAndMetricIds(List<Integer> sourceIds,
// @Nullable List<Integer> metricIds,
// DateTime startTime,
// DateTime endTime,
// TimelineChunkConsumer chunkConsumer,
// TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
//
// Integer insertLastStartTimes(StartTimes startTimes, CallContext context);
//
// StartTimes getLastStartTimes(TenantContext context);
//
// void deleteLastStartTimes(CallContext context);
//
// void bulkInsertTimelineChunks(List<TimelineChunk> timelineChunkList, CallContext context);
//
// void test(TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
// }
// Path: src/main/java/org/killbill/billing/plugin/meter/api/user/JsonSamplesOutputer.java
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nullable;
import org.joda.time.DateTime;
import org.killbill.billing.plugin.meter.timeline.TimelineEventHandler;
import org.killbill.billing.plugin.meter.timeline.chunks.TimelineChunk;
import org.killbill.billing.plugin.meter.timeline.codec.DefaultSampleCoder;
import org.killbill.billing.plugin.meter.timeline.codec.SampleCoder;
import org.killbill.billing.plugin.meter.timeline.consumer.TimelineChunkConsumer;
import org.killbill.billing.plugin.meter.timeline.persistent.TimelineDao;
import org.killbill.billing.util.callcontext.TenantContext;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
/*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.api.user;
public abstract class JsonSamplesOutputer {
protected static final ObjectMapper objectMapper = new ObjectMapper();
protected final TimelineEventHandler timelineEventHandler;
protected final TimelineDao timelineDao; | protected final SampleCoder sampleCoder; |
killbill/killbill-meter-plugin | src/main/java/org/killbill/billing/plugin/meter/timeline/codec/TimelineChunkAccumulator.java | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/samples/SampleBase.java
// public abstract class SampleBase {
//
// protected final SampleOpcode opcode;
//
// public SampleBase(final SampleOpcode opcode) {
// this.opcode = opcode;
// }
//
// public SampleOpcode getOpcode() {
// return opcode;
// }
// }
| import java.io.IOException;
import org.joda.time.DateTime;
import org.killbill.billing.plugin.meter.timeline.chunks.TimelineChunk;
import org.killbill.billing.plugin.meter.timeline.samples.SampleBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline.codec;
/**
* This class represents a sequence of values for a single attribute,
* e.g., "TP99 Response Time", for one source and one specific time range,
* as the object is being accumulated. It is not used to represent
* past timeline sequences; they are held in TimelineChunk objects.
* <p/>
* It accumulates samples in a byte array object. Readers can call
* getEncodedSamples() at any time to get the latest data.
*/
public class TimelineChunkAccumulator extends SampleAccumulator {
private static final Logger log = LoggerFactory.getLogger(TimelineChunkAccumulator.class);
private final int sourceId;
private final int metricId;
public TimelineChunkAccumulator(final int sourceId, final int metricId, final SampleCoder sampleCoder) {
super(sampleCoder);
this.sourceId = sourceId;
this.metricId = metricId;
}
| // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/samples/SampleBase.java
// public abstract class SampleBase {
//
// protected final SampleOpcode opcode;
//
// public SampleBase(final SampleOpcode opcode) {
// this.opcode = opcode;
// }
//
// public SampleOpcode getOpcode() {
// return opcode;
// }
// }
// Path: src/main/java/org/killbill/billing/plugin/meter/timeline/codec/TimelineChunkAccumulator.java
import java.io.IOException;
import org.joda.time.DateTime;
import org.killbill.billing.plugin.meter.timeline.chunks.TimelineChunk;
import org.killbill.billing.plugin.meter.timeline.samples.SampleBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline.codec;
/**
* This class represents a sequence of values for a single attribute,
* e.g., "TP99 Response Time", for one source and one specific time range,
* as the object is being accumulated. It is not used to represent
* past timeline sequences; they are held in TimelineChunk objects.
* <p/>
* It accumulates samples in a byte array object. Readers can call
* getEncodedSamples() at any time to get the latest data.
*/
public class TimelineChunkAccumulator extends SampleAccumulator {
private static final Logger log = LoggerFactory.getLogger(TimelineChunkAccumulator.class);
private final int sourceId;
private final int metricId;
public TimelineChunkAccumulator(final int sourceId, final int metricId, final SampleCoder sampleCoder) {
super(sampleCoder);
this.sourceId = sourceId;
this.metricId = metricId;
}
| private TimelineChunkAccumulator(final int sourceId, final int metricId, final byte[] bytes, final SampleBase lastSample, final int sampleCount, final SampleCoder sampleCoder) throws IOException { |
killbill/killbill-meter-plugin | src/main/java/org/killbill/billing/plugin/meter/timeline/chunks/TimelineChunkBinder.java | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/codec/TimesAndSamplesCoder.java
// public class TimesAndSamplesCoder {
//
// public static int getSizeOfTimeBytes(final byte[] timesAndSamples) {
// final DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(timesAndSamples));
// try {
// return inputStream.readInt();
// } catch (IOException e) {
// throw new IllegalStateException(String.format("Exception reading timeByteCount in TimelineChunkMapper.map() for timesAndSamples %s",
// new String(Hex.encodeHex(timesAndSamples))), e);
// }
// }
//
// public static int getEncodedLength(final TimelineChunk chunk) {
// return 4 + chunk.getTimeBytesAndSampleBytes().getTimeBytes().length +
// chunk.getTimeBytesAndSampleBytes().getSampleBytes().length;
// }
//
// public static byte[] getTimeBytes(final byte[] timesAndSamples) {
// final int timeByteCount = getSizeOfTimeBytes(timesAndSamples);
// return Arrays.copyOfRange(timesAndSamples, 4, 4 + timeByteCount);
// }
//
// public static byte[] getSampleBytes(final byte[] timesAndSamples) {
// final int timeByteCount = getSizeOfTimeBytes(timesAndSamples);
// return Arrays.copyOfRange(timesAndSamples, 4 + timeByteCount, timesAndSamples.length);
// }
//
// public static TimeBytesAndSampleBytes getTimesBytesAndSampleBytes(final byte[] timesAndSamples) {
// final int timeByteCount = getSizeOfTimeBytes(timesAndSamples);
// final byte[] timeBytes = Arrays.copyOfRange(timesAndSamples, 4, 4 + timeByteCount);
// final byte[] sampleBytes = Arrays.copyOfRange(timesAndSamples, 4 + timeByteCount, timesAndSamples.length);
// return new TimeBytesAndSampleBytes(timeBytes, sampleBytes);
// }
//
// public static byte[] combineTimesAndSamples(final byte[] times, final byte[] samples) {
// final int totalSamplesSize = 4 + times.length + samples.length;
// final ByteArrayOutputStream baStream = new ByteArrayOutputStream(totalSamplesSize);
// final DataOutputStream outputStream = new DataOutputStream(baStream);
// try {
// outputStream.writeInt(times.length);
// outputStream.write(times);
// outputStream.write(samples);
// outputStream.flush();
// return baStream.toByteArray();
// } catch (IOException e) {
// throw new IllegalStateException(String.format("Exception reading timeByteCount in TimelineChunkMapper.map() for times %s, samples %s",
// new String(Hex.encodeHex(times)), new String(Hex.encodeHex(samples))), e);
// }
// }
// }
//
// Path: src/main/java/org/killbill/billing/plugin/meter/timeline/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static DateTime dateTimeFromUnixSeconds(final int unixTime) {
// return new DateTime(((long) unixTime) * 1000L, DateTimeZone.UTC);
// }
//
// public static int unixSeconds(final DateTime dateTime) {
// final long millis = dateTime.toDateTime(DateTimeZone.UTC).getMillis();
// return (int) (millis / 1000L);
// }
// }
| import org.skife.jdbi.v2.sqlobject.BindingAnnotation;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.sql.Types;
import org.killbill.billing.plugin.meter.timeline.chunks.TimelineChunkBinder.TimelineChunkBinderFactory;
import org.killbill.billing.plugin.meter.timeline.codec.TimesAndSamplesCoder;
import org.killbill.billing.plugin.meter.timeline.util.DateTimeUtils;
import org.skife.jdbi.v2.SQLStatement;
import org.skife.jdbi.v2.sqlobject.Binder;
import org.skife.jdbi.v2.sqlobject.BinderFactory; | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline.chunks;
/**
* jdbi binder for TimelineChunk
*/
@BindingAnnotation(TimelineChunkBinderFactory.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
public @interface TimelineChunkBinder {
public static class TimelineChunkBinderFactory implements BinderFactory {
// Maximum size in bytes for a series of timesAndSamples to stay "in row" (stored as VARBINARY).
// Past this threshold, data is stored as a BLOB.
private static final int MAX_IN_ROW_BLOB_SIZE = 400;
public Binder build(final Annotation annotation) {
return new Binder<TimelineChunkBinder, TimelineChunk>() {
public void bind(final SQLStatement query, final TimelineChunkBinder binder, final TimelineChunk timelineChunk) {
query.bind("sourceRecordId", timelineChunk.getSourceId())
.bind("metricRecordId", timelineChunk.getMetricId())
.bind("sampleCount", timelineChunk.getSampleCount()) | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/codec/TimesAndSamplesCoder.java
// public class TimesAndSamplesCoder {
//
// public static int getSizeOfTimeBytes(final byte[] timesAndSamples) {
// final DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(timesAndSamples));
// try {
// return inputStream.readInt();
// } catch (IOException e) {
// throw new IllegalStateException(String.format("Exception reading timeByteCount in TimelineChunkMapper.map() for timesAndSamples %s",
// new String(Hex.encodeHex(timesAndSamples))), e);
// }
// }
//
// public static int getEncodedLength(final TimelineChunk chunk) {
// return 4 + chunk.getTimeBytesAndSampleBytes().getTimeBytes().length +
// chunk.getTimeBytesAndSampleBytes().getSampleBytes().length;
// }
//
// public static byte[] getTimeBytes(final byte[] timesAndSamples) {
// final int timeByteCount = getSizeOfTimeBytes(timesAndSamples);
// return Arrays.copyOfRange(timesAndSamples, 4, 4 + timeByteCount);
// }
//
// public static byte[] getSampleBytes(final byte[] timesAndSamples) {
// final int timeByteCount = getSizeOfTimeBytes(timesAndSamples);
// return Arrays.copyOfRange(timesAndSamples, 4 + timeByteCount, timesAndSamples.length);
// }
//
// public static TimeBytesAndSampleBytes getTimesBytesAndSampleBytes(final byte[] timesAndSamples) {
// final int timeByteCount = getSizeOfTimeBytes(timesAndSamples);
// final byte[] timeBytes = Arrays.copyOfRange(timesAndSamples, 4, 4 + timeByteCount);
// final byte[] sampleBytes = Arrays.copyOfRange(timesAndSamples, 4 + timeByteCount, timesAndSamples.length);
// return new TimeBytesAndSampleBytes(timeBytes, sampleBytes);
// }
//
// public static byte[] combineTimesAndSamples(final byte[] times, final byte[] samples) {
// final int totalSamplesSize = 4 + times.length + samples.length;
// final ByteArrayOutputStream baStream = new ByteArrayOutputStream(totalSamplesSize);
// final DataOutputStream outputStream = new DataOutputStream(baStream);
// try {
// outputStream.writeInt(times.length);
// outputStream.write(times);
// outputStream.write(samples);
// outputStream.flush();
// return baStream.toByteArray();
// } catch (IOException e) {
// throw new IllegalStateException(String.format("Exception reading timeByteCount in TimelineChunkMapper.map() for times %s, samples %s",
// new String(Hex.encodeHex(times)), new String(Hex.encodeHex(samples))), e);
// }
// }
// }
//
// Path: src/main/java/org/killbill/billing/plugin/meter/timeline/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static DateTime dateTimeFromUnixSeconds(final int unixTime) {
// return new DateTime(((long) unixTime) * 1000L, DateTimeZone.UTC);
// }
//
// public static int unixSeconds(final DateTime dateTime) {
// final long millis = dateTime.toDateTime(DateTimeZone.UTC).getMillis();
// return (int) (millis / 1000L);
// }
// }
// Path: src/main/java/org/killbill/billing/plugin/meter/timeline/chunks/TimelineChunkBinder.java
import org.skife.jdbi.v2.sqlobject.BindingAnnotation;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.sql.Types;
import org.killbill.billing.plugin.meter.timeline.chunks.TimelineChunkBinder.TimelineChunkBinderFactory;
import org.killbill.billing.plugin.meter.timeline.codec.TimesAndSamplesCoder;
import org.killbill.billing.plugin.meter.timeline.util.DateTimeUtils;
import org.skife.jdbi.v2.SQLStatement;
import org.skife.jdbi.v2.sqlobject.Binder;
import org.skife.jdbi.v2.sqlobject.BinderFactory;
/*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline.chunks;
/**
* jdbi binder for TimelineChunk
*/
@BindingAnnotation(TimelineChunkBinderFactory.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
public @interface TimelineChunkBinder {
public static class TimelineChunkBinderFactory implements BinderFactory {
// Maximum size in bytes for a series of timesAndSamples to stay "in row" (stored as VARBINARY).
// Past this threshold, data is stored as a BLOB.
private static final int MAX_IN_ROW_BLOB_SIZE = 400;
public Binder build(final Annotation annotation) {
return new Binder<TimelineChunkBinder, TimelineChunk>() {
public void bind(final SQLStatement query, final TimelineChunkBinder binder, final TimelineChunk timelineChunk) {
query.bind("sourceRecordId", timelineChunk.getSourceId())
.bind("metricRecordId", timelineChunk.getMetricId())
.bind("sampleCount", timelineChunk.getSampleCount()) | .bind("startTime", DateTimeUtils.unixSeconds(timelineChunk.getStartTime())) |
killbill/killbill-meter-plugin | src/main/java/org/killbill/billing/plugin/meter/timeline/chunks/TimelineChunkBinder.java | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/codec/TimesAndSamplesCoder.java
// public class TimesAndSamplesCoder {
//
// public static int getSizeOfTimeBytes(final byte[] timesAndSamples) {
// final DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(timesAndSamples));
// try {
// return inputStream.readInt();
// } catch (IOException e) {
// throw new IllegalStateException(String.format("Exception reading timeByteCount in TimelineChunkMapper.map() for timesAndSamples %s",
// new String(Hex.encodeHex(timesAndSamples))), e);
// }
// }
//
// public static int getEncodedLength(final TimelineChunk chunk) {
// return 4 + chunk.getTimeBytesAndSampleBytes().getTimeBytes().length +
// chunk.getTimeBytesAndSampleBytes().getSampleBytes().length;
// }
//
// public static byte[] getTimeBytes(final byte[] timesAndSamples) {
// final int timeByteCount = getSizeOfTimeBytes(timesAndSamples);
// return Arrays.copyOfRange(timesAndSamples, 4, 4 + timeByteCount);
// }
//
// public static byte[] getSampleBytes(final byte[] timesAndSamples) {
// final int timeByteCount = getSizeOfTimeBytes(timesAndSamples);
// return Arrays.copyOfRange(timesAndSamples, 4 + timeByteCount, timesAndSamples.length);
// }
//
// public static TimeBytesAndSampleBytes getTimesBytesAndSampleBytes(final byte[] timesAndSamples) {
// final int timeByteCount = getSizeOfTimeBytes(timesAndSamples);
// final byte[] timeBytes = Arrays.copyOfRange(timesAndSamples, 4, 4 + timeByteCount);
// final byte[] sampleBytes = Arrays.copyOfRange(timesAndSamples, 4 + timeByteCount, timesAndSamples.length);
// return new TimeBytesAndSampleBytes(timeBytes, sampleBytes);
// }
//
// public static byte[] combineTimesAndSamples(final byte[] times, final byte[] samples) {
// final int totalSamplesSize = 4 + times.length + samples.length;
// final ByteArrayOutputStream baStream = new ByteArrayOutputStream(totalSamplesSize);
// final DataOutputStream outputStream = new DataOutputStream(baStream);
// try {
// outputStream.writeInt(times.length);
// outputStream.write(times);
// outputStream.write(samples);
// outputStream.flush();
// return baStream.toByteArray();
// } catch (IOException e) {
// throw new IllegalStateException(String.format("Exception reading timeByteCount in TimelineChunkMapper.map() for times %s, samples %s",
// new String(Hex.encodeHex(times)), new String(Hex.encodeHex(samples))), e);
// }
// }
// }
//
// Path: src/main/java/org/killbill/billing/plugin/meter/timeline/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static DateTime dateTimeFromUnixSeconds(final int unixTime) {
// return new DateTime(((long) unixTime) * 1000L, DateTimeZone.UTC);
// }
//
// public static int unixSeconds(final DateTime dateTime) {
// final long millis = dateTime.toDateTime(DateTimeZone.UTC).getMillis();
// return (int) (millis / 1000L);
// }
// }
| import org.skife.jdbi.v2.sqlobject.BindingAnnotation;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.sql.Types;
import org.killbill.billing.plugin.meter.timeline.chunks.TimelineChunkBinder.TimelineChunkBinderFactory;
import org.killbill.billing.plugin.meter.timeline.codec.TimesAndSamplesCoder;
import org.killbill.billing.plugin.meter.timeline.util.DateTimeUtils;
import org.skife.jdbi.v2.SQLStatement;
import org.skife.jdbi.v2.sqlobject.Binder;
import org.skife.jdbi.v2.sqlobject.BinderFactory; | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline.chunks;
/**
* jdbi binder for TimelineChunk
*/
@BindingAnnotation(TimelineChunkBinderFactory.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
public @interface TimelineChunkBinder {
public static class TimelineChunkBinderFactory implements BinderFactory {
// Maximum size in bytes for a series of timesAndSamples to stay "in row" (stored as VARBINARY).
// Past this threshold, data is stored as a BLOB.
private static final int MAX_IN_ROW_BLOB_SIZE = 400;
public Binder build(final Annotation annotation) {
return new Binder<TimelineChunkBinder, TimelineChunk>() {
public void bind(final SQLStatement query, final TimelineChunkBinder binder, final TimelineChunk timelineChunk) {
query.bind("sourceRecordId", timelineChunk.getSourceId())
.bind("metricRecordId", timelineChunk.getMetricId())
.bind("sampleCount", timelineChunk.getSampleCount())
.bind("startTime", DateTimeUtils.unixSeconds(timelineChunk.getStartTime()))
.bind("endTime", DateTimeUtils.unixSeconds(timelineChunk.getEndTime()))
.bind("aggregationLevel", timelineChunk.getAggregationLevel())
.bind("notValid", timelineChunk.getNotValid() ? 1 : 0)
.bind("dontAggregate", timelineChunk.getDontAggregate() ? 1 : 0);
final byte[] times = timelineChunk.getTimeBytesAndSampleBytes().getTimeBytes();
final byte[] samples = timelineChunk.getTimeBytesAndSampleBytes().getSampleBytes(); | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/codec/TimesAndSamplesCoder.java
// public class TimesAndSamplesCoder {
//
// public static int getSizeOfTimeBytes(final byte[] timesAndSamples) {
// final DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(timesAndSamples));
// try {
// return inputStream.readInt();
// } catch (IOException e) {
// throw new IllegalStateException(String.format("Exception reading timeByteCount in TimelineChunkMapper.map() for timesAndSamples %s",
// new String(Hex.encodeHex(timesAndSamples))), e);
// }
// }
//
// public static int getEncodedLength(final TimelineChunk chunk) {
// return 4 + chunk.getTimeBytesAndSampleBytes().getTimeBytes().length +
// chunk.getTimeBytesAndSampleBytes().getSampleBytes().length;
// }
//
// public static byte[] getTimeBytes(final byte[] timesAndSamples) {
// final int timeByteCount = getSizeOfTimeBytes(timesAndSamples);
// return Arrays.copyOfRange(timesAndSamples, 4, 4 + timeByteCount);
// }
//
// public static byte[] getSampleBytes(final byte[] timesAndSamples) {
// final int timeByteCount = getSizeOfTimeBytes(timesAndSamples);
// return Arrays.copyOfRange(timesAndSamples, 4 + timeByteCount, timesAndSamples.length);
// }
//
// public static TimeBytesAndSampleBytes getTimesBytesAndSampleBytes(final byte[] timesAndSamples) {
// final int timeByteCount = getSizeOfTimeBytes(timesAndSamples);
// final byte[] timeBytes = Arrays.copyOfRange(timesAndSamples, 4, 4 + timeByteCount);
// final byte[] sampleBytes = Arrays.copyOfRange(timesAndSamples, 4 + timeByteCount, timesAndSamples.length);
// return new TimeBytesAndSampleBytes(timeBytes, sampleBytes);
// }
//
// public static byte[] combineTimesAndSamples(final byte[] times, final byte[] samples) {
// final int totalSamplesSize = 4 + times.length + samples.length;
// final ByteArrayOutputStream baStream = new ByteArrayOutputStream(totalSamplesSize);
// final DataOutputStream outputStream = new DataOutputStream(baStream);
// try {
// outputStream.writeInt(times.length);
// outputStream.write(times);
// outputStream.write(samples);
// outputStream.flush();
// return baStream.toByteArray();
// } catch (IOException e) {
// throw new IllegalStateException(String.format("Exception reading timeByteCount in TimelineChunkMapper.map() for times %s, samples %s",
// new String(Hex.encodeHex(times)), new String(Hex.encodeHex(samples))), e);
// }
// }
// }
//
// Path: src/main/java/org/killbill/billing/plugin/meter/timeline/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static DateTime dateTimeFromUnixSeconds(final int unixTime) {
// return new DateTime(((long) unixTime) * 1000L, DateTimeZone.UTC);
// }
//
// public static int unixSeconds(final DateTime dateTime) {
// final long millis = dateTime.toDateTime(DateTimeZone.UTC).getMillis();
// return (int) (millis / 1000L);
// }
// }
// Path: src/main/java/org/killbill/billing/plugin/meter/timeline/chunks/TimelineChunkBinder.java
import org.skife.jdbi.v2.sqlobject.BindingAnnotation;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.sql.Types;
import org.killbill.billing.plugin.meter.timeline.chunks.TimelineChunkBinder.TimelineChunkBinderFactory;
import org.killbill.billing.plugin.meter.timeline.codec.TimesAndSamplesCoder;
import org.killbill.billing.plugin.meter.timeline.util.DateTimeUtils;
import org.skife.jdbi.v2.SQLStatement;
import org.skife.jdbi.v2.sqlobject.Binder;
import org.skife.jdbi.v2.sqlobject.BinderFactory;
/*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline.chunks;
/**
* jdbi binder for TimelineChunk
*/
@BindingAnnotation(TimelineChunkBinderFactory.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
public @interface TimelineChunkBinder {
public static class TimelineChunkBinderFactory implements BinderFactory {
// Maximum size in bytes for a series of timesAndSamples to stay "in row" (stored as VARBINARY).
// Past this threshold, data is stored as a BLOB.
private static final int MAX_IN_ROW_BLOB_SIZE = 400;
public Binder build(final Annotation annotation) {
return new Binder<TimelineChunkBinder, TimelineChunk>() {
public void bind(final SQLStatement query, final TimelineChunkBinder binder, final TimelineChunk timelineChunk) {
query.bind("sourceRecordId", timelineChunk.getSourceId())
.bind("metricRecordId", timelineChunk.getMetricId())
.bind("sampleCount", timelineChunk.getSampleCount())
.bind("startTime", DateTimeUtils.unixSeconds(timelineChunk.getStartTime()))
.bind("endTime", DateTimeUtils.unixSeconds(timelineChunk.getEndTime()))
.bind("aggregationLevel", timelineChunk.getAggregationLevel())
.bind("notValid", timelineChunk.getNotValid() ? 1 : 0)
.bind("dontAggregate", timelineChunk.getDontAggregate() ? 1 : 0);
final byte[] times = timelineChunk.getTimeBytesAndSampleBytes().getTimeBytes();
final byte[] samples = timelineChunk.getTimeBytesAndSampleBytes().getSampleBytes(); | final byte[] timesAndSamples = TimesAndSamplesCoder.combineTimesAndSamples(times, samples); |
killbill/killbill-meter-plugin | src/test/java/org/killbill/billing/plugin/meter/timeline/TestDateTimeUtils.java | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static DateTime dateTimeFromUnixSeconds(final int unixTime) {
// return new DateTime(((long) unixTime) * 1000L, DateTimeZone.UTC);
// }
//
// public static int unixSeconds(final DateTime dateTime) {
// final long millis = dateTime.toDateTime(DateTimeZone.UTC).getMillis();
// return (int) (millis / 1000L);
// }
// }
| import org.joda.time.DateTime;
import org.joda.time.Seconds;
import org.killbill.billing.plugin.meter.MeterTestSuiteNoDB;
import org.killbill.billing.plugin.meter.timeline.util.DateTimeUtils;
import org.testng.Assert;
import org.testng.annotations.Test; | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline;
public class TestDateTimeUtils extends MeterTestSuiteNoDB {
@Test(groups = "fast")
public void testRoundTrip() throws Exception {
final DateTime utcNow = clock.getUTCNow(); | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static DateTime dateTimeFromUnixSeconds(final int unixTime) {
// return new DateTime(((long) unixTime) * 1000L, DateTimeZone.UTC);
// }
//
// public static int unixSeconds(final DateTime dateTime) {
// final long millis = dateTime.toDateTime(DateTimeZone.UTC).getMillis();
// return (int) (millis / 1000L);
// }
// }
// Path: src/test/java/org/killbill/billing/plugin/meter/timeline/TestDateTimeUtils.java
import org.joda.time.DateTime;
import org.joda.time.Seconds;
import org.killbill.billing.plugin.meter.MeterTestSuiteNoDB;
import org.killbill.billing.plugin.meter.timeline.util.DateTimeUtils;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline;
public class TestDateTimeUtils extends MeterTestSuiteNoDB {
@Test(groups = "fast")
public void testRoundTrip() throws Exception {
final DateTime utcNow = clock.getUTCNow(); | final int unixSeconds = DateTimeUtils.unixSeconds(utcNow); |
killbill/killbill-meter-plugin | src/test/java/org/killbill/billing/plugin/meter/timeline/consumer/filter/TestDecimatingFilter.java | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/samples/SampleOpcode.java
// public enum SampleOpcode {
// BYTE(1, 1),
// SHORT(2, 2),
// INT(3, 4),
// LONG(4, 8),
// FLOAT(5, 4),
// DOUBLE(6, 8),
// STRING(7, 0),
// NULL(8, 0, true),
// FLOAT_FOR_DOUBLE(10, 4, DOUBLE),
// HALF_FLOAT_FOR_DOUBLE(11, 2, DOUBLE),
// BYTE_FOR_DOUBLE(12, 1, DOUBLE),
// SHORT_FOR_DOUBLE(13, 2, DOUBLE),
// BIGINT(14, 0),
// DOUBLE_ZERO(15, 0, true),
// INT_ZERO(16, 0, true),
// REPEAT_BYTE(0xff, 1, true), // A repeat operation in which the repeat count fits in an unsigned byte
// REPEAT_SHORT(0xfe, 2, true); // A repeat operation in which the repeat count fits in an unsigned short
//
// private static final Logger log = LoggerFactory.getLogger(SampleOpcode.class);
//
// private int opcodeIndex;
// private final int byteSize;
// private final boolean repeater;
// private final boolean noArgs;
// private final SampleOpcode replacement;
//
// private SampleOpcode(int opcodeIndex, int byteSize) {
// this(opcodeIndex, byteSize, false);
// }
//
// private SampleOpcode(int opcodeIndex, int byteSize, boolean noArgs) {
// this(opcodeIndex, byteSize, noArgs, false);
// }
//
// private SampleOpcode(int opcodeIndex, int byteSize, boolean noArgs, boolean repeater) {
// this.opcodeIndex = opcodeIndex;
// this.byteSize = byteSize;
// this.noArgs = noArgs;
// this.repeater = repeater;
// this.replacement = this;
// }
//
// private SampleOpcode(int opcodeIndex, int byteSize, SampleOpcode replacement) {
// this(opcodeIndex, byteSize, false, false, replacement);
// }
//
// private SampleOpcode(final int opcodeIndex, final int byteSize, final boolean noArgs, final boolean repeater, final SampleOpcode replacement) {
// this.opcodeIndex = opcodeIndex;
// this.byteSize = byteSize;
// this.noArgs = noArgs;
// this.repeater = repeater;
// this.replacement = replacement;
// }
//
// public static SampleOpcode getOpcodeFromIndex(final int index) {
// for (SampleOpcode opcode : values()) {
// if (opcode.getOpcodeIndex() == index) {
// return opcode;
// }
// }
//
// final String s = String.format("In SampleOpcode.getOpcodefromIndex(), could not find opcode for index %d", index);
// log.error(s);
// throw new IllegalArgumentException(s);
// }
//
// public int getOpcodeIndex() {
// return opcodeIndex;
// }
//
// public int getByteSize() {
// return byteSize;
// }
//
// public boolean getNoArgs() {
// return noArgs;
// }
//
// public boolean getRepeater() {
// return repeater;
// }
//
// public SampleOpcode getReplacement() {
// return replacement;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("SampleOpcode");
// sb.append("{opcodeIndex=").append(opcodeIndex);
// sb.append(", byteSize=").append(byteSize);
// sb.append(", repeater=").append(repeater);
// sb.append(", noArgs=").append(noArgs);
// sb.append(", replacement=").append(replacement.name());
// sb.append('}');
// return sb.toString();
// }
// }
| import java.util.ArrayList;
import java.util.List;
import org.joda.time.DateTime;
import org.killbill.billing.plugin.meter.MeterTestSuiteNoDB;
import org.killbill.billing.plugin.meter.api.DecimationMode;
import org.killbill.billing.plugin.meter.timeline.consumer.TimeRangeSampleProcessor;
import org.killbill.billing.plugin.meter.timeline.samples.SampleOpcode;
import org.skife.config.TimeSpan;
import org.testng.Assert;
import org.testng.annotations.Test; | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline.consumer.filter;
public class TestDecimatingFilter extends MeterTestSuiteNoDB {
@Test(groups = "fast")
public void testBasicFilterOperations() throws Exception {
final List<Double> outputs = new ArrayList<Double>();
final long millisStart = System.currentTimeMillis() - 2000 * 100;
final DecimatingSampleFilter filter = new DecimatingSampleFilter(new DateTime(millisStart), new DateTime(millisStart + 2000 * 100), 25, 100, new TimeSpan("2s"), DecimationMode.PEAK_PICK,
new TimeRangeSampleProcessor() {
@Override | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/samples/SampleOpcode.java
// public enum SampleOpcode {
// BYTE(1, 1),
// SHORT(2, 2),
// INT(3, 4),
// LONG(4, 8),
// FLOAT(5, 4),
// DOUBLE(6, 8),
// STRING(7, 0),
// NULL(8, 0, true),
// FLOAT_FOR_DOUBLE(10, 4, DOUBLE),
// HALF_FLOAT_FOR_DOUBLE(11, 2, DOUBLE),
// BYTE_FOR_DOUBLE(12, 1, DOUBLE),
// SHORT_FOR_DOUBLE(13, 2, DOUBLE),
// BIGINT(14, 0),
// DOUBLE_ZERO(15, 0, true),
// INT_ZERO(16, 0, true),
// REPEAT_BYTE(0xff, 1, true), // A repeat operation in which the repeat count fits in an unsigned byte
// REPEAT_SHORT(0xfe, 2, true); // A repeat operation in which the repeat count fits in an unsigned short
//
// private static final Logger log = LoggerFactory.getLogger(SampleOpcode.class);
//
// private int opcodeIndex;
// private final int byteSize;
// private final boolean repeater;
// private final boolean noArgs;
// private final SampleOpcode replacement;
//
// private SampleOpcode(int opcodeIndex, int byteSize) {
// this(opcodeIndex, byteSize, false);
// }
//
// private SampleOpcode(int opcodeIndex, int byteSize, boolean noArgs) {
// this(opcodeIndex, byteSize, noArgs, false);
// }
//
// private SampleOpcode(int opcodeIndex, int byteSize, boolean noArgs, boolean repeater) {
// this.opcodeIndex = opcodeIndex;
// this.byteSize = byteSize;
// this.noArgs = noArgs;
// this.repeater = repeater;
// this.replacement = this;
// }
//
// private SampleOpcode(int opcodeIndex, int byteSize, SampleOpcode replacement) {
// this(opcodeIndex, byteSize, false, false, replacement);
// }
//
// private SampleOpcode(final int opcodeIndex, final int byteSize, final boolean noArgs, final boolean repeater, final SampleOpcode replacement) {
// this.opcodeIndex = opcodeIndex;
// this.byteSize = byteSize;
// this.noArgs = noArgs;
// this.repeater = repeater;
// this.replacement = replacement;
// }
//
// public static SampleOpcode getOpcodeFromIndex(final int index) {
// for (SampleOpcode opcode : values()) {
// if (opcode.getOpcodeIndex() == index) {
// return opcode;
// }
// }
//
// final String s = String.format("In SampleOpcode.getOpcodefromIndex(), could not find opcode for index %d", index);
// log.error(s);
// throw new IllegalArgumentException(s);
// }
//
// public int getOpcodeIndex() {
// return opcodeIndex;
// }
//
// public int getByteSize() {
// return byteSize;
// }
//
// public boolean getNoArgs() {
// return noArgs;
// }
//
// public boolean getRepeater() {
// return repeater;
// }
//
// public SampleOpcode getReplacement() {
// return replacement;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("SampleOpcode");
// sb.append("{opcodeIndex=").append(opcodeIndex);
// sb.append(", byteSize=").append(byteSize);
// sb.append(", repeater=").append(repeater);
// sb.append(", noArgs=").append(noArgs);
// sb.append(", replacement=").append(replacement.name());
// sb.append('}');
// return sb.toString();
// }
// }
// Path: src/test/java/org/killbill/billing/plugin/meter/timeline/consumer/filter/TestDecimatingFilter.java
import java.util.ArrayList;
import java.util.List;
import org.joda.time.DateTime;
import org.killbill.billing.plugin.meter.MeterTestSuiteNoDB;
import org.killbill.billing.plugin.meter.api.DecimationMode;
import org.killbill.billing.plugin.meter.timeline.consumer.TimeRangeSampleProcessor;
import org.killbill.billing.plugin.meter.timeline.samples.SampleOpcode;
import org.skife.config.TimeSpan;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline.consumer.filter;
public class TestDecimatingFilter extends MeterTestSuiteNoDB {
@Test(groups = "fast")
public void testBasicFilterOperations() throws Exception {
final List<Double> outputs = new ArrayList<Double>();
final long millisStart = System.currentTimeMillis() - 2000 * 100;
final DecimatingSampleFilter filter = new DecimatingSampleFilter(new DateTime(millisStart), new DateTime(millisStart + 2000 * 100), 25, 100, new TimeSpan("2s"), DecimationMode.PEAK_PICK,
new TimeRangeSampleProcessor() {
@Override | public void processOneSample(final DateTime time, final SampleOpcode opcode, final Object value) { |
killbill/killbill-meter-plugin | src/main/java/org/killbill/billing/plugin/meter/timeline/consumer/SampleProcessor.java | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/samples/SampleOpcode.java
// public enum SampleOpcode {
// BYTE(1, 1),
// SHORT(2, 2),
// INT(3, 4),
// LONG(4, 8),
// FLOAT(5, 4),
// DOUBLE(6, 8),
// STRING(7, 0),
// NULL(8, 0, true),
// FLOAT_FOR_DOUBLE(10, 4, DOUBLE),
// HALF_FLOAT_FOR_DOUBLE(11, 2, DOUBLE),
// BYTE_FOR_DOUBLE(12, 1, DOUBLE),
// SHORT_FOR_DOUBLE(13, 2, DOUBLE),
// BIGINT(14, 0),
// DOUBLE_ZERO(15, 0, true),
// INT_ZERO(16, 0, true),
// REPEAT_BYTE(0xff, 1, true), // A repeat operation in which the repeat count fits in an unsigned byte
// REPEAT_SHORT(0xfe, 2, true); // A repeat operation in which the repeat count fits in an unsigned short
//
// private static final Logger log = LoggerFactory.getLogger(SampleOpcode.class);
//
// private int opcodeIndex;
// private final int byteSize;
// private final boolean repeater;
// private final boolean noArgs;
// private final SampleOpcode replacement;
//
// private SampleOpcode(int opcodeIndex, int byteSize) {
// this(opcodeIndex, byteSize, false);
// }
//
// private SampleOpcode(int opcodeIndex, int byteSize, boolean noArgs) {
// this(opcodeIndex, byteSize, noArgs, false);
// }
//
// private SampleOpcode(int opcodeIndex, int byteSize, boolean noArgs, boolean repeater) {
// this.opcodeIndex = opcodeIndex;
// this.byteSize = byteSize;
// this.noArgs = noArgs;
// this.repeater = repeater;
// this.replacement = this;
// }
//
// private SampleOpcode(int opcodeIndex, int byteSize, SampleOpcode replacement) {
// this(opcodeIndex, byteSize, false, false, replacement);
// }
//
// private SampleOpcode(final int opcodeIndex, final int byteSize, final boolean noArgs, final boolean repeater, final SampleOpcode replacement) {
// this.opcodeIndex = opcodeIndex;
// this.byteSize = byteSize;
// this.noArgs = noArgs;
// this.repeater = repeater;
// this.replacement = replacement;
// }
//
// public static SampleOpcode getOpcodeFromIndex(final int index) {
// for (SampleOpcode opcode : values()) {
// if (opcode.getOpcodeIndex() == index) {
// return opcode;
// }
// }
//
// final String s = String.format("In SampleOpcode.getOpcodefromIndex(), could not find opcode for index %d", index);
// log.error(s);
// throw new IllegalArgumentException(s);
// }
//
// public int getOpcodeIndex() {
// return opcodeIndex;
// }
//
// public int getByteSize() {
// return byteSize;
// }
//
// public boolean getNoArgs() {
// return noArgs;
// }
//
// public boolean getRepeater() {
// return repeater;
// }
//
// public SampleOpcode getReplacement() {
// return replacement;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("SampleOpcode");
// sb.append("{opcodeIndex=").append(opcodeIndex);
// sb.append(", byteSize=").append(byteSize);
// sb.append(", repeater=").append(repeater);
// sb.append(", noArgs=").append(noArgs);
// sb.append(", replacement=").append(replacement.name());
// sb.append('}');
// return sb.toString();
// }
// }
| import org.killbill.billing.plugin.meter.timeline.samples.SampleOpcode;
import org.killbill.billing.plugin.meter.timeline.times.TimelineCursor; | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline.consumer;
public interface SampleProcessor {
/**
* Process sampleCount sequential samples with identical values. sampleCount will usually be 1,
* but may be larger than 1. Implementors may just loop processing identical values, but some
* implementations may optimize adding a bunch of repeated values
*
* @param timeCursor a TimeCursor object from which times can be found.
* @param sampleCount the count of sequential, identical values
* @param opcode the opcode of the sample value, which may not be a REPEAT opcode
* @param value the value of this kind of sample over the count of samples
*/
public void processSamples(final TimelineCursor timeCursor,
final int sampleCount, | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/samples/SampleOpcode.java
// public enum SampleOpcode {
// BYTE(1, 1),
// SHORT(2, 2),
// INT(3, 4),
// LONG(4, 8),
// FLOAT(5, 4),
// DOUBLE(6, 8),
// STRING(7, 0),
// NULL(8, 0, true),
// FLOAT_FOR_DOUBLE(10, 4, DOUBLE),
// HALF_FLOAT_FOR_DOUBLE(11, 2, DOUBLE),
// BYTE_FOR_DOUBLE(12, 1, DOUBLE),
// SHORT_FOR_DOUBLE(13, 2, DOUBLE),
// BIGINT(14, 0),
// DOUBLE_ZERO(15, 0, true),
// INT_ZERO(16, 0, true),
// REPEAT_BYTE(0xff, 1, true), // A repeat operation in which the repeat count fits in an unsigned byte
// REPEAT_SHORT(0xfe, 2, true); // A repeat operation in which the repeat count fits in an unsigned short
//
// private static final Logger log = LoggerFactory.getLogger(SampleOpcode.class);
//
// private int opcodeIndex;
// private final int byteSize;
// private final boolean repeater;
// private final boolean noArgs;
// private final SampleOpcode replacement;
//
// private SampleOpcode(int opcodeIndex, int byteSize) {
// this(opcodeIndex, byteSize, false);
// }
//
// private SampleOpcode(int opcodeIndex, int byteSize, boolean noArgs) {
// this(opcodeIndex, byteSize, noArgs, false);
// }
//
// private SampleOpcode(int opcodeIndex, int byteSize, boolean noArgs, boolean repeater) {
// this.opcodeIndex = opcodeIndex;
// this.byteSize = byteSize;
// this.noArgs = noArgs;
// this.repeater = repeater;
// this.replacement = this;
// }
//
// private SampleOpcode(int opcodeIndex, int byteSize, SampleOpcode replacement) {
// this(opcodeIndex, byteSize, false, false, replacement);
// }
//
// private SampleOpcode(final int opcodeIndex, final int byteSize, final boolean noArgs, final boolean repeater, final SampleOpcode replacement) {
// this.opcodeIndex = opcodeIndex;
// this.byteSize = byteSize;
// this.noArgs = noArgs;
// this.repeater = repeater;
// this.replacement = replacement;
// }
//
// public static SampleOpcode getOpcodeFromIndex(final int index) {
// for (SampleOpcode opcode : values()) {
// if (opcode.getOpcodeIndex() == index) {
// return opcode;
// }
// }
//
// final String s = String.format("In SampleOpcode.getOpcodefromIndex(), could not find opcode for index %d", index);
// log.error(s);
// throw new IllegalArgumentException(s);
// }
//
// public int getOpcodeIndex() {
// return opcodeIndex;
// }
//
// public int getByteSize() {
// return byteSize;
// }
//
// public boolean getNoArgs() {
// return noArgs;
// }
//
// public boolean getRepeater() {
// return repeater;
// }
//
// public SampleOpcode getReplacement() {
// return replacement;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("SampleOpcode");
// sb.append("{opcodeIndex=").append(opcodeIndex);
// sb.append(", byteSize=").append(byteSize);
// sb.append(", repeater=").append(repeater);
// sb.append(", noArgs=").append(noArgs);
// sb.append(", replacement=").append(replacement.name());
// sb.append('}');
// return sb.toString();
// }
// }
// Path: src/main/java/org/killbill/billing/plugin/meter/timeline/consumer/SampleProcessor.java
import org.killbill.billing.plugin.meter.timeline.samples.SampleOpcode;
import org.killbill.billing.plugin.meter.timeline.times.TimelineCursor;
/*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline.consumer;
public interface SampleProcessor {
/**
* Process sampleCount sequential samples with identical values. sampleCount will usually be 1,
* but may be larger than 1. Implementors may just loop processing identical values, but some
* implementations may optimize adding a bunch of repeated values
*
* @param timeCursor a TimeCursor object from which times can be found.
* @param sampleCount the count of sequential, identical values
* @param opcode the opcode of the sample value, which may not be a REPEAT opcode
* @param value the value of this kind of sample over the count of samples
*/
public void processSamples(final TimelineCursor timeCursor,
final int sampleCount, | final SampleOpcode opcode, |
killbill/killbill-meter-plugin | src/main/java/org/killbill/billing/plugin/meter/timeline/chunks/TimelineChunkMapper.java | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/codec/TimesAndSamplesCoder.java
// public class TimesAndSamplesCoder {
//
// public static int getSizeOfTimeBytes(final byte[] timesAndSamples) {
// final DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(timesAndSamples));
// try {
// return inputStream.readInt();
// } catch (IOException e) {
// throw new IllegalStateException(String.format("Exception reading timeByteCount in TimelineChunkMapper.map() for timesAndSamples %s",
// new String(Hex.encodeHex(timesAndSamples))), e);
// }
// }
//
// public static int getEncodedLength(final TimelineChunk chunk) {
// return 4 + chunk.getTimeBytesAndSampleBytes().getTimeBytes().length +
// chunk.getTimeBytesAndSampleBytes().getSampleBytes().length;
// }
//
// public static byte[] getTimeBytes(final byte[] timesAndSamples) {
// final int timeByteCount = getSizeOfTimeBytes(timesAndSamples);
// return Arrays.copyOfRange(timesAndSamples, 4, 4 + timeByteCount);
// }
//
// public static byte[] getSampleBytes(final byte[] timesAndSamples) {
// final int timeByteCount = getSizeOfTimeBytes(timesAndSamples);
// return Arrays.copyOfRange(timesAndSamples, 4 + timeByteCount, timesAndSamples.length);
// }
//
// public static TimeBytesAndSampleBytes getTimesBytesAndSampleBytes(final byte[] timesAndSamples) {
// final int timeByteCount = getSizeOfTimeBytes(timesAndSamples);
// final byte[] timeBytes = Arrays.copyOfRange(timesAndSamples, 4, 4 + timeByteCount);
// final byte[] sampleBytes = Arrays.copyOfRange(timesAndSamples, 4 + timeByteCount, timesAndSamples.length);
// return new TimeBytesAndSampleBytes(timeBytes, sampleBytes);
// }
//
// public static byte[] combineTimesAndSamples(final byte[] times, final byte[] samples) {
// final int totalSamplesSize = 4 + times.length + samples.length;
// final ByteArrayOutputStream baStream = new ByteArrayOutputStream(totalSamplesSize);
// final DataOutputStream outputStream = new DataOutputStream(baStream);
// try {
// outputStream.writeInt(times.length);
// outputStream.write(times);
// outputStream.write(samples);
// outputStream.flush();
// return baStream.toByteArray();
// } catch (IOException e) {
// throw new IllegalStateException(String.format("Exception reading timeByteCount in TimelineChunkMapper.map() for times %s, samples %s",
// new String(Hex.encodeHex(times)), new String(Hex.encodeHex(samples))), e);
// }
// }
// }
//
// Path: src/main/java/org/killbill/billing/plugin/meter/timeline/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static DateTime dateTimeFromUnixSeconds(final int unixTime) {
// return new DateTime(((long) unixTime) * 1000L, DateTimeZone.UTC);
// }
//
// public static int unixSeconds(final DateTime dateTime) {
// final long millis = dateTime.toDateTime(DateTimeZone.UTC).getMillis();
// return (int) (millis / 1000L);
// }
// }
| import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.joda.time.DateTime;
import org.killbill.billing.plugin.meter.timeline.codec.TimesAndSamplesCoder;
import org.killbill.billing.plugin.meter.timeline.util.DateTimeUtils;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.ResultSetMapper; | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline.chunks;
/**
* jdbi mapper for TimelineChunk
*/
public class TimelineChunkMapper implements ResultSetMapper<TimelineChunk> {
@Override
public TimelineChunk map(final int index, final ResultSet rs, final StatementContext ctx) throws SQLException {
final int chunkId = rs.getInt("record_id");
final int sourceId = rs.getInt("source_record_id");
final int metricId = rs.getInt("metric_record_id");
final int sampleCount = rs.getInt("sample_count"); | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/codec/TimesAndSamplesCoder.java
// public class TimesAndSamplesCoder {
//
// public static int getSizeOfTimeBytes(final byte[] timesAndSamples) {
// final DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(timesAndSamples));
// try {
// return inputStream.readInt();
// } catch (IOException e) {
// throw new IllegalStateException(String.format("Exception reading timeByteCount in TimelineChunkMapper.map() for timesAndSamples %s",
// new String(Hex.encodeHex(timesAndSamples))), e);
// }
// }
//
// public static int getEncodedLength(final TimelineChunk chunk) {
// return 4 + chunk.getTimeBytesAndSampleBytes().getTimeBytes().length +
// chunk.getTimeBytesAndSampleBytes().getSampleBytes().length;
// }
//
// public static byte[] getTimeBytes(final byte[] timesAndSamples) {
// final int timeByteCount = getSizeOfTimeBytes(timesAndSamples);
// return Arrays.copyOfRange(timesAndSamples, 4, 4 + timeByteCount);
// }
//
// public static byte[] getSampleBytes(final byte[] timesAndSamples) {
// final int timeByteCount = getSizeOfTimeBytes(timesAndSamples);
// return Arrays.copyOfRange(timesAndSamples, 4 + timeByteCount, timesAndSamples.length);
// }
//
// public static TimeBytesAndSampleBytes getTimesBytesAndSampleBytes(final byte[] timesAndSamples) {
// final int timeByteCount = getSizeOfTimeBytes(timesAndSamples);
// final byte[] timeBytes = Arrays.copyOfRange(timesAndSamples, 4, 4 + timeByteCount);
// final byte[] sampleBytes = Arrays.copyOfRange(timesAndSamples, 4 + timeByteCount, timesAndSamples.length);
// return new TimeBytesAndSampleBytes(timeBytes, sampleBytes);
// }
//
// public static byte[] combineTimesAndSamples(final byte[] times, final byte[] samples) {
// final int totalSamplesSize = 4 + times.length + samples.length;
// final ByteArrayOutputStream baStream = new ByteArrayOutputStream(totalSamplesSize);
// final DataOutputStream outputStream = new DataOutputStream(baStream);
// try {
// outputStream.writeInt(times.length);
// outputStream.write(times);
// outputStream.write(samples);
// outputStream.flush();
// return baStream.toByteArray();
// } catch (IOException e) {
// throw new IllegalStateException(String.format("Exception reading timeByteCount in TimelineChunkMapper.map() for times %s, samples %s",
// new String(Hex.encodeHex(times)), new String(Hex.encodeHex(samples))), e);
// }
// }
// }
//
// Path: src/main/java/org/killbill/billing/plugin/meter/timeline/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static DateTime dateTimeFromUnixSeconds(final int unixTime) {
// return new DateTime(((long) unixTime) * 1000L, DateTimeZone.UTC);
// }
//
// public static int unixSeconds(final DateTime dateTime) {
// final long millis = dateTime.toDateTime(DateTimeZone.UTC).getMillis();
// return (int) (millis / 1000L);
// }
// }
// Path: src/main/java/org/killbill/billing/plugin/meter/timeline/chunks/TimelineChunkMapper.java
import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.joda.time.DateTime;
import org.killbill.billing.plugin.meter.timeline.codec.TimesAndSamplesCoder;
import org.killbill.billing.plugin.meter.timeline.util.DateTimeUtils;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.ResultSetMapper;
/*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline.chunks;
/**
* jdbi mapper for TimelineChunk
*/
public class TimelineChunkMapper implements ResultSetMapper<TimelineChunk> {
@Override
public TimelineChunk map(final int index, final ResultSet rs, final StatementContext ctx) throws SQLException {
final int chunkId = rs.getInt("record_id");
final int sourceId = rs.getInt("source_record_id");
final int metricId = rs.getInt("metric_record_id");
final int sampleCount = rs.getInt("sample_count"); | final DateTime startTime = DateTimeUtils.dateTimeFromUnixSeconds(rs.getInt("start_time")); |
killbill/killbill-meter-plugin | src/main/java/org/killbill/billing/plugin/meter/timeline/chunks/TimelineChunkMapper.java | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/codec/TimesAndSamplesCoder.java
// public class TimesAndSamplesCoder {
//
// public static int getSizeOfTimeBytes(final byte[] timesAndSamples) {
// final DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(timesAndSamples));
// try {
// return inputStream.readInt();
// } catch (IOException e) {
// throw new IllegalStateException(String.format("Exception reading timeByteCount in TimelineChunkMapper.map() for timesAndSamples %s",
// new String(Hex.encodeHex(timesAndSamples))), e);
// }
// }
//
// public static int getEncodedLength(final TimelineChunk chunk) {
// return 4 + chunk.getTimeBytesAndSampleBytes().getTimeBytes().length +
// chunk.getTimeBytesAndSampleBytes().getSampleBytes().length;
// }
//
// public static byte[] getTimeBytes(final byte[] timesAndSamples) {
// final int timeByteCount = getSizeOfTimeBytes(timesAndSamples);
// return Arrays.copyOfRange(timesAndSamples, 4, 4 + timeByteCount);
// }
//
// public static byte[] getSampleBytes(final byte[] timesAndSamples) {
// final int timeByteCount = getSizeOfTimeBytes(timesAndSamples);
// return Arrays.copyOfRange(timesAndSamples, 4 + timeByteCount, timesAndSamples.length);
// }
//
// public static TimeBytesAndSampleBytes getTimesBytesAndSampleBytes(final byte[] timesAndSamples) {
// final int timeByteCount = getSizeOfTimeBytes(timesAndSamples);
// final byte[] timeBytes = Arrays.copyOfRange(timesAndSamples, 4, 4 + timeByteCount);
// final byte[] sampleBytes = Arrays.copyOfRange(timesAndSamples, 4 + timeByteCount, timesAndSamples.length);
// return new TimeBytesAndSampleBytes(timeBytes, sampleBytes);
// }
//
// public static byte[] combineTimesAndSamples(final byte[] times, final byte[] samples) {
// final int totalSamplesSize = 4 + times.length + samples.length;
// final ByteArrayOutputStream baStream = new ByteArrayOutputStream(totalSamplesSize);
// final DataOutputStream outputStream = new DataOutputStream(baStream);
// try {
// outputStream.writeInt(times.length);
// outputStream.write(times);
// outputStream.write(samples);
// outputStream.flush();
// return baStream.toByteArray();
// } catch (IOException e) {
// throw new IllegalStateException(String.format("Exception reading timeByteCount in TimelineChunkMapper.map() for times %s, samples %s",
// new String(Hex.encodeHex(times)), new String(Hex.encodeHex(samples))), e);
// }
// }
// }
//
// Path: src/main/java/org/killbill/billing/plugin/meter/timeline/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static DateTime dateTimeFromUnixSeconds(final int unixTime) {
// return new DateTime(((long) unixTime) * 1000L, DateTimeZone.UTC);
// }
//
// public static int unixSeconds(final DateTime dateTime) {
// final long millis = dateTime.toDateTime(DateTimeZone.UTC).getMillis();
// return (int) (millis / 1000L);
// }
// }
| import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.joda.time.DateTime;
import org.killbill.billing.plugin.meter.timeline.codec.TimesAndSamplesCoder;
import org.killbill.billing.plugin.meter.timeline.util.DateTimeUtils;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.ResultSetMapper; | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline.chunks;
/**
* jdbi mapper for TimelineChunk
*/
public class TimelineChunkMapper implements ResultSetMapper<TimelineChunk> {
@Override
public TimelineChunk map(final int index, final ResultSet rs, final StatementContext ctx) throws SQLException {
final int chunkId = rs.getInt("record_id");
final int sourceId = rs.getInt("source_record_id");
final int metricId = rs.getInt("metric_record_id");
final int sampleCount = rs.getInt("sample_count");
final DateTime startTime = DateTimeUtils.dateTimeFromUnixSeconds(rs.getInt("start_time"));
final DateTime endTime = DateTimeUtils.dateTimeFromUnixSeconds(rs.getInt("end_time"));
final int aggregationLevel = rs.getInt("aggregation_level");
final boolean notValid = rs.getInt("not_valid") == 0 ? false : true;
final boolean dontAggregate = rs.getInt("dont_aggregate") == 0 ? false : true;
byte[] samplesAndTimes = rs.getBytes("in_row_samples");
if (rs.wasNull()) {
final Blob blobSamples = rs.getBlob("blob_samples");
if (rs.wasNull()) {
samplesAndTimes = new byte[4];
} else {
samplesAndTimes = blobSamples.getBytes(1, (int) blobSamples.length());
}
}
| // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/codec/TimesAndSamplesCoder.java
// public class TimesAndSamplesCoder {
//
// public static int getSizeOfTimeBytes(final byte[] timesAndSamples) {
// final DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(timesAndSamples));
// try {
// return inputStream.readInt();
// } catch (IOException e) {
// throw new IllegalStateException(String.format("Exception reading timeByteCount in TimelineChunkMapper.map() for timesAndSamples %s",
// new String(Hex.encodeHex(timesAndSamples))), e);
// }
// }
//
// public static int getEncodedLength(final TimelineChunk chunk) {
// return 4 + chunk.getTimeBytesAndSampleBytes().getTimeBytes().length +
// chunk.getTimeBytesAndSampleBytes().getSampleBytes().length;
// }
//
// public static byte[] getTimeBytes(final byte[] timesAndSamples) {
// final int timeByteCount = getSizeOfTimeBytes(timesAndSamples);
// return Arrays.copyOfRange(timesAndSamples, 4, 4 + timeByteCount);
// }
//
// public static byte[] getSampleBytes(final byte[] timesAndSamples) {
// final int timeByteCount = getSizeOfTimeBytes(timesAndSamples);
// return Arrays.copyOfRange(timesAndSamples, 4 + timeByteCount, timesAndSamples.length);
// }
//
// public static TimeBytesAndSampleBytes getTimesBytesAndSampleBytes(final byte[] timesAndSamples) {
// final int timeByteCount = getSizeOfTimeBytes(timesAndSamples);
// final byte[] timeBytes = Arrays.copyOfRange(timesAndSamples, 4, 4 + timeByteCount);
// final byte[] sampleBytes = Arrays.copyOfRange(timesAndSamples, 4 + timeByteCount, timesAndSamples.length);
// return new TimeBytesAndSampleBytes(timeBytes, sampleBytes);
// }
//
// public static byte[] combineTimesAndSamples(final byte[] times, final byte[] samples) {
// final int totalSamplesSize = 4 + times.length + samples.length;
// final ByteArrayOutputStream baStream = new ByteArrayOutputStream(totalSamplesSize);
// final DataOutputStream outputStream = new DataOutputStream(baStream);
// try {
// outputStream.writeInt(times.length);
// outputStream.write(times);
// outputStream.write(samples);
// outputStream.flush();
// return baStream.toByteArray();
// } catch (IOException e) {
// throw new IllegalStateException(String.format("Exception reading timeByteCount in TimelineChunkMapper.map() for times %s, samples %s",
// new String(Hex.encodeHex(times)), new String(Hex.encodeHex(samples))), e);
// }
// }
// }
//
// Path: src/main/java/org/killbill/billing/plugin/meter/timeline/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static DateTime dateTimeFromUnixSeconds(final int unixTime) {
// return new DateTime(((long) unixTime) * 1000L, DateTimeZone.UTC);
// }
//
// public static int unixSeconds(final DateTime dateTime) {
// final long millis = dateTime.toDateTime(DateTimeZone.UTC).getMillis();
// return (int) (millis / 1000L);
// }
// }
// Path: src/main/java/org/killbill/billing/plugin/meter/timeline/chunks/TimelineChunkMapper.java
import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.joda.time.DateTime;
import org.killbill.billing.plugin.meter.timeline.codec.TimesAndSamplesCoder;
import org.killbill.billing.plugin.meter.timeline.util.DateTimeUtils;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.ResultSetMapper;
/*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline.chunks;
/**
* jdbi mapper for TimelineChunk
*/
public class TimelineChunkMapper implements ResultSetMapper<TimelineChunk> {
@Override
public TimelineChunk map(final int index, final ResultSet rs, final StatementContext ctx) throws SQLException {
final int chunkId = rs.getInt("record_id");
final int sourceId = rs.getInt("source_record_id");
final int metricId = rs.getInt("metric_record_id");
final int sampleCount = rs.getInt("sample_count");
final DateTime startTime = DateTimeUtils.dateTimeFromUnixSeconds(rs.getInt("start_time"));
final DateTime endTime = DateTimeUtils.dateTimeFromUnixSeconds(rs.getInt("end_time"));
final int aggregationLevel = rs.getInt("aggregation_level");
final boolean notValid = rs.getInt("not_valid") == 0 ? false : true;
final boolean dontAggregate = rs.getInt("dont_aggregate") == 0 ? false : true;
byte[] samplesAndTimes = rs.getBytes("in_row_samples");
if (rs.wasNull()) {
final Blob blobSamples = rs.getBlob("blob_samples");
if (rs.wasNull()) {
samplesAndTimes = new byte[4];
} else {
samplesAndTimes = blobSamples.getBytes(1, (int) blobSamples.length());
}
}
| final TimeBytesAndSampleBytes bytesPair = TimesAndSamplesCoder.getTimesBytesAndSampleBytes(samplesAndTimes); |
killbill/killbill-meter-plugin | src/main/java/org/killbill/billing/plugin/meter/timeline/shutdown/StartTimesBinder.java | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static DateTime dateTimeFromUnixSeconds(final int unixTime) {
// return new DateTime(((long) unixTime) * 1000L, DateTimeZone.UTC);
// }
//
// public static int unixSeconds(final DateTime dateTime) {
// final long millis = dateTime.toDateTime(DateTimeZone.UTC).getMillis();
// return (int) (millis / 1000L);
// }
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.killbill.billing.plugin.meter.timeline.shutdown.StartTimesBinder.StartTimesBinderFactory;
import org.killbill.billing.plugin.meter.timeline.util.DateTimeUtils;
import org.skife.jdbi.v2.SQLStatement;
import org.skife.jdbi.v2.sqlobject.Binder;
import org.skife.jdbi.v2.sqlobject.BinderFactory;
import org.skife.jdbi.v2.sqlobject.BindingAnnotation; | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline.shutdown;
@BindingAnnotation(StartTimesBinderFactory.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
public @interface StartTimesBinder {
public static class StartTimesBinderFactory implements BinderFactory {
private static final Logger log = LoggerFactory.getLogger(StartTimesBinderFactory.class);
private static final ObjectMapper mapper = new ObjectMapper();
public Binder build(final Annotation annotation) {
return new Binder<StartTimesBinder, StartTimes>() {
public void bind(final SQLStatement query, final StartTimesBinder binder, final StartTimes startTimes) {
try {
final String s = mapper.writeValueAsString(startTimes.getStartTimesMap());
query.bind("startTimes", s) | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static DateTime dateTimeFromUnixSeconds(final int unixTime) {
// return new DateTime(((long) unixTime) * 1000L, DateTimeZone.UTC);
// }
//
// public static int unixSeconds(final DateTime dateTime) {
// final long millis = dateTime.toDateTime(DateTimeZone.UTC).getMillis();
// return (int) (millis / 1000L);
// }
// }
// Path: src/main/java/org/killbill/billing/plugin/meter/timeline/shutdown/StartTimesBinder.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.killbill.billing.plugin.meter.timeline.shutdown.StartTimesBinder.StartTimesBinderFactory;
import org.killbill.billing.plugin.meter.timeline.util.DateTimeUtils;
import org.skife.jdbi.v2.SQLStatement;
import org.skife.jdbi.v2.sqlobject.Binder;
import org.skife.jdbi.v2.sqlobject.BinderFactory;
import org.skife.jdbi.v2.sqlobject.BindingAnnotation;
/*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline.shutdown;
@BindingAnnotation(StartTimesBinderFactory.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
public @interface StartTimesBinder {
public static class StartTimesBinderFactory implements BinderFactory {
private static final Logger log = LoggerFactory.getLogger(StartTimesBinderFactory.class);
private static final ObjectMapper mapper = new ObjectMapper();
public Binder build(final Annotation annotation) {
return new Binder<StartTimesBinder, StartTimes>() {
public void bind(final SQLStatement query, final StartTimesBinder binder, final StartTimes startTimes) {
try {
final String s = mapper.writeValueAsString(startTimes.getStartTimesMap());
query.bind("startTimes", s) | .bind("timeInserted", DateTimeUtils.unixSeconds(startTimes.getTimeInserted())); |
killbill/killbill-meter-plugin | src/main/java/org/killbill/billing/plugin/meter/timeline/shutdown/StartTimesMapper.java | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static DateTime dateTimeFromUnixSeconds(final int unixTime) {
// return new DateTime(((long) unixTime) * 1000L, DateTimeZone.UTC);
// }
//
// public static int unixSeconds(final DateTime dateTime) {
// final long millis = dateTime.toDateTime(DateTimeZone.UTC).getMillis();
// return (int) (millis / 1000L);
// }
// }
| import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import org.joda.time.DateTime;
import org.killbill.billing.plugin.meter.timeline.util.DateTimeUtils;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.ResultSetMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline.shutdown;
public class StartTimesMapper implements ResultSetMapper<StartTimes> {
private static final ObjectMapper mapper = new ObjectMapper();
@Override
public StartTimes map(final int index, final ResultSet r, final StatementContext ctx) throws SQLException {
try { | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static DateTime dateTimeFromUnixSeconds(final int unixTime) {
// return new DateTime(((long) unixTime) * 1000L, DateTimeZone.UTC);
// }
//
// public static int unixSeconds(final DateTime dateTime) {
// final long millis = dateTime.toDateTime(DateTimeZone.UTC).getMillis();
// return (int) (millis / 1000L);
// }
// }
// Path: src/main/java/org/killbill/billing/plugin/meter/timeline/shutdown/StartTimesMapper.java
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import org.joda.time.DateTime;
import org.killbill.billing.plugin.meter.timeline.util.DateTimeUtils;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.ResultSetMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
/*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline.shutdown;
public class StartTimesMapper implements ResultSetMapper<StartTimes> {
private static final ObjectMapper mapper = new ObjectMapper();
@Override
public StartTimes map(final int index, final ResultSet r, final StatementContext ctx) throws SQLException {
try { | return new StartTimes(DateTimeUtils.dateTimeFromUnixSeconds(r.getInt("time_inserted")), |
killbill/killbill-meter-plugin | src/main/java/org/killbill/billing/plugin/meter/timeline/persistent/TimelineDao.java | // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/shutdown/StartTimes.java
// public class StartTimes {
//
// private final DateTime timeInserted;
// private final Map<Integer, Map<Integer, DateTime>> startTimesMap;
// private DateTime minStartTime;
//
// public StartTimes(final DateTime timeInserted, final Map<Integer, Map<Integer, DateTime>> startTimesMap) {
// this.timeInserted = timeInserted;
// this.startTimesMap = startTimesMap;
// DateTime minDateTime = new DateTime(Long.MAX_VALUE);
// for (final Map<Integer, DateTime> categoryMap : startTimesMap.values()) {
// for (final DateTime startTime : categoryMap.values()) {
// if (minDateTime.isAfter(startTime)) {
// minDateTime = startTime;
// }
// }
// }
// this.minStartTime = minDateTime;
// }
//
// public StartTimes() {
// this.timeInserted = new DateTime();
// minStartTime = new DateTime(Long.MAX_VALUE);
// this.startTimesMap = new HashMap<Integer, Map<Integer, DateTime>>();
// }
//
// public void addTime(final int sourceId, final int categoryId, final DateTime dateTime) {
// Map<Integer, DateTime> sourceTimes = startTimesMap.get(sourceId);
// if (sourceTimes == null) {
// sourceTimes = new HashMap<Integer, DateTime>();
// startTimesMap.put(sourceId, sourceTimes);
// }
// sourceTimes.put(categoryId, dateTime);
// if (dateTime.isBefore(minStartTime)) {
// minStartTime = dateTime;
// }
// }
//
// public DateTime getStartTimeForSourceIdAndCategoryId(final int sourceId, final int categoryId) {
// final Map<Integer, DateTime> sourceTimes = startTimesMap.get(sourceId);
// if (sourceTimes != null) {
// return sourceTimes.get(categoryId);
// } else {
// return null;
// }
// }
//
// public Map<Integer, Map<Integer, DateTime>> getStartTimesMap() {
// return startTimesMap;
// }
//
// public DateTime getTimeInserted() {
// return timeInserted;
// }
//
// public DateTime getMinStartTime() {
// return minStartTime;
// }
// }
| import com.google.common.collect.BiMap;
import java.util.List;
import javax.annotation.Nullable;
import org.joda.time.DateTime;
import org.killbill.billing.plugin.meter.timeline.categories.CategoryRecordIdAndMetric;
import org.killbill.billing.plugin.meter.timeline.chunks.TimelineChunk;
import org.killbill.billing.plugin.meter.timeline.consumer.TimelineChunkConsumer;
import org.killbill.billing.plugin.meter.timeline.shutdown.StartTimes;
import org.killbill.billing.util.callcontext.CallContext;
import org.killbill.billing.util.callcontext.TenantContext;
import org.skife.jdbi.v2.exceptions.CallbackFailedException;
import org.skife.jdbi.v2.exceptions.UnableToObtainConnectionException; | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline.persistent;
public interface TimelineDao {
// Sources table
Integer getSourceId(String source, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
String getSource(Integer sourceId, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
BiMap<Integer, String> getSources(TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
int getOrAddSource(String source, CallContext context) throws UnableToObtainConnectionException, CallbackFailedException;
// Event categories table
Integer getEventCategoryId(String eventCategory, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
String getEventCategory(Integer eventCategoryId, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
BiMap<Integer, String> getEventCategories(TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
int getOrAddEventCategory(String eventCategory, CallContext context) throws UnableToObtainConnectionException, CallbackFailedException;
// Metrics table
Integer getMetricId(int eventCategory, String metric, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
CategoryRecordIdAndMetric getCategoryIdAndMetric(Integer metricId, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
BiMap<Integer, CategoryRecordIdAndMetric> getMetrics(TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
int getOrAddMetric(Integer eventCategoryId, String metric, CallContext context) throws UnableToObtainConnectionException, CallbackFailedException;
// Timelines tables
Long insertTimelineChunk(TimelineChunk timelineChunk, CallContext context) throws UnableToObtainConnectionException, CallbackFailedException;
void getSamplesBySourceIdsAndMetricIds(List<Integer> sourceIds,
@Nullable List<Integer> metricIds,
DateTime startTime,
DateTime endTime,
TimelineChunkConsumer chunkConsumer,
TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
| // Path: src/main/java/org/killbill/billing/plugin/meter/timeline/shutdown/StartTimes.java
// public class StartTimes {
//
// private final DateTime timeInserted;
// private final Map<Integer, Map<Integer, DateTime>> startTimesMap;
// private DateTime minStartTime;
//
// public StartTimes(final DateTime timeInserted, final Map<Integer, Map<Integer, DateTime>> startTimesMap) {
// this.timeInserted = timeInserted;
// this.startTimesMap = startTimesMap;
// DateTime minDateTime = new DateTime(Long.MAX_VALUE);
// for (final Map<Integer, DateTime> categoryMap : startTimesMap.values()) {
// for (final DateTime startTime : categoryMap.values()) {
// if (minDateTime.isAfter(startTime)) {
// minDateTime = startTime;
// }
// }
// }
// this.minStartTime = minDateTime;
// }
//
// public StartTimes() {
// this.timeInserted = new DateTime();
// minStartTime = new DateTime(Long.MAX_VALUE);
// this.startTimesMap = new HashMap<Integer, Map<Integer, DateTime>>();
// }
//
// public void addTime(final int sourceId, final int categoryId, final DateTime dateTime) {
// Map<Integer, DateTime> sourceTimes = startTimesMap.get(sourceId);
// if (sourceTimes == null) {
// sourceTimes = new HashMap<Integer, DateTime>();
// startTimesMap.put(sourceId, sourceTimes);
// }
// sourceTimes.put(categoryId, dateTime);
// if (dateTime.isBefore(minStartTime)) {
// minStartTime = dateTime;
// }
// }
//
// public DateTime getStartTimeForSourceIdAndCategoryId(final int sourceId, final int categoryId) {
// final Map<Integer, DateTime> sourceTimes = startTimesMap.get(sourceId);
// if (sourceTimes != null) {
// return sourceTimes.get(categoryId);
// } else {
// return null;
// }
// }
//
// public Map<Integer, Map<Integer, DateTime>> getStartTimesMap() {
// return startTimesMap;
// }
//
// public DateTime getTimeInserted() {
// return timeInserted;
// }
//
// public DateTime getMinStartTime() {
// return minStartTime;
// }
// }
// Path: src/main/java/org/killbill/billing/plugin/meter/timeline/persistent/TimelineDao.java
import com.google.common.collect.BiMap;
import java.util.List;
import javax.annotation.Nullable;
import org.joda.time.DateTime;
import org.killbill.billing.plugin.meter.timeline.categories.CategoryRecordIdAndMetric;
import org.killbill.billing.plugin.meter.timeline.chunks.TimelineChunk;
import org.killbill.billing.plugin.meter.timeline.consumer.TimelineChunkConsumer;
import org.killbill.billing.plugin.meter.timeline.shutdown.StartTimes;
import org.killbill.billing.util.callcontext.CallContext;
import org.killbill.billing.util.callcontext.TenantContext;
import org.skife.jdbi.v2.exceptions.CallbackFailedException;
import org.skife.jdbi.v2.exceptions.UnableToObtainConnectionException;
/*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning licenses this file to you 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 org.killbill.billing.plugin.meter.timeline.persistent;
public interface TimelineDao {
// Sources table
Integer getSourceId(String source, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
String getSource(Integer sourceId, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
BiMap<Integer, String> getSources(TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
int getOrAddSource(String source, CallContext context) throws UnableToObtainConnectionException, CallbackFailedException;
// Event categories table
Integer getEventCategoryId(String eventCategory, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
String getEventCategory(Integer eventCategoryId, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
BiMap<Integer, String> getEventCategories(TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
int getOrAddEventCategory(String eventCategory, CallContext context) throws UnableToObtainConnectionException, CallbackFailedException;
// Metrics table
Integer getMetricId(int eventCategory, String metric, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
CategoryRecordIdAndMetric getCategoryIdAndMetric(Integer metricId, TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
BiMap<Integer, CategoryRecordIdAndMetric> getMetrics(TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
int getOrAddMetric(Integer eventCategoryId, String metric, CallContext context) throws UnableToObtainConnectionException, CallbackFailedException;
// Timelines tables
Long insertTimelineChunk(TimelineChunk timelineChunk, CallContext context) throws UnableToObtainConnectionException, CallbackFailedException;
void getSamplesBySourceIdsAndMetricIds(List<Integer> sourceIds,
@Nullable List<Integer> metricIds,
DateTime startTime,
DateTime endTime,
TimelineChunkConsumer chunkConsumer,
TenantContext context) throws UnableToObtainConnectionException, CallbackFailedException;
| Integer insertLastStartTimes(StartTimes startTimes, CallContext context); |
ZhaoYukai/ManhuaHouse | src/com/zykmanhua/app/activity/LibraryFragment.java | // Path: src/com/zykmanhua/app/adapter/TabAdapter.java
// public class TabAdapter extends FragmentPagerAdapter {
//
// private List<Fragment> mFragments = null;
//
// public TabAdapter(FragmentManager fm) {
// super(fm);
//
// mFragments = new ArrayList<Fragment>();
//
// FirstTab firstTab = new FirstTab();
// mFragments.add(firstTab);
//
// SecondTab secondTab = new SecondTab();
// mFragments.add(secondTab);
//
// ThirdTab thirdTab = new ThirdTab();
// mFragments.add(thirdTab);
//
// ForthTab forthTab = new ForthTab();
// mFragments.add(forthTab);
//
// FifthTab fifthTab = new FifthTab();
// mFragments.add(fifthTab);
// }
//
// @Override
// public Fragment getItem(int position) {
// return mFragments.get(position);
// }
//
// @Override
// public int getCount() {
// return Config.TITLES.length;
// }
//
//
// @Override
// public CharSequence getPageTitle(int position) {
// return Config.TITLES[position];
// }
//
// }
| import com.viewpagerindicator.TabPageIndicator;
import com.zykmanhua.app.R;
import com.zykmanhua.app.adapter.TabAdapter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; | package com.zykmanhua.app.activity;
public class LibraryFragment extends Fragment {
private ViewPager mViewPager = null;
private TabPageIndicator mTabPageIndicator = null; | // Path: src/com/zykmanhua/app/adapter/TabAdapter.java
// public class TabAdapter extends FragmentPagerAdapter {
//
// private List<Fragment> mFragments = null;
//
// public TabAdapter(FragmentManager fm) {
// super(fm);
//
// mFragments = new ArrayList<Fragment>();
//
// FirstTab firstTab = new FirstTab();
// mFragments.add(firstTab);
//
// SecondTab secondTab = new SecondTab();
// mFragments.add(secondTab);
//
// ThirdTab thirdTab = new ThirdTab();
// mFragments.add(thirdTab);
//
// ForthTab forthTab = new ForthTab();
// mFragments.add(forthTab);
//
// FifthTab fifthTab = new FifthTab();
// mFragments.add(fifthTab);
// }
//
// @Override
// public Fragment getItem(int position) {
// return mFragments.get(position);
// }
//
// @Override
// public int getCount() {
// return Config.TITLES.length;
// }
//
//
// @Override
// public CharSequence getPageTitle(int position) {
// return Config.TITLES[position];
// }
//
// }
// Path: src/com/zykmanhua/app/activity/LibraryFragment.java
import com.viewpagerindicator.TabPageIndicator;
import com.zykmanhua.app.R;
import com.zykmanhua.app.adapter.TabAdapter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
package com.zykmanhua.app.activity;
public class LibraryFragment extends Fragment {
private ViewPager mViewPager = null;
private TabPageIndicator mTabPageIndicator = null; | private TabAdapter mAdapter = null; |
ZhaoYukai/ManhuaHouse | src/com/zykmanhua/app/util/GetManhuaChapterByName.java | // Path: src/com/zykmanhua/app/bean/ManhuaContent.java
// public class ManhuaContent {
//
// private int mTotal;
// private String mName = null;
// private String mChapterName = null;
// private int mChapterId;
//
//
// public String getmName() {
// return mName;
// }
// public void setmName(String mName) {
// this.mName = mName;
// }
// public String getmChapterName() {
// return mChapterName;
// }
// public int getmTotal() {
// return mTotal;
// }
// public void setmTotal(int mTotal) {
// this.mTotal = mTotal;
// }
// public void setmChapterName(String mChapterName) {
// this.mChapterName = mChapterName;
// }
// public int getmChapterId() {
// return mChapterId;
// }
// public void setmChapterId(int mChapterId) {
// this.mChapterId = mChapterId;
// }
//
//
//
// }
| import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import com.thinkland.sdk.android.DataCallBack;
import com.thinkland.sdk.android.JuheData;
import com.thinkland.sdk.android.Parameters;
import com.zykmanhua.app.bean.ManhuaContent;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message; | package com.zykmanhua.app.util;
public class GetManhuaChapterByName {
private Context mContext = null;
private Handler mHandler = null;
public GetManhuaChapterByName(Context context , Handler handler) {
mContext = context;
mHandler = handler;
}
public void getChapterByName(final String name , final int skipNumber) {
Parameters parameters = new Parameters();
parameters.add(Config.KEY, Config.APP_KEY);
parameters.add(Config.KEY_COMICNAME, name);
parameters.add(Config.KEY_SKIP, skipNumber);
JuheData.executeWithAPI(
mContext,
Config.APP_ID,
Config.URL_MANHUA_CHAPTER ,
JuheData.GET,
parameters,
new DataCallBack() {
@Override
public void onSuccess(int statusCode, String responseString) {
if(statusCode == Config.STATUS_CODE_SUCCESS) {
//把接收到的JSON数据保存到本地,通过skipNumber来作为key区分
@SuppressWarnings("static-access")
SharedPreferences.Editor editor = mContext.getSharedPreferences(Config.Path_offline_ManhuaChapter, mContext.MODE_PRIVATE).edit();
editor.putString(name + skipNumber, responseString);
editor.commit();
| // Path: src/com/zykmanhua/app/bean/ManhuaContent.java
// public class ManhuaContent {
//
// private int mTotal;
// private String mName = null;
// private String mChapterName = null;
// private int mChapterId;
//
//
// public String getmName() {
// return mName;
// }
// public void setmName(String mName) {
// this.mName = mName;
// }
// public String getmChapterName() {
// return mChapterName;
// }
// public int getmTotal() {
// return mTotal;
// }
// public void setmTotal(int mTotal) {
// this.mTotal = mTotal;
// }
// public void setmChapterName(String mChapterName) {
// this.mChapterName = mChapterName;
// }
// public int getmChapterId() {
// return mChapterId;
// }
// public void setmChapterId(int mChapterId) {
// this.mChapterId = mChapterId;
// }
//
//
//
// }
// Path: src/com/zykmanhua/app/util/GetManhuaChapterByName.java
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import com.thinkland.sdk.android.DataCallBack;
import com.thinkland.sdk.android.JuheData;
import com.thinkland.sdk.android.Parameters;
import com.zykmanhua.app.bean.ManhuaContent;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
package com.zykmanhua.app.util;
public class GetManhuaChapterByName {
private Context mContext = null;
private Handler mHandler = null;
public GetManhuaChapterByName(Context context , Handler handler) {
mContext = context;
mHandler = handler;
}
public void getChapterByName(final String name , final int skipNumber) {
Parameters parameters = new Parameters();
parameters.add(Config.KEY, Config.APP_KEY);
parameters.add(Config.KEY_COMICNAME, name);
parameters.add(Config.KEY_SKIP, skipNumber);
JuheData.executeWithAPI(
mContext,
Config.APP_ID,
Config.URL_MANHUA_CHAPTER ,
JuheData.GET,
parameters,
new DataCallBack() {
@Override
public void onSuccess(int statusCode, String responseString) {
if(statusCode == Config.STATUS_CODE_SUCCESS) {
//把接收到的JSON数据保存到本地,通过skipNumber来作为key区分
@SuppressWarnings("static-access")
SharedPreferences.Editor editor = mContext.getSharedPreferences(Config.Path_offline_ManhuaChapter, mContext.MODE_PRIVATE).edit();
editor.putString(name + skipNumber, responseString);
editor.commit();
| ArrayList<ManhuaContent> manhuaContentList = parseJSON(responseString); |
ZhaoYukai/ManhuaHouse | src/com/zykmanhua/app/util/GetChapterContent.java | // Path: src/com/zykmanhua/app/bean/ManhuaPicture.java
// public class ManhuaPicture {
//
// private String mName = null;
// private int mChapterId;
// private String mImageUrl = null;
// private int mId;
//
//
//
//
// public String getmName() {
// return mName;
// }
// public void setmName(String mName) {
// this.mName = mName;
// }
// public int getmChapterId() {
// return mChapterId;
// }
// public void setmChapterId(int mChapterId) {
// this.mChapterId = mChapterId;
// }
// public String getmImageUrl() {
// return mImageUrl;
// }
// public void setmImageUrl(String mImageUrl) {
// this.mImageUrl = mImageUrl;
// }
// public int getmId() {
// return mId;
// }
// public void setmId(int mId) {
// this.mId = mId;
// }
//
//
//
// }
| import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import com.thinkland.sdk.android.DataCallBack;
import com.thinkland.sdk.android.JuheData;
import com.thinkland.sdk.android.Parameters;
import com.zykmanhua.app.bean.ManhuaPicture;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message; | package com.zykmanhua.app.util;
public class GetChapterContent {
private Context mContext = null;
private Handler mHandler = null;
public GetChapterContent(Context context , Handler handler) {
mContext = context;
mHandler = handler;
}
public void getChapterContent(final String name , final int id) {
Parameters parameters = new Parameters();
parameters.add(Config.KEY, Config.APP_KEY);
parameters.add(Config.KEY_COMICNAME, name);
parameters.add(Config.KEY_ID, id);
JuheData.executeWithAPI(
mContext,
Config.APP_ID,
Config.URL_MANHUA_CONTENT ,
JuheData.GET,
parameters,
new DataCallBack() {
@Override
public void onSuccess(int statusCode, String responseString) {
if(statusCode == Config.STATUS_CODE_SUCCESS) {
//把接收到的JSON数据保存到本地,通过skipNumber来作为key区分
@SuppressWarnings("static-access")
SharedPreferences.Editor editor = mContext.getSharedPreferences(Config.Path_offline_ChapterContent, mContext.MODE_PRIVATE).edit();
editor.putString(name + id, responseString);
editor.commit();
| // Path: src/com/zykmanhua/app/bean/ManhuaPicture.java
// public class ManhuaPicture {
//
// private String mName = null;
// private int mChapterId;
// private String mImageUrl = null;
// private int mId;
//
//
//
//
// public String getmName() {
// return mName;
// }
// public void setmName(String mName) {
// this.mName = mName;
// }
// public int getmChapterId() {
// return mChapterId;
// }
// public void setmChapterId(int mChapterId) {
// this.mChapterId = mChapterId;
// }
// public String getmImageUrl() {
// return mImageUrl;
// }
// public void setmImageUrl(String mImageUrl) {
// this.mImageUrl = mImageUrl;
// }
// public int getmId() {
// return mId;
// }
// public void setmId(int mId) {
// this.mId = mId;
// }
//
//
//
// }
// Path: src/com/zykmanhua/app/util/GetChapterContent.java
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import com.thinkland.sdk.android.DataCallBack;
import com.thinkland.sdk.android.JuheData;
import com.thinkland.sdk.android.Parameters;
import com.zykmanhua.app.bean.ManhuaPicture;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
package com.zykmanhua.app.util;
public class GetChapterContent {
private Context mContext = null;
private Handler mHandler = null;
public GetChapterContent(Context context , Handler handler) {
mContext = context;
mHandler = handler;
}
public void getChapterContent(final String name , final int id) {
Parameters parameters = new Parameters();
parameters.add(Config.KEY, Config.APP_KEY);
parameters.add(Config.KEY_COMICNAME, name);
parameters.add(Config.KEY_ID, id);
JuheData.executeWithAPI(
mContext,
Config.APP_ID,
Config.URL_MANHUA_CONTENT ,
JuheData.GET,
parameters,
new DataCallBack() {
@Override
public void onSuccess(int statusCode, String responseString) {
if(statusCode == Config.STATUS_CODE_SUCCESS) {
//把接收到的JSON数据保存到本地,通过skipNumber来作为key区分
@SuppressWarnings("static-access")
SharedPreferences.Editor editor = mContext.getSharedPreferences(Config.Path_offline_ChapterContent, mContext.MODE_PRIVATE).edit();
editor.putString(name + id, responseString);
editor.commit();
| ArrayList<ManhuaPicture> manhuaPictureList = parseJSON(responseString); |
ZhaoYukai/ManhuaHouse | src/com/zykmanhua/app/util/GetManhuaTypeData.java | // Path: src/com/zykmanhua/app/bean/ManhuaType.java
// public class ManhuaType {
//
// private String mType = null;
//
//
// public String getmType() {
// return mType;
// }
//
// public void setmType(String mType) {
// this.mType = mType;
// }
//
//
//
// }
| import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import com.thinkland.sdk.android.DataCallBack;
import com.thinkland.sdk.android.JuheData;
import com.thinkland.sdk.android.Parameters;
import com.zykmanhua.app.bean.ManhuaType; | package com.zykmanhua.app.util;
public class GetManhuaTypeData {
private Context mContext = null;
private Handler mHandler = null;
public GetManhuaTypeData(Context context , Handler handler) {
mContext = context;
mHandler = handler;
}
public void getManhuaType() {
Parameters parameters = new Parameters();
parameters.add(Config.KEY, Config.APP_KEY);
JuheData.executeWithAPI(
mContext,
Config.APP_ID,
Config.URL_MANHUA_TYPE ,
JuheData.GET,
parameters,
new DataCallBack() {
@Override
public void onSuccess(int statusCode, String responseString) {
if(statusCode == Config.STATUS_CODE_SUCCESS) { | // Path: src/com/zykmanhua/app/bean/ManhuaType.java
// public class ManhuaType {
//
// private String mType = null;
//
//
// public String getmType() {
// return mType;
// }
//
// public void setmType(String mType) {
// this.mType = mType;
// }
//
//
//
// }
// Path: src/com/zykmanhua/app/util/GetManhuaTypeData.java
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import com.thinkland.sdk.android.DataCallBack;
import com.thinkland.sdk.android.JuheData;
import com.thinkland.sdk.android.Parameters;
import com.zykmanhua.app.bean.ManhuaType;
package com.zykmanhua.app.util;
public class GetManhuaTypeData {
private Context mContext = null;
private Handler mHandler = null;
public GetManhuaTypeData(Context context , Handler handler) {
mContext = context;
mHandler = handler;
}
public void getManhuaType() {
Parameters parameters = new Parameters();
parameters.add(Config.KEY, Config.APP_KEY);
JuheData.executeWithAPI(
mContext,
Config.APP_ID,
Config.URL_MANHUA_TYPE ,
JuheData.GET,
parameters,
new DataCallBack() {
@Override
public void onSuccess(int statusCode, String responseString) {
if(statusCode == Config.STATUS_CODE_SUCCESS) { | ArrayList<ManhuaType> manhuaTypeList = parseJSON(responseString); |
ZhaoYukai/ManhuaHouse | src/com/zykmanhua/app/util/GetManhuaBookData.java | // Path: src/com/zykmanhua/app/bean/Manhua.java
// public class Manhua {
//
// private String mType = null;
// private String mName = null;
// private String mDes = null;
// private boolean mFinish = false;
// private int mLastUpdate;
// private String mCoverImg = null;
//
//
// public Manhua() {
//
// }
//
// public Manhua(String mType, String mName, String mDes, boolean mFinish, int mLastUpdate, String mCoverImg) {
// super();
// this.mType = mType;
// this.mName = mName;
// this.mDes = mDes;
// this.mFinish = mFinish;
// this.mLastUpdate = mLastUpdate;
// this.mCoverImg = mCoverImg;
// }
//
//
//
//
// public String getmType() {
// return mType;
// }
//
// public void setmType(String mType) {
// this.mType = mType;
// }
//
// public String getmName() {
// return mName;
// }
//
// public void setmName(String mName) {
// this.mName = mName;
// }
//
// public String getmDes() {
// return mDes;
// }
//
// public void setmDes(String mDes) {
// this.mDes = mDes;
// }
//
// public boolean ismFinish() {
// return mFinish;
// }
//
// public void setmFinish(boolean mFinish) {
// this.mFinish = mFinish;
// }
//
// public int getmLastUpdate() {
// return mLastUpdate;
// }
//
// public void setmLastUpdate(int mLastUpdate) {
// this.mLastUpdate = mLastUpdate;
// }
//
// public String getmCoverImg() {
// return mCoverImg;
// }
//
// public void setmCoverImg(String mCoverImg) {
// this.mCoverImg = mCoverImg;
// }
//
//
//
//
//
// }
| import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import com.thinkland.sdk.android.DataCallBack;
import com.thinkland.sdk.android.JuheData;
import com.thinkland.sdk.android.Parameters;
import com.zykmanhua.app.bean.Manhua;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message; | package com.zykmanhua.app.util;
public class GetManhuaBookData {
private Context mContext = null;
private Handler mHandler = null;
public GetManhuaBookData(Context context , Handler handler) {
mContext = context;
mHandler = handler;
}
public void getManhuaBook(final int skipNumber) {
Parameters parameters = new Parameters();
parameters.add(Config.KEY, Config.APP_KEY);
parameters.add(Config.KEY_SKIP, skipNumber);
JuheData.executeWithAPI(
mContext,
Config.APP_ID,
Config.URL_MANHUA_BOOK ,
JuheData.GET,
parameters,
new DataCallBack() {
@Override
public void onSuccess(int statusCode, String responseString) {
if(statusCode == Config.STATUS_CODE_SUCCESS) {
//°Ñ½ÓÊÕµ½µÄJSONÊý¾Ý±£´æµ½±¾µØ£¬Í¨¹ýskipNumberÀ´×÷ΪkeyÇø·Ö
@SuppressWarnings("static-access")
SharedPreferences.Editor editor = mContext.getSharedPreferences(Config.Path_offline_ManhuaData, mContext.MODE_PRIVATE).edit();
editor.putString(skipNumber + "", responseString);
editor.commit();
| // Path: src/com/zykmanhua/app/bean/Manhua.java
// public class Manhua {
//
// private String mType = null;
// private String mName = null;
// private String mDes = null;
// private boolean mFinish = false;
// private int mLastUpdate;
// private String mCoverImg = null;
//
//
// public Manhua() {
//
// }
//
// public Manhua(String mType, String mName, String mDes, boolean mFinish, int mLastUpdate, String mCoverImg) {
// super();
// this.mType = mType;
// this.mName = mName;
// this.mDes = mDes;
// this.mFinish = mFinish;
// this.mLastUpdate = mLastUpdate;
// this.mCoverImg = mCoverImg;
// }
//
//
//
//
// public String getmType() {
// return mType;
// }
//
// public void setmType(String mType) {
// this.mType = mType;
// }
//
// public String getmName() {
// return mName;
// }
//
// public void setmName(String mName) {
// this.mName = mName;
// }
//
// public String getmDes() {
// return mDes;
// }
//
// public void setmDes(String mDes) {
// this.mDes = mDes;
// }
//
// public boolean ismFinish() {
// return mFinish;
// }
//
// public void setmFinish(boolean mFinish) {
// this.mFinish = mFinish;
// }
//
// public int getmLastUpdate() {
// return mLastUpdate;
// }
//
// public void setmLastUpdate(int mLastUpdate) {
// this.mLastUpdate = mLastUpdate;
// }
//
// public String getmCoverImg() {
// return mCoverImg;
// }
//
// public void setmCoverImg(String mCoverImg) {
// this.mCoverImg = mCoverImg;
// }
//
//
//
//
//
// }
// Path: src/com/zykmanhua/app/util/GetManhuaBookData.java
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import com.thinkland.sdk.android.DataCallBack;
import com.thinkland.sdk.android.JuheData;
import com.thinkland.sdk.android.Parameters;
import com.zykmanhua.app.bean.Manhua;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
package com.zykmanhua.app.util;
public class GetManhuaBookData {
private Context mContext = null;
private Handler mHandler = null;
public GetManhuaBookData(Context context , Handler handler) {
mContext = context;
mHandler = handler;
}
public void getManhuaBook(final int skipNumber) {
Parameters parameters = new Parameters();
parameters.add(Config.KEY, Config.APP_KEY);
parameters.add(Config.KEY_SKIP, skipNumber);
JuheData.executeWithAPI(
mContext,
Config.APP_ID,
Config.URL_MANHUA_BOOK ,
JuheData.GET,
parameters,
new DataCallBack() {
@Override
public void onSuccess(int statusCode, String responseString) {
if(statusCode == Config.STATUS_CODE_SUCCESS) {
//°Ñ½ÓÊÕµ½µÄJSONÊý¾Ý±£´æµ½±¾µØ£¬Í¨¹ýskipNumberÀ´×÷ΪkeyÇø·Ö
@SuppressWarnings("static-access")
SharedPreferences.Editor editor = mContext.getSharedPreferences(Config.Path_offline_ManhuaData, mContext.MODE_PRIVATE).edit();
editor.putString(skipNumber + "", responseString);
editor.commit();
| ArrayList<Manhua> manhuaList = parseJSON(responseString); |
ZhaoYukai/ManhuaHouse | src/com/zykmanhua/app/util/GetManhuaDataByType.java | // Path: src/com/zykmanhua/app/bean/Manhua.java
// public class Manhua {
//
// private String mType = null;
// private String mName = null;
// private String mDes = null;
// private boolean mFinish = false;
// private int mLastUpdate;
// private String mCoverImg = null;
//
//
// public Manhua() {
//
// }
//
// public Manhua(String mType, String mName, String mDes, boolean mFinish, int mLastUpdate, String mCoverImg) {
// super();
// this.mType = mType;
// this.mName = mName;
// this.mDes = mDes;
// this.mFinish = mFinish;
// this.mLastUpdate = mLastUpdate;
// this.mCoverImg = mCoverImg;
// }
//
//
//
//
// public String getmType() {
// return mType;
// }
//
// public void setmType(String mType) {
// this.mType = mType;
// }
//
// public String getmName() {
// return mName;
// }
//
// public void setmName(String mName) {
// this.mName = mName;
// }
//
// public String getmDes() {
// return mDes;
// }
//
// public void setmDes(String mDes) {
// this.mDes = mDes;
// }
//
// public boolean ismFinish() {
// return mFinish;
// }
//
// public void setmFinish(boolean mFinish) {
// this.mFinish = mFinish;
// }
//
// public int getmLastUpdate() {
// return mLastUpdate;
// }
//
// public void setmLastUpdate(int mLastUpdate) {
// this.mLastUpdate = mLastUpdate;
// }
//
// public String getmCoverImg() {
// return mCoverImg;
// }
//
// public void setmCoverImg(String mCoverImg) {
// this.mCoverImg = mCoverImg;
// }
//
//
//
//
//
// }
| import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import com.thinkland.sdk.android.DataCallBack;
import com.thinkland.sdk.android.JuheData;
import com.thinkland.sdk.android.Parameters;
import com.zykmanhua.app.bean.Manhua; | package com.zykmanhua.app.util;
public class GetManhuaDataByType {
private Context mContext = null;
private Handler mHandler = null;
public GetManhuaDataByType(Context context , Handler handler) {
mContext = context;
mHandler = handler;
}
public void getManhuaBook(final String manhuaType , final int skipNumber) {
Parameters parameters = new Parameters();
parameters.add(Config.KEY, Config.APP_KEY);
parameters.add(Config.KEY_Type, manhuaType);
parameters.add(Config.KEY_SKIP, skipNumber);
JuheData.executeWithAPI(
mContext,
Config.APP_ID,
Config.URL_MANHUA_BOOK ,
JuheData.GET,
parameters,
new DataCallBack() {
@Override
public void onSuccess(int statusCode, String responseString) {
if(statusCode == Config.STATUS_CODE_SUCCESS) {
//°Ñ½ÓÊÕµ½µÄJSONÊý¾Ý±£´æµ½±¾µØ£¬Í¨¹ýskipNumberÀ´×÷ΪkeyÇø·Ö
@SuppressWarnings("static-access")
SharedPreferences.Editor editor = mContext.getSharedPreferences(Config.Path_offline_ManhuaData, mContext.MODE_PRIVATE).edit();
editor.putString(manhuaType + skipNumber, responseString);
editor.commit();
| // Path: src/com/zykmanhua/app/bean/Manhua.java
// public class Manhua {
//
// private String mType = null;
// private String mName = null;
// private String mDes = null;
// private boolean mFinish = false;
// private int mLastUpdate;
// private String mCoverImg = null;
//
//
// public Manhua() {
//
// }
//
// public Manhua(String mType, String mName, String mDes, boolean mFinish, int mLastUpdate, String mCoverImg) {
// super();
// this.mType = mType;
// this.mName = mName;
// this.mDes = mDes;
// this.mFinish = mFinish;
// this.mLastUpdate = mLastUpdate;
// this.mCoverImg = mCoverImg;
// }
//
//
//
//
// public String getmType() {
// return mType;
// }
//
// public void setmType(String mType) {
// this.mType = mType;
// }
//
// public String getmName() {
// return mName;
// }
//
// public void setmName(String mName) {
// this.mName = mName;
// }
//
// public String getmDes() {
// return mDes;
// }
//
// public void setmDes(String mDes) {
// this.mDes = mDes;
// }
//
// public boolean ismFinish() {
// return mFinish;
// }
//
// public void setmFinish(boolean mFinish) {
// this.mFinish = mFinish;
// }
//
// public int getmLastUpdate() {
// return mLastUpdate;
// }
//
// public void setmLastUpdate(int mLastUpdate) {
// this.mLastUpdate = mLastUpdate;
// }
//
// public String getmCoverImg() {
// return mCoverImg;
// }
//
// public void setmCoverImg(String mCoverImg) {
// this.mCoverImg = mCoverImg;
// }
//
//
//
//
//
// }
// Path: src/com/zykmanhua/app/util/GetManhuaDataByType.java
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import com.thinkland.sdk.android.DataCallBack;
import com.thinkland.sdk.android.JuheData;
import com.thinkland.sdk.android.Parameters;
import com.zykmanhua.app.bean.Manhua;
package com.zykmanhua.app.util;
public class GetManhuaDataByType {
private Context mContext = null;
private Handler mHandler = null;
public GetManhuaDataByType(Context context , Handler handler) {
mContext = context;
mHandler = handler;
}
public void getManhuaBook(final String manhuaType , final int skipNumber) {
Parameters parameters = new Parameters();
parameters.add(Config.KEY, Config.APP_KEY);
parameters.add(Config.KEY_Type, manhuaType);
parameters.add(Config.KEY_SKIP, skipNumber);
JuheData.executeWithAPI(
mContext,
Config.APP_ID,
Config.URL_MANHUA_BOOK ,
JuheData.GET,
parameters,
new DataCallBack() {
@Override
public void onSuccess(int statusCode, String responseString) {
if(statusCode == Config.STATUS_CODE_SUCCESS) {
//°Ñ½ÓÊÕµ½µÄJSONÊý¾Ý±£´æµ½±¾µØ£¬Í¨¹ýskipNumberÀ´×÷ΪkeyÇø·Ö
@SuppressWarnings("static-access")
SharedPreferences.Editor editor = mContext.getSharedPreferences(Config.Path_offline_ManhuaData, mContext.MODE_PRIVATE).edit();
editor.putString(manhuaType + skipNumber, responseString);
editor.commit();
| ArrayList<Manhua> manhuaList = parseJSON(responseString); |
ZhaoYukai/ManhuaHouse | src/com/zykmanhua/app/util/GetManhuaDataByName.java | // Path: src/com/zykmanhua/app/bean/Manhua.java
// public class Manhua {
//
// private String mType = null;
// private String mName = null;
// private String mDes = null;
// private boolean mFinish = false;
// private int mLastUpdate;
// private String mCoverImg = null;
//
//
// public Manhua() {
//
// }
//
// public Manhua(String mType, String mName, String mDes, boolean mFinish, int mLastUpdate, String mCoverImg) {
// super();
// this.mType = mType;
// this.mName = mName;
// this.mDes = mDes;
// this.mFinish = mFinish;
// this.mLastUpdate = mLastUpdate;
// this.mCoverImg = mCoverImg;
// }
//
//
//
//
// public String getmType() {
// return mType;
// }
//
// public void setmType(String mType) {
// this.mType = mType;
// }
//
// public String getmName() {
// return mName;
// }
//
// public void setmName(String mName) {
// this.mName = mName;
// }
//
// public String getmDes() {
// return mDes;
// }
//
// public void setmDes(String mDes) {
// this.mDes = mDes;
// }
//
// public boolean ismFinish() {
// return mFinish;
// }
//
// public void setmFinish(boolean mFinish) {
// this.mFinish = mFinish;
// }
//
// public int getmLastUpdate() {
// return mLastUpdate;
// }
//
// public void setmLastUpdate(int mLastUpdate) {
// this.mLastUpdate = mLastUpdate;
// }
//
// public String getmCoverImg() {
// return mCoverImg;
// }
//
// public void setmCoverImg(String mCoverImg) {
// this.mCoverImg = mCoverImg;
// }
//
//
//
//
//
// }
| import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import com.thinkland.sdk.android.DataCallBack;
import com.thinkland.sdk.android.JuheData;
import com.thinkland.sdk.android.Parameters;
import com.zykmanhua.app.bean.Manhua; | package com.zykmanhua.app.util;
public class GetManhuaDataByName {
private Context mContext = null;
private Handler mHandler = null;
public GetManhuaDataByName(Context context , Handler handler) {
mContext = context;
mHandler = handler;
}
public void getManhuaBook(final String manhuaName) {
Parameters parameters = new Parameters();
parameters.add(Config.KEY, Config.APP_KEY);
parameters.add(Config.KEY_Name, manhuaName);
JuheData.executeWithAPI(
mContext,
Config.APP_ID,
Config.URL_MANHUA_BOOK ,
JuheData.GET,
parameters,
new DataCallBack() {
@Override
public void onSuccess(int statusCode, String responseString) {
if(statusCode == Config.STATUS_CODE_SUCCESS) {
//°Ñ½ÓÊÕµ½µÄJSONÊý¾Ý±£´æµ½±¾µØ£¬Í¨¹ýskipNumberÀ´×÷ΪkeyÇø·Ö
@SuppressWarnings("static-access")
SharedPreferences.Editor editor = mContext.getSharedPreferences(Config.Path_offline_SearchManhuaData, mContext.MODE_PRIVATE).edit();
editor.putString(manhuaName, responseString);
editor.commit();
| // Path: src/com/zykmanhua/app/bean/Manhua.java
// public class Manhua {
//
// private String mType = null;
// private String mName = null;
// private String mDes = null;
// private boolean mFinish = false;
// private int mLastUpdate;
// private String mCoverImg = null;
//
//
// public Manhua() {
//
// }
//
// public Manhua(String mType, String mName, String mDes, boolean mFinish, int mLastUpdate, String mCoverImg) {
// super();
// this.mType = mType;
// this.mName = mName;
// this.mDes = mDes;
// this.mFinish = mFinish;
// this.mLastUpdate = mLastUpdate;
// this.mCoverImg = mCoverImg;
// }
//
//
//
//
// public String getmType() {
// return mType;
// }
//
// public void setmType(String mType) {
// this.mType = mType;
// }
//
// public String getmName() {
// return mName;
// }
//
// public void setmName(String mName) {
// this.mName = mName;
// }
//
// public String getmDes() {
// return mDes;
// }
//
// public void setmDes(String mDes) {
// this.mDes = mDes;
// }
//
// public boolean ismFinish() {
// return mFinish;
// }
//
// public void setmFinish(boolean mFinish) {
// this.mFinish = mFinish;
// }
//
// public int getmLastUpdate() {
// return mLastUpdate;
// }
//
// public void setmLastUpdate(int mLastUpdate) {
// this.mLastUpdate = mLastUpdate;
// }
//
// public String getmCoverImg() {
// return mCoverImg;
// }
//
// public void setmCoverImg(String mCoverImg) {
// this.mCoverImg = mCoverImg;
// }
//
//
//
//
//
// }
// Path: src/com/zykmanhua/app/util/GetManhuaDataByName.java
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import com.thinkland.sdk.android.DataCallBack;
import com.thinkland.sdk.android.JuheData;
import com.thinkland.sdk.android.Parameters;
import com.zykmanhua.app.bean.Manhua;
package com.zykmanhua.app.util;
public class GetManhuaDataByName {
private Context mContext = null;
private Handler mHandler = null;
public GetManhuaDataByName(Context context , Handler handler) {
mContext = context;
mHandler = handler;
}
public void getManhuaBook(final String manhuaName) {
Parameters parameters = new Parameters();
parameters.add(Config.KEY, Config.APP_KEY);
parameters.add(Config.KEY_Name, manhuaName);
JuheData.executeWithAPI(
mContext,
Config.APP_ID,
Config.URL_MANHUA_BOOK ,
JuheData.GET,
parameters,
new DataCallBack() {
@Override
public void onSuccess(int statusCode, String responseString) {
if(statusCode == Config.STATUS_CODE_SUCCESS) {
//°Ñ½ÓÊÕµ½µÄJSONÊý¾Ý±£´æµ½±¾µØ£¬Í¨¹ýskipNumberÀ´×÷ΪkeyÇø·Ö
@SuppressWarnings("static-access")
SharedPreferences.Editor editor = mContext.getSharedPreferences(Config.Path_offline_SearchManhuaData, mContext.MODE_PRIVATE).edit();
editor.putString(manhuaName, responseString);
editor.commit();
| ArrayList<Manhua> manhuaList = parseJSON(responseString); |
ZhaoYukai/ManhuaHouse | src/com/zykmanhua/app/adapter/ManhuaCollectAdapter.java | // Path: src/com/zykmanhua/app/bean/GroupCollect.java
// public class GroupCollect {
//
// private Map<String , Manhua> collectHashMap = null;
//
// public GroupCollect() {
// this.collectHashMap = new HashMap<String, Manhua>();
// }
//
// public Map<String, Manhua> getCollectMap() {
// return this.collectHashMap;
// }
//
// public void setCollectMap(Map<String, Manhua> collectHashMap) {
// this.collectHashMap = collectHashMap;
// }
//
// public void addCollect(Manhua collectHashMap) {
// String url = collectHashMap.getmCoverImg();
// String key = MD5Tools.hashKeyForDisk(url);
// this.collectHashMap.put(key , collectHashMap);
// }
//
// public void removeCollect(String url) {
// String key = MD5Tools.hashKeyForDisk(url);
// this.collectHashMap.remove(key);
// }
//
// }
//
// Path: src/com/zykmanhua/app/bean/Manhua.java
// public class Manhua {
//
// private String mType = null;
// private String mName = null;
// private String mDes = null;
// private boolean mFinish = false;
// private int mLastUpdate;
// private String mCoverImg = null;
//
//
// public Manhua() {
//
// }
//
// public Manhua(String mType, String mName, String mDes, boolean mFinish, int mLastUpdate, String mCoverImg) {
// super();
// this.mType = mType;
// this.mName = mName;
// this.mDes = mDes;
// this.mFinish = mFinish;
// this.mLastUpdate = mLastUpdate;
// this.mCoverImg = mCoverImg;
// }
//
//
//
//
// public String getmType() {
// return mType;
// }
//
// public void setmType(String mType) {
// this.mType = mType;
// }
//
// public String getmName() {
// return mName;
// }
//
// public void setmName(String mName) {
// this.mName = mName;
// }
//
// public String getmDes() {
// return mDes;
// }
//
// public void setmDes(String mDes) {
// this.mDes = mDes;
// }
//
// public boolean ismFinish() {
// return mFinish;
// }
//
// public void setmFinish(boolean mFinish) {
// this.mFinish = mFinish;
// }
//
// public int getmLastUpdate() {
// return mLastUpdate;
// }
//
// public void setmLastUpdate(int mLastUpdate) {
// this.mLastUpdate = mLastUpdate;
// }
//
// public String getmCoverImg() {
// return mCoverImg;
// }
//
// public void setmCoverImg(String mCoverImg) {
// this.mCoverImg = mCoverImg;
// }
//
//
//
//
//
// }
| import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.zykmanhua.app.R;
import com.zykmanhua.app.bean.GroupCollect;
import com.zykmanhua.app.bean.Manhua;
import android.content.Context;
import android.graphics.Bitmap.Config;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView; | package com.zykmanhua.app.adapter;
public class ManhuaCollectAdapter extends BaseAdapter {
private Context mContext = null;
private LayoutInflater mLayoutInflater = null;
private ImageLoader mImageLoader = null;
private DisplayImageOptions mOptions = null; | // Path: src/com/zykmanhua/app/bean/GroupCollect.java
// public class GroupCollect {
//
// private Map<String , Manhua> collectHashMap = null;
//
// public GroupCollect() {
// this.collectHashMap = new HashMap<String, Manhua>();
// }
//
// public Map<String, Manhua> getCollectMap() {
// return this.collectHashMap;
// }
//
// public void setCollectMap(Map<String, Manhua> collectHashMap) {
// this.collectHashMap = collectHashMap;
// }
//
// public void addCollect(Manhua collectHashMap) {
// String url = collectHashMap.getmCoverImg();
// String key = MD5Tools.hashKeyForDisk(url);
// this.collectHashMap.put(key , collectHashMap);
// }
//
// public void removeCollect(String url) {
// String key = MD5Tools.hashKeyForDisk(url);
// this.collectHashMap.remove(key);
// }
//
// }
//
// Path: src/com/zykmanhua/app/bean/Manhua.java
// public class Manhua {
//
// private String mType = null;
// private String mName = null;
// private String mDes = null;
// private boolean mFinish = false;
// private int mLastUpdate;
// private String mCoverImg = null;
//
//
// public Manhua() {
//
// }
//
// public Manhua(String mType, String mName, String mDes, boolean mFinish, int mLastUpdate, String mCoverImg) {
// super();
// this.mType = mType;
// this.mName = mName;
// this.mDes = mDes;
// this.mFinish = mFinish;
// this.mLastUpdate = mLastUpdate;
// this.mCoverImg = mCoverImg;
// }
//
//
//
//
// public String getmType() {
// return mType;
// }
//
// public void setmType(String mType) {
// this.mType = mType;
// }
//
// public String getmName() {
// return mName;
// }
//
// public void setmName(String mName) {
// this.mName = mName;
// }
//
// public String getmDes() {
// return mDes;
// }
//
// public void setmDes(String mDes) {
// this.mDes = mDes;
// }
//
// public boolean ismFinish() {
// return mFinish;
// }
//
// public void setmFinish(boolean mFinish) {
// this.mFinish = mFinish;
// }
//
// public int getmLastUpdate() {
// return mLastUpdate;
// }
//
// public void setmLastUpdate(int mLastUpdate) {
// this.mLastUpdate = mLastUpdate;
// }
//
// public String getmCoverImg() {
// return mCoverImg;
// }
//
// public void setmCoverImg(String mCoverImg) {
// this.mCoverImg = mCoverImg;
// }
//
//
//
//
//
// }
// Path: src/com/zykmanhua/app/adapter/ManhuaCollectAdapter.java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.zykmanhua.app.R;
import com.zykmanhua.app.bean.GroupCollect;
import com.zykmanhua.app.bean.Manhua;
import android.content.Context;
import android.graphics.Bitmap.Config;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
package com.zykmanhua.app.adapter;
public class ManhuaCollectAdapter extends BaseAdapter {
private Context mContext = null;
private LayoutInflater mLayoutInflater = null;
private ImageLoader mImageLoader = null;
private DisplayImageOptions mOptions = null; | private GroupCollect mGroupCollect = null; |
ZhaoYukai/ManhuaHouse | src/com/zykmanhua/app/adapter/ManhuaCollectAdapter.java | // Path: src/com/zykmanhua/app/bean/GroupCollect.java
// public class GroupCollect {
//
// private Map<String , Manhua> collectHashMap = null;
//
// public GroupCollect() {
// this.collectHashMap = new HashMap<String, Manhua>();
// }
//
// public Map<String, Manhua> getCollectMap() {
// return this.collectHashMap;
// }
//
// public void setCollectMap(Map<String, Manhua> collectHashMap) {
// this.collectHashMap = collectHashMap;
// }
//
// public void addCollect(Manhua collectHashMap) {
// String url = collectHashMap.getmCoverImg();
// String key = MD5Tools.hashKeyForDisk(url);
// this.collectHashMap.put(key , collectHashMap);
// }
//
// public void removeCollect(String url) {
// String key = MD5Tools.hashKeyForDisk(url);
// this.collectHashMap.remove(key);
// }
//
// }
//
// Path: src/com/zykmanhua/app/bean/Manhua.java
// public class Manhua {
//
// private String mType = null;
// private String mName = null;
// private String mDes = null;
// private boolean mFinish = false;
// private int mLastUpdate;
// private String mCoverImg = null;
//
//
// public Manhua() {
//
// }
//
// public Manhua(String mType, String mName, String mDes, boolean mFinish, int mLastUpdate, String mCoverImg) {
// super();
// this.mType = mType;
// this.mName = mName;
// this.mDes = mDes;
// this.mFinish = mFinish;
// this.mLastUpdate = mLastUpdate;
// this.mCoverImg = mCoverImg;
// }
//
//
//
//
// public String getmType() {
// return mType;
// }
//
// public void setmType(String mType) {
// this.mType = mType;
// }
//
// public String getmName() {
// return mName;
// }
//
// public void setmName(String mName) {
// this.mName = mName;
// }
//
// public String getmDes() {
// return mDes;
// }
//
// public void setmDes(String mDes) {
// this.mDes = mDes;
// }
//
// public boolean ismFinish() {
// return mFinish;
// }
//
// public void setmFinish(boolean mFinish) {
// this.mFinish = mFinish;
// }
//
// public int getmLastUpdate() {
// return mLastUpdate;
// }
//
// public void setmLastUpdate(int mLastUpdate) {
// this.mLastUpdate = mLastUpdate;
// }
//
// public String getmCoverImg() {
// return mCoverImg;
// }
//
// public void setmCoverImg(String mCoverImg) {
// this.mCoverImg = mCoverImg;
// }
//
//
//
//
//
// }
| import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.zykmanhua.app.R;
import com.zykmanhua.app.bean.GroupCollect;
import com.zykmanhua.app.bean.Manhua;
import android.content.Context;
import android.graphics.Bitmap.Config;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView; | package com.zykmanhua.app.adapter;
public class ManhuaCollectAdapter extends BaseAdapter {
private Context mContext = null;
private LayoutInflater mLayoutInflater = null;
private ImageLoader mImageLoader = null;
private DisplayImageOptions mOptions = null;
private GroupCollect mGroupCollect = null; | // Path: src/com/zykmanhua/app/bean/GroupCollect.java
// public class GroupCollect {
//
// private Map<String , Manhua> collectHashMap = null;
//
// public GroupCollect() {
// this.collectHashMap = new HashMap<String, Manhua>();
// }
//
// public Map<String, Manhua> getCollectMap() {
// return this.collectHashMap;
// }
//
// public void setCollectMap(Map<String, Manhua> collectHashMap) {
// this.collectHashMap = collectHashMap;
// }
//
// public void addCollect(Manhua collectHashMap) {
// String url = collectHashMap.getmCoverImg();
// String key = MD5Tools.hashKeyForDisk(url);
// this.collectHashMap.put(key , collectHashMap);
// }
//
// public void removeCollect(String url) {
// String key = MD5Tools.hashKeyForDisk(url);
// this.collectHashMap.remove(key);
// }
//
// }
//
// Path: src/com/zykmanhua/app/bean/Manhua.java
// public class Manhua {
//
// private String mType = null;
// private String mName = null;
// private String mDes = null;
// private boolean mFinish = false;
// private int mLastUpdate;
// private String mCoverImg = null;
//
//
// public Manhua() {
//
// }
//
// public Manhua(String mType, String mName, String mDes, boolean mFinish, int mLastUpdate, String mCoverImg) {
// super();
// this.mType = mType;
// this.mName = mName;
// this.mDes = mDes;
// this.mFinish = mFinish;
// this.mLastUpdate = mLastUpdate;
// this.mCoverImg = mCoverImg;
// }
//
//
//
//
// public String getmType() {
// return mType;
// }
//
// public void setmType(String mType) {
// this.mType = mType;
// }
//
// public String getmName() {
// return mName;
// }
//
// public void setmName(String mName) {
// this.mName = mName;
// }
//
// public String getmDes() {
// return mDes;
// }
//
// public void setmDes(String mDes) {
// this.mDes = mDes;
// }
//
// public boolean ismFinish() {
// return mFinish;
// }
//
// public void setmFinish(boolean mFinish) {
// this.mFinish = mFinish;
// }
//
// public int getmLastUpdate() {
// return mLastUpdate;
// }
//
// public void setmLastUpdate(int mLastUpdate) {
// this.mLastUpdate = mLastUpdate;
// }
//
// public String getmCoverImg() {
// return mCoverImg;
// }
//
// public void setmCoverImg(String mCoverImg) {
// this.mCoverImg = mCoverImg;
// }
//
//
//
//
//
// }
// Path: src/com/zykmanhua/app/adapter/ManhuaCollectAdapter.java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.zykmanhua.app.R;
import com.zykmanhua.app.bean.GroupCollect;
import com.zykmanhua.app.bean.Manhua;
import android.content.Context;
import android.graphics.Bitmap.Config;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
package com.zykmanhua.app.adapter;
public class ManhuaCollectAdapter extends BaseAdapter {
private Context mContext = null;
private LayoutInflater mLayoutInflater = null;
private ImageLoader mImageLoader = null;
private DisplayImageOptions mOptions = null;
private GroupCollect mGroupCollect = null; | private Map<String, Manhua> mManhuaMap = null; |
ZhaoYukai/ManhuaHouse | src/com/zykmanhua/app/adapter/ContentAdapter.java | // Path: src/com/zykmanhua/app/bean/ManhuaPicture.java
// public class ManhuaPicture {
//
// private String mName = null;
// private int mChapterId;
// private String mImageUrl = null;
// private int mId;
//
//
//
//
// public String getmName() {
// return mName;
// }
// public void setmName(String mName) {
// this.mName = mName;
// }
// public int getmChapterId() {
// return mChapterId;
// }
// public void setmChapterId(int mChapterId) {
// this.mChapterId = mChapterId;
// }
// public String getmImageUrl() {
// return mImageUrl;
// }
// public void setmImageUrl(String mImageUrl) {
// this.mImageUrl = mImageUrl;
// }
// public int getmId() {
// return mId;
// }
// public void setmId(int mId) {
// this.mId = mId;
// }
//
//
//
// }
| import java.util.List;
import uk.co.senab.photoview.PhotoViewAttacher;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.zykmanhua.app.R;
import com.zykmanhua.app.bean.ManhuaPicture;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView; | package com.zykmanhua.app.adapter;
public class ContentAdapter extends PagerAdapter {
private Context mContext = null; | // Path: src/com/zykmanhua/app/bean/ManhuaPicture.java
// public class ManhuaPicture {
//
// private String mName = null;
// private int mChapterId;
// private String mImageUrl = null;
// private int mId;
//
//
//
//
// public String getmName() {
// return mName;
// }
// public void setmName(String mName) {
// this.mName = mName;
// }
// public int getmChapterId() {
// return mChapterId;
// }
// public void setmChapterId(int mChapterId) {
// this.mChapterId = mChapterId;
// }
// public String getmImageUrl() {
// return mImageUrl;
// }
// public void setmImageUrl(String mImageUrl) {
// this.mImageUrl = mImageUrl;
// }
// public int getmId() {
// return mId;
// }
// public void setmId(int mId) {
// this.mId = mId;
// }
//
//
//
// }
// Path: src/com/zykmanhua/app/adapter/ContentAdapter.java
import java.util.List;
import uk.co.senab.photoview.PhotoViewAttacher;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.zykmanhua.app.R;
import com.zykmanhua.app.bean.ManhuaPicture;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
package com.zykmanhua.app.adapter;
public class ContentAdapter extends PagerAdapter {
private Context mContext = null; | private List<ManhuaPicture> mManhuaPictures = null; |
ZhaoYukai/ManhuaHouse | src/com/zykmanhua/app/bean/GroupCollect.java | // Path: src/com/zykmanhua/app/util/MD5Tools.java
// public class MD5Tools {
//
// public static String hashKeyForDisk(String key) {
// String cacheKey;
// try {
// final MessageDigest mDigest = MessageDigest.getInstance("MD5");
// mDigest.update(key.getBytes());
// cacheKey = bytesToHexString(mDigest.digest());
// }
// catch (NoSuchAlgorithmException e) {
// cacheKey = String.valueOf(key.hashCode());
// }
//
// return cacheKey;
// }
//
// private static String bytesToHexString(byte[] bytes) {
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < bytes.length; i++) {
// String hex = Integer.toHexString(0xFF & bytes[i]);
// if (hex.length() == 1) {
// sb.append('0');
// }
// sb.append(hex);
// }
// return sb.toString();
// }
//
// }
| import java.util.HashMap;
import java.util.Map;
import com.zykmanhua.app.util.MD5Tools; | package com.zykmanhua.app.bean;
public class GroupCollect {
private Map<String , Manhua> collectHashMap = null;
public GroupCollect() {
this.collectHashMap = new HashMap<String, Manhua>();
}
public Map<String, Manhua> getCollectMap() {
return this.collectHashMap;
}
public void setCollectMap(Map<String, Manhua> collectHashMap) {
this.collectHashMap = collectHashMap;
}
public void addCollect(Manhua collectHashMap) {
String url = collectHashMap.getmCoverImg(); | // Path: src/com/zykmanhua/app/util/MD5Tools.java
// public class MD5Tools {
//
// public static String hashKeyForDisk(String key) {
// String cacheKey;
// try {
// final MessageDigest mDigest = MessageDigest.getInstance("MD5");
// mDigest.update(key.getBytes());
// cacheKey = bytesToHexString(mDigest.digest());
// }
// catch (NoSuchAlgorithmException e) {
// cacheKey = String.valueOf(key.hashCode());
// }
//
// return cacheKey;
// }
//
// private static String bytesToHexString(byte[] bytes) {
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < bytes.length; i++) {
// String hex = Integer.toHexString(0xFF & bytes[i]);
// if (hex.length() == 1) {
// sb.append('0');
// }
// sb.append(hex);
// }
// return sb.toString();
// }
//
// }
// Path: src/com/zykmanhua/app/bean/GroupCollect.java
import java.util.HashMap;
import java.util.Map;
import com.zykmanhua.app.util.MD5Tools;
package com.zykmanhua.app.bean;
public class GroupCollect {
private Map<String , Manhua> collectHashMap = null;
public GroupCollect() {
this.collectHashMap = new HashMap<String, Manhua>();
}
public Map<String, Manhua> getCollectMap() {
return this.collectHashMap;
}
public void setCollectMap(Map<String, Manhua> collectHashMap) {
this.collectHashMap = collectHashMap;
}
public void addCollect(Manhua collectHashMap) {
String url = collectHashMap.getmCoverImg(); | String key = MD5Tools.hashKeyForDisk(url); |
ZhaoYukai/ManhuaHouse | src/com/zykmanhua/app/activity/MyRecordFragment.java | // Path: src/com/zykmanhua/app/adapter/MyRecordAdapter.java
// public class MyRecordAdapter extends FragmentPagerAdapter {
//
// private List<Fragment> mMyRecordFragments = null;
//
// public MyRecordAdapter(FragmentManager fm) {
// super(fm);
//
// mMyRecordFragments = new ArrayList<Fragment>();
//
// MyRecordCollect myRecordCollect = new MyRecordCollect();
// mMyRecordFragments.add(myRecordCollect);
//
// MyRecordHistory myRecordHistory = new MyRecordHistory();
// mMyRecordFragments.add(myRecordHistory);
// }
//
// @Override
// public Fragment getItem(int position) {
// return mMyRecordFragments.get(position);
// }
//
// @Override
// public int getCount() {
// return Config.MYRECORD_TITLES.length;
// }
//
//
// @Override
// public CharSequence getPageTitle(int position) {
// return Config.MYRECORD_TITLES[position];
// }
//
// }
| import com.viewpagerindicator.TabPageIndicator;
import com.zykmanhua.app.R;
import com.zykmanhua.app.adapter.MyRecordAdapter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; | package com.zykmanhua.app.activity;
public class MyRecordFragment extends Fragment {
private ViewPager mMyRecordViewPager = null;
private TabPageIndicator mMyRecordTabPageIndicator = null; | // Path: src/com/zykmanhua/app/adapter/MyRecordAdapter.java
// public class MyRecordAdapter extends FragmentPagerAdapter {
//
// private List<Fragment> mMyRecordFragments = null;
//
// public MyRecordAdapter(FragmentManager fm) {
// super(fm);
//
// mMyRecordFragments = new ArrayList<Fragment>();
//
// MyRecordCollect myRecordCollect = new MyRecordCollect();
// mMyRecordFragments.add(myRecordCollect);
//
// MyRecordHistory myRecordHistory = new MyRecordHistory();
// mMyRecordFragments.add(myRecordHistory);
// }
//
// @Override
// public Fragment getItem(int position) {
// return mMyRecordFragments.get(position);
// }
//
// @Override
// public int getCount() {
// return Config.MYRECORD_TITLES.length;
// }
//
//
// @Override
// public CharSequence getPageTitle(int position) {
// return Config.MYRECORD_TITLES[position];
// }
//
// }
// Path: src/com/zykmanhua/app/activity/MyRecordFragment.java
import com.viewpagerindicator.TabPageIndicator;
import com.zykmanhua.app.R;
import com.zykmanhua.app.adapter.MyRecordAdapter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
package com.zykmanhua.app.activity;
public class MyRecordFragment extends Fragment {
private ViewPager mMyRecordViewPager = null;
private TabPageIndicator mMyRecordTabPageIndicator = null; | private MyRecordAdapter mMyRecordAdapter = null; |
ZhaoYukai/ManhuaHouse | src/com/zykmanhua/app/adapter/ChapterAdapter.java | // Path: src/com/zykmanhua/app/bean/ManhuaContent.java
// public class ManhuaContent {
//
// private int mTotal;
// private String mName = null;
// private String mChapterName = null;
// private int mChapterId;
//
//
// public String getmName() {
// return mName;
// }
// public void setmName(String mName) {
// this.mName = mName;
// }
// public String getmChapterName() {
// return mChapterName;
// }
// public int getmTotal() {
// return mTotal;
// }
// public void setmTotal(int mTotal) {
// this.mTotal = mTotal;
// }
// public void setmChapterName(String mChapterName) {
// this.mChapterName = mChapterName;
// }
// public int getmChapterId() {
// return mChapterId;
// }
// public void setmChapterId(int mChapterId) {
// this.mChapterId = mChapterId;
// }
//
//
//
// }
| import java.util.List;
import com.zykmanhua.app.R;
import com.zykmanhua.app.bean.ManhuaContent;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView; | package com.zykmanhua.app.adapter;
public class ChapterAdapter extends BaseAdapter {
private Context mContext = null; | // Path: src/com/zykmanhua/app/bean/ManhuaContent.java
// public class ManhuaContent {
//
// private int mTotal;
// private String mName = null;
// private String mChapterName = null;
// private int mChapterId;
//
//
// public String getmName() {
// return mName;
// }
// public void setmName(String mName) {
// this.mName = mName;
// }
// public String getmChapterName() {
// return mChapterName;
// }
// public int getmTotal() {
// return mTotal;
// }
// public void setmTotal(int mTotal) {
// this.mTotal = mTotal;
// }
// public void setmChapterName(String mChapterName) {
// this.mChapterName = mChapterName;
// }
// public int getmChapterId() {
// return mChapterId;
// }
// public void setmChapterId(int mChapterId) {
// this.mChapterId = mChapterId;
// }
//
//
//
// }
// Path: src/com/zykmanhua/app/adapter/ChapterAdapter.java
import java.util.List;
import com.zykmanhua.app.R;
import com.zykmanhua.app.bean.ManhuaContent;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
package com.zykmanhua.app.adapter;
public class ChapterAdapter extends BaseAdapter {
private Context mContext = null; | private List<ManhuaContent> mManhuaContents = null; |
teisun/SunmiUI | SunmiDesign/app/src/main/java/sunmi/sunmidesign/TitleListActivity.java | // Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/list/SunmiList.java
// public class SunmiList extends LinearLayout {
//
// private ListView mListView;
// private TextView mTvTitle;
//
// public SunmiList(Context context) {
// super(context);
// initView();
// }
//
// public SunmiList(Context context, AttributeSet attrs) {
// super(context, attrs);
// initView();
// }
//
// public SunmiList(Context context, AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// initView();
// }
//
// private void initView( ) {
// View view = getAdapterView();
// this.addView(view);
// mTvTitle = (TextView) view.findViewById(R.id.tv_title);
// mListView = (ListView) view.findViewById(R.id.list_view);
// }
//
// /**
// * 适配
// * @return
// */
// private View getAdapterView( ) {
// switch (Adaptation.proportion) {
// case Adaptation.SCREEN_9_16:
// return View.inflate(getContext(), R.layout.list_v1_9_16, null);
// case Adaptation.SCREEN_3_4:
// return View.inflate(getContext(), R.layout.list_v1_9_16, null);
// case Adaptation.SCREEN_4_3:
// return View.inflate(getContext(), R.layout.list_t1_16_9, null);
// case Adaptation.SCREEN_16_9:
// return View.inflate(getContext(), R.layout.list_t1_16_9, null);
// default:
// return View.inflate(getContext(), R.layout.list_v1_9_16, null);
// }
// }
//
// /**
// * 设置标题
// * @param title
// */
// public void setTitleText(String title) {
// mTvTitle.setText(title);
// }
//
// /**
// * 设置条目
// * @param list
// */
// public void setListAdapter(List<SunmiListBean> list) {
// mListView.setAdapter(new SunmiListAdapter(getContext(), list));
// }
//
// /**
// * 条目点击
// * @param listener
// */
// public void onItemClick(AdapterView.OnItemClickListener listener) {
// mListView.setOnItemClickListener(listener);
// }
//
// }
//
// Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/list/SunmiListBean.java
// public class SunmiListBean {
// public String title;
// public String content;
//
//
// public SunmiListBean() {
// super();
// }
//
// public SunmiListBean(String title, String content) {
// this.title = title;
// this.content = content;
// }
// }
| import android.app.Activity;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
import sunmi.sunmiui.list.SunmiList;
import sunmi.sunmiui.list.SunmiListBean; | package sunmi.sunmidesign;
public class TitleListActivity extends Activity {
private SunmiList sunmiList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_title_list);
sunmiList = (SunmiList) this.findViewById(R.id.sunmi_list); | // Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/list/SunmiList.java
// public class SunmiList extends LinearLayout {
//
// private ListView mListView;
// private TextView mTvTitle;
//
// public SunmiList(Context context) {
// super(context);
// initView();
// }
//
// public SunmiList(Context context, AttributeSet attrs) {
// super(context, attrs);
// initView();
// }
//
// public SunmiList(Context context, AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// initView();
// }
//
// private void initView( ) {
// View view = getAdapterView();
// this.addView(view);
// mTvTitle = (TextView) view.findViewById(R.id.tv_title);
// mListView = (ListView) view.findViewById(R.id.list_view);
// }
//
// /**
// * 适配
// * @return
// */
// private View getAdapterView( ) {
// switch (Adaptation.proportion) {
// case Adaptation.SCREEN_9_16:
// return View.inflate(getContext(), R.layout.list_v1_9_16, null);
// case Adaptation.SCREEN_3_4:
// return View.inflate(getContext(), R.layout.list_v1_9_16, null);
// case Adaptation.SCREEN_4_3:
// return View.inflate(getContext(), R.layout.list_t1_16_9, null);
// case Adaptation.SCREEN_16_9:
// return View.inflate(getContext(), R.layout.list_t1_16_9, null);
// default:
// return View.inflate(getContext(), R.layout.list_v1_9_16, null);
// }
// }
//
// /**
// * 设置标题
// * @param title
// */
// public void setTitleText(String title) {
// mTvTitle.setText(title);
// }
//
// /**
// * 设置条目
// * @param list
// */
// public void setListAdapter(List<SunmiListBean> list) {
// mListView.setAdapter(new SunmiListAdapter(getContext(), list));
// }
//
// /**
// * 条目点击
// * @param listener
// */
// public void onItemClick(AdapterView.OnItemClickListener listener) {
// mListView.setOnItemClickListener(listener);
// }
//
// }
//
// Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/list/SunmiListBean.java
// public class SunmiListBean {
// public String title;
// public String content;
//
//
// public SunmiListBean() {
// super();
// }
//
// public SunmiListBean(String title, String content) {
// this.title = title;
// this.content = content;
// }
// }
// Path: SunmiDesign/app/src/main/java/sunmi/sunmidesign/TitleListActivity.java
import android.app.Activity;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
import sunmi.sunmiui.list.SunmiList;
import sunmi.sunmiui.list.SunmiListBean;
package sunmi.sunmidesign;
public class TitleListActivity extends Activity {
private SunmiList sunmiList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_title_list);
sunmiList = (SunmiList) this.findViewById(R.id.sunmi_list); | List<SunmiListBean> sunmiListBeanList = new ArrayList<>(); |
teisun/SunmiUI | SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/title/TitleHead.java | // Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/utils/Adaptation.java
// public class Adaptation {
//
// public static int screenHeight = 0;
// public static int screenWidth = 0;
// public static float screenDensity = 0;
// public static int densityDpi = 0;
// // public static int version = Integer.valueOf(android.os.Build.VERSION.SDK_INT);
//
// public static final int SCREEN_9_16 = 1; // 9:16
// public static final int SCREEN_3_4 = 2; // 3:4
// public static final int SCREEN_4_3 = 3; // 4:3
// public static final int SCREEN_16_9 = 4; // 16:9
// public static int proportion = SCREEN_9_16;
//
// // public static final float PROPORTION_9_16 = 0.56f; // 9:16
// // public static final float PROPORTION_3_4 = 0.75f; // 3:4
// // public static final float PROPORTION_4_3 = 1.33f; // 4:3
// // public static final float PROPORTION_16_9 = 1.77f; // 16:9
//
// public static final float AVERAGE1 = 0.655f; // (9:16+3:4)/2
// public static final float AVERAGE2 = 1.04f; // (3:4+4:3)/2
// public static final float AVERAGE3 = 1.55f; // (4:3+16:9)/2
//
// public static void init(Context context) {
// if (screenDensity == 0 || screenWidth == 0 || screenHeight == 0) {
// DisplayMetrics dm = new DisplayMetrics();
// WindowManager wm = (WindowManager) context
// .getSystemService(Context.WINDOW_SERVICE);
// wm.getDefaultDisplay().getMetrics(dm);
// Adaptation.screenDensity = dm.density;
// Adaptation.screenHeight = dm.heightPixels;
// Adaptation.screenWidth = dm.widthPixels;
// Adaptation.densityDpi = dm.densityDpi;
// }
//
// float proportionF = (float) screenWidth / (float) screenHeight;
//
// if (proportionF <= AVERAGE1) {
// proportion = SCREEN_9_16;
// } else if (proportionF <= AVERAGE2) {
// proportion = SCREEN_3_4;
// } else if (proportionF <= AVERAGE3) {
// proportion = SCREEN_4_3;
// } else if (proportionF > AVERAGE3) {
// proportion = SCREEN_16_9;
// }
//
// Log.i("SCREEN CONFIG", "screenHeight:" + screenHeight + ";screenWidth:"
// + screenWidth + ";screenDensity:" + screenDensity
// + ";densityDpi:" + densityDpi);
//
// }
//
// }
| import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import sunmi.sunmiui.R;
import sunmi.sunmiui.utils.Adaptation; | package sunmi.sunmiui.title;
/**
* 项目名称:SunmiDesign
* 类描述:一级标题(仅有文字无图标)
* 创建人:Abtswiath丶lxy
* 创建时间:2016/10/26 11:07
* 修改人:longx
* 修改时间:2016/10/26 11:07
* 修改备注:
*/
public class TitleHead extends FrameLayout{
private View mView;
private TextView title;
public TitleHead(Context context) {
super(context);
init();
}
public TitleHead(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public TitleHead(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init(){
mView = getView();
title = (TextView) mView.findViewById(R.id.txt);
}
private View getView(){ | // Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/utils/Adaptation.java
// public class Adaptation {
//
// public static int screenHeight = 0;
// public static int screenWidth = 0;
// public static float screenDensity = 0;
// public static int densityDpi = 0;
// // public static int version = Integer.valueOf(android.os.Build.VERSION.SDK_INT);
//
// public static final int SCREEN_9_16 = 1; // 9:16
// public static final int SCREEN_3_4 = 2; // 3:4
// public static final int SCREEN_4_3 = 3; // 4:3
// public static final int SCREEN_16_9 = 4; // 16:9
// public static int proportion = SCREEN_9_16;
//
// // public static final float PROPORTION_9_16 = 0.56f; // 9:16
// // public static final float PROPORTION_3_4 = 0.75f; // 3:4
// // public static final float PROPORTION_4_3 = 1.33f; // 4:3
// // public static final float PROPORTION_16_9 = 1.77f; // 16:9
//
// public static final float AVERAGE1 = 0.655f; // (9:16+3:4)/2
// public static final float AVERAGE2 = 1.04f; // (3:4+4:3)/2
// public static final float AVERAGE3 = 1.55f; // (4:3+16:9)/2
//
// public static void init(Context context) {
// if (screenDensity == 0 || screenWidth == 0 || screenHeight == 0) {
// DisplayMetrics dm = new DisplayMetrics();
// WindowManager wm = (WindowManager) context
// .getSystemService(Context.WINDOW_SERVICE);
// wm.getDefaultDisplay().getMetrics(dm);
// Adaptation.screenDensity = dm.density;
// Adaptation.screenHeight = dm.heightPixels;
// Adaptation.screenWidth = dm.widthPixels;
// Adaptation.densityDpi = dm.densityDpi;
// }
//
// float proportionF = (float) screenWidth / (float) screenHeight;
//
// if (proportionF <= AVERAGE1) {
// proportion = SCREEN_9_16;
// } else if (proportionF <= AVERAGE2) {
// proportion = SCREEN_3_4;
// } else if (proportionF <= AVERAGE3) {
// proportion = SCREEN_4_3;
// } else if (proportionF > AVERAGE3) {
// proportion = SCREEN_16_9;
// }
//
// Log.i("SCREEN CONFIG", "screenHeight:" + screenHeight + ";screenWidth:"
// + screenWidth + ";screenDensity:" + screenDensity
// + ";densityDpi:" + densityDpi);
//
// }
//
// }
// Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/title/TitleHead.java
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import sunmi.sunmiui.R;
import sunmi.sunmiui.utils.Adaptation;
package sunmi.sunmiui.title;
/**
* 项目名称:SunmiDesign
* 类描述:一级标题(仅有文字无图标)
* 创建人:Abtswiath丶lxy
* 创建时间:2016/10/26 11:07
* 修改人:longx
* 修改时间:2016/10/26 11:07
* 修改备注:
*/
public class TitleHead extends FrameLayout{
private View mView;
private TextView title;
public TitleHead(Context context) {
super(context);
init();
}
public TitleHead(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public TitleHead(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init(){
mView = getView();
title = (TextView) mView.findViewById(R.id.txt);
}
private View getView(){ | switch (Adaptation.proportion) { |
teisun/SunmiUI | SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/list/SunmiList.java | // Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/utils/Adaptation.java
// public class Adaptation {
//
// public static int screenHeight = 0;
// public static int screenWidth = 0;
// public static float screenDensity = 0;
// public static int densityDpi = 0;
// // public static int version = Integer.valueOf(android.os.Build.VERSION.SDK_INT);
//
// public static final int SCREEN_9_16 = 1; // 9:16
// public static final int SCREEN_3_4 = 2; // 3:4
// public static final int SCREEN_4_3 = 3; // 4:3
// public static final int SCREEN_16_9 = 4; // 16:9
// public static int proportion = SCREEN_9_16;
//
// // public static final float PROPORTION_9_16 = 0.56f; // 9:16
// // public static final float PROPORTION_3_4 = 0.75f; // 3:4
// // public static final float PROPORTION_4_3 = 1.33f; // 4:3
// // public static final float PROPORTION_16_9 = 1.77f; // 16:9
//
// public static final float AVERAGE1 = 0.655f; // (9:16+3:4)/2
// public static final float AVERAGE2 = 1.04f; // (3:4+4:3)/2
// public static final float AVERAGE3 = 1.55f; // (4:3+16:9)/2
//
// public static void init(Context context) {
// if (screenDensity == 0 || screenWidth == 0 || screenHeight == 0) {
// DisplayMetrics dm = new DisplayMetrics();
// WindowManager wm = (WindowManager) context
// .getSystemService(Context.WINDOW_SERVICE);
// wm.getDefaultDisplay().getMetrics(dm);
// Adaptation.screenDensity = dm.density;
// Adaptation.screenHeight = dm.heightPixels;
// Adaptation.screenWidth = dm.widthPixels;
// Adaptation.densityDpi = dm.densityDpi;
// }
//
// float proportionF = (float) screenWidth / (float) screenHeight;
//
// if (proportionF <= AVERAGE1) {
// proportion = SCREEN_9_16;
// } else if (proportionF <= AVERAGE2) {
// proportion = SCREEN_3_4;
// } else if (proportionF <= AVERAGE3) {
// proportion = SCREEN_4_3;
// } else if (proportionF > AVERAGE3) {
// proportion = SCREEN_16_9;
// }
//
// Log.i("SCREEN CONFIG", "screenHeight:" + screenHeight + ";screenWidth:"
// + screenWidth + ";screenDensity:" + screenDensity
// + ";densityDpi:" + densityDpi);
//
// }
//
// }
| import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import java.util.List;
import sunmi.sunmiui.R;
import sunmi.sunmiui.utils.Adaptation; | package sunmi.sunmiui.list;
/**
* Created by bps .
*/
public class SunmiList extends LinearLayout {
private ListView mListView;
private TextView mTvTitle;
public SunmiList(Context context) {
super(context);
initView();
}
public SunmiList(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public SunmiList(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
private void initView( ) {
View view = getAdapterView();
this.addView(view);
mTvTitle = (TextView) view.findViewById(R.id.tv_title);
mListView = (ListView) view.findViewById(R.id.list_view);
}
/**
* 适配
* @return
*/
private View getAdapterView( ) { | // Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/utils/Adaptation.java
// public class Adaptation {
//
// public static int screenHeight = 0;
// public static int screenWidth = 0;
// public static float screenDensity = 0;
// public static int densityDpi = 0;
// // public static int version = Integer.valueOf(android.os.Build.VERSION.SDK_INT);
//
// public static final int SCREEN_9_16 = 1; // 9:16
// public static final int SCREEN_3_4 = 2; // 3:4
// public static final int SCREEN_4_3 = 3; // 4:3
// public static final int SCREEN_16_9 = 4; // 16:9
// public static int proportion = SCREEN_9_16;
//
// // public static final float PROPORTION_9_16 = 0.56f; // 9:16
// // public static final float PROPORTION_3_4 = 0.75f; // 3:4
// // public static final float PROPORTION_4_3 = 1.33f; // 4:3
// // public static final float PROPORTION_16_9 = 1.77f; // 16:9
//
// public static final float AVERAGE1 = 0.655f; // (9:16+3:4)/2
// public static final float AVERAGE2 = 1.04f; // (3:4+4:3)/2
// public static final float AVERAGE3 = 1.55f; // (4:3+16:9)/2
//
// public static void init(Context context) {
// if (screenDensity == 0 || screenWidth == 0 || screenHeight == 0) {
// DisplayMetrics dm = new DisplayMetrics();
// WindowManager wm = (WindowManager) context
// .getSystemService(Context.WINDOW_SERVICE);
// wm.getDefaultDisplay().getMetrics(dm);
// Adaptation.screenDensity = dm.density;
// Adaptation.screenHeight = dm.heightPixels;
// Adaptation.screenWidth = dm.widthPixels;
// Adaptation.densityDpi = dm.densityDpi;
// }
//
// float proportionF = (float) screenWidth / (float) screenHeight;
//
// if (proportionF <= AVERAGE1) {
// proportion = SCREEN_9_16;
// } else if (proportionF <= AVERAGE2) {
// proportion = SCREEN_3_4;
// } else if (proportionF <= AVERAGE3) {
// proportion = SCREEN_4_3;
// } else if (proportionF > AVERAGE3) {
// proportion = SCREEN_16_9;
// }
//
// Log.i("SCREEN CONFIG", "screenHeight:" + screenHeight + ";screenWidth:"
// + screenWidth + ";screenDensity:" + screenDensity
// + ";densityDpi:" + densityDpi);
//
// }
//
// }
// Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/list/SunmiList.java
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import java.util.List;
import sunmi.sunmiui.R;
import sunmi.sunmiui.utils.Adaptation;
package sunmi.sunmiui.list;
/**
* Created by bps .
*/
public class SunmiList extends LinearLayout {
private ListView mListView;
private TextView mTvTitle;
public SunmiList(Context context) {
super(context);
initView();
}
public SunmiList(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public SunmiList(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
private void initView( ) {
View view = getAdapterView();
this.addView(view);
mTvTitle = (TextView) view.findViewById(R.id.tv_title);
mListView = (ListView) view.findViewById(R.id.list_view);
}
/**
* 适配
* @return
*/
private View getAdapterView( ) { | switch (Adaptation.proportion) { |
teisun/SunmiUI | SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/dialog/DialogCreater.java | // Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/utils/Adaptation.java
// public class Adaptation {
//
// public static int screenHeight = 0;
// public static int screenWidth = 0;
// public static float screenDensity = 0;
// public static int densityDpi = 0;
// // public static int version = Integer.valueOf(android.os.Build.VERSION.SDK_INT);
//
// public static final int SCREEN_9_16 = 1; // 9:16
// public static final int SCREEN_3_4 = 2; // 3:4
// public static final int SCREEN_4_3 = 3; // 4:3
// public static final int SCREEN_16_9 = 4; // 16:9
// public static int proportion = SCREEN_9_16;
//
// // public static final float PROPORTION_9_16 = 0.56f; // 9:16
// // public static final float PROPORTION_3_4 = 0.75f; // 3:4
// // public static final float PROPORTION_4_3 = 1.33f; // 4:3
// // public static final float PROPORTION_16_9 = 1.77f; // 16:9
//
// public static final float AVERAGE1 = 0.655f; // (9:16+3:4)/2
// public static final float AVERAGE2 = 1.04f; // (3:4+4:3)/2
// public static final float AVERAGE3 = 1.55f; // (4:3+16:9)/2
//
// public static void init(Context context) {
// if (screenDensity == 0 || screenWidth == 0 || screenHeight == 0) {
// DisplayMetrics dm = new DisplayMetrics();
// WindowManager wm = (WindowManager) context
// .getSystemService(Context.WINDOW_SERVICE);
// wm.getDefaultDisplay().getMetrics(dm);
// Adaptation.screenDensity = dm.density;
// Adaptation.screenHeight = dm.heightPixels;
// Adaptation.screenWidth = dm.widthPixels;
// Adaptation.densityDpi = dm.densityDpi;
// }
//
// float proportionF = (float) screenWidth / (float) screenHeight;
//
// if (proportionF <= AVERAGE1) {
// proportion = SCREEN_9_16;
// } else if (proportionF <= AVERAGE2) {
// proportion = SCREEN_3_4;
// } else if (proportionF <= AVERAGE3) {
// proportion = SCREEN_4_3;
// } else if (proportionF > AVERAGE3) {
// proportion = SCREEN_16_9;
// }
//
// Log.i("SCREEN CONFIG", "screenHeight:" + screenHeight + ";screenWidth:"
// + screenWidth + ";screenDensity:" + screenDensity
// + ";densityDpi:" + densityDpi);
//
// }
//
// }
| import android.app.Dialog;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import sunmi.sunmiui.R;
import sunmi.sunmiui.utils.Adaptation; | package sunmi.sunmiui.dialog;
/**
* 两个按钮,一个icon,一个title的dialog,如果第四个参数(textRight)传null,则为单按钮的弹框,第七个参数(right)也应传null
*
* @author tomcat
*/
public class DialogCreater {
public static HintDialog createHintDialog(Context context, int iconId, String textLeft, String textRight, String message, View.OnClickListener left, View.OnClickListener right,boolean isSystem) {
HintDialog dialogProxy = HintDialog.getInstance();
if (dialogProxy.hasDialog()) {
return dialogProxy;
}
Dialog dialog = setHintDialogContentView(context);
ImageView img = (ImageView) dialog.findViewById(R.id.img);
img.setImageResource(iconId);
TextView tvMsg = (TextView) dialog.findViewById(R.id.content);
TextView btnLeft = (TextView) dialog.findViewById(R.id.left);
TextView btnRight = (TextView) dialog.findViewById(R.id.right);
tvMsg.setText(message);
btnLeft.setText(textLeft);
btnLeft.setOnClickListener(left);
if(isSystem){
dialogProxy.setSystemDialog(dialog);
}else {
dialogProxy.setDialog(dialog);
}
View line = dialog.findViewById(R.id.line2);
if (TextUtils.isEmpty(textRight)) {
btnRight.setVisibility(View.GONE);
line.setVisibility(View.GONE); | // Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/utils/Adaptation.java
// public class Adaptation {
//
// public static int screenHeight = 0;
// public static int screenWidth = 0;
// public static float screenDensity = 0;
// public static int densityDpi = 0;
// // public static int version = Integer.valueOf(android.os.Build.VERSION.SDK_INT);
//
// public static final int SCREEN_9_16 = 1; // 9:16
// public static final int SCREEN_3_4 = 2; // 3:4
// public static final int SCREEN_4_3 = 3; // 4:3
// public static final int SCREEN_16_9 = 4; // 16:9
// public static int proportion = SCREEN_9_16;
//
// // public static final float PROPORTION_9_16 = 0.56f; // 9:16
// // public static final float PROPORTION_3_4 = 0.75f; // 3:4
// // public static final float PROPORTION_4_3 = 1.33f; // 4:3
// // public static final float PROPORTION_16_9 = 1.77f; // 16:9
//
// public static final float AVERAGE1 = 0.655f; // (9:16+3:4)/2
// public static final float AVERAGE2 = 1.04f; // (3:4+4:3)/2
// public static final float AVERAGE3 = 1.55f; // (4:3+16:9)/2
//
// public static void init(Context context) {
// if (screenDensity == 0 || screenWidth == 0 || screenHeight == 0) {
// DisplayMetrics dm = new DisplayMetrics();
// WindowManager wm = (WindowManager) context
// .getSystemService(Context.WINDOW_SERVICE);
// wm.getDefaultDisplay().getMetrics(dm);
// Adaptation.screenDensity = dm.density;
// Adaptation.screenHeight = dm.heightPixels;
// Adaptation.screenWidth = dm.widthPixels;
// Adaptation.densityDpi = dm.densityDpi;
// }
//
// float proportionF = (float) screenWidth / (float) screenHeight;
//
// if (proportionF <= AVERAGE1) {
// proportion = SCREEN_9_16;
// } else if (proportionF <= AVERAGE2) {
// proportion = SCREEN_3_4;
// } else if (proportionF <= AVERAGE3) {
// proportion = SCREEN_4_3;
// } else if (proportionF > AVERAGE3) {
// proportion = SCREEN_16_9;
// }
//
// Log.i("SCREEN CONFIG", "screenHeight:" + screenHeight + ";screenWidth:"
// + screenWidth + ";screenDensity:" + screenDensity
// + ";densityDpi:" + densityDpi);
//
// }
//
// }
// Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/dialog/DialogCreater.java
import android.app.Dialog;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import sunmi.sunmiui.R;
import sunmi.sunmiui.utils.Adaptation;
package sunmi.sunmiui.dialog;
/**
* 两个按钮,一个icon,一个title的dialog,如果第四个参数(textRight)传null,则为单按钮的弹框,第七个参数(right)也应传null
*
* @author tomcat
*/
public class DialogCreater {
public static HintDialog createHintDialog(Context context, int iconId, String textLeft, String textRight, String message, View.OnClickListener left, View.OnClickListener right,boolean isSystem) {
HintDialog dialogProxy = HintDialog.getInstance();
if (dialogProxy.hasDialog()) {
return dialogProxy;
}
Dialog dialog = setHintDialogContentView(context);
ImageView img = (ImageView) dialog.findViewById(R.id.img);
img.setImageResource(iconId);
TextView tvMsg = (TextView) dialog.findViewById(R.id.content);
TextView btnLeft = (TextView) dialog.findViewById(R.id.left);
TextView btnRight = (TextView) dialog.findViewById(R.id.right);
tvMsg.setText(message);
btnLeft.setText(textLeft);
btnLeft.setOnClickListener(left);
if(isSystem){
dialogProxy.setSystemDialog(dialog);
}else {
dialogProxy.setDialog(dialog);
}
View line = dialog.findViewById(R.id.line2);
if (TextUtils.isEmpty(textRight)) {
btnRight.setVisibility(View.GONE);
line.setVisibility(View.GONE); | if (Adaptation.proportion == Adaptation.SCREEN_9_16) { |
teisun/SunmiUI | SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/dialog/CodeDialog.java | // Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/utils/BitmapUtil.java
// public class BitmapUtil {
// public static Bitmap stringtoBitmap(String string) {
// //将字符串转换成Bitmap类型
// Bitmap bitmap = null;
// try {
// byte[] bitmapArray;
// bitmapArray = Base64.decode(string, Base64.DEFAULT);
// bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// return bitmap;
// }
//
//
// public static String bitmaptoString(Bitmap bitmap) {
// //将Bitmap转换成字符串
// String string = null;
// ByteArrayOutputStream bStream = new ByteArrayOutputStream();
// bitmap.compress(Bitmap.CompressFormat.PNG, 100, bStream);
// byte[] bytes = bStream.toByteArray();
// string = Base64.encodeToString(bytes, Base64.DEFAULT);
// return string;
// }
// }
| import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import sunmi.sunmiui.R;
import sunmi.sunmiui.utils.BitmapUtil; | }
return instance;
}
@Override
protected void init() {
title = (TextView) dialog.findViewById(R.id.txt);
code = (ImageView) dialog.findViewById(R.id.code);
editText = (EditText) dialog.findViewById(R.id.editText);
clear = (ImageView) dialog.findViewById(R.id.clear);
load = (ImageView) dialog.findViewById(R.id.load);
error = (TextView) dialog.findViewById(R.id.txt_error);
clear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
editText.setText("");
}
});
error.setVisibility(View.GONE);
load.setVisibility(View.GONE);
clear.setVisibility(View.GONE);
}
public void setData(String titleString, String imgBase64, final CodeInputSuccess listener, View.OnClickListener incodeOnClickListener) {
isReq = false;
error.setVisibility(View.GONE);
load.clearAnimation();
load.setVisibility(View.GONE);
clear.setVisibility(View.GONE);
title.setText(titleString); | // Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/utils/BitmapUtil.java
// public class BitmapUtil {
// public static Bitmap stringtoBitmap(String string) {
// //将字符串转换成Bitmap类型
// Bitmap bitmap = null;
// try {
// byte[] bitmapArray;
// bitmapArray = Base64.decode(string, Base64.DEFAULT);
// bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// return bitmap;
// }
//
//
// public static String bitmaptoString(Bitmap bitmap) {
// //将Bitmap转换成字符串
// String string = null;
// ByteArrayOutputStream bStream = new ByteArrayOutputStream();
// bitmap.compress(Bitmap.CompressFormat.PNG, 100, bStream);
// byte[] bytes = bStream.toByteArray();
// string = Base64.encodeToString(bytes, Base64.DEFAULT);
// return string;
// }
// }
// Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/dialog/CodeDialog.java
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import sunmi.sunmiui.R;
import sunmi.sunmiui.utils.BitmapUtil;
}
return instance;
}
@Override
protected void init() {
title = (TextView) dialog.findViewById(R.id.txt);
code = (ImageView) dialog.findViewById(R.id.code);
editText = (EditText) dialog.findViewById(R.id.editText);
clear = (ImageView) dialog.findViewById(R.id.clear);
load = (ImageView) dialog.findViewById(R.id.load);
error = (TextView) dialog.findViewById(R.id.txt_error);
clear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
editText.setText("");
}
});
error.setVisibility(View.GONE);
load.setVisibility(View.GONE);
clear.setVisibility(View.GONE);
}
public void setData(String titleString, String imgBase64, final CodeInputSuccess listener, View.OnClickListener incodeOnClickListener) {
isReq = false;
error.setVisibility(View.GONE);
load.clearAnimation();
load.setVisibility(View.GONE);
clear.setVisibility(View.GONE);
title.setText(titleString); | code.setImageBitmap(BitmapUtil.stringtoBitmap(imgBase64)); |
teisun/SunmiUI | SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/viewgraoup/TabViewPager.java | // Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/utils/Adaptation.java
// public class Adaptation {
//
// public static int screenHeight = 0;
// public static int screenWidth = 0;
// public static float screenDensity = 0;
// public static int densityDpi = 0;
// // public static int version = Integer.valueOf(android.os.Build.VERSION.SDK_INT);
//
// public static final int SCREEN_9_16 = 1; // 9:16
// public static final int SCREEN_3_4 = 2; // 3:4
// public static final int SCREEN_4_3 = 3; // 4:3
// public static final int SCREEN_16_9 = 4; // 16:9
// public static int proportion = SCREEN_9_16;
//
// // public static final float PROPORTION_9_16 = 0.56f; // 9:16
// // public static final float PROPORTION_3_4 = 0.75f; // 3:4
// // public static final float PROPORTION_4_3 = 1.33f; // 4:3
// // public static final float PROPORTION_16_9 = 1.77f; // 16:9
//
// public static final float AVERAGE1 = 0.655f; // (9:16+3:4)/2
// public static final float AVERAGE2 = 1.04f; // (3:4+4:3)/2
// public static final float AVERAGE3 = 1.55f; // (4:3+16:9)/2
//
// public static void init(Context context) {
// if (screenDensity == 0 || screenWidth == 0 || screenHeight == 0) {
// DisplayMetrics dm = new DisplayMetrics();
// WindowManager wm = (WindowManager) context
// .getSystemService(Context.WINDOW_SERVICE);
// wm.getDefaultDisplay().getMetrics(dm);
// Adaptation.screenDensity = dm.density;
// Adaptation.screenHeight = dm.heightPixels;
// Adaptation.screenWidth = dm.widthPixels;
// Adaptation.densityDpi = dm.densityDpi;
// }
//
// float proportionF = (float) screenWidth / (float) screenHeight;
//
// if (proportionF <= AVERAGE1) {
// proportion = SCREEN_9_16;
// } else if (proportionF <= AVERAGE2) {
// proportion = SCREEN_3_4;
// } else if (proportionF <= AVERAGE3) {
// proportion = SCREEN_4_3;
// } else if (proportionF > AVERAGE3) {
// proportion = SCREEN_16_9;
// }
//
// Log.i("SCREEN CONFIG", "screenHeight:" + screenHeight + ";screenWidth:"
// + screenWidth + ";screenDensity:" + screenDensity
// + ";densityDpi:" + densityDpi);
//
// }
//
// }
| import android.content.Context;
import android.graphics.Color;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import java.util.ArrayList;
import java.util.List;
import sunmi.sunmiui.R;
import sunmi.sunmiui.utils.Adaptation; | }
public void setTextColor(int textColor){
tab.setTextColor(textColor);
}
public void setData(List<String> tabStringList, List<View> viewList) throws Exception{
String error = null;
if(viewList==null||tabStringList==null){
error ="参数都不能为null";
}
if((viewList!=null&&viewList.size()==0)||(tabStringList!=null&&tabStringList.size()==0)){
error ="参数的size必须大于0";
}
if(viewList!=null&&tabStringList!=null &&viewList.size()==0 &&tabStringList.size()==0 &&viewList.size()!=tabStringList.size()){
error ="参数的size必须相等";
}
if(!TextUtils.isEmpty(error)) {
try {
throw new Exception(error);
} catch (Exception e) {
e.printStackTrace();
}
return;
}
viewPager.setAdapter(new ViewPagerAdapter(tabStringList, viewList));
tab.setViewPager(viewPager);
}
private View adapterView() { | // Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/utils/Adaptation.java
// public class Adaptation {
//
// public static int screenHeight = 0;
// public static int screenWidth = 0;
// public static float screenDensity = 0;
// public static int densityDpi = 0;
// // public static int version = Integer.valueOf(android.os.Build.VERSION.SDK_INT);
//
// public static final int SCREEN_9_16 = 1; // 9:16
// public static final int SCREEN_3_4 = 2; // 3:4
// public static final int SCREEN_4_3 = 3; // 4:3
// public static final int SCREEN_16_9 = 4; // 16:9
// public static int proportion = SCREEN_9_16;
//
// // public static final float PROPORTION_9_16 = 0.56f; // 9:16
// // public static final float PROPORTION_3_4 = 0.75f; // 3:4
// // public static final float PROPORTION_4_3 = 1.33f; // 4:3
// // public static final float PROPORTION_16_9 = 1.77f; // 16:9
//
// public static final float AVERAGE1 = 0.655f; // (9:16+3:4)/2
// public static final float AVERAGE2 = 1.04f; // (3:4+4:3)/2
// public static final float AVERAGE3 = 1.55f; // (4:3+16:9)/2
//
// public static void init(Context context) {
// if (screenDensity == 0 || screenWidth == 0 || screenHeight == 0) {
// DisplayMetrics dm = new DisplayMetrics();
// WindowManager wm = (WindowManager) context
// .getSystemService(Context.WINDOW_SERVICE);
// wm.getDefaultDisplay().getMetrics(dm);
// Adaptation.screenDensity = dm.density;
// Adaptation.screenHeight = dm.heightPixels;
// Adaptation.screenWidth = dm.widthPixels;
// Adaptation.densityDpi = dm.densityDpi;
// }
//
// float proportionF = (float) screenWidth / (float) screenHeight;
//
// if (proportionF <= AVERAGE1) {
// proportion = SCREEN_9_16;
// } else if (proportionF <= AVERAGE2) {
// proportion = SCREEN_3_4;
// } else if (proportionF <= AVERAGE3) {
// proportion = SCREEN_4_3;
// } else if (proportionF > AVERAGE3) {
// proportion = SCREEN_16_9;
// }
//
// Log.i("SCREEN CONFIG", "screenHeight:" + screenHeight + ";screenWidth:"
// + screenWidth + ";screenDensity:" + screenDensity
// + ";densityDpi:" + densityDpi);
//
// }
//
// }
// Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/viewgraoup/TabViewPager.java
import android.content.Context;
import android.graphics.Color;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import java.util.ArrayList;
import java.util.List;
import sunmi.sunmiui.R;
import sunmi.sunmiui.utils.Adaptation;
}
public void setTextColor(int textColor){
tab.setTextColor(textColor);
}
public void setData(List<String> tabStringList, List<View> viewList) throws Exception{
String error = null;
if(viewList==null||tabStringList==null){
error ="参数都不能为null";
}
if((viewList!=null&&viewList.size()==0)||(tabStringList!=null&&tabStringList.size()==0)){
error ="参数的size必须大于0";
}
if(viewList!=null&&tabStringList!=null &&viewList.size()==0 &&tabStringList.size()==0 &&viewList.size()!=tabStringList.size()){
error ="参数的size必须相等";
}
if(!TextUtils.isEmpty(error)) {
try {
throw new Exception(error);
} catch (Exception e) {
e.printStackTrace();
}
return;
}
viewPager.setAdapter(new ViewPagerAdapter(tabStringList, viewList));
tab.setViewPager(viewPager);
}
private View adapterView() { | switch (Adaptation.proportion) { |
teisun/SunmiUI | SunmiDesign/app/src/main/java/sunmi/sunmidesign/transitions/CustomTransition.java | // Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/utils/LogUtil.java
// public class LogUtil {
//
// public static final int VERBOSE = 1;
// public static final int DEBUG = 2;
// public static final int INFO = 3;
// public static final int WARN = 4;
// public static final int ERROR = 5;
// public static final int NOTHING = 6;
// public static int LEVEL = VERBOSE;
//
// public static void setLevel(int Level) {
// LEVEL = Level;
// }
//
// public static void v(String TAG, String msg) {
// if (LEVEL <= VERBOSE && !TextUtils.isEmpty(msg)) {
// MyLog(VERBOSE, TAG, msg);
// }
// }
//
// public static void d(String TAG, String msg) {
// if (LEVEL <= DEBUG && !TextUtils.isEmpty(msg)) {
// MyLog(DEBUG, TAG, msg);
// }
// }
//
// public static void i(String TAG, String msg) {
// if (LEVEL <= INFO && !TextUtils.isEmpty(msg)) {
// MyLog(INFO, TAG, msg);
// }
// }
//
// public static void w(String TAG, String msg) {
// if (LEVEL <= WARN && !TextUtils.isEmpty(msg)) {
// MyLog(WARN, TAG, msg);
// }
// }
//
// public static void e(String TAG, String msg) {
// if (LEVEL <= ERROR && !TextUtils.isEmpty(msg)) {
// MyLog(ERROR, TAG, msg);
// }
// }
//
// private static void MyLog(int type, String TAG, String msg) {
// StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
//
// int index = 4;
// String className = stackTrace[index].getFileName();
// String methodName = stackTrace[index].getMethodName();
// int lineNumber = stackTrace[index].getLineNumber();
//
// methodName = methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
//
// StringBuilder stringBuilder = new StringBuilder();
// stringBuilder.append("[ (").append(className).append(":").append(lineNumber).append(")#").append(methodName).append(" ] ");
// stringBuilder.append(msg);
// String logStr = stringBuilder.toString();
// switch (type) {
// case VERBOSE:
// Log.v(TAG, logStr);
// break;
// case DEBUG:
// Log.d(TAG, logStr);
// break;
// case INFO:
// Log.i(TAG, logStr);
// break;
// case WARN:
// Log.w(TAG, logStr);
// break;
// case ERROR:
// Log.e(TAG, logStr);
// break;
// default:
// break;
// }
//
// }
//
// }
| import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.graphics.Rect;
import android.support.v4.view.ViewCompat;
import android.transition.Transition;
import android.transition.TransitionValues;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewGroup;
import sunmi.sunmidesign.R;
import sunmi.sunmiui.utils.LogUtil; | package sunmi.sunmidesign.transitions;
/**
* Created by KenMa on 2016/12/5.
*/
public class CustomTransition extends Transition {
private static final String TAG = "CustomTransition";
//可参考 http://blog.csdn.net/qibin0506/article/details/53248597
private final String RECT = "rect";
@Override
public void captureStartValues(TransitionValues transitionValues) {
View view = transitionValues.view;
Rect rect = new Rect();
view.getHitRect(rect);
transitionValues.values.put(RECT, rect);
}
@Override
public void captureEndValues(TransitionValues transitionValues) {
View view = transitionValues.view;
Rect rect = new Rect();
view.getHitRect(rect);
transitionValues.values.put(RECT, rect);
}
@Override
public Animator createAnimator(ViewGroup sceneRoot, TransitionValues startValues, TransitionValues endValues) {
if (startValues == null || endValues == null) return null;
final View startView = startValues.view;
final View endView = endValues.view;
final Rect startRect = (Rect) startValues.values.get(RECT);
final Rect endRect = (Rect) endValues.values.get(RECT);
| // Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/utils/LogUtil.java
// public class LogUtil {
//
// public static final int VERBOSE = 1;
// public static final int DEBUG = 2;
// public static final int INFO = 3;
// public static final int WARN = 4;
// public static final int ERROR = 5;
// public static final int NOTHING = 6;
// public static int LEVEL = VERBOSE;
//
// public static void setLevel(int Level) {
// LEVEL = Level;
// }
//
// public static void v(String TAG, String msg) {
// if (LEVEL <= VERBOSE && !TextUtils.isEmpty(msg)) {
// MyLog(VERBOSE, TAG, msg);
// }
// }
//
// public static void d(String TAG, String msg) {
// if (LEVEL <= DEBUG && !TextUtils.isEmpty(msg)) {
// MyLog(DEBUG, TAG, msg);
// }
// }
//
// public static void i(String TAG, String msg) {
// if (LEVEL <= INFO && !TextUtils.isEmpty(msg)) {
// MyLog(INFO, TAG, msg);
// }
// }
//
// public static void w(String TAG, String msg) {
// if (LEVEL <= WARN && !TextUtils.isEmpty(msg)) {
// MyLog(WARN, TAG, msg);
// }
// }
//
// public static void e(String TAG, String msg) {
// if (LEVEL <= ERROR && !TextUtils.isEmpty(msg)) {
// MyLog(ERROR, TAG, msg);
// }
// }
//
// private static void MyLog(int type, String TAG, String msg) {
// StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
//
// int index = 4;
// String className = stackTrace[index].getFileName();
// String methodName = stackTrace[index].getMethodName();
// int lineNumber = stackTrace[index].getLineNumber();
//
// methodName = methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
//
// StringBuilder stringBuilder = new StringBuilder();
// stringBuilder.append("[ (").append(className).append(":").append(lineNumber).append(")#").append(methodName).append(" ] ");
// stringBuilder.append(msg);
// String logStr = stringBuilder.toString();
// switch (type) {
// case VERBOSE:
// Log.v(TAG, logStr);
// break;
// case DEBUG:
// Log.d(TAG, logStr);
// break;
// case INFO:
// Log.i(TAG, logStr);
// break;
// case WARN:
// Log.w(TAG, logStr);
// break;
// case ERROR:
// Log.e(TAG, logStr);
// break;
// default:
// break;
// }
//
// }
//
// }
// Path: SunmiDesign/app/src/main/java/sunmi/sunmidesign/transitions/CustomTransition.java
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.graphics.Rect;
import android.support.v4.view.ViewCompat;
import android.transition.Transition;
import android.transition.TransitionValues;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewGroup;
import sunmi.sunmidesign.R;
import sunmi.sunmiui.utils.LogUtil;
package sunmi.sunmidesign.transitions;
/**
* Created by KenMa on 2016/12/5.
*/
public class CustomTransition extends Transition {
private static final String TAG = "CustomTransition";
//可参考 http://blog.csdn.net/qibin0506/article/details/53248597
private final String RECT = "rect";
@Override
public void captureStartValues(TransitionValues transitionValues) {
View view = transitionValues.view;
Rect rect = new Rect();
view.getHitRect(rect);
transitionValues.values.put(RECT, rect);
}
@Override
public void captureEndValues(TransitionValues transitionValues) {
View view = transitionValues.view;
Rect rect = new Rect();
view.getHitRect(rect);
transitionValues.values.put(RECT, rect);
}
@Override
public Animator createAnimator(ViewGroup sceneRoot, TransitionValues startValues, TransitionValues endValues) {
if (startValues == null || endValues == null) return null;
final View startView = startValues.view;
final View endView = endValues.view;
final Rect startRect = (Rect) startValues.values.get(RECT);
final Rect endRect = (Rect) endValues.values.get(RECT);
| LogUtil.d(TAG,startRect.toString()); |
teisun/SunmiUI | SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/view/LoadView.java | // Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/utils/Adaptation.java
// public class Adaptation {
//
// public static int screenHeight = 0;
// public static int screenWidth = 0;
// public static float screenDensity = 0;
// public static int densityDpi = 0;
// // public static int version = Integer.valueOf(android.os.Build.VERSION.SDK_INT);
//
// public static final int SCREEN_9_16 = 1; // 9:16
// public static final int SCREEN_3_4 = 2; // 3:4
// public static final int SCREEN_4_3 = 3; // 4:3
// public static final int SCREEN_16_9 = 4; // 16:9
// public static int proportion = SCREEN_9_16;
//
// // public static final float PROPORTION_9_16 = 0.56f; // 9:16
// // public static final float PROPORTION_3_4 = 0.75f; // 3:4
// // public static final float PROPORTION_4_3 = 1.33f; // 4:3
// // public static final float PROPORTION_16_9 = 1.77f; // 16:9
//
// public static final float AVERAGE1 = 0.655f; // (9:16+3:4)/2
// public static final float AVERAGE2 = 1.04f; // (3:4+4:3)/2
// public static final float AVERAGE3 = 1.55f; // (4:3+16:9)/2
//
// public static void init(Context context) {
// if (screenDensity == 0 || screenWidth == 0 || screenHeight == 0) {
// DisplayMetrics dm = new DisplayMetrics();
// WindowManager wm = (WindowManager) context
// .getSystemService(Context.WINDOW_SERVICE);
// wm.getDefaultDisplay().getMetrics(dm);
// Adaptation.screenDensity = dm.density;
// Adaptation.screenHeight = dm.heightPixels;
// Adaptation.screenWidth = dm.widthPixels;
// Adaptation.densityDpi = dm.densityDpi;
// }
//
// float proportionF = (float) screenWidth / (float) screenHeight;
//
// if (proportionF <= AVERAGE1) {
// proportion = SCREEN_9_16;
// } else if (proportionF <= AVERAGE2) {
// proportion = SCREEN_3_4;
// } else if (proportionF <= AVERAGE3) {
// proportion = SCREEN_4_3;
// } else if (proportionF > AVERAGE3) {
// proportion = SCREEN_16_9;
// }
//
// Log.i("SCREEN CONFIG", "screenHeight:" + screenHeight + ";screenWidth:"
// + screenWidth + ";screenDensity:" + screenDensity
// + ";densityDpi:" + densityDpi);
//
// }
//
// }
| import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import sunmi.sunmiui.R;
import sunmi.sunmiui.utils.Adaptation; | package sunmi.sunmiui.view;
/**
* 项目名称:SunmiDesign
* 类描述:
* 创建人:Abtswiath丶lxy
* 创建时间:2016/10/26 17:58
* 修改人:longx
* 修改时间:2016/10/26 17:58
* 修改备注:
*/
public class LoadView extends FrameLayout {
private View mView;
private TextView mText;
private ImageView img;
public LoadView(Context context) {
super(context);
init();
}
public LoadView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public LoadView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init(){
mView = getView();
mText = (TextView)mView.findViewById(R.id.txt);
img = (ImageView)mView.findViewById(R.id.img);
Animation operatingAnim = AnimationUtils.loadAnimation(getContext(), R.anim.loading_anim);
LinearInterpolator lin = new LinearInterpolator();
operatingAnim.setInterpolator(lin);
img.setAnimation(operatingAnim);
img.startAnimation(operatingAnim);
}
private View getView(){ | // Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/utils/Adaptation.java
// public class Adaptation {
//
// public static int screenHeight = 0;
// public static int screenWidth = 0;
// public static float screenDensity = 0;
// public static int densityDpi = 0;
// // public static int version = Integer.valueOf(android.os.Build.VERSION.SDK_INT);
//
// public static final int SCREEN_9_16 = 1; // 9:16
// public static final int SCREEN_3_4 = 2; // 3:4
// public static final int SCREEN_4_3 = 3; // 4:3
// public static final int SCREEN_16_9 = 4; // 16:9
// public static int proportion = SCREEN_9_16;
//
// // public static final float PROPORTION_9_16 = 0.56f; // 9:16
// // public static final float PROPORTION_3_4 = 0.75f; // 3:4
// // public static final float PROPORTION_4_3 = 1.33f; // 4:3
// // public static final float PROPORTION_16_9 = 1.77f; // 16:9
//
// public static final float AVERAGE1 = 0.655f; // (9:16+3:4)/2
// public static final float AVERAGE2 = 1.04f; // (3:4+4:3)/2
// public static final float AVERAGE3 = 1.55f; // (4:3+16:9)/2
//
// public static void init(Context context) {
// if (screenDensity == 0 || screenWidth == 0 || screenHeight == 0) {
// DisplayMetrics dm = new DisplayMetrics();
// WindowManager wm = (WindowManager) context
// .getSystemService(Context.WINDOW_SERVICE);
// wm.getDefaultDisplay().getMetrics(dm);
// Adaptation.screenDensity = dm.density;
// Adaptation.screenHeight = dm.heightPixels;
// Adaptation.screenWidth = dm.widthPixels;
// Adaptation.densityDpi = dm.densityDpi;
// }
//
// float proportionF = (float) screenWidth / (float) screenHeight;
//
// if (proportionF <= AVERAGE1) {
// proportion = SCREEN_9_16;
// } else if (proportionF <= AVERAGE2) {
// proportion = SCREEN_3_4;
// } else if (proportionF <= AVERAGE3) {
// proportion = SCREEN_4_3;
// } else if (proportionF > AVERAGE3) {
// proportion = SCREEN_16_9;
// }
//
// Log.i("SCREEN CONFIG", "screenHeight:" + screenHeight + ";screenWidth:"
// + screenWidth + ";screenDensity:" + screenDensity
// + ";densityDpi:" + densityDpi);
//
// }
//
// }
// Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/view/LoadView.java
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import sunmi.sunmiui.R;
import sunmi.sunmiui.utils.Adaptation;
package sunmi.sunmiui.view;
/**
* 项目名称:SunmiDesign
* 类描述:
* 创建人:Abtswiath丶lxy
* 创建时间:2016/10/26 17:58
* 修改人:longx
* 修改时间:2016/10/26 17:58
* 修改备注:
*/
public class LoadView extends FrameLayout {
private View mView;
private TextView mText;
private ImageView img;
public LoadView(Context context) {
super(context);
init();
}
public LoadView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public LoadView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init(){
mView = getView();
mText = (TextView)mView.findViewById(R.id.txt);
img = (ImageView)mView.findViewById(R.id.img);
Animation operatingAnim = AnimationUtils.loadAnimation(getContext(), R.anim.loading_anim);
LinearInterpolator lin = new LinearInterpolator();
operatingAnim.setInterpolator(lin);
img.setAnimation(operatingAnim);
img.startAnimation(operatingAnim);
}
private View getView(){ | switch (Adaptation.proportion) { |
teisun/SunmiUI | SunmiDesign/app/src/main/java/sunmi/sunmidesign/ErrorActivity.java | // Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/view/ErrorView.java
// public class ErrorView extends FrameLayout {
//
// private View mView;
// private ImageView imgError;
// private TextView textMsg, textT;
//
// public ErrorView(Context context) {
// super(context);
// init();
// }
//
// public ErrorView(Context context, AttributeSet attrs) {
// super(context, attrs);
// init();
// }
//
// public ErrorView(Context context, AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// init();
// }
//
// private void init() {
// mView = View.inflate(getContext(), R.layout.view_error, this);
// imgError = (ImageView) mView.findViewById(R.id.img_error);
// textMsg = (TextView) mView.findViewById(R.id.text_error);
// textT = (TextView) mView.findViewById(R.id.text_on);
// }
//
// public void setErrorTypr(ErroType erroType) {
// switch (erroType) {
// case NET_ERROR:
// set(R.drawable.img_no_net,getContext().getString(R.string.net_error),getContext().getString(R.string.click_screen_try));
// break;
// case SERVER_ERROR:
// set(R.drawable.img_server_error,getContext().getString(R.string.server_error),getContext().getString(R.string.click_screen_try));
// break;
// case NO_ORDER:
// set(R.drawable.img_no_order,getContext().getString(R.string.no_order),"");
// break;
// }
// }
//
// private void set(int drawable,CharSequence errorMsg,CharSequence prompt){
// imgError.setImageResource(drawable);
// textMsg.setText(errorMsg);
// textT.setText(prompt);
// }
//
// public void setMsg(CharSequence errorMsg){
// textMsg.setText(errorMsg);
// }
//
// public void setImgError(int drawable){
// imgError.setImageResource(drawable);
// }
//
// public void setClickText(CharSequence prompt){
// textT.setText(prompt);
// }
//
// public enum ErroType {
// NET_ERROR, SERVER_ERROR, NO_ORDER;
// }
//
// }
//
// Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/view/LoadView.java
// public class LoadView extends FrameLayout {
//
// private View mView;
// private TextView mText;
// private ImageView img;
//
// public LoadView(Context context) {
// super(context);
// init();
// }
//
// public LoadView(Context context, AttributeSet attrs) {
// super(context, attrs);
// init();
// }
//
// public LoadView(Context context, AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// init();
// }
//
// private void init(){
// mView = getView();
// mText = (TextView)mView.findViewById(R.id.txt);
// img = (ImageView)mView.findViewById(R.id.img);
// Animation operatingAnim = AnimationUtils.loadAnimation(getContext(), R.anim.loading_anim);
// LinearInterpolator lin = new LinearInterpolator();
// operatingAnim.setInterpolator(lin);
// img.setAnimation(operatingAnim);
// img.startAnimation(operatingAnim);
// }
//
// private View getView(){
// switch (Adaptation.proportion) {
// case Adaptation.SCREEN_9_16:
// return View.inflate(getContext(), R.layout.view_load_9_16, this);
// case Adaptation.SCREEN_3_4:
// return View.inflate(getContext(), R.layout.view_load_9_16, this);
// case Adaptation.SCREEN_4_3:
// return View.inflate(getContext(), R.layout.view_load_16_9, this);
// case Adaptation.SCREEN_16_9:
// return View.inflate(getContext(), R.layout.view_load_16_9, this);
// default:
// return View.inflate(getContext(), R.layout.view_load_9_16, this);
// }
// }
//
// public void setText(CharSequence text){
// mText.setText(text);
// }
// }
| import android.app.Activity;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.view.View;
import sunmi.sunmiui.view.ErrorView;
import sunmi.sunmiui.view.LoadView; | package sunmi.sunmidesign;
/**
* 项目名称:SunmiDesign
* 类描述:
* 创建人:Abtswiath丶lxy
* 创建时间:2016/10/26 17:10
* 修改人:longx
* 修改时间:2016/10/26 17:10
* 修改备注:
*/
public class ErrorActivity extends Activity {
private ErrorView errorView; | // Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/view/ErrorView.java
// public class ErrorView extends FrameLayout {
//
// private View mView;
// private ImageView imgError;
// private TextView textMsg, textT;
//
// public ErrorView(Context context) {
// super(context);
// init();
// }
//
// public ErrorView(Context context, AttributeSet attrs) {
// super(context, attrs);
// init();
// }
//
// public ErrorView(Context context, AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// init();
// }
//
// private void init() {
// mView = View.inflate(getContext(), R.layout.view_error, this);
// imgError = (ImageView) mView.findViewById(R.id.img_error);
// textMsg = (TextView) mView.findViewById(R.id.text_error);
// textT = (TextView) mView.findViewById(R.id.text_on);
// }
//
// public void setErrorTypr(ErroType erroType) {
// switch (erroType) {
// case NET_ERROR:
// set(R.drawable.img_no_net,getContext().getString(R.string.net_error),getContext().getString(R.string.click_screen_try));
// break;
// case SERVER_ERROR:
// set(R.drawable.img_server_error,getContext().getString(R.string.server_error),getContext().getString(R.string.click_screen_try));
// break;
// case NO_ORDER:
// set(R.drawable.img_no_order,getContext().getString(R.string.no_order),"");
// break;
// }
// }
//
// private void set(int drawable,CharSequence errorMsg,CharSequence prompt){
// imgError.setImageResource(drawable);
// textMsg.setText(errorMsg);
// textT.setText(prompt);
// }
//
// public void setMsg(CharSequence errorMsg){
// textMsg.setText(errorMsg);
// }
//
// public void setImgError(int drawable){
// imgError.setImageResource(drawable);
// }
//
// public void setClickText(CharSequence prompt){
// textT.setText(prompt);
// }
//
// public enum ErroType {
// NET_ERROR, SERVER_ERROR, NO_ORDER;
// }
//
// }
//
// Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/view/LoadView.java
// public class LoadView extends FrameLayout {
//
// private View mView;
// private TextView mText;
// private ImageView img;
//
// public LoadView(Context context) {
// super(context);
// init();
// }
//
// public LoadView(Context context, AttributeSet attrs) {
// super(context, attrs);
// init();
// }
//
// public LoadView(Context context, AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// init();
// }
//
// private void init(){
// mView = getView();
// mText = (TextView)mView.findViewById(R.id.txt);
// img = (ImageView)mView.findViewById(R.id.img);
// Animation operatingAnim = AnimationUtils.loadAnimation(getContext(), R.anim.loading_anim);
// LinearInterpolator lin = new LinearInterpolator();
// operatingAnim.setInterpolator(lin);
// img.setAnimation(operatingAnim);
// img.startAnimation(operatingAnim);
// }
//
// private View getView(){
// switch (Adaptation.proportion) {
// case Adaptation.SCREEN_9_16:
// return View.inflate(getContext(), R.layout.view_load_9_16, this);
// case Adaptation.SCREEN_3_4:
// return View.inflate(getContext(), R.layout.view_load_9_16, this);
// case Adaptation.SCREEN_4_3:
// return View.inflate(getContext(), R.layout.view_load_16_9, this);
// case Adaptation.SCREEN_16_9:
// return View.inflate(getContext(), R.layout.view_load_16_9, this);
// default:
// return View.inflate(getContext(), R.layout.view_load_9_16, this);
// }
// }
//
// public void setText(CharSequence text){
// mText.setText(text);
// }
// }
// Path: SunmiDesign/app/src/main/java/sunmi/sunmidesign/ErrorActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.view.View;
import sunmi.sunmiui.view.ErrorView;
import sunmi.sunmiui.view.LoadView;
package sunmi.sunmidesign;
/**
* 项目名称:SunmiDesign
* 类描述:
* 创建人:Abtswiath丶lxy
* 创建时间:2016/10/26 17:10
* 修改人:longx
* 修改时间:2016/10/26 17:10
* 修改备注:
*/
public class ErrorActivity extends Activity {
private ErrorView errorView; | private LoadView loadView; |
teisun/SunmiUI | SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/list/SunmiListAdapter.java | // Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/utils/Adaptation.java
// public class Adaptation {
//
// public static int screenHeight = 0;
// public static int screenWidth = 0;
// public static float screenDensity = 0;
// public static int densityDpi = 0;
// // public static int version = Integer.valueOf(android.os.Build.VERSION.SDK_INT);
//
// public static final int SCREEN_9_16 = 1; // 9:16
// public static final int SCREEN_3_4 = 2; // 3:4
// public static final int SCREEN_4_3 = 3; // 4:3
// public static final int SCREEN_16_9 = 4; // 16:9
// public static int proportion = SCREEN_9_16;
//
// // public static final float PROPORTION_9_16 = 0.56f; // 9:16
// // public static final float PROPORTION_3_4 = 0.75f; // 3:4
// // public static final float PROPORTION_4_3 = 1.33f; // 4:3
// // public static final float PROPORTION_16_9 = 1.77f; // 16:9
//
// public static final float AVERAGE1 = 0.655f; // (9:16+3:4)/2
// public static final float AVERAGE2 = 1.04f; // (3:4+4:3)/2
// public static final float AVERAGE3 = 1.55f; // (4:3+16:9)/2
//
// public static void init(Context context) {
// if (screenDensity == 0 || screenWidth == 0 || screenHeight == 0) {
// DisplayMetrics dm = new DisplayMetrics();
// WindowManager wm = (WindowManager) context
// .getSystemService(Context.WINDOW_SERVICE);
// wm.getDefaultDisplay().getMetrics(dm);
// Adaptation.screenDensity = dm.density;
// Adaptation.screenHeight = dm.heightPixels;
// Adaptation.screenWidth = dm.widthPixels;
// Adaptation.densityDpi = dm.densityDpi;
// }
//
// float proportionF = (float) screenWidth / (float) screenHeight;
//
// if (proportionF <= AVERAGE1) {
// proportion = SCREEN_9_16;
// } else if (proportionF <= AVERAGE2) {
// proportion = SCREEN_3_4;
// } else if (proportionF <= AVERAGE3) {
// proportion = SCREEN_4_3;
// } else if (proportionF > AVERAGE3) {
// proportion = SCREEN_16_9;
// }
//
// Log.i("SCREEN CONFIG", "screenHeight:" + screenHeight + ";screenWidth:"
// + screenWidth + ";screenDensity:" + screenDensity
// + ";densityDpi:" + densityDpi);
//
// }
//
// }
| import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
import sunmi.sunmiui.R;
import sunmi.sunmiui.utils.Adaptation; |
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getAdapterView();
}
TextView tvTitle = (TextView) convertView.findViewById(R.id.tv_title);
TextView tvContent = (TextView) convertView.findViewById(R.id.tv_content);
tvTitle.setText(list.get(position).title);
tvContent.setText(list.get(position).content);
return convertView;
}
public View getAdapterView() { | // Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/utils/Adaptation.java
// public class Adaptation {
//
// public static int screenHeight = 0;
// public static int screenWidth = 0;
// public static float screenDensity = 0;
// public static int densityDpi = 0;
// // public static int version = Integer.valueOf(android.os.Build.VERSION.SDK_INT);
//
// public static final int SCREEN_9_16 = 1; // 9:16
// public static final int SCREEN_3_4 = 2; // 3:4
// public static final int SCREEN_4_3 = 3; // 4:3
// public static final int SCREEN_16_9 = 4; // 16:9
// public static int proportion = SCREEN_9_16;
//
// // public static final float PROPORTION_9_16 = 0.56f; // 9:16
// // public static final float PROPORTION_3_4 = 0.75f; // 3:4
// // public static final float PROPORTION_4_3 = 1.33f; // 4:3
// // public static final float PROPORTION_16_9 = 1.77f; // 16:9
//
// public static final float AVERAGE1 = 0.655f; // (9:16+3:4)/2
// public static final float AVERAGE2 = 1.04f; // (3:4+4:3)/2
// public static final float AVERAGE3 = 1.55f; // (4:3+16:9)/2
//
// public static void init(Context context) {
// if (screenDensity == 0 || screenWidth == 0 || screenHeight == 0) {
// DisplayMetrics dm = new DisplayMetrics();
// WindowManager wm = (WindowManager) context
// .getSystemService(Context.WINDOW_SERVICE);
// wm.getDefaultDisplay().getMetrics(dm);
// Adaptation.screenDensity = dm.density;
// Adaptation.screenHeight = dm.heightPixels;
// Adaptation.screenWidth = dm.widthPixels;
// Adaptation.densityDpi = dm.densityDpi;
// }
//
// float proportionF = (float) screenWidth / (float) screenHeight;
//
// if (proportionF <= AVERAGE1) {
// proportion = SCREEN_9_16;
// } else if (proportionF <= AVERAGE2) {
// proportion = SCREEN_3_4;
// } else if (proportionF <= AVERAGE3) {
// proportion = SCREEN_4_3;
// } else if (proportionF > AVERAGE3) {
// proportion = SCREEN_16_9;
// }
//
// Log.i("SCREEN CONFIG", "screenHeight:" + screenHeight + ";screenWidth:"
// + screenWidth + ";screenDensity:" + screenDensity
// + ";densityDpi:" + densityDpi);
//
// }
//
// }
// Path: SunmiDesign/sunmiui/src/main/java/sunmi/sunmiui/list/SunmiListAdapter.java
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
import sunmi.sunmiui.R;
import sunmi.sunmiui.utils.Adaptation;
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getAdapterView();
}
TextView tvTitle = (TextView) convertView.findViewById(R.id.tv_title);
TextView tvContent = (TextView) convertView.findViewById(R.id.tv_content);
tvTitle.setText(list.get(position).title);
tvContent.setText(list.get(position).content);
return convertView;
}
public View getAdapterView() { | switch (Adaptation.proportion) { |
Merck/Halyard | sail/src/test/java/com/msd/gin/halyard/sail/HBaseSailConfigTest.java | // Path: strategy/src/main/java/com/msd/gin/halyard/vocab/VOID_EXT.java
// public final class VOID_EXT {
//
// VOID_EXT(){}
//
// public static final String PREFIX = "void-ext";
//
// public static final String NAMESPACE = "http://ldf.fi/void-ext#";
//
// private static final SimpleValueFactory SVF = SimpleValueFactory.getInstance();
//
// public static final IRI DISTINCT_IRI_REFERENCE_SUBJECTS = SVF.createIRI(NAMESPACE, "distinctIRIReferenceSubjects");
//
// public static final IRI DISTINCT_IRI_REFERENCE_OBJECTS = SVF.createIRI(NAMESPACE, "distinctIRIReferenceObjects");
//
// public static final IRI DISTINCT_BLANK_NODE_OBJECTS = SVF.createIRI(NAMESPACE, "distinctBlankNodeObjects");
//
// public static final IRI DISTINCT_BLANK_NODE_SUBJECTS = SVF.createIRI(NAMESPACE, "distinctBlankNodeSubjects");
//
// public static final IRI DISTINCT_LITERALS = SVF.createIRI(NAMESPACE, "distinctLiterals");
//
// public static final IRI SUBJECT = SVF.createIRI(NAMESPACE, "subject");
//
// public static final IRI SUBJECT_PARTITION = SVF.createIRI(NAMESPACE, "subjectPartition");
//
// public static final IRI OBJECT = SVF.createIRI(NAMESPACE, "object");
//
// public static final IRI OBJECT_PARTITION = SVF.createIRI(NAMESPACE, "objectPartition");
//
// }
//
// Path: strategy/src/main/java/com/msd/gin/halyard/vocab/HALYARD.java
// public final class HALYARD {
//
// HALYARD() {}
//
// private static final SimpleValueFactory SVF = SimpleValueFactory.getInstance();
//
// public static final String PREFIX = "halyard";
//
// public static final String NAMESPACE = "http://merck.github.io/Halyard/ns#";
//
// public static final IRI STATS_ROOT_NODE = SVF.createIRI(NAMESPACE, "statsRoot");
//
// public static final IRI STATS_GRAPH_CONTEXT = SVF.createIRI(NAMESPACE, "statsContext");
//
// public static final IRI SYSTEM_GRAPH_CONTEXT = SVF.createIRI(NAMESPACE, "system");
//
// public static final IRI NAMESPACE_PREFIX_PROPERTY = HALYARD.SVF.createIRI(NAMESPACE, "namespacePrefix");
//
// public final static IRI TABLE_NAME_PROPERTY = SVF.createIRI(NAMESPACE, "tableName");
//
// public final static IRI SPLITBITS_PROPERTY = SVF.createIRI(NAMESPACE, "splitBits");
//
// public final static IRI CREATE_TABLE_PROPERTY = SVF.createIRI(NAMESPACE, "createTable");
//
// public final static IRI PUSH_STRATEGY_PROPERTY = SVF.createIRI(NAMESPACE, "pushStrategy");
//
// public final static IRI EVALUATION_TIMEOUT_PROPERTY = SVF.createIRI(NAMESPACE, "evaluationTimeout");
//
// public final static IRI ELASTIC_INDEX_URL_PROPERTY = SVF.createIRI(NAMESPACE, "elasticIndexURL");
//
// public final static IRI SEARCH_TYPE = SVF.createIRI(NAMESPACE, "search");
//
// public final static IRI PARALLEL_SPLIT_FUNCTION = SVF.createIRI(NAMESPACE, "forkAndFilterBy");
//
// }
| import com.msd.gin.halyard.vocab.VOID_EXT;
import com.msd.gin.halyard.vocab.HALYARD;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.model.impl.TreeModel;
import org.eclipse.rdf4j.repository.config.RepositoryConfigSchema;
import org.eclipse.rdf4j.repository.sail.config.SailRepositorySchema;
import org.eclipse.rdf4j.sail.config.SailConfigException;
import org.eclipse.rdf4j.sail.config.SailConfigSchema;
import org.junit.Test;
import static org.junit.Assert.*; | cfg.setSplitBits(5);
cfg.setCreate(true);
cfg.setPush(true);
TreeModel g = new TreeModel();
cfg.export(g);
cfg = new HBaseSailConfig();
cfg.parse(g, null);
assertNull(cfg.getTablespace());
assertEquals(5, cfg.getSplitBits());
assertTrue(cfg.isCreate());
assertTrue(cfg.isPush());
assertEquals("", cfg.getElasticIndexURL());
}
@Test
public void testParseEmpty() throws Exception {
TreeModel g = new TreeModel();
HBaseSailConfig cfg = new HBaseSailConfig();
cfg.parse(g, null);
assertNull(cfg.getTablespace());
assertEquals(0, cfg.getSplitBits());
assertTrue(cfg.isCreate());
assertTrue(cfg.isPush());
assertEquals("", cfg.getElasticIndexURL());
}
@Test
public void testEmptyTableSpace() throws Exception {
TreeModel g = new TreeModel();
IRI node = SimpleValueFactory.getInstance().createIRI("http://node"); | // Path: strategy/src/main/java/com/msd/gin/halyard/vocab/VOID_EXT.java
// public final class VOID_EXT {
//
// VOID_EXT(){}
//
// public static final String PREFIX = "void-ext";
//
// public static final String NAMESPACE = "http://ldf.fi/void-ext#";
//
// private static final SimpleValueFactory SVF = SimpleValueFactory.getInstance();
//
// public static final IRI DISTINCT_IRI_REFERENCE_SUBJECTS = SVF.createIRI(NAMESPACE, "distinctIRIReferenceSubjects");
//
// public static final IRI DISTINCT_IRI_REFERENCE_OBJECTS = SVF.createIRI(NAMESPACE, "distinctIRIReferenceObjects");
//
// public static final IRI DISTINCT_BLANK_NODE_OBJECTS = SVF.createIRI(NAMESPACE, "distinctBlankNodeObjects");
//
// public static final IRI DISTINCT_BLANK_NODE_SUBJECTS = SVF.createIRI(NAMESPACE, "distinctBlankNodeSubjects");
//
// public static final IRI DISTINCT_LITERALS = SVF.createIRI(NAMESPACE, "distinctLiterals");
//
// public static final IRI SUBJECT = SVF.createIRI(NAMESPACE, "subject");
//
// public static final IRI SUBJECT_PARTITION = SVF.createIRI(NAMESPACE, "subjectPartition");
//
// public static final IRI OBJECT = SVF.createIRI(NAMESPACE, "object");
//
// public static final IRI OBJECT_PARTITION = SVF.createIRI(NAMESPACE, "objectPartition");
//
// }
//
// Path: strategy/src/main/java/com/msd/gin/halyard/vocab/HALYARD.java
// public final class HALYARD {
//
// HALYARD() {}
//
// private static final SimpleValueFactory SVF = SimpleValueFactory.getInstance();
//
// public static final String PREFIX = "halyard";
//
// public static final String NAMESPACE = "http://merck.github.io/Halyard/ns#";
//
// public static final IRI STATS_ROOT_NODE = SVF.createIRI(NAMESPACE, "statsRoot");
//
// public static final IRI STATS_GRAPH_CONTEXT = SVF.createIRI(NAMESPACE, "statsContext");
//
// public static final IRI SYSTEM_GRAPH_CONTEXT = SVF.createIRI(NAMESPACE, "system");
//
// public static final IRI NAMESPACE_PREFIX_PROPERTY = HALYARD.SVF.createIRI(NAMESPACE, "namespacePrefix");
//
// public final static IRI TABLE_NAME_PROPERTY = SVF.createIRI(NAMESPACE, "tableName");
//
// public final static IRI SPLITBITS_PROPERTY = SVF.createIRI(NAMESPACE, "splitBits");
//
// public final static IRI CREATE_TABLE_PROPERTY = SVF.createIRI(NAMESPACE, "createTable");
//
// public final static IRI PUSH_STRATEGY_PROPERTY = SVF.createIRI(NAMESPACE, "pushStrategy");
//
// public final static IRI EVALUATION_TIMEOUT_PROPERTY = SVF.createIRI(NAMESPACE, "evaluationTimeout");
//
// public final static IRI ELASTIC_INDEX_URL_PROPERTY = SVF.createIRI(NAMESPACE, "elasticIndexURL");
//
// public final static IRI SEARCH_TYPE = SVF.createIRI(NAMESPACE, "search");
//
// public final static IRI PARALLEL_SPLIT_FUNCTION = SVF.createIRI(NAMESPACE, "forkAndFilterBy");
//
// }
// Path: sail/src/test/java/com/msd/gin/halyard/sail/HBaseSailConfigTest.java
import com.msd.gin.halyard.vocab.VOID_EXT;
import com.msd.gin.halyard.vocab.HALYARD;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.model.impl.TreeModel;
import org.eclipse.rdf4j.repository.config.RepositoryConfigSchema;
import org.eclipse.rdf4j.repository.sail.config.SailRepositorySchema;
import org.eclipse.rdf4j.sail.config.SailConfigException;
import org.eclipse.rdf4j.sail.config.SailConfigSchema;
import org.junit.Test;
import static org.junit.Assert.*;
cfg.setSplitBits(5);
cfg.setCreate(true);
cfg.setPush(true);
TreeModel g = new TreeModel();
cfg.export(g);
cfg = new HBaseSailConfig();
cfg.parse(g, null);
assertNull(cfg.getTablespace());
assertEquals(5, cfg.getSplitBits());
assertTrue(cfg.isCreate());
assertTrue(cfg.isPush());
assertEquals("", cfg.getElasticIndexURL());
}
@Test
public void testParseEmpty() throws Exception {
TreeModel g = new TreeModel();
HBaseSailConfig cfg = new HBaseSailConfig();
cfg.parse(g, null);
assertNull(cfg.getTablespace());
assertEquals(0, cfg.getSplitBits());
assertTrue(cfg.isCreate());
assertTrue(cfg.isPush());
assertEquals("", cfg.getElasticIndexURL());
}
@Test
public void testEmptyTableSpace() throws Exception {
TreeModel g = new TreeModel();
IRI node = SimpleValueFactory.getInstance().createIRI("http://node"); | g.add(node, HALYARD.TABLE_NAME_PROPERTY, SimpleValueFactory.getInstance().createLiteral("")); |
Merck/Halyard | tools/src/main/java/com/msd/gin/halyard/tools/ParallelSplitFunction.java | // Path: strategy/src/main/java/com/msd/gin/halyard/vocab/HALYARD.java
// public final static IRI PARALLEL_SPLIT_FUNCTION = SVF.createIRI(NAMESPACE, "forkAndFilterBy");
| import java.util.Arrays;
import java.util.List;
import org.eclipse.rdf4j.model.Value;
import org.eclipse.rdf4j.model.ValueFactory;
import org.eclipse.rdf4j.query.QueryLanguage;
import org.eclipse.rdf4j.query.algebra.FunctionCall;
import org.eclipse.rdf4j.query.algebra.UpdateExpr;
import org.eclipse.rdf4j.query.algebra.ValueConstant;
import org.eclipse.rdf4j.query.algebra.ValueExpr;
import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException;
import org.eclipse.rdf4j.query.algebra.evaluation.function.Function;
import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor;
import org.eclipse.rdf4j.query.parser.QueryParserUtil;
import static com.msd.gin.halyard.vocab.HALYARD.PARALLEL_SPLIT_FUNCTION; | /*
* Copyright 2018 Merck Sharp & Dohme Corp. a subsidiary of Merck & Co.,
* Inc., Kenilworth, NJ, USA.
*
* 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.msd.gin.halyard.tools;
/**
*
* @author Adam Sotona (MSD)
*/
public final class ParallelSplitFunction implements Function {
private final int forkIndex;
public ParallelSplitFunction(int forkIndex) {
this.forkIndex = forkIndex;
}
@Override
public String getURI() { | // Path: strategy/src/main/java/com/msd/gin/halyard/vocab/HALYARD.java
// public final static IRI PARALLEL_SPLIT_FUNCTION = SVF.createIRI(NAMESPACE, "forkAndFilterBy");
// Path: tools/src/main/java/com/msd/gin/halyard/tools/ParallelSplitFunction.java
import java.util.Arrays;
import java.util.List;
import org.eclipse.rdf4j.model.Value;
import org.eclipse.rdf4j.model.ValueFactory;
import org.eclipse.rdf4j.query.QueryLanguage;
import org.eclipse.rdf4j.query.algebra.FunctionCall;
import org.eclipse.rdf4j.query.algebra.UpdateExpr;
import org.eclipse.rdf4j.query.algebra.ValueConstant;
import org.eclipse.rdf4j.query.algebra.ValueExpr;
import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException;
import org.eclipse.rdf4j.query.algebra.evaluation.function.Function;
import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor;
import org.eclipse.rdf4j.query.parser.QueryParserUtil;
import static com.msd.gin.halyard.vocab.HALYARD.PARALLEL_SPLIT_FUNCTION;
/*
* Copyright 2018 Merck Sharp & Dohme Corp. a subsidiary of Merck & Co.,
* Inc., Kenilworth, NJ, USA.
*
* 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.msd.gin.halyard.tools;
/**
*
* @author Adam Sotona (MSD)
*/
public final class ParallelSplitFunction implements Function {
private final int forkIndex;
public ParallelSplitFunction(int forkIndex) {
this.forkIndex = forkIndex;
}
@Override
public String getURI() { | return PARALLEL_SPLIT_FUNCTION.toString(); |
Merck/Halyard | sail/src/test/java/com/msd/gin/halyard/sail/HBaseRepositoryManagerTest.java | // Path: common/src/test/java/com/msd/gin/halyard/common/HBaseServerTestInstance.java
// public class HBaseServerTestInstance {
//
// private static Configuration conf = null;
//
// public static synchronized Configuration getInstanceConfig() throws Exception {
// if (conf == null) {
// File zooRoot = File.createTempFile("hbase-zookeeper", "");
// zooRoot.delete();
// ZooKeeperServer zookeper = new ZooKeeperServer(zooRoot, zooRoot, 2000);
// ServerCnxnFactory factory = ServerCnxnFactory.createFactory(new InetSocketAddress("localhost", 0), 5000);
// factory.startup(zookeper);
//
// YarnConfiguration yconf = new YarnConfiguration();
// String argLine = System.getProperty("argLine");
// if (argLine != null) {
// yconf.set("yarn.app.mapreduce.am.command-opts", argLine.replace("jacoco.exec", "jacocoMR.exec"));
// }
// yconf.setBoolean(MRConfig.MAPREDUCE_MINICLUSTER_CONTROL_RESOURCE_MONITORING, false);
// yconf.setClass(YarnConfiguration.RM_SCHEDULER, FifoScheduler.class, ResourceScheduler.class);
// MiniMRYarnCluster miniCluster = new MiniMRYarnCluster("testCluster");
// miniCluster.init(yconf);
// String resourceManagerLink = yconf.get(YarnConfiguration.RM_ADDRESS);
// yconf.setBoolean(MRJobConfig.JOB_UBERTASK_ENABLE, true);
// miniCluster.start();
// miniCluster.waitForNodeManagersToConnect(10000);
// // following condition set in MiniYarnCluster:273
// while (resourceManagerLink.endsWith(":0")) {
// Thread.sleep(100);
// resourceManagerLink = yconf.get(YarnConfiguration.RM_ADDRESS);
// }
//
// File hbaseRoot = File.createTempFile("hbase-root", "");
// hbaseRoot.delete();
// conf = HBaseConfiguration.create(miniCluster.getConfig());
// conf.set(HConstants.HBASE_DIR, hbaseRoot.toURI().toURL().toString());
// conf.setInt(HConstants.ZOOKEEPER_CLIENT_PORT, factory.getLocalPort());
// conf.set("hbase.master.hostname", "localhost");
// conf.set("hbase.regionserver.hostname", "localhost");
// conf.setInt("hbase.master.info.port", -1);
// conf.set("hbase.fs.tmp.dir", new File(System.getProperty("java.io.tmpdir")).toURI().toURL().toString());
// LocalHBaseCluster cluster = new LocalHBaseCluster(conf);
// cluster.startup();
// }
// return new Configuration(conf);
// }
// }
| import com.msd.gin.halyard.common.HBaseServerTestInstance;
import java.net.MalformedURLException;
import java.util.Collection;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.eclipse.rdf4j.repository.Repository;
import org.eclipse.rdf4j.repository.config.RepositoryConfig;
import org.eclipse.rdf4j.repository.sail.config.SailRepositoryConfig;
import org.eclipse.rdf4j.sail.memory.config.MemoryStoreConfig;
import org.junit.Test;
import static org.junit.Assert.*; | /*
* Copyright 2019 Merck Sharp & Dohme Corp. a subsidiary of Merck & Co.,
* Inc., Kenilworth, NJ, USA.
*
* 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.msd.gin.halyard.sail;
/**
*
* @author Adam Sotona (MSD)
*/
public class HBaseRepositoryManagerTest {
@Test (expected = MalformedURLException.class)
public void testGetLocation() throws Exception {
new HBaseRepositoryManager().getLocation();
}
@Test
public void testHttpClient() {
HBaseRepositoryManager rm = new HBaseRepositoryManager();
assertNull(rm.getHttpClient());
@SuppressWarnings("deprecation")
HttpClient cl = new DefaultHttpClient();
rm.setHttpClient(cl);
assertEquals(cl, rm.getHttpClient());
}
@Test
public void testAddRepositoryPersists() throws Exception {
HBaseRepositoryManager rm = new HBaseRepositoryManager(); | // Path: common/src/test/java/com/msd/gin/halyard/common/HBaseServerTestInstance.java
// public class HBaseServerTestInstance {
//
// private static Configuration conf = null;
//
// public static synchronized Configuration getInstanceConfig() throws Exception {
// if (conf == null) {
// File zooRoot = File.createTempFile("hbase-zookeeper", "");
// zooRoot.delete();
// ZooKeeperServer zookeper = new ZooKeeperServer(zooRoot, zooRoot, 2000);
// ServerCnxnFactory factory = ServerCnxnFactory.createFactory(new InetSocketAddress("localhost", 0), 5000);
// factory.startup(zookeper);
//
// YarnConfiguration yconf = new YarnConfiguration();
// String argLine = System.getProperty("argLine");
// if (argLine != null) {
// yconf.set("yarn.app.mapreduce.am.command-opts", argLine.replace("jacoco.exec", "jacocoMR.exec"));
// }
// yconf.setBoolean(MRConfig.MAPREDUCE_MINICLUSTER_CONTROL_RESOURCE_MONITORING, false);
// yconf.setClass(YarnConfiguration.RM_SCHEDULER, FifoScheduler.class, ResourceScheduler.class);
// MiniMRYarnCluster miniCluster = new MiniMRYarnCluster("testCluster");
// miniCluster.init(yconf);
// String resourceManagerLink = yconf.get(YarnConfiguration.RM_ADDRESS);
// yconf.setBoolean(MRJobConfig.JOB_UBERTASK_ENABLE, true);
// miniCluster.start();
// miniCluster.waitForNodeManagersToConnect(10000);
// // following condition set in MiniYarnCluster:273
// while (resourceManagerLink.endsWith(":0")) {
// Thread.sleep(100);
// resourceManagerLink = yconf.get(YarnConfiguration.RM_ADDRESS);
// }
//
// File hbaseRoot = File.createTempFile("hbase-root", "");
// hbaseRoot.delete();
// conf = HBaseConfiguration.create(miniCluster.getConfig());
// conf.set(HConstants.HBASE_DIR, hbaseRoot.toURI().toURL().toString());
// conf.setInt(HConstants.ZOOKEEPER_CLIENT_PORT, factory.getLocalPort());
// conf.set("hbase.master.hostname", "localhost");
// conf.set("hbase.regionserver.hostname", "localhost");
// conf.setInt("hbase.master.info.port", -1);
// conf.set("hbase.fs.tmp.dir", new File(System.getProperty("java.io.tmpdir")).toURI().toURL().toString());
// LocalHBaseCluster cluster = new LocalHBaseCluster(conf);
// cluster.startup();
// }
// return new Configuration(conf);
// }
// }
// Path: sail/src/test/java/com/msd/gin/halyard/sail/HBaseRepositoryManagerTest.java
import com.msd.gin.halyard.common.HBaseServerTestInstance;
import java.net.MalformedURLException;
import java.util.Collection;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.eclipse.rdf4j.repository.Repository;
import org.eclipse.rdf4j.repository.config.RepositoryConfig;
import org.eclipse.rdf4j.repository.sail.config.SailRepositoryConfig;
import org.eclipse.rdf4j.sail.memory.config.MemoryStoreConfig;
import org.junit.Test;
import static org.junit.Assert.*;
/*
* Copyright 2019 Merck Sharp & Dohme Corp. a subsidiary of Merck & Co.,
* Inc., Kenilworth, NJ, USA.
*
* 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.msd.gin.halyard.sail;
/**
*
* @author Adam Sotona (MSD)
*/
public class HBaseRepositoryManagerTest {
@Test (expected = MalformedURLException.class)
public void testGetLocation() throws Exception {
new HBaseRepositoryManager().getLocation();
}
@Test
public void testHttpClient() {
HBaseRepositoryManager rm = new HBaseRepositoryManager();
assertNull(rm.getHttpClient());
@SuppressWarnings("deprecation")
HttpClient cl = new DefaultHttpClient();
rm.setHttpClient(cl);
assertEquals(cl, rm.getHttpClient());
}
@Test
public void testAddRepositoryPersists() throws Exception {
HBaseRepositoryManager rm = new HBaseRepositoryManager(); | rm.overrideConfiguration(HBaseServerTestInstance.getInstanceConfig()); |
Merck/Halyard | sail/src/main/java/com/msd/gin/halyard/sail/HBaseSailConfig.java | // Path: strategy/src/main/java/com/msd/gin/halyard/vocab/HALYARD.java
// public final class HALYARD {
//
// HALYARD() {}
//
// private static final SimpleValueFactory SVF = SimpleValueFactory.getInstance();
//
// public static final String PREFIX = "halyard";
//
// public static final String NAMESPACE = "http://merck.github.io/Halyard/ns#";
//
// public static final IRI STATS_ROOT_NODE = SVF.createIRI(NAMESPACE, "statsRoot");
//
// public static final IRI STATS_GRAPH_CONTEXT = SVF.createIRI(NAMESPACE, "statsContext");
//
// public static final IRI SYSTEM_GRAPH_CONTEXT = SVF.createIRI(NAMESPACE, "system");
//
// public static final IRI NAMESPACE_PREFIX_PROPERTY = HALYARD.SVF.createIRI(NAMESPACE, "namespacePrefix");
//
// public final static IRI TABLE_NAME_PROPERTY = SVF.createIRI(NAMESPACE, "tableName");
//
// public final static IRI SPLITBITS_PROPERTY = SVF.createIRI(NAMESPACE, "splitBits");
//
// public final static IRI CREATE_TABLE_PROPERTY = SVF.createIRI(NAMESPACE, "createTable");
//
// public final static IRI PUSH_STRATEGY_PROPERTY = SVF.createIRI(NAMESPACE, "pushStrategy");
//
// public final static IRI EVALUATION_TIMEOUT_PROPERTY = SVF.createIRI(NAMESPACE, "evaluationTimeout");
//
// public final static IRI ELASTIC_INDEX_URL_PROPERTY = SVF.createIRI(NAMESPACE, "elasticIndexURL");
//
// public final static IRI SEARCH_TYPE = SVF.createIRI(NAMESPACE, "search");
//
// public final static IRI PARALLEL_SPLIT_FUNCTION = SVF.createIRI(NAMESPACE, "forkAndFilterBy");
//
// }
| import org.eclipse.rdf4j.sail.config.SailConfigException;
import org.eclipse.rdf4j.sail.config.SailConfigSchema;
import com.msd.gin.halyard.vocab.HALYARD;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.model.Model;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.model.ValueFactory;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.model.util.Models;
import org.eclipse.rdf4j.repository.config.RepositoryConfigSchema;
import org.eclipse.rdf4j.repository.sail.config.SailRepositorySchema;
import org.eclipse.rdf4j.sail.config.AbstractSailImplConfig; | /*
* Copyright 2016 Merck Sharp & Dohme Corp. a subsidiary of Merck & Co.,
* Inc., Kenilworth, NJ, USA.
*
* 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.msd.gin.halyard.sail;
/**
* Configuration information for the HBase SAIL and methods to serialize/ deserialize the configuration.
* @author Adam Sotona (MSD)
*/
public final class HBaseSailConfig extends AbstractSailImplConfig {
private static final Map<IRI, IRI> BACK_COMPATIBILITY_MAP = new HashMap<>();
private static final String OLD_NAMESPACE = "http://gin.msd.com/halyard/sail/hbase#";
static {
ValueFactory factory = SimpleValueFactory.getInstance(); | // Path: strategy/src/main/java/com/msd/gin/halyard/vocab/HALYARD.java
// public final class HALYARD {
//
// HALYARD() {}
//
// private static final SimpleValueFactory SVF = SimpleValueFactory.getInstance();
//
// public static final String PREFIX = "halyard";
//
// public static final String NAMESPACE = "http://merck.github.io/Halyard/ns#";
//
// public static final IRI STATS_ROOT_NODE = SVF.createIRI(NAMESPACE, "statsRoot");
//
// public static final IRI STATS_GRAPH_CONTEXT = SVF.createIRI(NAMESPACE, "statsContext");
//
// public static final IRI SYSTEM_GRAPH_CONTEXT = SVF.createIRI(NAMESPACE, "system");
//
// public static final IRI NAMESPACE_PREFIX_PROPERTY = HALYARD.SVF.createIRI(NAMESPACE, "namespacePrefix");
//
// public final static IRI TABLE_NAME_PROPERTY = SVF.createIRI(NAMESPACE, "tableName");
//
// public final static IRI SPLITBITS_PROPERTY = SVF.createIRI(NAMESPACE, "splitBits");
//
// public final static IRI CREATE_TABLE_PROPERTY = SVF.createIRI(NAMESPACE, "createTable");
//
// public final static IRI PUSH_STRATEGY_PROPERTY = SVF.createIRI(NAMESPACE, "pushStrategy");
//
// public final static IRI EVALUATION_TIMEOUT_PROPERTY = SVF.createIRI(NAMESPACE, "evaluationTimeout");
//
// public final static IRI ELASTIC_INDEX_URL_PROPERTY = SVF.createIRI(NAMESPACE, "elasticIndexURL");
//
// public final static IRI SEARCH_TYPE = SVF.createIRI(NAMESPACE, "search");
//
// public final static IRI PARALLEL_SPLIT_FUNCTION = SVF.createIRI(NAMESPACE, "forkAndFilterBy");
//
// }
// Path: sail/src/main/java/com/msd/gin/halyard/sail/HBaseSailConfig.java
import org.eclipse.rdf4j.sail.config.SailConfigException;
import org.eclipse.rdf4j.sail.config.SailConfigSchema;
import com.msd.gin.halyard.vocab.HALYARD;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.model.Model;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.model.ValueFactory;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.model.util.Models;
import org.eclipse.rdf4j.repository.config.RepositoryConfigSchema;
import org.eclipse.rdf4j.repository.sail.config.SailRepositorySchema;
import org.eclipse.rdf4j.sail.config.AbstractSailImplConfig;
/*
* Copyright 2016 Merck Sharp & Dohme Corp. a subsidiary of Merck & Co.,
* Inc., Kenilworth, NJ, USA.
*
* 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.msd.gin.halyard.sail;
/**
* Configuration information for the HBase SAIL and methods to serialize/ deserialize the configuration.
* @author Adam Sotona (MSD)
*/
public final class HBaseSailConfig extends AbstractSailImplConfig {
private static final Map<IRI, IRI> BACK_COMPATIBILITY_MAP = new HashMap<>();
private static final String OLD_NAMESPACE = "http://gin.msd.com/halyard/sail/hbase#";
static {
ValueFactory factory = SimpleValueFactory.getInstance(); | BACK_COMPATIBILITY_MAP.put(HALYARD.TABLE_NAME_PROPERTY, factory.createIRI(OLD_NAMESPACE, "tablespace")); |
Merck/Halyard | tools/src/test/java/com/msd/gin/halyard/tools/ParallelSplitFunctionTest.java | // Path: strategy/src/main/java/com/msd/gin/halyard/vocab/HALYARD.java
// public final static IRI PARALLEL_SPLIT_FUNCTION = SVF.createIRI(NAMESPACE, "forkAndFilterBy");
| import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException;
import org.junit.Test;
import static org.junit.Assert.*;
import static com.msd.gin.halyard.vocab.HALYARD.PARALLEL_SPLIT_FUNCTION; | /*
* Copyright 2018 Merck Sharp & Dohme Corp. a subsidiary of Merck & Co.,
* Inc., Kenilworth, NJ, USA.
*
* 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.msd.gin.halyard.tools;
/**
*
* @author Adam Sotona (MSD)
*/
public class ParallelSplitFunctionTest {
private static final SimpleValueFactory SVF = SimpleValueFactory.getInstance();
@Test
public void testGetURI() { | // Path: strategy/src/main/java/com/msd/gin/halyard/vocab/HALYARD.java
// public final static IRI PARALLEL_SPLIT_FUNCTION = SVF.createIRI(NAMESPACE, "forkAndFilterBy");
// Path: tools/src/test/java/com/msd/gin/halyard/tools/ParallelSplitFunctionTest.java
import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException;
import org.junit.Test;
import static org.junit.Assert.*;
import static com.msd.gin.halyard.vocab.HALYARD.PARALLEL_SPLIT_FUNCTION;
/*
* Copyright 2018 Merck Sharp & Dohme Corp. a subsidiary of Merck & Co.,
* Inc., Kenilworth, NJ, USA.
*
* 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.msd.gin.halyard.tools;
/**
*
* @author Adam Sotona (MSD)
*/
public class ParallelSplitFunctionTest {
private static final SimpleValueFactory SVF = SimpleValueFactory.getInstance();
@Test
public void testGetURI() { | assertEquals(PARALLEL_SPLIT_FUNCTION.toString(), new ParallelSplitFunction(1).getURI()); |
Merck/Halyard | strategy/src/main/java/com/msd/gin/halyard/strategy/HalyardStatementPatternEvaluation.java | // Path: strategy/src/main/java/com/msd/gin/halyard/strategy/HalyardEvaluationStrategy.java
// public static final class ServiceRoot extends QueryRoot {
// private static final long serialVersionUID = 7052207623408379003L;
//
// public final TupleExpr originalServiceArgs;
//
// public ServiceRoot(TupleExpr serviceArgs) {
// super(serviceArgs.clone());
// this.originalServiceArgs = serviceArgs;
// }
// }
| import com.msd.gin.halyard.strategy.HalyardEvaluationStrategy.ServiceRoot;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.rdf4j.common.iteration.CloseableIteration;
import org.eclipse.rdf4j.common.iteration.ConvertingIteration;
import org.eclipse.rdf4j.common.iteration.FilterIteration;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.Value;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.model.vocabulary.SESAME;
import org.eclipse.rdf4j.query.BindingSet;
import org.eclipse.rdf4j.query.Dataset;
import org.eclipse.rdf4j.query.QueryEvaluationException;
import org.eclipse.rdf4j.query.algebra.Filter;
import org.eclipse.rdf4j.query.algebra.LeftJoin;
import org.eclipse.rdf4j.query.algebra.QueryModelNode;
import org.eclipse.rdf4j.query.algebra.Service;
import org.eclipse.rdf4j.query.algebra.StatementPattern;
import org.eclipse.rdf4j.query.algebra.Var;
import org.eclipse.rdf4j.query.algebra.evaluation.QueryBindingSet;
import org.eclipse.rdf4j.query.algebra.evaluation.TripleSource;
import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor; |
private final Dataset dataset;
private final TripleSource tripleSource;
//a map of query model nodes and their priority
private static final Map<IdentityWrapper<QueryModelNode>, Integer> PRIORITY_MAP_CACHE = Collections.synchronizedMap(new WeakHashMap<>());
private static final PriorityQueue<PipeAndIteration> PRIORITY_QUEUE = new PriorityQueue<>();
/**
* Queues a binding set and {@code QueryModelNode} for evaluation using the current priority.
* @param pipe the pipe that evaluation results are returned on
* @param iter
* @param node an implementation of any {@QueryModelNode} sub-type, typically a {@code ValueExpression}, {@Code UpdateExpression} or {@TupleExpression}
*/
static void enqueue(HalyardTupleExprEvaluation.BindingSetPipe pipe, CloseableIteration<BindingSet, QueryEvaluationException> iter, QueryModelNode node) {
int priority = getPriorityForNode(node);
PRIORITY_QUEUE.put(priority, new PipeAndIteration(pipe, iter, priority));
}
/**
* Get the priority of this node from the PRIORITY_MAP_CACHE or determine the priority and then cache it. Also caches priority for sub-nodes of {@code node}
* @param node the node that you want the priority for
* @return the priority of the node, a count of the number of child nodes of {@code node}.
*/
private static int getPriorityForNode(final QueryModelNode node) {
Integer p = PRIORITY_MAP_CACHE.get(new IdentityWrapper<>(node));
if (p != null) {
return p;
} else {
QueryModelNode root = node;
while (root.getParentNode() != null) root = root.getParentNode(); //traverse to the root of the query model | // Path: strategy/src/main/java/com/msd/gin/halyard/strategy/HalyardEvaluationStrategy.java
// public static final class ServiceRoot extends QueryRoot {
// private static final long serialVersionUID = 7052207623408379003L;
//
// public final TupleExpr originalServiceArgs;
//
// public ServiceRoot(TupleExpr serviceArgs) {
// super(serviceArgs.clone());
// this.originalServiceArgs = serviceArgs;
// }
// }
// Path: strategy/src/main/java/com/msd/gin/halyard/strategy/HalyardStatementPatternEvaluation.java
import com.msd.gin.halyard.strategy.HalyardEvaluationStrategy.ServiceRoot;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.rdf4j.common.iteration.CloseableIteration;
import org.eclipse.rdf4j.common.iteration.ConvertingIteration;
import org.eclipse.rdf4j.common.iteration.FilterIteration;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.Value;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.model.vocabulary.SESAME;
import org.eclipse.rdf4j.query.BindingSet;
import org.eclipse.rdf4j.query.Dataset;
import org.eclipse.rdf4j.query.QueryEvaluationException;
import org.eclipse.rdf4j.query.algebra.Filter;
import org.eclipse.rdf4j.query.algebra.LeftJoin;
import org.eclipse.rdf4j.query.algebra.QueryModelNode;
import org.eclipse.rdf4j.query.algebra.Service;
import org.eclipse.rdf4j.query.algebra.StatementPattern;
import org.eclipse.rdf4j.query.algebra.Var;
import org.eclipse.rdf4j.query.algebra.evaluation.QueryBindingSet;
import org.eclipse.rdf4j.query.algebra.evaluation.TripleSource;
import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor;
private final Dataset dataset;
private final TripleSource tripleSource;
//a map of query model nodes and their priority
private static final Map<IdentityWrapper<QueryModelNode>, Integer> PRIORITY_MAP_CACHE = Collections.synchronizedMap(new WeakHashMap<>());
private static final PriorityQueue<PipeAndIteration> PRIORITY_QUEUE = new PriorityQueue<>();
/**
* Queues a binding set and {@code QueryModelNode} for evaluation using the current priority.
* @param pipe the pipe that evaluation results are returned on
* @param iter
* @param node an implementation of any {@QueryModelNode} sub-type, typically a {@code ValueExpression}, {@Code UpdateExpression} or {@TupleExpression}
*/
static void enqueue(HalyardTupleExprEvaluation.BindingSetPipe pipe, CloseableIteration<BindingSet, QueryEvaluationException> iter, QueryModelNode node) {
int priority = getPriorityForNode(node);
PRIORITY_QUEUE.put(priority, new PipeAndIteration(pipe, iter, priority));
}
/**
* Get the priority of this node from the PRIORITY_MAP_CACHE or determine the priority and then cache it. Also caches priority for sub-nodes of {@code node}
* @param node the node that you want the priority for
* @return the priority of the node, a count of the number of child nodes of {@code node}.
*/
private static int getPriorityForNode(final QueryModelNode node) {
Integer p = PRIORITY_MAP_CACHE.get(new IdentityWrapper<>(node));
if (p != null) {
return p;
} else {
QueryModelNode root = node;
while (root.getParentNode() != null) root = root.getParentNode(); //traverse to the root of the query model | final AtomicInteger counter = new AtomicInteger(root instanceof ServiceRoot ? getPriorityForNode(((ServiceRoot)root).originalServiceArgs) : 0); //starting priority for ServiceRoot must be evaluated from the original service args node |
Merck/Halyard | strategy/src/test/java/com/msd/gin/halyard/optimizers/HalyardEvaluationStatisticsTest.java | // Path: strategy/src/main/java/com/msd/gin/halyard/vocab/HALYARD.java
// public final class HALYARD {
//
// HALYARD() {}
//
// private static final SimpleValueFactory SVF = SimpleValueFactory.getInstance();
//
// public static final String PREFIX = "halyard";
//
// public static final String NAMESPACE = "http://merck.github.io/Halyard/ns#";
//
// public static final IRI STATS_ROOT_NODE = SVF.createIRI(NAMESPACE, "statsRoot");
//
// public static final IRI STATS_GRAPH_CONTEXT = SVF.createIRI(NAMESPACE, "statsContext");
//
// public static final IRI SYSTEM_GRAPH_CONTEXT = SVF.createIRI(NAMESPACE, "system");
//
// public static final IRI NAMESPACE_PREFIX_PROPERTY = HALYARD.SVF.createIRI(NAMESPACE, "namespacePrefix");
//
// public final static IRI TABLE_NAME_PROPERTY = SVF.createIRI(NAMESPACE, "tableName");
//
// public final static IRI SPLITBITS_PROPERTY = SVF.createIRI(NAMESPACE, "splitBits");
//
// public final static IRI CREATE_TABLE_PROPERTY = SVF.createIRI(NAMESPACE, "createTable");
//
// public final static IRI PUSH_STRATEGY_PROPERTY = SVF.createIRI(NAMESPACE, "pushStrategy");
//
// public final static IRI EVALUATION_TIMEOUT_PROPERTY = SVF.createIRI(NAMESPACE, "evaluationTimeout");
//
// public final static IRI ELASTIC_INDEX_URL_PROPERTY = SVF.createIRI(NAMESPACE, "elasticIndexURL");
//
// public final static IRI SEARCH_TYPE = SVF.createIRI(NAMESPACE, "search");
//
// public final static IRI PARALLEL_SPLIT_FUNCTION = SVF.createIRI(NAMESPACE, "forkAndFilterBy");
//
// }
| import com.msd.gin.halyard.vocab.HALYARD;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.rdf4j.query.parser.sparql.SPARQLParser;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized; | /*
* Copyright 2018 Merck Sharp & Dohme Corp. a subsidiary of Merck & Co.,
* Inc., Kenilworth, NJ, USA.
*
* 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.msd.gin.halyard.optimizers;
/**
*
* @author Adam Sotona (MSD)
*/
@RunWith(Parameterized.class)
public class HalyardEvaluationStatisticsTest {
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{"select * where {?s a ?o}", 1.0E2, null, null},
{"select * where {?s ?p ?o}", 1.0E3, null, null},
{"select * where {?s a \"1\"}", 1.0E1, null, null},
{"select * where {?a ?b ?c; ?d ?e}", 1.0E8, null, null},
{"select * where {?a a ?c; ?d ?e}", 1.0E6, null, null},
{"select * where {?a ?b ?c; a ?e}", 1.0E7, null, null},
{"select * where {?s a ?o}", 1.0E1, new String[]{"o"}, null},
{"select * where {?s ?p ?o}", 1.0E1, new String[]{"s", "o"}, null},
{"select * where {?s a \"1\"}", 1.0, new String[]{"s"}, null},
{"select * where {?a ?b ?c; ?d ?e}", 1.0E4, new String[]{"b", "c"}, null},
{"select * where {?a a ?c; ?d ?e}", 1.0E3, new String[]{"d", "c"}, null},
{"select * where {?a ?b ?c; a ?e}", 1.0E2, new String[]{"b", "e", "c"}, null},
{"select * where {{?a a \"1\". optional {?a a ?b}} union {?a a \"2\"}}", 1010.0, null, null}, | // Path: strategy/src/main/java/com/msd/gin/halyard/vocab/HALYARD.java
// public final class HALYARD {
//
// HALYARD() {}
//
// private static final SimpleValueFactory SVF = SimpleValueFactory.getInstance();
//
// public static final String PREFIX = "halyard";
//
// public static final String NAMESPACE = "http://merck.github.io/Halyard/ns#";
//
// public static final IRI STATS_ROOT_NODE = SVF.createIRI(NAMESPACE, "statsRoot");
//
// public static final IRI STATS_GRAPH_CONTEXT = SVF.createIRI(NAMESPACE, "statsContext");
//
// public static final IRI SYSTEM_GRAPH_CONTEXT = SVF.createIRI(NAMESPACE, "system");
//
// public static final IRI NAMESPACE_PREFIX_PROPERTY = HALYARD.SVF.createIRI(NAMESPACE, "namespacePrefix");
//
// public final static IRI TABLE_NAME_PROPERTY = SVF.createIRI(NAMESPACE, "tableName");
//
// public final static IRI SPLITBITS_PROPERTY = SVF.createIRI(NAMESPACE, "splitBits");
//
// public final static IRI CREATE_TABLE_PROPERTY = SVF.createIRI(NAMESPACE, "createTable");
//
// public final static IRI PUSH_STRATEGY_PROPERTY = SVF.createIRI(NAMESPACE, "pushStrategy");
//
// public final static IRI EVALUATION_TIMEOUT_PROPERTY = SVF.createIRI(NAMESPACE, "evaluationTimeout");
//
// public final static IRI ELASTIC_INDEX_URL_PROPERTY = SVF.createIRI(NAMESPACE, "elasticIndexURL");
//
// public final static IRI SEARCH_TYPE = SVF.createIRI(NAMESPACE, "search");
//
// public final static IRI PARALLEL_SPLIT_FUNCTION = SVF.createIRI(NAMESPACE, "forkAndFilterBy");
//
// }
// Path: strategy/src/test/java/com/msd/gin/halyard/optimizers/HalyardEvaluationStatisticsTest.java
import com.msd.gin.halyard.vocab.HALYARD;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.rdf4j.query.parser.sparql.SPARQLParser;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
/*
* Copyright 2018 Merck Sharp & Dohme Corp. a subsidiary of Merck & Co.,
* Inc., Kenilworth, NJ, USA.
*
* 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.msd.gin.halyard.optimizers;
/**
*
* @author Adam Sotona (MSD)
*/
@RunWith(Parameterized.class)
public class HalyardEvaluationStatisticsTest {
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{"select * where {?s a ?o}", 1.0E2, null, null},
{"select * where {?s ?p ?o}", 1.0E3, null, null},
{"select * where {?s a \"1\"}", 1.0E1, null, null},
{"select * where {?a ?b ?c; ?d ?e}", 1.0E8, null, null},
{"select * where {?a a ?c; ?d ?e}", 1.0E6, null, null},
{"select * where {?a ?b ?c; a ?e}", 1.0E7, null, null},
{"select * where {?s a ?o}", 1.0E1, new String[]{"o"}, null},
{"select * where {?s ?p ?o}", 1.0E1, new String[]{"s", "o"}, null},
{"select * where {?s a \"1\"}", 1.0, new String[]{"s"}, null},
{"select * where {?a ?b ?c; ?d ?e}", 1.0E4, new String[]{"b", "c"}, null},
{"select * where {?a a ?c; ?d ?e}", 1.0E3, new String[]{"d", "c"}, null},
{"select * where {?a ?b ?c; a ?e}", 1.0E2, new String[]{"b", "e", "c"}, null},
{"select * where {{?a a \"1\". optional {?a a ?b}} union {?a a \"2\"}}", 1010.0, null, null}, | {"select * where {?s a \"1\"^^<" + HALYARD.SEARCH_TYPE + ">}", 1.0E-4, new String[]{"s"}, null}, |
Merck/Halyard | strategy/src/main/java/com/msd/gin/halyard/optimizers/HalyardEvaluationStatistics.java | // Path: strategy/src/main/java/com/msd/gin/halyard/vocab/HALYARD.java
// public final class HALYARD {
//
// HALYARD() {}
//
// private static final SimpleValueFactory SVF = SimpleValueFactory.getInstance();
//
// public static final String PREFIX = "halyard";
//
// public static final String NAMESPACE = "http://merck.github.io/Halyard/ns#";
//
// public static final IRI STATS_ROOT_NODE = SVF.createIRI(NAMESPACE, "statsRoot");
//
// public static final IRI STATS_GRAPH_CONTEXT = SVF.createIRI(NAMESPACE, "statsContext");
//
// public static final IRI SYSTEM_GRAPH_CONTEXT = SVF.createIRI(NAMESPACE, "system");
//
// public static final IRI NAMESPACE_PREFIX_PROPERTY = HALYARD.SVF.createIRI(NAMESPACE, "namespacePrefix");
//
// public final static IRI TABLE_NAME_PROPERTY = SVF.createIRI(NAMESPACE, "tableName");
//
// public final static IRI SPLITBITS_PROPERTY = SVF.createIRI(NAMESPACE, "splitBits");
//
// public final static IRI CREATE_TABLE_PROPERTY = SVF.createIRI(NAMESPACE, "createTable");
//
// public final static IRI PUSH_STRATEGY_PROPERTY = SVF.createIRI(NAMESPACE, "pushStrategy");
//
// public final static IRI EVALUATION_TIMEOUT_PROPERTY = SVF.createIRI(NAMESPACE, "evaluationTimeout");
//
// public final static IRI ELASTIC_INDEX_URL_PROPERTY = SVF.createIRI(NAMESPACE, "elasticIndexURL");
//
// public final static IRI SEARCH_TYPE = SVF.createIRI(NAMESPACE, "search");
//
// public final static IRI PARALLEL_SPLIT_FUNCTION = SVF.createIRI(NAMESPACE, "forkAndFilterBy");
//
// }
| import com.msd.gin.halyard.vocab.HALYARD;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.query.algebra.ArbitraryLengthPath;
import org.eclipse.rdf4j.query.algebra.BinaryTupleOperator;
import org.eclipse.rdf4j.query.algebra.BindingSetAssignment;
import org.eclipse.rdf4j.query.algebra.EmptySet;
import org.eclipse.rdf4j.query.algebra.Filter;
import org.eclipse.rdf4j.query.algebra.Join;
import org.eclipse.rdf4j.query.algebra.LeftJoin;
import org.eclipse.rdf4j.query.algebra.QueryModelNode;
import org.eclipse.rdf4j.query.algebra.Service;
import org.eclipse.rdf4j.query.algebra.SingletonSet;
import org.eclipse.rdf4j.query.algebra.StatementPattern;
import org.eclipse.rdf4j.query.algebra.TupleExpr;
import org.eclipse.rdf4j.query.algebra.UnaryTupleOperator;
import org.eclipse.rdf4j.query.algebra.Var;
import org.eclipse.rdf4j.query.algebra.ZeroLengthPath;
import org.eclipse.rdf4j.query.algebra.evaluation.impl.EvaluationStatistics;
import org.eclipse.rdf4j.query.algebra.evaluation.impl.ExternalSet; |
public synchronized double getCardinality(TupleExpr expr, final Set<String> boundVariables, final Set<String> priorityVariables) {
if (cc == null) {
cc = new HalyardCardinalityCalcualtor(boundVariables, priorityVariables, null);
}
expr.visit(cc);
return cc.getCardinality();
}
@Override
protected CardinalityCalculator createCardinalityCalculator() {
return new HalyardCardinalityCalcualtor(Collections.emptySet(), Collections.emptySet(), null);
}
private class HalyardCardinalityCalcualtor extends CardinalityCalculator {
private Set<String> boundVars;
private final Set<String> priorityVariables;
private final Map<TupleExpr, Double> mapToUpdate;
public HalyardCardinalityCalcualtor(Set<String> boundVariables, Set<String> priorityVariables, Map<TupleExpr, Double> mapToUpdate) {
this.boundVars = boundVariables;
this.priorityVariables = priorityVariables;
this.mapToUpdate = mapToUpdate;
}
@Override
protected double getCardinality(StatementPattern sp) {
//always preffer HALYARD.SEARCH_TYPE object literals to move such statements higher in the joins tree
Var objectVar = sp.getObjectVar(); | // Path: strategy/src/main/java/com/msd/gin/halyard/vocab/HALYARD.java
// public final class HALYARD {
//
// HALYARD() {}
//
// private static final SimpleValueFactory SVF = SimpleValueFactory.getInstance();
//
// public static final String PREFIX = "halyard";
//
// public static final String NAMESPACE = "http://merck.github.io/Halyard/ns#";
//
// public static final IRI STATS_ROOT_NODE = SVF.createIRI(NAMESPACE, "statsRoot");
//
// public static final IRI STATS_GRAPH_CONTEXT = SVF.createIRI(NAMESPACE, "statsContext");
//
// public static final IRI SYSTEM_GRAPH_CONTEXT = SVF.createIRI(NAMESPACE, "system");
//
// public static final IRI NAMESPACE_PREFIX_PROPERTY = HALYARD.SVF.createIRI(NAMESPACE, "namespacePrefix");
//
// public final static IRI TABLE_NAME_PROPERTY = SVF.createIRI(NAMESPACE, "tableName");
//
// public final static IRI SPLITBITS_PROPERTY = SVF.createIRI(NAMESPACE, "splitBits");
//
// public final static IRI CREATE_TABLE_PROPERTY = SVF.createIRI(NAMESPACE, "createTable");
//
// public final static IRI PUSH_STRATEGY_PROPERTY = SVF.createIRI(NAMESPACE, "pushStrategy");
//
// public final static IRI EVALUATION_TIMEOUT_PROPERTY = SVF.createIRI(NAMESPACE, "evaluationTimeout");
//
// public final static IRI ELASTIC_INDEX_URL_PROPERTY = SVF.createIRI(NAMESPACE, "elasticIndexURL");
//
// public final static IRI SEARCH_TYPE = SVF.createIRI(NAMESPACE, "search");
//
// public final static IRI PARALLEL_SPLIT_FUNCTION = SVF.createIRI(NAMESPACE, "forkAndFilterBy");
//
// }
// Path: strategy/src/main/java/com/msd/gin/halyard/optimizers/HalyardEvaluationStatistics.java
import com.msd.gin.halyard.vocab.HALYARD;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.query.algebra.ArbitraryLengthPath;
import org.eclipse.rdf4j.query.algebra.BinaryTupleOperator;
import org.eclipse.rdf4j.query.algebra.BindingSetAssignment;
import org.eclipse.rdf4j.query.algebra.EmptySet;
import org.eclipse.rdf4j.query.algebra.Filter;
import org.eclipse.rdf4j.query.algebra.Join;
import org.eclipse.rdf4j.query.algebra.LeftJoin;
import org.eclipse.rdf4j.query.algebra.QueryModelNode;
import org.eclipse.rdf4j.query.algebra.Service;
import org.eclipse.rdf4j.query.algebra.SingletonSet;
import org.eclipse.rdf4j.query.algebra.StatementPattern;
import org.eclipse.rdf4j.query.algebra.TupleExpr;
import org.eclipse.rdf4j.query.algebra.UnaryTupleOperator;
import org.eclipse.rdf4j.query.algebra.Var;
import org.eclipse.rdf4j.query.algebra.ZeroLengthPath;
import org.eclipse.rdf4j.query.algebra.evaluation.impl.EvaluationStatistics;
import org.eclipse.rdf4j.query.algebra.evaluation.impl.ExternalSet;
public synchronized double getCardinality(TupleExpr expr, final Set<String> boundVariables, final Set<String> priorityVariables) {
if (cc == null) {
cc = new HalyardCardinalityCalcualtor(boundVariables, priorityVariables, null);
}
expr.visit(cc);
return cc.getCardinality();
}
@Override
protected CardinalityCalculator createCardinalityCalculator() {
return new HalyardCardinalityCalcualtor(Collections.emptySet(), Collections.emptySet(), null);
}
private class HalyardCardinalityCalcualtor extends CardinalityCalculator {
private Set<String> boundVars;
private final Set<String> priorityVariables;
private final Map<TupleExpr, Double> mapToUpdate;
public HalyardCardinalityCalcualtor(Set<String> boundVariables, Set<String> priorityVariables, Map<TupleExpr, Double> mapToUpdate) {
this.boundVars = boundVariables;
this.priorityVariables = priorityVariables;
this.mapToUpdate = mapToUpdate;
}
@Override
protected double getCardinality(StatementPattern sp) {
//always preffer HALYARD.SEARCH_TYPE object literals to move such statements higher in the joins tree
Var objectVar = sp.getObjectVar(); | if (objectVar.hasValue() && (objectVar.getValue() instanceof Literal) && HALYARD.SEARCH_TYPE.equals(((Literal) objectVar.getValue()).getDatatype())) { |
Merck/Halyard | strategy/src/test/java/com/msd/gin/halyard/optimizers/HalyardQueryJoinOptimizerTest.java | // Path: strategy/src/main/java/com/msd/gin/halyard/vocab/HALYARD.java
// public final class HALYARD {
//
// HALYARD() {}
//
// private static final SimpleValueFactory SVF = SimpleValueFactory.getInstance();
//
// public static final String PREFIX = "halyard";
//
// public static final String NAMESPACE = "http://merck.github.io/Halyard/ns#";
//
// public static final IRI STATS_ROOT_NODE = SVF.createIRI(NAMESPACE, "statsRoot");
//
// public static final IRI STATS_GRAPH_CONTEXT = SVF.createIRI(NAMESPACE, "statsContext");
//
// public static final IRI SYSTEM_GRAPH_CONTEXT = SVF.createIRI(NAMESPACE, "system");
//
// public static final IRI NAMESPACE_PREFIX_PROPERTY = HALYARD.SVF.createIRI(NAMESPACE, "namespacePrefix");
//
// public final static IRI TABLE_NAME_PROPERTY = SVF.createIRI(NAMESPACE, "tableName");
//
// public final static IRI SPLITBITS_PROPERTY = SVF.createIRI(NAMESPACE, "splitBits");
//
// public final static IRI CREATE_TABLE_PROPERTY = SVF.createIRI(NAMESPACE, "createTable");
//
// public final static IRI PUSH_STRATEGY_PROPERTY = SVF.createIRI(NAMESPACE, "pushStrategy");
//
// public final static IRI EVALUATION_TIMEOUT_PROPERTY = SVF.createIRI(NAMESPACE, "evaluationTimeout");
//
// public final static IRI ELASTIC_INDEX_URL_PROPERTY = SVF.createIRI(NAMESPACE, "elasticIndexURL");
//
// public final static IRI SEARCH_TYPE = SVF.createIRI(NAMESPACE, "search");
//
// public final static IRI PARALLEL_SPLIT_FUNCTION = SVF.createIRI(NAMESPACE, "forkAndFilterBy");
//
// }
| import com.msd.gin.halyard.vocab.HALYARD;
import org.eclipse.rdf4j.query.algebra.Join;
import org.eclipse.rdf4j.query.algebra.StatementPattern;
import org.eclipse.rdf4j.query.algebra.TupleExpr;
import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor;
import org.eclipse.rdf4j.query.parser.sparql.SPARQLParser;
import org.junit.Test;
import static org.junit.Assert.*; | /*
* Copyright 2018 Merck Sharp & Dohme Corp. a subsidiary of Merck & Co.,
* Inc., Kenilworth, NJ, USA.
*
* 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.msd.gin.halyard.optimizers;
/**
*
* @author Adam Sotona (MSD)
*/
public class HalyardQueryJoinOptimizerTest {
@Test
public void testQueryJoinOptimizer() {
final TupleExpr expr = new SPARQLParser().parseQuery("select * where {?a ?b ?c, \"1\".}", "http://baseuri/").getTupleExpr();
new HalyardQueryJoinOptimizer(new HalyardEvaluationStatistics(null, null)).optimize(expr, null, null);
expr.visit(new AbstractQueryModelVisitor<RuntimeException>(){
@Override
public void meet(Join node) throws RuntimeException {
assertTrue(expr.toString(), ((StatementPattern)node.getLeftArg()).getObjectVar().hasValue());
assertEquals(expr.toString(), "c", ((StatementPattern)node.getRightArg()).getObjectVar().getName());
}
});
}
@Test
public void testQueryJoinOptimizerWithSplitFunction() { | // Path: strategy/src/main/java/com/msd/gin/halyard/vocab/HALYARD.java
// public final class HALYARD {
//
// HALYARD() {}
//
// private static final SimpleValueFactory SVF = SimpleValueFactory.getInstance();
//
// public static final String PREFIX = "halyard";
//
// public static final String NAMESPACE = "http://merck.github.io/Halyard/ns#";
//
// public static final IRI STATS_ROOT_NODE = SVF.createIRI(NAMESPACE, "statsRoot");
//
// public static final IRI STATS_GRAPH_CONTEXT = SVF.createIRI(NAMESPACE, "statsContext");
//
// public static final IRI SYSTEM_GRAPH_CONTEXT = SVF.createIRI(NAMESPACE, "system");
//
// public static final IRI NAMESPACE_PREFIX_PROPERTY = HALYARD.SVF.createIRI(NAMESPACE, "namespacePrefix");
//
// public final static IRI TABLE_NAME_PROPERTY = SVF.createIRI(NAMESPACE, "tableName");
//
// public final static IRI SPLITBITS_PROPERTY = SVF.createIRI(NAMESPACE, "splitBits");
//
// public final static IRI CREATE_TABLE_PROPERTY = SVF.createIRI(NAMESPACE, "createTable");
//
// public final static IRI PUSH_STRATEGY_PROPERTY = SVF.createIRI(NAMESPACE, "pushStrategy");
//
// public final static IRI EVALUATION_TIMEOUT_PROPERTY = SVF.createIRI(NAMESPACE, "evaluationTimeout");
//
// public final static IRI ELASTIC_INDEX_URL_PROPERTY = SVF.createIRI(NAMESPACE, "elasticIndexURL");
//
// public final static IRI SEARCH_TYPE = SVF.createIRI(NAMESPACE, "search");
//
// public final static IRI PARALLEL_SPLIT_FUNCTION = SVF.createIRI(NAMESPACE, "forkAndFilterBy");
//
// }
// Path: strategy/src/test/java/com/msd/gin/halyard/optimizers/HalyardQueryJoinOptimizerTest.java
import com.msd.gin.halyard.vocab.HALYARD;
import org.eclipse.rdf4j.query.algebra.Join;
import org.eclipse.rdf4j.query.algebra.StatementPattern;
import org.eclipse.rdf4j.query.algebra.TupleExpr;
import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor;
import org.eclipse.rdf4j.query.parser.sparql.SPARQLParser;
import org.junit.Test;
import static org.junit.Assert.*;
/*
* Copyright 2018 Merck Sharp & Dohme Corp. a subsidiary of Merck & Co.,
* Inc., Kenilworth, NJ, USA.
*
* 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.msd.gin.halyard.optimizers;
/**
*
* @author Adam Sotona (MSD)
*/
public class HalyardQueryJoinOptimizerTest {
@Test
public void testQueryJoinOptimizer() {
final TupleExpr expr = new SPARQLParser().parseQuery("select * where {?a ?b ?c, \"1\".}", "http://baseuri/").getTupleExpr();
new HalyardQueryJoinOptimizer(new HalyardEvaluationStatistics(null, null)).optimize(expr, null, null);
expr.visit(new AbstractQueryModelVisitor<RuntimeException>(){
@Override
public void meet(Join node) throws RuntimeException {
assertTrue(expr.toString(), ((StatementPattern)node.getLeftArg()).getObjectVar().hasValue());
assertEquals(expr.toString(), "c", ((StatementPattern)node.getRightArg()).getObjectVar().getName());
}
});
}
@Test
public void testQueryJoinOptimizerWithSplitFunction() { | final TupleExpr expr = new SPARQLParser().parseQuery("select * where {?a a \"1\";?b ?d. filter (<" + HALYARD.PARALLEL_SPLIT_FUNCTION + ">(10, ?d))}", "http://baseuri/").getTupleExpr(); |
Merck/Halyard | strategy/src/main/java/com/msd/gin/halyard/optimizers/HalyardQueryJoinOptimizer.java | // Path: strategy/src/main/java/com/msd/gin/halyard/vocab/HALYARD.java
// public final class HALYARD {
//
// HALYARD() {}
//
// private static final SimpleValueFactory SVF = SimpleValueFactory.getInstance();
//
// public static final String PREFIX = "halyard";
//
// public static final String NAMESPACE = "http://merck.github.io/Halyard/ns#";
//
// public static final IRI STATS_ROOT_NODE = SVF.createIRI(NAMESPACE, "statsRoot");
//
// public static final IRI STATS_GRAPH_CONTEXT = SVF.createIRI(NAMESPACE, "statsContext");
//
// public static final IRI SYSTEM_GRAPH_CONTEXT = SVF.createIRI(NAMESPACE, "system");
//
// public static final IRI NAMESPACE_PREFIX_PROPERTY = HALYARD.SVF.createIRI(NAMESPACE, "namespacePrefix");
//
// public final static IRI TABLE_NAME_PROPERTY = SVF.createIRI(NAMESPACE, "tableName");
//
// public final static IRI SPLITBITS_PROPERTY = SVF.createIRI(NAMESPACE, "splitBits");
//
// public final static IRI CREATE_TABLE_PROPERTY = SVF.createIRI(NAMESPACE, "createTable");
//
// public final static IRI PUSH_STRATEGY_PROPERTY = SVF.createIRI(NAMESPACE, "pushStrategy");
//
// public final static IRI EVALUATION_TIMEOUT_PROPERTY = SVF.createIRI(NAMESPACE, "evaluationTimeout");
//
// public final static IRI ELASTIC_INDEX_URL_PROPERTY = SVF.createIRI(NAMESPACE, "elasticIndexURL");
//
// public final static IRI SEARCH_TYPE = SVF.createIRI(NAMESPACE, "search");
//
// public final static IRI PARALLEL_SPLIT_FUNCTION = SVF.createIRI(NAMESPACE, "forkAndFilterBy");
//
// }
| import org.eclipse.rdf4j.query.algebra.evaluation.impl.QueryJoinOptimizer;
import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor;
import com.msd.gin.halyard.vocab.HALYARD;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.rdf4j.query.BindingSet;
import org.eclipse.rdf4j.query.Dataset;
import org.eclipse.rdf4j.query.IncompatibleOperationException;
import org.eclipse.rdf4j.query.algebra.Extension;
import org.eclipse.rdf4j.query.algebra.FunctionCall;
import org.eclipse.rdf4j.query.algebra.Join;
import org.eclipse.rdf4j.query.algebra.TupleExpr;
import org.eclipse.rdf4j.query.algebra.ValueExpr;
import org.eclipse.rdf4j.query.algebra.Var; | /*
* Copyright 2018 Merck Sharp & Dohme Corp. a subsidiary of Merck & Co.,
* Inc., Kenilworth, NJ, USA.
*
* 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.msd.gin.halyard.optimizers;
/**
*
* @author Adam Sotona (MSD)
*/
public final class HalyardQueryJoinOptimizer extends QueryJoinOptimizer {
public HalyardQueryJoinOptimizer(HalyardEvaluationStatistics statistics) {
super(statistics);
}
@Override
public void optimize(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings) {
final Set<String> parallelSplitBounds = new HashSet<>();
tupleExpr.visit(new AbstractQueryModelVisitor<IncompatibleOperationException>() {
@Override
public void meet(FunctionCall node) throws IncompatibleOperationException { | // Path: strategy/src/main/java/com/msd/gin/halyard/vocab/HALYARD.java
// public final class HALYARD {
//
// HALYARD() {}
//
// private static final SimpleValueFactory SVF = SimpleValueFactory.getInstance();
//
// public static final String PREFIX = "halyard";
//
// public static final String NAMESPACE = "http://merck.github.io/Halyard/ns#";
//
// public static final IRI STATS_ROOT_NODE = SVF.createIRI(NAMESPACE, "statsRoot");
//
// public static final IRI STATS_GRAPH_CONTEXT = SVF.createIRI(NAMESPACE, "statsContext");
//
// public static final IRI SYSTEM_GRAPH_CONTEXT = SVF.createIRI(NAMESPACE, "system");
//
// public static final IRI NAMESPACE_PREFIX_PROPERTY = HALYARD.SVF.createIRI(NAMESPACE, "namespacePrefix");
//
// public final static IRI TABLE_NAME_PROPERTY = SVF.createIRI(NAMESPACE, "tableName");
//
// public final static IRI SPLITBITS_PROPERTY = SVF.createIRI(NAMESPACE, "splitBits");
//
// public final static IRI CREATE_TABLE_PROPERTY = SVF.createIRI(NAMESPACE, "createTable");
//
// public final static IRI PUSH_STRATEGY_PROPERTY = SVF.createIRI(NAMESPACE, "pushStrategy");
//
// public final static IRI EVALUATION_TIMEOUT_PROPERTY = SVF.createIRI(NAMESPACE, "evaluationTimeout");
//
// public final static IRI ELASTIC_INDEX_URL_PROPERTY = SVF.createIRI(NAMESPACE, "elasticIndexURL");
//
// public final static IRI SEARCH_TYPE = SVF.createIRI(NAMESPACE, "search");
//
// public final static IRI PARALLEL_SPLIT_FUNCTION = SVF.createIRI(NAMESPACE, "forkAndFilterBy");
//
// }
// Path: strategy/src/main/java/com/msd/gin/halyard/optimizers/HalyardQueryJoinOptimizer.java
import org.eclipse.rdf4j.query.algebra.evaluation.impl.QueryJoinOptimizer;
import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor;
import com.msd.gin.halyard.vocab.HALYARD;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.rdf4j.query.BindingSet;
import org.eclipse.rdf4j.query.Dataset;
import org.eclipse.rdf4j.query.IncompatibleOperationException;
import org.eclipse.rdf4j.query.algebra.Extension;
import org.eclipse.rdf4j.query.algebra.FunctionCall;
import org.eclipse.rdf4j.query.algebra.Join;
import org.eclipse.rdf4j.query.algebra.TupleExpr;
import org.eclipse.rdf4j.query.algebra.ValueExpr;
import org.eclipse.rdf4j.query.algebra.Var;
/*
* Copyright 2018 Merck Sharp & Dohme Corp. a subsidiary of Merck & Co.,
* Inc., Kenilworth, NJ, USA.
*
* 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.msd.gin.halyard.optimizers;
/**
*
* @author Adam Sotona (MSD)
*/
public final class HalyardQueryJoinOptimizer extends QueryJoinOptimizer {
public HalyardQueryJoinOptimizer(HalyardEvaluationStatistics statistics) {
super(statistics);
}
@Override
public void optimize(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings) {
final Set<String> parallelSplitBounds = new HashSet<>();
tupleExpr.visit(new AbstractQueryModelVisitor<IncompatibleOperationException>() {
@Override
public void meet(FunctionCall node) throws IncompatibleOperationException { | if (HALYARD.PARALLEL_SPLIT_FUNCTION.toString().equals(node.getURI())) { |
Merck/Halyard | sail/src/test/java/com/msd/gin/halyard/sail/HBaseSailAddRemoveTest.java | // Path: common/src/test/java/com/msd/gin/halyard/common/HBaseServerTestInstance.java
// public class HBaseServerTestInstance {
//
// private static Configuration conf = null;
//
// public static synchronized Configuration getInstanceConfig() throws Exception {
// if (conf == null) {
// File zooRoot = File.createTempFile("hbase-zookeeper", "");
// zooRoot.delete();
// ZooKeeperServer zookeper = new ZooKeeperServer(zooRoot, zooRoot, 2000);
// ServerCnxnFactory factory = ServerCnxnFactory.createFactory(new InetSocketAddress("localhost", 0), 5000);
// factory.startup(zookeper);
//
// YarnConfiguration yconf = new YarnConfiguration();
// String argLine = System.getProperty("argLine");
// if (argLine != null) {
// yconf.set("yarn.app.mapreduce.am.command-opts", argLine.replace("jacoco.exec", "jacocoMR.exec"));
// }
// yconf.setBoolean(MRConfig.MAPREDUCE_MINICLUSTER_CONTROL_RESOURCE_MONITORING, false);
// yconf.setClass(YarnConfiguration.RM_SCHEDULER, FifoScheduler.class, ResourceScheduler.class);
// MiniMRYarnCluster miniCluster = new MiniMRYarnCluster("testCluster");
// miniCluster.init(yconf);
// String resourceManagerLink = yconf.get(YarnConfiguration.RM_ADDRESS);
// yconf.setBoolean(MRJobConfig.JOB_UBERTASK_ENABLE, true);
// miniCluster.start();
// miniCluster.waitForNodeManagersToConnect(10000);
// // following condition set in MiniYarnCluster:273
// while (resourceManagerLink.endsWith(":0")) {
// Thread.sleep(100);
// resourceManagerLink = yconf.get(YarnConfiguration.RM_ADDRESS);
// }
//
// File hbaseRoot = File.createTempFile("hbase-root", "");
// hbaseRoot.delete();
// conf = HBaseConfiguration.create(miniCluster.getConfig());
// conf.set(HConstants.HBASE_DIR, hbaseRoot.toURI().toURL().toString());
// conf.setInt(HConstants.ZOOKEEPER_CLIENT_PORT, factory.getLocalPort());
// conf.set("hbase.master.hostname", "localhost");
// conf.set("hbase.regionserver.hostname", "localhost");
// conf.setInt("hbase.master.info.port", -1);
// conf.set("hbase.fs.tmp.dir", new File(System.getProperty("java.io.tmpdir")).toURI().toURL().toString());
// LocalHBaseCluster cluster = new LocalHBaseCluster(conf);
// cluster.startup();
// }
// return new Configuration(conf);
// }
// }
| import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import com.msd.gin.halyard.common.HBaseServerTestInstance;
import java.util.Arrays;
import java.util.Collection;
import org.eclipse.rdf4j.common.iteration.CloseableIteration;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.Value;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.sail.SailException;
import org.junit.AfterClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.BeforeClass; | /*
* Copyright 2016 Merck Sharp & Dohme Corp. a subsidiary of Merck & Co.,
* Inc., Kenilworth, NJ, USA.
*
* 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.msd.gin.halyard.sail;
/**
*
* @author Adam Sotona (MSD)
*/
@RunWith(Parameterized.class)
public class HBaseSailAddRemoveTest {
private static final Resource SUBJ = SimpleValueFactory.getInstance().createIRI("http://whatever/subject/");
private static final IRI PRED = SimpleValueFactory.getInstance().createIRI("http://whatever/pred/");
private static final Value OBJ = SimpleValueFactory.getInstance().createLiteral("whatever literal");
private static final IRI CONTEXT = SimpleValueFactory.getInstance().createIRI("http://whatever/cont/");
private static HBaseSail explicitSail;
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{null, null, null},
{SUBJ, null, null},
{null, PRED, null},
{null, null, OBJ},
{SUBJ, PRED, null},
{null, PRED, OBJ},
{SUBJ, null, OBJ},
{SUBJ, PRED, OBJ},
});
}
@BeforeClass
public static void setup() throws Exception { | // Path: common/src/test/java/com/msd/gin/halyard/common/HBaseServerTestInstance.java
// public class HBaseServerTestInstance {
//
// private static Configuration conf = null;
//
// public static synchronized Configuration getInstanceConfig() throws Exception {
// if (conf == null) {
// File zooRoot = File.createTempFile("hbase-zookeeper", "");
// zooRoot.delete();
// ZooKeeperServer zookeper = new ZooKeeperServer(zooRoot, zooRoot, 2000);
// ServerCnxnFactory factory = ServerCnxnFactory.createFactory(new InetSocketAddress("localhost", 0), 5000);
// factory.startup(zookeper);
//
// YarnConfiguration yconf = new YarnConfiguration();
// String argLine = System.getProperty("argLine");
// if (argLine != null) {
// yconf.set("yarn.app.mapreduce.am.command-opts", argLine.replace("jacoco.exec", "jacocoMR.exec"));
// }
// yconf.setBoolean(MRConfig.MAPREDUCE_MINICLUSTER_CONTROL_RESOURCE_MONITORING, false);
// yconf.setClass(YarnConfiguration.RM_SCHEDULER, FifoScheduler.class, ResourceScheduler.class);
// MiniMRYarnCluster miniCluster = new MiniMRYarnCluster("testCluster");
// miniCluster.init(yconf);
// String resourceManagerLink = yconf.get(YarnConfiguration.RM_ADDRESS);
// yconf.setBoolean(MRJobConfig.JOB_UBERTASK_ENABLE, true);
// miniCluster.start();
// miniCluster.waitForNodeManagersToConnect(10000);
// // following condition set in MiniYarnCluster:273
// while (resourceManagerLink.endsWith(":0")) {
// Thread.sleep(100);
// resourceManagerLink = yconf.get(YarnConfiguration.RM_ADDRESS);
// }
//
// File hbaseRoot = File.createTempFile("hbase-root", "");
// hbaseRoot.delete();
// conf = HBaseConfiguration.create(miniCluster.getConfig());
// conf.set(HConstants.HBASE_DIR, hbaseRoot.toURI().toURL().toString());
// conf.setInt(HConstants.ZOOKEEPER_CLIENT_PORT, factory.getLocalPort());
// conf.set("hbase.master.hostname", "localhost");
// conf.set("hbase.regionserver.hostname", "localhost");
// conf.setInt("hbase.master.info.port", -1);
// conf.set("hbase.fs.tmp.dir", new File(System.getProperty("java.io.tmpdir")).toURI().toURL().toString());
// LocalHBaseCluster cluster = new LocalHBaseCluster(conf);
// cluster.startup();
// }
// return new Configuration(conf);
// }
// }
// Path: sail/src/test/java/com/msd/gin/halyard/sail/HBaseSailAddRemoveTest.java
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import com.msd.gin.halyard.common.HBaseServerTestInstance;
import java.util.Arrays;
import java.util.Collection;
import org.eclipse.rdf4j.common.iteration.CloseableIteration;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.Value;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.sail.SailException;
import org.junit.AfterClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.BeforeClass;
/*
* Copyright 2016 Merck Sharp & Dohme Corp. a subsidiary of Merck & Co.,
* Inc., Kenilworth, NJ, USA.
*
* 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.msd.gin.halyard.sail;
/**
*
* @author Adam Sotona (MSD)
*/
@RunWith(Parameterized.class)
public class HBaseSailAddRemoveTest {
private static final Resource SUBJ = SimpleValueFactory.getInstance().createIRI("http://whatever/subject/");
private static final IRI PRED = SimpleValueFactory.getInstance().createIRI("http://whatever/pred/");
private static final Value OBJ = SimpleValueFactory.getInstance().createLiteral("whatever literal");
private static final IRI CONTEXT = SimpleValueFactory.getInstance().createIRI("http://whatever/cont/");
private static HBaseSail explicitSail;
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{null, null, null},
{SUBJ, null, null},
{null, PRED, null},
{null, null, OBJ},
{SUBJ, PRED, null},
{null, PRED, OBJ},
{SUBJ, null, OBJ},
{SUBJ, PRED, OBJ},
});
}
@BeforeClass
public static void setup() throws Exception { | explicitSail = new HBaseSail(HBaseServerTestInstance.getInstanceConfig(), "testAddRemove", true, 0, true, 0, null, null); |
Merck/Halyard | sail/src/test/java/com/msd/gin/halyard/sail/SES2154SubselectOptionalTest.java | // Path: common/src/test/java/com/msd/gin/halyard/common/HBaseServerTestInstance.java
// public class HBaseServerTestInstance {
//
// private static Configuration conf = null;
//
// public static synchronized Configuration getInstanceConfig() throws Exception {
// if (conf == null) {
// File zooRoot = File.createTempFile("hbase-zookeeper", "");
// zooRoot.delete();
// ZooKeeperServer zookeper = new ZooKeeperServer(zooRoot, zooRoot, 2000);
// ServerCnxnFactory factory = ServerCnxnFactory.createFactory(new InetSocketAddress("localhost", 0), 5000);
// factory.startup(zookeper);
//
// YarnConfiguration yconf = new YarnConfiguration();
// String argLine = System.getProperty("argLine");
// if (argLine != null) {
// yconf.set("yarn.app.mapreduce.am.command-opts", argLine.replace("jacoco.exec", "jacocoMR.exec"));
// }
// yconf.setBoolean(MRConfig.MAPREDUCE_MINICLUSTER_CONTROL_RESOURCE_MONITORING, false);
// yconf.setClass(YarnConfiguration.RM_SCHEDULER, FifoScheduler.class, ResourceScheduler.class);
// MiniMRYarnCluster miniCluster = new MiniMRYarnCluster("testCluster");
// miniCluster.init(yconf);
// String resourceManagerLink = yconf.get(YarnConfiguration.RM_ADDRESS);
// yconf.setBoolean(MRJobConfig.JOB_UBERTASK_ENABLE, true);
// miniCluster.start();
// miniCluster.waitForNodeManagersToConnect(10000);
// // following condition set in MiniYarnCluster:273
// while (resourceManagerLink.endsWith(":0")) {
// Thread.sleep(100);
// resourceManagerLink = yconf.get(YarnConfiguration.RM_ADDRESS);
// }
//
// File hbaseRoot = File.createTempFile("hbase-root", "");
// hbaseRoot.delete();
// conf = HBaseConfiguration.create(miniCluster.getConfig());
// conf.set(HConstants.HBASE_DIR, hbaseRoot.toURI().toURL().toString());
// conf.setInt(HConstants.ZOOKEEPER_CLIENT_PORT, factory.getLocalPort());
// conf.set("hbase.master.hostname", "localhost");
// conf.set("hbase.regionserver.hostname", "localhost");
// conf.setInt("hbase.master.info.port", -1);
// conf.set("hbase.fs.tmp.dir", new File(System.getProperty("java.io.tmpdir")).toURI().toURL().toString());
// LocalHBaseCluster cluster = new LocalHBaseCluster(conf);
// cluster.startup();
// }
// return new Configuration(conf);
// }
// }
| import com.msd.gin.halyard.common.HBaseServerTestInstance;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.model.vocabulary.RDF;
import org.eclipse.rdf4j.query.QueryLanguage;
import org.eclipse.rdf4j.query.TupleQueryResult;
import org.eclipse.rdf4j.repository.sail.SailRepository;
import static org.junit.Assert.assertEquals;
import org.junit.Test; | /*
* Copyright 2018 Merck Sharp & Dohme Corp. a subsidiary of Merck & Co.,
* Inc., Kenilworth, NJ, USA.
*
* 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.msd.gin.halyard.sail;
/**
*
* @author Adam Sotona (MSD)
*/
public class SES2154SubselectOptionalTest {
@Test
public void testSES2154SubselectOptional() throws Exception { | // Path: common/src/test/java/com/msd/gin/halyard/common/HBaseServerTestInstance.java
// public class HBaseServerTestInstance {
//
// private static Configuration conf = null;
//
// public static synchronized Configuration getInstanceConfig() throws Exception {
// if (conf == null) {
// File zooRoot = File.createTempFile("hbase-zookeeper", "");
// zooRoot.delete();
// ZooKeeperServer zookeper = new ZooKeeperServer(zooRoot, zooRoot, 2000);
// ServerCnxnFactory factory = ServerCnxnFactory.createFactory(new InetSocketAddress("localhost", 0), 5000);
// factory.startup(zookeper);
//
// YarnConfiguration yconf = new YarnConfiguration();
// String argLine = System.getProperty("argLine");
// if (argLine != null) {
// yconf.set("yarn.app.mapreduce.am.command-opts", argLine.replace("jacoco.exec", "jacocoMR.exec"));
// }
// yconf.setBoolean(MRConfig.MAPREDUCE_MINICLUSTER_CONTROL_RESOURCE_MONITORING, false);
// yconf.setClass(YarnConfiguration.RM_SCHEDULER, FifoScheduler.class, ResourceScheduler.class);
// MiniMRYarnCluster miniCluster = new MiniMRYarnCluster("testCluster");
// miniCluster.init(yconf);
// String resourceManagerLink = yconf.get(YarnConfiguration.RM_ADDRESS);
// yconf.setBoolean(MRJobConfig.JOB_UBERTASK_ENABLE, true);
// miniCluster.start();
// miniCluster.waitForNodeManagersToConnect(10000);
// // following condition set in MiniYarnCluster:273
// while (resourceManagerLink.endsWith(":0")) {
// Thread.sleep(100);
// resourceManagerLink = yconf.get(YarnConfiguration.RM_ADDRESS);
// }
//
// File hbaseRoot = File.createTempFile("hbase-root", "");
// hbaseRoot.delete();
// conf = HBaseConfiguration.create(miniCluster.getConfig());
// conf.set(HConstants.HBASE_DIR, hbaseRoot.toURI().toURL().toString());
// conf.setInt(HConstants.ZOOKEEPER_CLIENT_PORT, factory.getLocalPort());
// conf.set("hbase.master.hostname", "localhost");
// conf.set("hbase.regionserver.hostname", "localhost");
// conf.setInt("hbase.master.info.port", -1);
// conf.set("hbase.fs.tmp.dir", new File(System.getProperty("java.io.tmpdir")).toURI().toURL().toString());
// LocalHBaseCluster cluster = new LocalHBaseCluster(conf);
// cluster.startup();
// }
// return new Configuration(conf);
// }
// }
// Path: sail/src/test/java/com/msd/gin/halyard/sail/SES2154SubselectOptionalTest.java
import com.msd.gin.halyard.common.HBaseServerTestInstance;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.model.vocabulary.RDF;
import org.eclipse.rdf4j.query.QueryLanguage;
import org.eclipse.rdf4j.query.TupleQueryResult;
import org.eclipse.rdf4j.repository.sail.SailRepository;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/*
* Copyright 2018 Merck Sharp & Dohme Corp. a subsidiary of Merck & Co.,
* Inc., Kenilworth, NJ, USA.
*
* 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.msd.gin.halyard.sail;
/**
*
* @author Adam Sotona (MSD)
*/
public class SES2154SubselectOptionalTest {
@Test
public void testSES2154SubselectOptional() throws Exception { | HBaseSail sail = new HBaseSail(HBaseServerTestInstance.getInstanceConfig(), "SES2154SubselectOptionaltable", true, 0, true, 0, null, null); |
Merck/Halyard | tools/src/main/java/com/msd/gin/halyard/tools/HalyardBulkExport.java | // Path: strategy/src/main/java/com/msd/gin/halyard/vocab/HALYARD.java
// public final static IRI PARALLEL_SPLIT_FUNCTION = SVF.createIRI(NAMESPACE, "forkAndFilterBy");
| import com.yammer.metrics.core.Gauge;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.logging.Level;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.codec.binary.Base64;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.hbase.protobuf.generated.AuthenticationProtos;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
import org.apache.htrace.Trace;
import org.eclipse.rdf4j.query.algebra.evaluation.function.Function;
import org.eclipse.rdf4j.query.algebra.evaluation.function.FunctionRegistry;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.RDFParser;
import org.eclipse.rdf4j.rio.Rio;
import org.eclipse.rdf4j.rio.helpers.AbstractRDFHandler;
import org.eclipse.rdf4j.rio.ntriples.NTriplesUtil;
import static com.msd.gin.halyard.vocab.HALYARD.PARALLEL_SPLIT_FUNCTION; | HalyardExport.StatusLog log = new HalyardExport.StatusLog() {
@Override
public void tick() {
context.progress();
}
@Override
public void logStatus(String status) {
context.setStatus(name + ": " + status);
}
};
Configuration cfg = context.getConfiguration();
String[] props = cfg.getStrings(JDBC_PROPERTIES);
if (props != null) {
for (int i=0; i<props.length; i++) {
props[i] = new String(Base64.decodeBase64(props[i]), StandardCharsets.UTF_8);
}
}
HalyardExport.export(cfg, log, cfg.get(SOURCE), query, MessageFormat.format(cfg.get(TARGET), bName, qis.getRepeatIndex()), cfg.get(JDBC_DRIVER), cfg.get(JDBC_CLASSPATH), props, false, cfg.get(HalyardBulkUpdate.ELASTIC_INDEX_URL));
} catch (Exception e) {
throw new IOException(e);
} finally {
FunctionRegistry.getInstance().remove(fn);
}
}
}
public HalyardBulkExport() {
super("bulkexport",
"Halyard Bulk Export is a MapReduce application that executes multiple Halyard Exports in MapReduce framework. "
+ "Query file name (without extension) can be used in the target URL pattern. Order of queries execution is not guaranteed. " | // Path: strategy/src/main/java/com/msd/gin/halyard/vocab/HALYARD.java
// public final static IRI PARALLEL_SPLIT_FUNCTION = SVF.createIRI(NAMESPACE, "forkAndFilterBy");
// Path: tools/src/main/java/com/msd/gin/halyard/tools/HalyardBulkExport.java
import com.yammer.metrics.core.Gauge;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.logging.Level;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.codec.binary.Base64;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.hbase.protobuf.generated.AuthenticationProtos;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
import org.apache.htrace.Trace;
import org.eclipse.rdf4j.query.algebra.evaluation.function.Function;
import org.eclipse.rdf4j.query.algebra.evaluation.function.FunctionRegistry;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.RDFParser;
import org.eclipse.rdf4j.rio.Rio;
import org.eclipse.rdf4j.rio.helpers.AbstractRDFHandler;
import org.eclipse.rdf4j.rio.ntriples.NTriplesUtil;
import static com.msd.gin.halyard.vocab.HALYARD.PARALLEL_SPLIT_FUNCTION;
HalyardExport.StatusLog log = new HalyardExport.StatusLog() {
@Override
public void tick() {
context.progress();
}
@Override
public void logStatus(String status) {
context.setStatus(name + ": " + status);
}
};
Configuration cfg = context.getConfiguration();
String[] props = cfg.getStrings(JDBC_PROPERTIES);
if (props != null) {
for (int i=0; i<props.length; i++) {
props[i] = new String(Base64.decodeBase64(props[i]), StandardCharsets.UTF_8);
}
}
HalyardExport.export(cfg, log, cfg.get(SOURCE), query, MessageFormat.format(cfg.get(TARGET), bName, qis.getRepeatIndex()), cfg.get(JDBC_DRIVER), cfg.get(JDBC_CLASSPATH), props, false, cfg.get(HalyardBulkUpdate.ELASTIC_INDEX_URL));
} catch (Exception e) {
throw new IOException(e);
} finally {
FunctionRegistry.getInstance().remove(fn);
}
}
}
public HalyardBulkExport() {
super("bulkexport",
"Halyard Bulk Export is a MapReduce application that executes multiple Halyard Exports in MapReduce framework. "
+ "Query file name (without extension) can be used in the target URL pattern. Order of queries execution is not guaranteed. " | + "Another internal level of parallelisation is done using a custom SPARQL function halyard:" + PARALLEL_SPLIT_FUNCTION.toString() + "(<constant_number_of_forks>, ?a_binding, ...). " |
amitshekhariitbhu/Fast-Android-Networking | rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/Rx2GetObjectApiTest.java | // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
//
// Path: rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/model/User.java
// public class User {
//
// public String firstName;
// public String lastName;
//
// }
| import java.util.concurrent.atomic.AtomicReference;
import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import static java.util.concurrent.TimeUnit.SECONDS;
import android.app.Application;
import android.test.ApplicationTestCase;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.error.ANError;
import com.rx2androidnetworking.model.User;
import org.junit.Rule;
import java.util.List;
import java.util.concurrent.CountDownLatch; | /*
*
* * Copyright (C) 2016 Amit Shekhar
* * Copyright (C) 2011 Android Open Source Project
* *
* * 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.rx2androidnetworking;
/**
* Created by amitshekhar on 26/04/17.
*/
public class Rx2GetObjectApiTest extends ApplicationTestCase<Application> {
@Rule
public final MockWebServer server = new MockWebServer();
public Rx2GetObjectApiTest() {
super(Application.class);
}
@Override
public void setUp() throws Exception {
super.setUp();
createApplication();
}
public void testObjectGetRequest() throws InterruptedException {
server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}"));
final AtomicReference<String> firstNameRef = new AtomicReference<>();
final AtomicReference<String> lastNameRef = new AtomicReference<>();
final AtomicReference<Boolean> isSubscribedRef = new AtomicReference<>();
final AtomicReference<Boolean> isCompletedRef = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(2);
Rx2AndroidNetworking.get(server.url("/").toString())
.build() | // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
//
// Path: rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/model/User.java
// public class User {
//
// public String firstName;
// public String lastName;
//
// }
// Path: rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/Rx2GetObjectApiTest.java
import java.util.concurrent.atomic.AtomicReference;
import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import static java.util.concurrent.TimeUnit.SECONDS;
import android.app.Application;
import android.test.ApplicationTestCase;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.error.ANError;
import com.rx2androidnetworking.model.User;
import org.junit.Rule;
import java.util.List;
import java.util.concurrent.CountDownLatch;
/*
*
* * Copyright (C) 2016 Amit Shekhar
* * Copyright (C) 2011 Android Open Source Project
* *
* * 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.rx2androidnetworking;
/**
* Created by amitshekhar on 26/04/17.
*/
public class Rx2GetObjectApiTest extends ApplicationTestCase<Application> {
@Rule
public final MockWebServer server = new MockWebServer();
public Rx2GetObjectApiTest() {
super(Application.class);
}
@Override
public void setUp() throws Exception {
super.setUp();
createApplication();
}
public void testObjectGetRequest() throws InterruptedException {
server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}"));
final AtomicReference<String> firstNameRef = new AtomicReference<>();
final AtomicReference<String> lastNameRef = new AtomicReference<>();
final AtomicReference<Boolean> isSubscribedRef = new AtomicReference<>();
final AtomicReference<Boolean> isCompletedRef = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(2);
Rx2AndroidNetworking.get(server.url("/").toString())
.build() | .getObjectObservable(User.class) |
amitshekhariitbhu/Fast-Android-Networking | rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/Rx2GetObjectApiTest.java | // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
//
// Path: rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/model/User.java
// public class User {
//
// public String firstName;
// public String lastName;
//
// }
| import java.util.concurrent.atomic.AtomicReference;
import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import static java.util.concurrent.TimeUnit.SECONDS;
import android.app.Application;
import android.test.ApplicationTestCase;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.error.ANError;
import com.rx2androidnetworking.model.User;
import org.junit.Rule;
import java.util.List;
import java.util.concurrent.CountDownLatch; | .subscribe(new Observer<User>() {
@Override
public void onSubscribe(Disposable d) {
isSubscribedRef.set(true);
}
@Override
public void onNext(User user) {
assertTrue(false);
}
@Override
public void onError(Throwable e) {
ANError anError = (ANError) e;
errorBodyRef.set(anError.getErrorBody());
errorDetailRef.set(anError.getErrorDetail());
errorCodeRef.set(anError.getErrorCode());
latch.countDown();
}
@Override
public void onComplete() {
assertTrue(false);
}
});
assertTrue(latch.await(2, SECONDS));
assertTrue(isSubscribedRef.get());
| // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
//
// Path: rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/model/User.java
// public class User {
//
// public String firstName;
// public String lastName;
//
// }
// Path: rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/Rx2GetObjectApiTest.java
import java.util.concurrent.atomic.AtomicReference;
import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import static java.util.concurrent.TimeUnit.SECONDS;
import android.app.Application;
import android.test.ApplicationTestCase;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.error.ANError;
import com.rx2androidnetworking.model.User;
import org.junit.Rule;
import java.util.List;
import java.util.concurrent.CountDownLatch;
.subscribe(new Observer<User>() {
@Override
public void onSubscribe(Disposable d) {
isSubscribedRef.set(true);
}
@Override
public void onNext(User user) {
assertTrue(false);
}
@Override
public void onError(Throwable e) {
ANError anError = (ANError) e;
errorBodyRef.set(anError.getErrorBody());
errorDetailRef.set(anError.getErrorDetail());
errorCodeRef.set(anError.getErrorCode());
latch.countDown();
}
@Override
public void onComplete() {
assertTrue(false);
}
});
assertTrue(latch.await(2, SECONDS));
assertTrue(isSubscribedRef.get());
| assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); |
amitshekhariitbhu/Fast-Android-Networking | rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/Rx2GetStringApiTest.java | // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
| import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import static java.util.concurrent.TimeUnit.SECONDS;
import android.app.Application;
import android.test.ApplicationTestCase;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.error.ANError;
import org.junit.Rule;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference; | .subscribe(new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
isSubscribedRef.set(true);
}
@Override
public void onNext(String response) {
assertTrue(false);
}
@Override
public void onError(Throwable e) {
ANError anError = (ANError) e;
errorBodyRef.set(anError.getErrorBody());
errorDetailRef.set(anError.getErrorDetail());
errorCodeRef.set(anError.getErrorCode());
latch.countDown();
}
@Override
public void onComplete() {
assertTrue(false);
}
});
assertTrue(latch.await(2, SECONDS));
assertTrue(isSubscribedRef.get());
| // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
// Path: rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/Rx2GetStringApiTest.java
import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import static java.util.concurrent.TimeUnit.SECONDS;
import android.app.Application;
import android.test.ApplicationTestCase;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.error.ANError;
import org.junit.Rule;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
.subscribe(new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
isSubscribedRef.set(true);
}
@Override
public void onNext(String response) {
assertTrue(false);
}
@Override
public void onError(Throwable e) {
ANError anError = (ANError) e;
errorBodyRef.set(anError.getErrorBody());
errorDetailRef.set(anError.getErrorDetail());
errorCodeRef.set(anError.getErrorCode());
latch.countDown();
}
@Override
public void onComplete() {
assertTrue(false);
}
});
assertTrue(latch.await(2, SECONDS));
assertTrue(isSubscribedRef.get());
| assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); |
amitshekhariitbhu/Fast-Android-Networking | rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/Rx2PostObjectApiTest.java | // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
//
// Path: rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/model/User.java
// public class User {
//
// public String firstName;
// public String lastName;
//
// }
| import java.util.concurrent.atomic.AtomicReference;
import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import static java.util.concurrent.TimeUnit.SECONDS;
import android.app.Application;
import android.test.ApplicationTestCase;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.error.ANError;
import com.rx2androidnetworking.model.User;
import org.junit.Rule;
import java.util.List;
import java.util.concurrent.CountDownLatch; | /*
*
* * Copyright (C) 2016 Amit Shekhar
* * Copyright (C) 2011 Android Open Source Project
* *
* * 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.rx2androidnetworking;
/**
* Created by amitshekhar on 28/04/17.
*/
public class Rx2PostObjectApiTest extends ApplicationTestCase<Application> {
@Rule
public final MockWebServer server = new MockWebServer();
public Rx2PostObjectApiTest() {
super(Application.class);
}
@Override
public void setUp() throws Exception {
super.setUp();
createApplication();
}
public void testObjectPostRequest() throws InterruptedException {
server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}"));
final AtomicReference<String> firstNameRef = new AtomicReference<>();
final AtomicReference<String> lastNameRef = new AtomicReference<>();
final AtomicReference<Boolean> isSubscribedRef = new AtomicReference<>();
final AtomicReference<Boolean> isCompletedRef = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(2);
Rx2AndroidNetworking.post(server.url("/").toString())
.addBodyParameter("fistName", "Amit")
.addBodyParameter("lastName", "Shekhar")
.build() | // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
//
// Path: rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/model/User.java
// public class User {
//
// public String firstName;
// public String lastName;
//
// }
// Path: rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/Rx2PostObjectApiTest.java
import java.util.concurrent.atomic.AtomicReference;
import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import static java.util.concurrent.TimeUnit.SECONDS;
import android.app.Application;
import android.test.ApplicationTestCase;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.error.ANError;
import com.rx2androidnetworking.model.User;
import org.junit.Rule;
import java.util.List;
import java.util.concurrent.CountDownLatch;
/*
*
* * Copyright (C) 2016 Amit Shekhar
* * Copyright (C) 2011 Android Open Source Project
* *
* * 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.rx2androidnetworking;
/**
* Created by amitshekhar on 28/04/17.
*/
public class Rx2PostObjectApiTest extends ApplicationTestCase<Application> {
@Rule
public final MockWebServer server = new MockWebServer();
public Rx2PostObjectApiTest() {
super(Application.class);
}
@Override
public void setUp() throws Exception {
super.setUp();
createApplication();
}
public void testObjectPostRequest() throws InterruptedException {
server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}"));
final AtomicReference<String> firstNameRef = new AtomicReference<>();
final AtomicReference<String> lastNameRef = new AtomicReference<>();
final AtomicReference<Boolean> isSubscribedRef = new AtomicReference<>();
final AtomicReference<Boolean> isCompletedRef = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(2);
Rx2AndroidNetworking.post(server.url("/").toString())
.addBodyParameter("fistName", "Amit")
.addBodyParameter("lastName", "Shekhar")
.build() | .getObjectObservable(User.class) |
amitshekhariitbhu/Fast-Android-Networking | rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/Rx2PostObjectApiTest.java | // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
//
// Path: rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/model/User.java
// public class User {
//
// public String firstName;
// public String lastName;
//
// }
| import java.util.concurrent.atomic.AtomicReference;
import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import static java.util.concurrent.TimeUnit.SECONDS;
import android.app.Application;
import android.test.ApplicationTestCase;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.error.ANError;
import com.rx2androidnetworking.model.User;
import org.junit.Rule;
import java.util.List;
import java.util.concurrent.CountDownLatch; | .subscribe(new Observer<User>() {
@Override
public void onSubscribe(Disposable d) {
isSubscribedRef.set(true);
}
@Override
public void onNext(User user) {
assertTrue(false);
}
@Override
public void onError(Throwable e) {
ANError anError = (ANError) e;
errorBodyRef.set(anError.getErrorBody());
errorDetailRef.set(anError.getErrorDetail());
errorCodeRef.set(anError.getErrorCode());
latch.countDown();
}
@Override
public void onComplete() {
assertTrue(false);
}
});
assertTrue(latch.await(2, SECONDS));
assertTrue(isSubscribedRef.get());
| // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
//
// Path: rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/model/User.java
// public class User {
//
// public String firstName;
// public String lastName;
//
// }
// Path: rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/Rx2PostObjectApiTest.java
import java.util.concurrent.atomic.AtomicReference;
import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import static java.util.concurrent.TimeUnit.SECONDS;
import android.app.Application;
import android.test.ApplicationTestCase;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.error.ANError;
import com.rx2androidnetworking.model.User;
import org.junit.Rule;
import java.util.List;
import java.util.concurrent.CountDownLatch;
.subscribe(new Observer<User>() {
@Override
public void onSubscribe(Disposable d) {
isSubscribedRef.set(true);
}
@Override
public void onNext(User user) {
assertTrue(false);
}
@Override
public void onError(Throwable e) {
ANError anError = (ANError) e;
errorBodyRef.set(anError.getErrorBody());
errorDetailRef.set(anError.getErrorDetail());
errorCodeRef.set(anError.getErrorCode());
latch.countDown();
}
@Override
public void onComplete() {
assertTrue(false);
}
});
assertTrue(latch.await(2, SECONDS));
assertTrue(isSubscribedRef.get());
| assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); |
amitshekhariitbhu/Fast-Android-Networking | rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/Rx2MultipartStringApiTest.java | // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
| import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import static java.util.concurrent.TimeUnit.SECONDS;
import android.app.Application;
import android.test.ApplicationTestCase;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.error.ANError;
import org.junit.Rule;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference; | .subscribe(new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
isSubscribedRef.set(true);
}
@Override
public void onNext(String response) {
assertTrue(false);
}
@Override
public void onError(Throwable e) {
ANError anError = (ANError) e;
errorBodyRef.set(anError.getErrorBody());
errorDetailRef.set(anError.getErrorDetail());
errorCodeRef.set(anError.getErrorCode());
latch.countDown();
}
@Override
public void onComplete() {
assertTrue(false);
}
});
assertTrue(latch.await(2, SECONDS));
assertTrue(isSubscribedRef.get());
| // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
// Path: rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/Rx2MultipartStringApiTest.java
import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import static java.util.concurrent.TimeUnit.SECONDS;
import android.app.Application;
import android.test.ApplicationTestCase;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.error.ANError;
import org.junit.Rule;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
.subscribe(new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
isSubscribedRef.set(true);
}
@Override
public void onNext(String response) {
assertTrue(false);
}
@Override
public void onError(Throwable e) {
ANError anError = (ANError) e;
errorBodyRef.set(anError.getErrorBody());
errorDetailRef.set(anError.getErrorDetail());
errorCodeRef.set(anError.getErrorCode());
latch.countDown();
}
@Override
public void onComplete() {
assertTrue(false);
}
});
assertTrue(latch.await(2, SECONDS));
assertTrue(isSubscribedRef.get());
| assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); |
amitshekhariitbhu/Fast-Android-Networking | rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/Rx2MultipartJSONApiTest.java | // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
| import android.app.Application;
import android.test.ApplicationTestCase;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.error.ANError;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Rule;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import static java.util.concurrent.TimeUnit.SECONDS; | .subscribe(new Observer<JSONObject>() {
@Override
public void onSubscribe(Disposable d) {
isSubscribedRef.set(true);
}
@Override
public void onNext(JSONObject response) {
assertTrue(false);
}
@Override
public void onError(Throwable e) {
ANError anError = (ANError) e;
errorBodyRef.set(anError.getErrorBody());
errorDetailRef.set(anError.getErrorDetail());
errorCodeRef.set(anError.getErrorCode());
latch.countDown();
}
@Override
public void onComplete() {
assertTrue(false);
}
});
assertTrue(latch.await(2, SECONDS));
assertTrue(isSubscribedRef.get());
| // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
// Path: rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/Rx2MultipartJSONApiTest.java
import android.app.Application;
import android.test.ApplicationTestCase;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.error.ANError;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Rule;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import static java.util.concurrent.TimeUnit.SECONDS;
.subscribe(new Observer<JSONObject>() {
@Override
public void onSubscribe(Disposable d) {
isSubscribedRef.set(true);
}
@Override
public void onNext(JSONObject response) {
assertTrue(false);
}
@Override
public void onError(Throwable e) {
ANError anError = (ANError) e;
errorBodyRef.set(anError.getErrorBody());
errorDetailRef.set(anError.getErrorDetail());
errorCodeRef.set(anError.getErrorCode());
latch.countDown();
}
@Override
public void onComplete() {
assertTrue(false);
}
});
assertTrue(latch.await(2, SECONDS));
assertTrue(isSubscribedRef.get());
| assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); |
amitshekhariitbhu/Fast-Android-Networking | rxsampleapp/src/main/java/com/rxsampleapp/RxOperatorExampleActivity.java | // Path: rx-android-networking/src/main/java/com/rxandroidnetworking/RxAndroidNetworking.java
// public class RxAndroidNetworking {
//
// /**
// * private constructor to prevent instantiation of this class
// */
// private RxAndroidNetworking() {
// }
//
// /**
// * Method to make GET request
// *
// * @param url The url on which request is to be made
// * @return The GetRequestBuilder
// */
// public static RxANRequest.GetRequestBuilder get(String url) {
// return new RxANRequest.GetRequestBuilder(url);
// }
//
// /**
// * Method to make HEAD request
// *
// * @param url The url on which request is to be made
// * @return The HeadRequestBuilder
// */
// public static RxANRequest.HeadRequestBuilder head(String url) {
// return new RxANRequest.HeadRequestBuilder(url);
// }
//
// /**
// * Method to make OPTIONS request
// *
// * @param url The url on which request is to be made
// * @return The OptionsRequestBuilder
// */
// public static RxANRequest.OptionsRequestBuilder options(String url) {
// return new RxANRequest.OptionsRequestBuilder(url);
// }
//
// /**
// * Method to make POST request
// *
// * @param url The url on which request is to be made
// * @return The PostRequestBuilder
// */
// public static RxANRequest.PostRequestBuilder post(String url) {
// return new RxANRequest.PostRequestBuilder(url);
// }
//
// /**
// * Method to make PUT request
// *
// * @param url The url on which request is to be made
// * @return The PutRequestBuilder
// */
// public static RxANRequest.PutRequestBuilder put(String url) {
// return new RxANRequest.PutRequestBuilder(url);
// }
//
// /**
// * Method to make DELETE request
// *
// * @param url The url on which request is to be made
// * @return The DeleteRequestBuilder
// */
// public static RxANRequest.DeleteRequestBuilder delete(String url) {
// return new RxANRequest.DeleteRequestBuilder(url);
// }
//
// /**
// * Method to make PATCH request
// *
// * @param url The url on which request is to be made
// * @return The PatchRequestBuilder
// */
// public static RxANRequest.PatchRequestBuilder patch(String url) {
// return new RxANRequest.PatchRequestBuilder(url);
// }
//
// /**
// * Method to make download request
// *
// * @param url The url on which request is to be made
// * @param dirPath The directory path on which file is to be saved
// * @param fileName The file name with which file is to be saved
// * @return The DownloadBuilder
// */
// public static RxANRequest.DownloadBuilder download(String url, String dirPath, String fileName) {
// return new RxANRequest.DownloadBuilder(url, dirPath, fileName);
// }
//
// /**
// * Method to make upload request
// *
// * @param url The url on which request is to be made
// * @return The MultiPartBuilder
// */
// public static RxANRequest.MultiPartBuilder upload(String url) {
// return new RxANRequest.MultiPartBuilder(url);
// }
//
// /**
// * Method to make Dynamic request
// *
// * @param url The url on which request is to be made
// * @param method The HTTP METHOD for the request
// * @return The DynamicRequestBuilder
// */
// public static RxANRequest.DynamicRequestBuilder request(String url, int method) {
// return new RxANRequest.DynamicRequestBuilder(url, method);
// }
// }
//
// Path: rxsampleapp/src/main/java/com/rxsampleapp/model/ApiUser.java
// public class ApiUser {
// public long id;
// public String firstname;
// public String lastname;
// }
//
// Path: rxsampleapp/src/main/java/com/rxsampleapp/model/UserDetail.java
// public class UserDetail {
//
// public long id;
// public String firstname;
// public String lastname;
//
// }
| import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import com.androidnetworking.interfaces.AnalyticsListener;
import com.google.gson.reflect.TypeToken;
import com.rxandroidnetworking.RxAndroidNetworking;
import com.rxsampleapp.model.ApiUser;
import com.rxsampleapp.model.User;
import com.rxsampleapp.model.UserDetail;
import com.rxsampleapp.utils.Utils;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.schedulers.Schedulers; | /*
*
* * Copyright (C) 2016 Amit Shekhar
* * Copyright (C) 2011 Android Open Source Project
* *
* * 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.rxsampleapp;
/**
* Created by amitshekhar on 31/07/16.
*/
public class RxOperatorExampleActivity extends AppCompatActivity {
private static final String TAG = RxOperatorExampleActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rx_operator_example);
testApi();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
/************************************
* Just an test api start
************************************/
private void testApi() { | // Path: rx-android-networking/src/main/java/com/rxandroidnetworking/RxAndroidNetworking.java
// public class RxAndroidNetworking {
//
// /**
// * private constructor to prevent instantiation of this class
// */
// private RxAndroidNetworking() {
// }
//
// /**
// * Method to make GET request
// *
// * @param url The url on which request is to be made
// * @return The GetRequestBuilder
// */
// public static RxANRequest.GetRequestBuilder get(String url) {
// return new RxANRequest.GetRequestBuilder(url);
// }
//
// /**
// * Method to make HEAD request
// *
// * @param url The url on which request is to be made
// * @return The HeadRequestBuilder
// */
// public static RxANRequest.HeadRequestBuilder head(String url) {
// return new RxANRequest.HeadRequestBuilder(url);
// }
//
// /**
// * Method to make OPTIONS request
// *
// * @param url The url on which request is to be made
// * @return The OptionsRequestBuilder
// */
// public static RxANRequest.OptionsRequestBuilder options(String url) {
// return new RxANRequest.OptionsRequestBuilder(url);
// }
//
// /**
// * Method to make POST request
// *
// * @param url The url on which request is to be made
// * @return The PostRequestBuilder
// */
// public static RxANRequest.PostRequestBuilder post(String url) {
// return new RxANRequest.PostRequestBuilder(url);
// }
//
// /**
// * Method to make PUT request
// *
// * @param url The url on which request is to be made
// * @return The PutRequestBuilder
// */
// public static RxANRequest.PutRequestBuilder put(String url) {
// return new RxANRequest.PutRequestBuilder(url);
// }
//
// /**
// * Method to make DELETE request
// *
// * @param url The url on which request is to be made
// * @return The DeleteRequestBuilder
// */
// public static RxANRequest.DeleteRequestBuilder delete(String url) {
// return new RxANRequest.DeleteRequestBuilder(url);
// }
//
// /**
// * Method to make PATCH request
// *
// * @param url The url on which request is to be made
// * @return The PatchRequestBuilder
// */
// public static RxANRequest.PatchRequestBuilder patch(String url) {
// return new RxANRequest.PatchRequestBuilder(url);
// }
//
// /**
// * Method to make download request
// *
// * @param url The url on which request is to be made
// * @param dirPath The directory path on which file is to be saved
// * @param fileName The file name with which file is to be saved
// * @return The DownloadBuilder
// */
// public static RxANRequest.DownloadBuilder download(String url, String dirPath, String fileName) {
// return new RxANRequest.DownloadBuilder(url, dirPath, fileName);
// }
//
// /**
// * Method to make upload request
// *
// * @param url The url on which request is to be made
// * @return The MultiPartBuilder
// */
// public static RxANRequest.MultiPartBuilder upload(String url) {
// return new RxANRequest.MultiPartBuilder(url);
// }
//
// /**
// * Method to make Dynamic request
// *
// * @param url The url on which request is to be made
// * @param method The HTTP METHOD for the request
// * @return The DynamicRequestBuilder
// */
// public static RxANRequest.DynamicRequestBuilder request(String url, int method) {
// return new RxANRequest.DynamicRequestBuilder(url, method);
// }
// }
//
// Path: rxsampleapp/src/main/java/com/rxsampleapp/model/ApiUser.java
// public class ApiUser {
// public long id;
// public String firstname;
// public String lastname;
// }
//
// Path: rxsampleapp/src/main/java/com/rxsampleapp/model/UserDetail.java
// public class UserDetail {
//
// public long id;
// public String firstname;
// public String lastname;
//
// }
// Path: rxsampleapp/src/main/java/com/rxsampleapp/RxOperatorExampleActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import com.androidnetworking.interfaces.AnalyticsListener;
import com.google.gson.reflect.TypeToken;
import com.rxandroidnetworking.RxAndroidNetworking;
import com.rxsampleapp.model.ApiUser;
import com.rxsampleapp.model.User;
import com.rxsampleapp.model.UserDetail;
import com.rxsampleapp.utils.Utils;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.schedulers.Schedulers;
/*
*
* * Copyright (C) 2016 Amit Shekhar
* * Copyright (C) 2011 Android Open Source Project
* *
* * 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.rxsampleapp;
/**
* Created by amitshekhar on 31/07/16.
*/
public class RxOperatorExampleActivity extends AppCompatActivity {
private static final String TAG = RxOperatorExampleActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rx_operator_example);
testApi();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
/************************************
* Just an test api start
************************************/
private void testApi() { | RxAndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllUsers/{pageNumber}") |
amitshekhariitbhu/Fast-Android-Networking | rxsampleapp/src/main/java/com/rxsampleapp/RxOperatorExampleActivity.java | // Path: rx-android-networking/src/main/java/com/rxandroidnetworking/RxAndroidNetworking.java
// public class RxAndroidNetworking {
//
// /**
// * private constructor to prevent instantiation of this class
// */
// private RxAndroidNetworking() {
// }
//
// /**
// * Method to make GET request
// *
// * @param url The url on which request is to be made
// * @return The GetRequestBuilder
// */
// public static RxANRequest.GetRequestBuilder get(String url) {
// return new RxANRequest.GetRequestBuilder(url);
// }
//
// /**
// * Method to make HEAD request
// *
// * @param url The url on which request is to be made
// * @return The HeadRequestBuilder
// */
// public static RxANRequest.HeadRequestBuilder head(String url) {
// return new RxANRequest.HeadRequestBuilder(url);
// }
//
// /**
// * Method to make OPTIONS request
// *
// * @param url The url on which request is to be made
// * @return The OptionsRequestBuilder
// */
// public static RxANRequest.OptionsRequestBuilder options(String url) {
// return new RxANRequest.OptionsRequestBuilder(url);
// }
//
// /**
// * Method to make POST request
// *
// * @param url The url on which request is to be made
// * @return The PostRequestBuilder
// */
// public static RxANRequest.PostRequestBuilder post(String url) {
// return new RxANRequest.PostRequestBuilder(url);
// }
//
// /**
// * Method to make PUT request
// *
// * @param url The url on which request is to be made
// * @return The PutRequestBuilder
// */
// public static RxANRequest.PutRequestBuilder put(String url) {
// return new RxANRequest.PutRequestBuilder(url);
// }
//
// /**
// * Method to make DELETE request
// *
// * @param url The url on which request is to be made
// * @return The DeleteRequestBuilder
// */
// public static RxANRequest.DeleteRequestBuilder delete(String url) {
// return new RxANRequest.DeleteRequestBuilder(url);
// }
//
// /**
// * Method to make PATCH request
// *
// * @param url The url on which request is to be made
// * @return The PatchRequestBuilder
// */
// public static RxANRequest.PatchRequestBuilder patch(String url) {
// return new RxANRequest.PatchRequestBuilder(url);
// }
//
// /**
// * Method to make download request
// *
// * @param url The url on which request is to be made
// * @param dirPath The directory path on which file is to be saved
// * @param fileName The file name with which file is to be saved
// * @return The DownloadBuilder
// */
// public static RxANRequest.DownloadBuilder download(String url, String dirPath, String fileName) {
// return new RxANRequest.DownloadBuilder(url, dirPath, fileName);
// }
//
// /**
// * Method to make upload request
// *
// * @param url The url on which request is to be made
// * @return The MultiPartBuilder
// */
// public static RxANRequest.MultiPartBuilder upload(String url) {
// return new RxANRequest.MultiPartBuilder(url);
// }
//
// /**
// * Method to make Dynamic request
// *
// * @param url The url on which request is to be made
// * @param method The HTTP METHOD for the request
// * @return The DynamicRequestBuilder
// */
// public static RxANRequest.DynamicRequestBuilder request(String url, int method) {
// return new RxANRequest.DynamicRequestBuilder(url, method);
// }
// }
//
// Path: rxsampleapp/src/main/java/com/rxsampleapp/model/ApiUser.java
// public class ApiUser {
// public long id;
// public String firstname;
// public String lastname;
// }
//
// Path: rxsampleapp/src/main/java/com/rxsampleapp/model/UserDetail.java
// public class UserDetail {
//
// public long id;
// public String firstname;
// public String lastname;
//
// }
| import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import com.androidnetworking.interfaces.AnalyticsListener;
import com.google.gson.reflect.TypeToken;
import com.rxandroidnetworking.RxAndroidNetworking;
import com.rxsampleapp.model.ApiUser;
import com.rxsampleapp.model.User;
import com.rxsampleapp.model.UserDetail;
import com.rxsampleapp.utils.Utils;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.schedulers.Schedulers; | @Override
public void onCompleted() {
Log.d(TAG, "onComplete Detail : getAllUsers completed");
}
@Override
public void onError(Throwable e) {
Utils.logError(TAG, e);
}
@Override
public void onNext(List<User> users) {
Log.d(TAG, "userList size : " + users.size());
for (User user : users) {
Log.d(TAG, "id : " + user.id);
Log.d(TAG, "firstname : " + user.firstname);
Log.d(TAG, "lastname : " + user.lastname);
}
}
});
}
/************************************
* map operator start
************************************/
public void map(View view) {
RxAndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAnUser/{userId}")
.addPathParameter("userId", "1")
.build() | // Path: rx-android-networking/src/main/java/com/rxandroidnetworking/RxAndroidNetworking.java
// public class RxAndroidNetworking {
//
// /**
// * private constructor to prevent instantiation of this class
// */
// private RxAndroidNetworking() {
// }
//
// /**
// * Method to make GET request
// *
// * @param url The url on which request is to be made
// * @return The GetRequestBuilder
// */
// public static RxANRequest.GetRequestBuilder get(String url) {
// return new RxANRequest.GetRequestBuilder(url);
// }
//
// /**
// * Method to make HEAD request
// *
// * @param url The url on which request is to be made
// * @return The HeadRequestBuilder
// */
// public static RxANRequest.HeadRequestBuilder head(String url) {
// return new RxANRequest.HeadRequestBuilder(url);
// }
//
// /**
// * Method to make OPTIONS request
// *
// * @param url The url on which request is to be made
// * @return The OptionsRequestBuilder
// */
// public static RxANRequest.OptionsRequestBuilder options(String url) {
// return new RxANRequest.OptionsRequestBuilder(url);
// }
//
// /**
// * Method to make POST request
// *
// * @param url The url on which request is to be made
// * @return The PostRequestBuilder
// */
// public static RxANRequest.PostRequestBuilder post(String url) {
// return new RxANRequest.PostRequestBuilder(url);
// }
//
// /**
// * Method to make PUT request
// *
// * @param url The url on which request is to be made
// * @return The PutRequestBuilder
// */
// public static RxANRequest.PutRequestBuilder put(String url) {
// return new RxANRequest.PutRequestBuilder(url);
// }
//
// /**
// * Method to make DELETE request
// *
// * @param url The url on which request is to be made
// * @return The DeleteRequestBuilder
// */
// public static RxANRequest.DeleteRequestBuilder delete(String url) {
// return new RxANRequest.DeleteRequestBuilder(url);
// }
//
// /**
// * Method to make PATCH request
// *
// * @param url The url on which request is to be made
// * @return The PatchRequestBuilder
// */
// public static RxANRequest.PatchRequestBuilder patch(String url) {
// return new RxANRequest.PatchRequestBuilder(url);
// }
//
// /**
// * Method to make download request
// *
// * @param url The url on which request is to be made
// * @param dirPath The directory path on which file is to be saved
// * @param fileName The file name with which file is to be saved
// * @return The DownloadBuilder
// */
// public static RxANRequest.DownloadBuilder download(String url, String dirPath, String fileName) {
// return new RxANRequest.DownloadBuilder(url, dirPath, fileName);
// }
//
// /**
// * Method to make upload request
// *
// * @param url The url on which request is to be made
// * @return The MultiPartBuilder
// */
// public static RxANRequest.MultiPartBuilder upload(String url) {
// return new RxANRequest.MultiPartBuilder(url);
// }
//
// /**
// * Method to make Dynamic request
// *
// * @param url The url on which request is to be made
// * @param method The HTTP METHOD for the request
// * @return The DynamicRequestBuilder
// */
// public static RxANRequest.DynamicRequestBuilder request(String url, int method) {
// return new RxANRequest.DynamicRequestBuilder(url, method);
// }
// }
//
// Path: rxsampleapp/src/main/java/com/rxsampleapp/model/ApiUser.java
// public class ApiUser {
// public long id;
// public String firstname;
// public String lastname;
// }
//
// Path: rxsampleapp/src/main/java/com/rxsampleapp/model/UserDetail.java
// public class UserDetail {
//
// public long id;
// public String firstname;
// public String lastname;
//
// }
// Path: rxsampleapp/src/main/java/com/rxsampleapp/RxOperatorExampleActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import com.androidnetworking.interfaces.AnalyticsListener;
import com.google.gson.reflect.TypeToken;
import com.rxandroidnetworking.RxAndroidNetworking;
import com.rxsampleapp.model.ApiUser;
import com.rxsampleapp.model.User;
import com.rxsampleapp.model.UserDetail;
import com.rxsampleapp.utils.Utils;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.schedulers.Schedulers;
@Override
public void onCompleted() {
Log.d(TAG, "onComplete Detail : getAllUsers completed");
}
@Override
public void onError(Throwable e) {
Utils.logError(TAG, e);
}
@Override
public void onNext(List<User> users) {
Log.d(TAG, "userList size : " + users.size());
for (User user : users) {
Log.d(TAG, "id : " + user.id);
Log.d(TAG, "firstname : " + user.firstname);
Log.d(TAG, "lastname : " + user.lastname);
}
}
});
}
/************************************
* map operator start
************************************/
public void map(View view) {
RxAndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAnUser/{userId}")
.addPathParameter("userId", "1")
.build() | .getParseObservable(new TypeToken<ApiUser>() { |
amitshekhariitbhu/Fast-Android-Networking | rxsampleapp/src/main/java/com/rxsampleapp/RxOperatorExampleActivity.java | // Path: rx-android-networking/src/main/java/com/rxandroidnetworking/RxAndroidNetworking.java
// public class RxAndroidNetworking {
//
// /**
// * private constructor to prevent instantiation of this class
// */
// private RxAndroidNetworking() {
// }
//
// /**
// * Method to make GET request
// *
// * @param url The url on which request is to be made
// * @return The GetRequestBuilder
// */
// public static RxANRequest.GetRequestBuilder get(String url) {
// return new RxANRequest.GetRequestBuilder(url);
// }
//
// /**
// * Method to make HEAD request
// *
// * @param url The url on which request is to be made
// * @return The HeadRequestBuilder
// */
// public static RxANRequest.HeadRequestBuilder head(String url) {
// return new RxANRequest.HeadRequestBuilder(url);
// }
//
// /**
// * Method to make OPTIONS request
// *
// * @param url The url on which request is to be made
// * @return The OptionsRequestBuilder
// */
// public static RxANRequest.OptionsRequestBuilder options(String url) {
// return new RxANRequest.OptionsRequestBuilder(url);
// }
//
// /**
// * Method to make POST request
// *
// * @param url The url on which request is to be made
// * @return The PostRequestBuilder
// */
// public static RxANRequest.PostRequestBuilder post(String url) {
// return new RxANRequest.PostRequestBuilder(url);
// }
//
// /**
// * Method to make PUT request
// *
// * @param url The url on which request is to be made
// * @return The PutRequestBuilder
// */
// public static RxANRequest.PutRequestBuilder put(String url) {
// return new RxANRequest.PutRequestBuilder(url);
// }
//
// /**
// * Method to make DELETE request
// *
// * @param url The url on which request is to be made
// * @return The DeleteRequestBuilder
// */
// public static RxANRequest.DeleteRequestBuilder delete(String url) {
// return new RxANRequest.DeleteRequestBuilder(url);
// }
//
// /**
// * Method to make PATCH request
// *
// * @param url The url on which request is to be made
// * @return The PatchRequestBuilder
// */
// public static RxANRequest.PatchRequestBuilder patch(String url) {
// return new RxANRequest.PatchRequestBuilder(url);
// }
//
// /**
// * Method to make download request
// *
// * @param url The url on which request is to be made
// * @param dirPath The directory path on which file is to be saved
// * @param fileName The file name with which file is to be saved
// * @return The DownloadBuilder
// */
// public static RxANRequest.DownloadBuilder download(String url, String dirPath, String fileName) {
// return new RxANRequest.DownloadBuilder(url, dirPath, fileName);
// }
//
// /**
// * Method to make upload request
// *
// * @param url The url on which request is to be made
// * @return The MultiPartBuilder
// */
// public static RxANRequest.MultiPartBuilder upload(String url) {
// return new RxANRequest.MultiPartBuilder(url);
// }
//
// /**
// * Method to make Dynamic request
// *
// * @param url The url on which request is to be made
// * @param method The HTTP METHOD for the request
// * @return The DynamicRequestBuilder
// */
// public static RxANRequest.DynamicRequestBuilder request(String url, int method) {
// return new RxANRequest.DynamicRequestBuilder(url, method);
// }
// }
//
// Path: rxsampleapp/src/main/java/com/rxsampleapp/model/ApiUser.java
// public class ApiUser {
// public long id;
// public String firstname;
// public String lastname;
// }
//
// Path: rxsampleapp/src/main/java/com/rxsampleapp/model/UserDetail.java
// public class UserDetail {
//
// public long id;
// public String firstname;
// public String lastname;
//
// }
| import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import com.androidnetworking.interfaces.AnalyticsListener;
import com.google.gson.reflect.TypeToken;
import com.rxandroidnetworking.RxAndroidNetworking;
import com.rxsampleapp.model.ApiUser;
import com.rxsampleapp.model.User;
import com.rxsampleapp.model.UserDetail;
import com.rxsampleapp.utils.Utils;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.schedulers.Schedulers; | @Override
public void onError(Throwable e) {
}
@Override
public void onNext(User user) {
// only four user comes here one by one
Log.d(TAG, "id : " + user.id);
Log.d(TAG, "firstname : " + user.firstname);
Log.d(TAG, "lastname : " + user.lastname);
Log.d(TAG, "isFollowing : " + user.isFollowing);
}
});
}
/************************************
* flatMap operator start
************************************/
public void flatMap(View view) {
getUserListObservable()
.flatMap(new Func1<List<User>, Observable<User>>() { // flatMap - to return users one by one
@Override
public Observable<User> call(List<User> usersList) {
return Observable.from(usersList); // returning user one by one from usersList.
}
}) | // Path: rx-android-networking/src/main/java/com/rxandroidnetworking/RxAndroidNetworking.java
// public class RxAndroidNetworking {
//
// /**
// * private constructor to prevent instantiation of this class
// */
// private RxAndroidNetworking() {
// }
//
// /**
// * Method to make GET request
// *
// * @param url The url on which request is to be made
// * @return The GetRequestBuilder
// */
// public static RxANRequest.GetRequestBuilder get(String url) {
// return new RxANRequest.GetRequestBuilder(url);
// }
//
// /**
// * Method to make HEAD request
// *
// * @param url The url on which request is to be made
// * @return The HeadRequestBuilder
// */
// public static RxANRequest.HeadRequestBuilder head(String url) {
// return new RxANRequest.HeadRequestBuilder(url);
// }
//
// /**
// * Method to make OPTIONS request
// *
// * @param url The url on which request is to be made
// * @return The OptionsRequestBuilder
// */
// public static RxANRequest.OptionsRequestBuilder options(String url) {
// return new RxANRequest.OptionsRequestBuilder(url);
// }
//
// /**
// * Method to make POST request
// *
// * @param url The url on which request is to be made
// * @return The PostRequestBuilder
// */
// public static RxANRequest.PostRequestBuilder post(String url) {
// return new RxANRequest.PostRequestBuilder(url);
// }
//
// /**
// * Method to make PUT request
// *
// * @param url The url on which request is to be made
// * @return The PutRequestBuilder
// */
// public static RxANRequest.PutRequestBuilder put(String url) {
// return new RxANRequest.PutRequestBuilder(url);
// }
//
// /**
// * Method to make DELETE request
// *
// * @param url The url on which request is to be made
// * @return The DeleteRequestBuilder
// */
// public static RxANRequest.DeleteRequestBuilder delete(String url) {
// return new RxANRequest.DeleteRequestBuilder(url);
// }
//
// /**
// * Method to make PATCH request
// *
// * @param url The url on which request is to be made
// * @return The PatchRequestBuilder
// */
// public static RxANRequest.PatchRequestBuilder patch(String url) {
// return new RxANRequest.PatchRequestBuilder(url);
// }
//
// /**
// * Method to make download request
// *
// * @param url The url on which request is to be made
// * @param dirPath The directory path on which file is to be saved
// * @param fileName The file name with which file is to be saved
// * @return The DownloadBuilder
// */
// public static RxANRequest.DownloadBuilder download(String url, String dirPath, String fileName) {
// return new RxANRequest.DownloadBuilder(url, dirPath, fileName);
// }
//
// /**
// * Method to make upload request
// *
// * @param url The url on which request is to be made
// * @return The MultiPartBuilder
// */
// public static RxANRequest.MultiPartBuilder upload(String url) {
// return new RxANRequest.MultiPartBuilder(url);
// }
//
// /**
// * Method to make Dynamic request
// *
// * @param url The url on which request is to be made
// * @param method The HTTP METHOD for the request
// * @return The DynamicRequestBuilder
// */
// public static RxANRequest.DynamicRequestBuilder request(String url, int method) {
// return new RxANRequest.DynamicRequestBuilder(url, method);
// }
// }
//
// Path: rxsampleapp/src/main/java/com/rxsampleapp/model/ApiUser.java
// public class ApiUser {
// public long id;
// public String firstname;
// public String lastname;
// }
//
// Path: rxsampleapp/src/main/java/com/rxsampleapp/model/UserDetail.java
// public class UserDetail {
//
// public long id;
// public String firstname;
// public String lastname;
//
// }
// Path: rxsampleapp/src/main/java/com/rxsampleapp/RxOperatorExampleActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import com.androidnetworking.interfaces.AnalyticsListener;
import com.google.gson.reflect.TypeToken;
import com.rxandroidnetworking.RxAndroidNetworking;
import com.rxsampleapp.model.ApiUser;
import com.rxsampleapp.model.User;
import com.rxsampleapp.model.UserDetail;
import com.rxsampleapp.utils.Utils;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.schedulers.Schedulers;
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(User user) {
// only four user comes here one by one
Log.d(TAG, "id : " + user.id);
Log.d(TAG, "firstname : " + user.firstname);
Log.d(TAG, "lastname : " + user.lastname);
Log.d(TAG, "isFollowing : " + user.isFollowing);
}
});
}
/************************************
* flatMap operator start
************************************/
public void flatMap(View view) {
getUserListObservable()
.flatMap(new Func1<List<User>, Observable<User>>() { // flatMap - to return users one by one
@Override
public Observable<User> call(List<User> usersList) {
return Observable.from(usersList); // returning user one by one from usersList.
}
}) | .flatMap(new Func1<User, Observable<UserDetail>>() { |
amitshekhariitbhu/Fast-Android-Networking | android-networking/src/main/java/com/androidnetworking/internal/UploadProgressHandler.java | // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
| import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.interfaces.UploadProgressListener;
import com.androidnetworking.model.Progress; | /*
* Copyright (C) 2016 Amit Shekhar
* Copyright (C) 2011 Android Open Source Project
*
* 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.androidnetworking.internal;
/**
* Created by amitshekhar on 24/05/16.
*/
public class UploadProgressHandler extends Handler {
private final UploadProgressListener mUploadProgressListener;
public UploadProgressHandler(UploadProgressListener uploadProgressListener) {
super(Looper.getMainLooper());
mUploadProgressListener = uploadProgressListener;
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) { | // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
// Path: android-networking/src/main/java/com/androidnetworking/internal/UploadProgressHandler.java
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.interfaces.UploadProgressListener;
import com.androidnetworking.model.Progress;
/*
* Copyright (C) 2016 Amit Shekhar
* Copyright (C) 2011 Android Open Source Project
*
* 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.androidnetworking.internal;
/**
* Created by amitshekhar on 24/05/16.
*/
public class UploadProgressHandler extends Handler {
private final UploadProgressListener mUploadProgressListener;
public UploadProgressHandler(UploadProgressListener uploadProgressListener) {
super(Looper.getMainLooper());
mUploadProgressListener = uploadProgressListener;
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) { | case ANConstants.UPDATE: |
amitshekhariitbhu/Fast-Android-Networking | android-networking/src/main/java/com/androidnetworking/internal/DownloadProgressHandler.java | // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
| import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.interfaces.DownloadProgressListener;
import com.androidnetworking.model.Progress; | /*
* Copyright (C) 2016 Amit Shekhar
* Copyright (C) 2011 Android Open Source Project
*
* 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.androidnetworking.internal;
/**
* Created by amitshekhar on 24/05/16.
*/
public class DownloadProgressHandler extends Handler {
private final DownloadProgressListener mDownloadProgressListener;
public DownloadProgressHandler(DownloadProgressListener downloadProgressListener) {
super(Looper.getMainLooper());
mDownloadProgressListener = downloadProgressListener;
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) { | // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
// Path: android-networking/src/main/java/com/androidnetworking/internal/DownloadProgressHandler.java
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.interfaces.DownloadProgressListener;
import com.androidnetworking.model.Progress;
/*
* Copyright (C) 2016 Amit Shekhar
* Copyright (C) 2011 Android Open Source Project
*
* 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.androidnetworking.internal;
/**
* Created by amitshekhar on 24/05/16.
*/
public class DownloadProgressHandler extends Handler {
private final DownloadProgressListener mDownloadProgressListener;
public DownloadProgressHandler(DownloadProgressListener downloadProgressListener) {
super(Looper.getMainLooper());
mDownloadProgressListener = downloadProgressListener;
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) { | case ANConstants.UPDATE: |
amitshekhariitbhu/Fast-Android-Networking | rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/Rx2PostJSONApiTest.java | // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
| import android.app.Application;
import android.test.ApplicationTestCase;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.error.ANError;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Rule;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import static java.util.concurrent.TimeUnit.SECONDS; | .subscribe(new Observer<JSONObject>() {
@Override
public void onSubscribe(Disposable d) {
isSubscribedRef.set(true);
}
@Override
public void onNext(JSONObject response) {
assertTrue(false);
}
@Override
public void onError(Throwable e) {
ANError anError = (ANError) e;
errorBodyRef.set(anError.getErrorBody());
errorDetailRef.set(anError.getErrorDetail());
errorCodeRef.set(anError.getErrorCode());
latch.countDown();
}
@Override
public void onComplete() {
assertTrue(false);
}
});
assertTrue(latch.await(2, SECONDS));
assertTrue(isSubscribedRef.get());
| // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
// Path: rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/Rx2PostJSONApiTest.java
import android.app.Application;
import android.test.ApplicationTestCase;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.error.ANError;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Rule;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import static java.util.concurrent.TimeUnit.SECONDS;
.subscribe(new Observer<JSONObject>() {
@Override
public void onSubscribe(Disposable d) {
isSubscribedRef.set(true);
}
@Override
public void onNext(JSONObject response) {
assertTrue(false);
}
@Override
public void onError(Throwable e) {
ANError anError = (ANError) e;
errorBodyRef.set(anError.getErrorBody());
errorDetailRef.set(anError.getErrorDetail());
errorCodeRef.set(anError.getErrorCode());
latch.countDown();
}
@Override
public void onComplete() {
assertTrue(false);
}
});
assertTrue(latch.await(2, SECONDS));
assertTrue(isSubscribedRef.get());
| assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); |
amitshekhariitbhu/Fast-Android-Networking | android-networking/src/main/java/com/androidnetworking/internal/RequestProgressBody.java | // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
| import com.androidnetworking.common.ANConstants;
import com.androidnetworking.interfaces.UploadProgressListener;
import com.androidnetworking.model.Progress;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink; | return requestBody.contentType();
}
@Override
public long contentLength() throws IOException {
return requestBody.contentLength();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
if (bufferedSink == null) {
bufferedSink = Okio.buffer(sink(sink));
}
requestBody.writeTo(bufferedSink);
bufferedSink.flush();
}
private Sink sink(Sink sink) {
return new ForwardingSink(sink) {
long bytesWritten = 0L;
long contentLength = 0L;
@Override
public void write(Buffer source, long byteCount) throws IOException {
super.write(source, byteCount);
if (contentLength == 0) {
contentLength = contentLength();
}
bytesWritten += byteCount;
if (uploadProgressHandler != null) { | // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
// Path: android-networking/src/main/java/com/androidnetworking/internal/RequestProgressBody.java
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.interfaces.UploadProgressListener;
import com.androidnetworking.model.Progress;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;
return requestBody.contentType();
}
@Override
public long contentLength() throws IOException {
return requestBody.contentLength();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
if (bufferedSink == null) {
bufferedSink = Okio.buffer(sink(sink));
}
requestBody.writeTo(bufferedSink);
bufferedSink.flush();
}
private Sink sink(Sink sink) {
return new ForwardingSink(sink) {
long bytesWritten = 0L;
long contentLength = 0L;
@Override
public void write(Buffer source, long byteCount) throws IOException {
super.write(source, byteCount);
if (contentLength == 0) {
contentLength = contentLength();
}
bytesWritten += byteCount;
if (uploadProgressHandler != null) { | uploadProgressHandler.obtainMessage(ANConstants.UPDATE, |
amitshekhariitbhu/Fast-Android-Networking | rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/Rx2PostStringApiTest.java | // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
| import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import static java.util.concurrent.TimeUnit.SECONDS;
import android.app.Application;
import android.test.ApplicationTestCase;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.error.ANError;
import org.junit.Rule;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference; | .subscribe(new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
isSubscribedRef.set(true);
}
@Override
public void onNext(String response) {
assertTrue(false);
}
@Override
public void onError(Throwable e) {
ANError anError = (ANError) e;
errorBodyRef.set(anError.getErrorBody());
errorDetailRef.set(anError.getErrorDetail());
errorCodeRef.set(anError.getErrorCode());
latch.countDown();
}
@Override
public void onComplete() {
assertTrue(false);
}
});
assertTrue(latch.await(2, SECONDS));
assertTrue(isSubscribedRef.get());
| // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
// Path: rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/Rx2PostStringApiTest.java
import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import static java.util.concurrent.TimeUnit.SECONDS;
import android.app.Application;
import android.test.ApplicationTestCase;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.error.ANError;
import org.junit.Rule;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
.subscribe(new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
isSubscribedRef.set(true);
}
@Override
public void onNext(String response) {
assertTrue(false);
}
@Override
public void onError(Throwable e) {
ANError anError = (ANError) e;
errorBodyRef.set(anError.getErrorBody());
errorDetailRef.set(anError.getErrorDetail());
errorCodeRef.set(anError.getErrorCode());
latch.countDown();
}
@Override
public void onComplete() {
assertTrue(false);
}
});
assertTrue(latch.await(2, SECONDS));
assertTrue(isSubscribedRef.get());
| assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); |
amitshekhariitbhu/Fast-Android-Networking | rxsampleapp/src/main/java/com/rxsampleapp/SubscriptionActivity.java | // Path: rx-android-networking/src/main/java/com/rxandroidnetworking/RxAndroidNetworking.java
// public class RxAndroidNetworking {
//
// /**
// * private constructor to prevent instantiation of this class
// */
// private RxAndroidNetworking() {
// }
//
// /**
// * Method to make GET request
// *
// * @param url The url on which request is to be made
// * @return The GetRequestBuilder
// */
// public static RxANRequest.GetRequestBuilder get(String url) {
// return new RxANRequest.GetRequestBuilder(url);
// }
//
// /**
// * Method to make HEAD request
// *
// * @param url The url on which request is to be made
// * @return The HeadRequestBuilder
// */
// public static RxANRequest.HeadRequestBuilder head(String url) {
// return new RxANRequest.HeadRequestBuilder(url);
// }
//
// /**
// * Method to make OPTIONS request
// *
// * @param url The url on which request is to be made
// * @return The OptionsRequestBuilder
// */
// public static RxANRequest.OptionsRequestBuilder options(String url) {
// return new RxANRequest.OptionsRequestBuilder(url);
// }
//
// /**
// * Method to make POST request
// *
// * @param url The url on which request is to be made
// * @return The PostRequestBuilder
// */
// public static RxANRequest.PostRequestBuilder post(String url) {
// return new RxANRequest.PostRequestBuilder(url);
// }
//
// /**
// * Method to make PUT request
// *
// * @param url The url on which request is to be made
// * @return The PutRequestBuilder
// */
// public static RxANRequest.PutRequestBuilder put(String url) {
// return new RxANRequest.PutRequestBuilder(url);
// }
//
// /**
// * Method to make DELETE request
// *
// * @param url The url on which request is to be made
// * @return The DeleteRequestBuilder
// */
// public static RxANRequest.DeleteRequestBuilder delete(String url) {
// return new RxANRequest.DeleteRequestBuilder(url);
// }
//
// /**
// * Method to make PATCH request
// *
// * @param url The url on which request is to be made
// * @return The PatchRequestBuilder
// */
// public static RxANRequest.PatchRequestBuilder patch(String url) {
// return new RxANRequest.PatchRequestBuilder(url);
// }
//
// /**
// * Method to make download request
// *
// * @param url The url on which request is to be made
// * @param dirPath The directory path on which file is to be saved
// * @param fileName The file name with which file is to be saved
// * @return The DownloadBuilder
// */
// public static RxANRequest.DownloadBuilder download(String url, String dirPath, String fileName) {
// return new RxANRequest.DownloadBuilder(url, dirPath, fileName);
// }
//
// /**
// * Method to make upload request
// *
// * @param url The url on which request is to be made
// * @return The MultiPartBuilder
// */
// public static RxANRequest.MultiPartBuilder upload(String url) {
// return new RxANRequest.MultiPartBuilder(url);
// }
//
// /**
// * Method to make Dynamic request
// *
// * @param url The url on which request is to be made
// * @param method The HTTP METHOD for the request
// * @return The DynamicRequestBuilder
// */
// public static RxANRequest.DynamicRequestBuilder request(String url, int method) {
// return new RxANRequest.DynamicRequestBuilder(url, method);
// }
// }
| import rx.schedulers.Schedulers;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import com.rxandroidnetworking.RxAndroidNetworking;
import com.rxsampleapp.utils.Utils;
import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers; | /*
* Copyright (C) 2016 Amit Shekhar
* Copyright (C) 2011 Android Open Source Project
*
* 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.rxsampleapp;
/**
* Created by amitshekhar on 31/07/16.
*/
public class SubscriptionActivity extends AppCompatActivity {
private static final String TAG = SubscriptionActivity.class.getSimpleName();
private static final String URL = "http://i.imgur.com/AtbX9iX.png";
private String dirPath;
private String fileName = "imgurimage.png";
Subscription subscription;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subscription);
dirPath = Utils.getRootDirPath(getApplicationContext());
}
@Override
protected void onDestroy() {
super.onDestroy();
if (subscription != null) {
subscription.unsubscribe();
}
}
public Observable<String> getObservable() { | // Path: rx-android-networking/src/main/java/com/rxandroidnetworking/RxAndroidNetworking.java
// public class RxAndroidNetworking {
//
// /**
// * private constructor to prevent instantiation of this class
// */
// private RxAndroidNetworking() {
// }
//
// /**
// * Method to make GET request
// *
// * @param url The url on which request is to be made
// * @return The GetRequestBuilder
// */
// public static RxANRequest.GetRequestBuilder get(String url) {
// return new RxANRequest.GetRequestBuilder(url);
// }
//
// /**
// * Method to make HEAD request
// *
// * @param url The url on which request is to be made
// * @return The HeadRequestBuilder
// */
// public static RxANRequest.HeadRequestBuilder head(String url) {
// return new RxANRequest.HeadRequestBuilder(url);
// }
//
// /**
// * Method to make OPTIONS request
// *
// * @param url The url on which request is to be made
// * @return The OptionsRequestBuilder
// */
// public static RxANRequest.OptionsRequestBuilder options(String url) {
// return new RxANRequest.OptionsRequestBuilder(url);
// }
//
// /**
// * Method to make POST request
// *
// * @param url The url on which request is to be made
// * @return The PostRequestBuilder
// */
// public static RxANRequest.PostRequestBuilder post(String url) {
// return new RxANRequest.PostRequestBuilder(url);
// }
//
// /**
// * Method to make PUT request
// *
// * @param url The url on which request is to be made
// * @return The PutRequestBuilder
// */
// public static RxANRequest.PutRequestBuilder put(String url) {
// return new RxANRequest.PutRequestBuilder(url);
// }
//
// /**
// * Method to make DELETE request
// *
// * @param url The url on which request is to be made
// * @return The DeleteRequestBuilder
// */
// public static RxANRequest.DeleteRequestBuilder delete(String url) {
// return new RxANRequest.DeleteRequestBuilder(url);
// }
//
// /**
// * Method to make PATCH request
// *
// * @param url The url on which request is to be made
// * @return The PatchRequestBuilder
// */
// public static RxANRequest.PatchRequestBuilder patch(String url) {
// return new RxANRequest.PatchRequestBuilder(url);
// }
//
// /**
// * Method to make download request
// *
// * @param url The url on which request is to be made
// * @param dirPath The directory path on which file is to be saved
// * @param fileName The file name with which file is to be saved
// * @return The DownloadBuilder
// */
// public static RxANRequest.DownloadBuilder download(String url, String dirPath, String fileName) {
// return new RxANRequest.DownloadBuilder(url, dirPath, fileName);
// }
//
// /**
// * Method to make upload request
// *
// * @param url The url on which request is to be made
// * @return The MultiPartBuilder
// */
// public static RxANRequest.MultiPartBuilder upload(String url) {
// return new RxANRequest.MultiPartBuilder(url);
// }
//
// /**
// * Method to make Dynamic request
// *
// * @param url The url on which request is to be made
// * @param method The HTTP METHOD for the request
// * @return The DynamicRequestBuilder
// */
// public static RxANRequest.DynamicRequestBuilder request(String url, int method) {
// return new RxANRequest.DynamicRequestBuilder(url, method);
// }
// }
// Path: rxsampleapp/src/main/java/com/rxsampleapp/SubscriptionActivity.java
import rx.schedulers.Schedulers;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import com.rxandroidnetworking.RxAndroidNetworking;
import com.rxsampleapp.utils.Utils;
import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
/*
* Copyright (C) 2016 Amit Shekhar
* Copyright (C) 2011 Android Open Source Project
*
* 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.rxsampleapp;
/**
* Created by amitshekhar on 31/07/16.
*/
public class SubscriptionActivity extends AppCompatActivity {
private static final String TAG = SubscriptionActivity.class.getSimpleName();
private static final String URL = "http://i.imgur.com/AtbX9iX.png";
private String dirPath;
private String fileName = "imgurimage.png";
Subscription subscription;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subscription);
dirPath = Utils.getRootDirPath(getApplicationContext());
}
@Override
protected void onDestroy() {
super.onDestroy();
if (subscription != null) {
subscription.unsubscribe();
}
}
public Observable<String> getObservable() { | return RxAndroidNetworking.download(URL, dirPath, fileName) |
amitshekhariitbhu/Fast-Android-Networking | rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/Rx2GetJSONApiTest.java | // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
| import android.app.Application;
import android.test.ApplicationTestCase;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.error.ANError;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Rule;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import static java.util.concurrent.TimeUnit.SECONDS; | .subscribe(new Observer<JSONObject>() {
@Override
public void onSubscribe(Disposable d) {
isSubscribedRef.set(true);
}
@Override
public void onNext(JSONObject response) {
assertTrue(false);
}
@Override
public void onError(Throwable e) {
ANError anError = (ANError) e;
errorBodyRef.set(anError.getErrorBody());
errorDetailRef.set(anError.getErrorDetail());
errorCodeRef.set(anError.getErrorCode());
latch.countDown();
}
@Override
public void onComplete() {
assertTrue(false);
}
});
assertTrue(latch.await(2, SECONDS));
assertTrue(isSubscribedRef.get());
| // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
// Path: rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/Rx2GetJSONApiTest.java
import android.app.Application;
import android.test.ApplicationTestCase;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.error.ANError;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Rule;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import static java.util.concurrent.TimeUnit.SECONDS;
.subscribe(new Observer<JSONObject>() {
@Override
public void onSubscribe(Disposable d) {
isSubscribedRef.set(true);
}
@Override
public void onNext(JSONObject response) {
assertTrue(false);
}
@Override
public void onError(Throwable e) {
ANError anError = (ANError) e;
errorBodyRef.set(anError.getErrorBody());
errorDetailRef.set(anError.getErrorDetail());
errorCodeRef.set(anError.getErrorCode());
latch.countDown();
}
@Override
public void onComplete() {
assertTrue(false);
}
});
assertTrue(latch.await(2, SECONDS));
assertTrue(isSubscribedRef.get());
| assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); |
amitshekhariitbhu/Fast-Android-Networking | rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/Rx2MultipartObjectApiTest.java | // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
//
// Path: rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/model/User.java
// public class User {
//
// public String firstName;
// public String lastName;
//
// }
| import java.util.concurrent.atomic.AtomicReference;
import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import static java.util.concurrent.TimeUnit.SECONDS;
import android.app.Application;
import android.test.ApplicationTestCase;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.error.ANError;
import com.rx2androidnetworking.model.User;
import org.junit.Rule;
import java.util.List;
import java.util.concurrent.CountDownLatch; | /*
*
* * Copyright (C) 2016 Amit Shekhar
* * Copyright (C) 2011 Android Open Source Project
* *
* * 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.rx2androidnetworking;
/**
* Created by amitshekhar on 29/04/17.
*/
public class Rx2MultipartObjectApiTest extends ApplicationTestCase<Application> {
@Rule
public final MockWebServer server = new MockWebServer();
public Rx2MultipartObjectApiTest() {
super(Application.class);
}
@Override
public void setUp() throws Exception {
super.setUp();
createApplication();
}
public void testObjectMultipartRequest() throws InterruptedException {
server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}"));
final AtomicReference<String> firstNameRef = new AtomicReference<>();
final AtomicReference<String> lastNameRef = new AtomicReference<>();
final AtomicReference<Boolean> isSubscribedRef = new AtomicReference<>();
final AtomicReference<Boolean> isCompletedRef = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(2);
Rx2AndroidNetworking.upload(server.url("/").toString())
.addMultipartParameter("key", "value")
.build() | // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
//
// Path: rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/model/User.java
// public class User {
//
// public String firstName;
// public String lastName;
//
// }
// Path: rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/Rx2MultipartObjectApiTest.java
import java.util.concurrent.atomic.AtomicReference;
import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import static java.util.concurrent.TimeUnit.SECONDS;
import android.app.Application;
import android.test.ApplicationTestCase;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.error.ANError;
import com.rx2androidnetworking.model.User;
import org.junit.Rule;
import java.util.List;
import java.util.concurrent.CountDownLatch;
/*
*
* * Copyright (C) 2016 Amit Shekhar
* * Copyright (C) 2011 Android Open Source Project
* *
* * 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.rx2androidnetworking;
/**
* Created by amitshekhar on 29/04/17.
*/
public class Rx2MultipartObjectApiTest extends ApplicationTestCase<Application> {
@Rule
public final MockWebServer server = new MockWebServer();
public Rx2MultipartObjectApiTest() {
super(Application.class);
}
@Override
public void setUp() throws Exception {
super.setUp();
createApplication();
}
public void testObjectMultipartRequest() throws InterruptedException {
server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}"));
final AtomicReference<String> firstNameRef = new AtomicReference<>();
final AtomicReference<String> lastNameRef = new AtomicReference<>();
final AtomicReference<Boolean> isSubscribedRef = new AtomicReference<>();
final AtomicReference<Boolean> isCompletedRef = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(2);
Rx2AndroidNetworking.upload(server.url("/").toString())
.addMultipartParameter("key", "value")
.build() | .getObjectObservable(User.class) |
amitshekhariitbhu/Fast-Android-Networking | rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/Rx2MultipartObjectApiTest.java | // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
//
// Path: rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/model/User.java
// public class User {
//
// public String firstName;
// public String lastName;
//
// }
| import java.util.concurrent.atomic.AtomicReference;
import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import static java.util.concurrent.TimeUnit.SECONDS;
import android.app.Application;
import android.test.ApplicationTestCase;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.error.ANError;
import com.rx2androidnetworking.model.User;
import org.junit.Rule;
import java.util.List;
import java.util.concurrent.CountDownLatch; | .subscribe(new Observer<User>() {
@Override
public void onSubscribe(Disposable d) {
isSubscribedRef.set(true);
}
@Override
public void onNext(User user) {
assertTrue(false);
}
@Override
public void onError(Throwable e) {
ANError anError = (ANError) e;
errorBodyRef.set(anError.getErrorBody());
errorDetailRef.set(anError.getErrorDetail());
errorCodeRef.set(anError.getErrorCode());
latch.countDown();
}
@Override
public void onComplete() {
assertTrue(false);
}
});
assertTrue(latch.await(2, SECONDS));
assertTrue(isSubscribedRef.get());
| // Path: android-networking/src/main/java/com/androidnetworking/common/ANConstants.java
// public final class ANConstants {
// public static final int MAX_CACHE_SIZE = 10 * 1024 * 1024;
// public static final int UPDATE = 0x01;
// public static final String CACHE_DIR_NAME = "cache_an";
// public static final String CONNECTION_ERROR = "connectionError";
// public static final String RESPONSE_FROM_SERVER_ERROR = "responseFromServerError";
// public static final String REQUEST_CANCELLED_ERROR = "requestCancelledError";
// public static final String PARSE_ERROR = "parseError";
// public static final String PREFETCH = "prefetch";
// public static final String FAST_ANDROID_NETWORKING = "FastAndroidNetworking";
// public static final String USER_AGENT = "User-Agent";
// public static final String SUCCESS = "success";
// public static final String OPTIONS = "OPTIONS";
// }
//
// Path: rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/model/User.java
// public class User {
//
// public String firstName;
// public String lastName;
//
// }
// Path: rx2-android-networking/src/androidTest/java/com/rx2androidnetworking/Rx2MultipartObjectApiTest.java
import java.util.concurrent.atomic.AtomicReference;
import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import static java.util.concurrent.TimeUnit.SECONDS;
import android.app.Application;
import android.test.ApplicationTestCase;
import com.androidnetworking.common.ANConstants;
import com.androidnetworking.error.ANError;
import com.rx2androidnetworking.model.User;
import org.junit.Rule;
import java.util.List;
import java.util.concurrent.CountDownLatch;
.subscribe(new Observer<User>() {
@Override
public void onSubscribe(Disposable d) {
isSubscribedRef.set(true);
}
@Override
public void onNext(User user) {
assertTrue(false);
}
@Override
public void onError(Throwable e) {
ANError anError = (ANError) e;
errorBodyRef.set(anError.getErrorBody());
errorDetailRef.set(anError.getErrorDetail());
errorCodeRef.set(anError.getErrorCode());
latch.countDown();
}
@Override
public void onComplete() {
assertTrue(false);
}
});
assertTrue(latch.await(2, SECONDS));
assertTrue(isSubscribedRef.get());
| assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get()); |
mediaworx/opencms-intellijplugin | src/com/mediaworx/intellij/opencmsplugin/configuration/FormTools.java | // Path: src/com/mediaworx/intellij/opencmsplugin/connector/AutoPublishMode.java
// public enum AutoPublishMode {
// OFF,
// FILECHANGE,
// ALL
// }
//
// Path: src/com/mediaworx/intellij/opencmsplugin/sync/SyncMode.java
// public enum SyncMode {
// PUSH,
// SYNC,
// PULL
// }
| import com.mediaworx.intellij.opencmsplugin.connector.AutoPublishMode;
import com.mediaworx.intellij.opencmsplugin.sync.SyncMode;
import javax.swing.*;
import javax.swing.text.JTextComponent; | /*
* This file is part of the OpenCms plugin for IntelliJ by mediaworx.
*
* For further information about the OpenCms plugin for IntelliJ, please
* see the project website at GitHub:
* https://github.com/mediaworx/opencms-intellijplugin
*
* Copyright (C) 2007-2016 mediaworx berlin AG (http://www.mediaworx.com)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.mediaworx.intellij.opencmsplugin.configuration;
/**
* Some helper methods used by configuration forms
*/
public class FormTools {
/**
* Reads the content of the given combo box and returns the corresponding sync mode
* @param comboBox the combo box to check
* @return the sync mode that corresponds to the value selected in the combo box
*/
public static SyncMode getSyncModeFromComboBox(JComboBox comboBox) {
String syncModeStr = (String)comboBox.getSelectedItem();
if (syncModeStr == null || syncModeStr.length() == 0) {
return SyncMode.SYNC;
}
syncModeStr = syncModeStr.replaceAll("([A-Z]+) ?.*", "$1");
return SyncMode.valueOf(syncModeStr);
}
/**
* Reads the content of the given combo box and returns the corresponding auto publish mode
* @param comboBox the combo box to check
* @return the auto publish mode that corresponds to the value selected in the combo box
*/ | // Path: src/com/mediaworx/intellij/opencmsplugin/connector/AutoPublishMode.java
// public enum AutoPublishMode {
// OFF,
// FILECHANGE,
// ALL
// }
//
// Path: src/com/mediaworx/intellij/opencmsplugin/sync/SyncMode.java
// public enum SyncMode {
// PUSH,
// SYNC,
// PULL
// }
// Path: src/com/mediaworx/intellij/opencmsplugin/configuration/FormTools.java
import com.mediaworx.intellij.opencmsplugin.connector.AutoPublishMode;
import com.mediaworx.intellij.opencmsplugin.sync.SyncMode;
import javax.swing.*;
import javax.swing.text.JTextComponent;
/*
* This file is part of the OpenCms plugin for IntelliJ by mediaworx.
*
* For further information about the OpenCms plugin for IntelliJ, please
* see the project website at GitHub:
* https://github.com/mediaworx/opencms-intellijplugin
*
* Copyright (C) 2007-2016 mediaworx berlin AG (http://www.mediaworx.com)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.mediaworx.intellij.opencmsplugin.configuration;
/**
* Some helper methods used by configuration forms
*/
public class FormTools {
/**
* Reads the content of the given combo box and returns the corresponding sync mode
* @param comboBox the combo box to check
* @return the sync mode that corresponds to the value selected in the combo box
*/
public static SyncMode getSyncModeFromComboBox(JComboBox comboBox) {
String syncModeStr = (String)comboBox.getSelectedItem();
if (syncModeStr == null || syncModeStr.length() == 0) {
return SyncMode.SYNC;
}
syncModeStr = syncModeStr.replaceAll("([A-Z]+) ?.*", "$1");
return SyncMode.valueOf(syncModeStr);
}
/**
* Reads the content of the given combo box and returns the corresponding auto publish mode
* @param comboBox the combo box to check
* @return the auto publish mode that corresponds to the value selected in the combo box
*/ | public static AutoPublishMode getAutoPublishModeFromCombobox(JComboBox comboBox) { |
mediaworx/opencms-intellijplugin | src/com/mediaworx/intellij/opencmsplugin/configuration/OpenCmsModuleConfigurationForm.java | // Path: src/com/mediaworx/intellij/opencmsplugin/sync/SyncMode.java
// public enum SyncMode {
// PUSH,
// SYNC,
// PULL
// }
| import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.regex.Pattern;
import com.intellij.openapi.module.Module;
import com.mediaworx.intellij.opencmsplugin.sync.SyncMode;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; | else {
useProjectDefaultModuleNameRadioButton.setSelected(false);
useModuleSpecificMoudleNameRadioButton.setSelected(true);
moduleName.setEnabled(true);
}
FormTools.setConfiguredOrKeepDefault(moduleName, data.getModuleName());
if (data.isUseProjectDefaultVfsRootEnabled()) {
useProjectDefaultVfsRootRadioButton.setSelected(true);
useModuleSpecificVfsRootRadioButton.setSelected(false);
localVfsRoot.setEnabled(false);
}
else {
useProjectDefaultVfsRootRadioButton.setSelected(false);
useModuleSpecificVfsRootRadioButton.setSelected(true);
localVfsRoot.setEnabled(true);
}
FormTools.setConfiguredOrKeepDefault(localVfsRoot, data.getLocalVfsRoot());
FormTools.setConfiguredOrKeepDefault(exportImportSiteRoot, data.getExportImportSiteRoot());
if (data.isUseProjectDefaultSyncModeEnabled()) {
useProjectDefaultSyncModeRadioButton.setSelected(true);
useModuleSpecificSyncModeRadioButton.setSelected(false);
syncMode.setEnabled(false);
}
else {
useProjectDefaultSyncModeRadioButton.setSelected(false);
useModuleSpecificSyncModeRadioButton.setSelected(true);
syncMode.setEnabled(true);
} | // Path: src/com/mediaworx/intellij/opencmsplugin/sync/SyncMode.java
// public enum SyncMode {
// PUSH,
// SYNC,
// PULL
// }
// Path: src/com/mediaworx/intellij/opencmsplugin/configuration/OpenCmsModuleConfigurationForm.java
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.regex.Pattern;
import com.intellij.openapi.module.Module;
import com.mediaworx.intellij.opencmsplugin.sync.SyncMode;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
else {
useProjectDefaultModuleNameRadioButton.setSelected(false);
useModuleSpecificMoudleNameRadioButton.setSelected(true);
moduleName.setEnabled(true);
}
FormTools.setConfiguredOrKeepDefault(moduleName, data.getModuleName());
if (data.isUseProjectDefaultVfsRootEnabled()) {
useProjectDefaultVfsRootRadioButton.setSelected(true);
useModuleSpecificVfsRootRadioButton.setSelected(false);
localVfsRoot.setEnabled(false);
}
else {
useProjectDefaultVfsRootRadioButton.setSelected(false);
useModuleSpecificVfsRootRadioButton.setSelected(true);
localVfsRoot.setEnabled(true);
}
FormTools.setConfiguredOrKeepDefault(localVfsRoot, data.getLocalVfsRoot());
FormTools.setConfiguredOrKeepDefault(exportImportSiteRoot, data.getExportImportSiteRoot());
if (data.isUseProjectDefaultSyncModeEnabled()) {
useProjectDefaultSyncModeRadioButton.setSelected(true);
useModuleSpecificSyncModeRadioButton.setSelected(false);
syncMode.setEnabled(false);
}
else {
useProjectDefaultSyncModeRadioButton.setSelected(false);
useModuleSpecificSyncModeRadioButton.setSelected(true);
syncMode.setEnabled(true);
} | if (data.getSyncMode() == SyncMode.PUSH) { |
mediaworx/opencms-intellijplugin | src/com/mediaworx/intellij/opencmsplugin/opencms/OpenCmsModuleResource.java | // Path: src/com/mediaworx/intellij/opencmsplugin/tools/PluginTools.java
// public class PluginTools {
//
// /**
// * @param module an IntelliJ module
// * @return the content root for the module. It is assumed that IntelliJ modules representing OpenCms modules
// * have only one content root. If multiple content roots exist for the IntelliJ module, only the first is
// * returned.
// */
// public static String getModuleContentRoot(Module module) {
// String moduleContentRoot = null;
// if (module != null) {
// VirtualFile[] moduleRoots = ModuleRootManager.getInstance(module).getContentRoots();
// if (moduleRoots.length == 0) {
// return null;
// }
// // we assume that for OpenCms modules there is only one content root
// moduleContentRoot = moduleRoots[0].getPath();
// }
// return moduleContentRoot;
// }
//
//
// /**
// * Converts an array of IntelliJ's VirtualFiles to a list of standard Java File handles.
// * @param virtualFiles the IntelliJ VirtualFile array
// * @return a list of corresponding standard Java File handles
// */
// public static List<File> getRealFilesFromVirtualFiles(VirtualFile[] virtualFiles) {
// List<File> realFiles = new ArrayList<>(virtualFiles.length);
// for (VirtualFile virtualFile : virtualFiles) {
// realFiles.add(new File(virtualFile.getPath()));
// }
// return realFiles;
// }
//
// /**
// * Converts the windows File separator "\" to the Unix/Linux/Mac separator "/"
// * @param path the path to convert
// * @return a path woth all backward slashes replaced by forward ones
// */
// public static String ensureUnixPath(String path) {
// if (path == null || path.length() == 0) {
// return path;
// }
// return path.replaceAll("\\\\", "/");
// }
//
// /**
// * converts any newline format (\r\n or \r) to Unix/Linux/Mac newline format (\n)
// * @param in the String to convert
// * @return the original String with all newlines converted to \n
// */
// public static String ensureUnixNewline(String in) {
// return in.replaceAll("\\r\\n|\\r", "\n");
// }
//
// /**
// * If the module has a site root other than "/" configured, then the site root is removed from the beginning of
// * the given vfsPath
// * @param module the module the path belongs to
// * @param vfsPath the VFS path to be stripped of the site root
// * @return the given vfsPath with the site root removed
// */
// public static String stripVfsSiteRootFromVfsPath(OpenCmsModule module, String vfsPath) {
// String localPath;
// if ("/".equals(module.getExportImportSiteRoot())) {
// localPath = vfsPath;
// }
// else {
// localPath = vfsPath.replaceFirst("^" + module.getExportImportSiteRoot(), "");
// }
// return localPath;
// }
//
//
// /**
// * If the module has a site root other than "/" configured, then the site root is added to the beginning of
// * the given local path
// *
// * @param module the module the path belongs to
// * @param localPath the local path that the site root should be added to
// * @return the given local path with the site root added as prefix
// */
// public static String addVfsSiteRootToLocalPath(OpenCmsModule module, String localPath) {
// String vfsRootPath = localPath;
// if (!"/".equals(module.getExportImportSiteRoot())) {
// vfsRootPath = module.getExportImportSiteRoot() + vfsRootPath;
// }
// return vfsRootPath;
//
// }
// }
| import com.mediaworx.intellij.opencmsplugin.tools.PluginTools; | /*
* This file is part of the OpenCms plugin for IntelliJ by mediaworx.
*
* For further information about the OpenCms plugin for IntelliJ, please
* see the project website at GitHub:
* https://github.com/mediaworx/opencms-intellijplugin
*
* Copyright (C) 2007-2016 mediaworx berlin AG (http://www.mediaworx.com)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.mediaworx.intellij.opencmsplugin.opencms;
/**
* Bean linking a resource path to its corresponding OpenCms module
*/
public class OpenCmsModuleResource {
private OpenCmsModule openCmsModule;
private String resourcePath;
/**
* @param openCmsModule the OpenCms module this resource belongs to
* @param resourcePath the resource path (VFS relative path)
*/
public OpenCmsModuleResource(OpenCmsModule openCmsModule, String resourcePath) {
this.openCmsModule = openCmsModule; | // Path: src/com/mediaworx/intellij/opencmsplugin/tools/PluginTools.java
// public class PluginTools {
//
// /**
// * @param module an IntelliJ module
// * @return the content root for the module. It is assumed that IntelliJ modules representing OpenCms modules
// * have only one content root. If multiple content roots exist for the IntelliJ module, only the first is
// * returned.
// */
// public static String getModuleContentRoot(Module module) {
// String moduleContentRoot = null;
// if (module != null) {
// VirtualFile[] moduleRoots = ModuleRootManager.getInstance(module).getContentRoots();
// if (moduleRoots.length == 0) {
// return null;
// }
// // we assume that for OpenCms modules there is only one content root
// moduleContentRoot = moduleRoots[0].getPath();
// }
// return moduleContentRoot;
// }
//
//
// /**
// * Converts an array of IntelliJ's VirtualFiles to a list of standard Java File handles.
// * @param virtualFiles the IntelliJ VirtualFile array
// * @return a list of corresponding standard Java File handles
// */
// public static List<File> getRealFilesFromVirtualFiles(VirtualFile[] virtualFiles) {
// List<File> realFiles = new ArrayList<>(virtualFiles.length);
// for (VirtualFile virtualFile : virtualFiles) {
// realFiles.add(new File(virtualFile.getPath()));
// }
// return realFiles;
// }
//
// /**
// * Converts the windows File separator "\" to the Unix/Linux/Mac separator "/"
// * @param path the path to convert
// * @return a path woth all backward slashes replaced by forward ones
// */
// public static String ensureUnixPath(String path) {
// if (path == null || path.length() == 0) {
// return path;
// }
// return path.replaceAll("\\\\", "/");
// }
//
// /**
// * converts any newline format (\r\n or \r) to Unix/Linux/Mac newline format (\n)
// * @param in the String to convert
// * @return the original String with all newlines converted to \n
// */
// public static String ensureUnixNewline(String in) {
// return in.replaceAll("\\r\\n|\\r", "\n");
// }
//
// /**
// * If the module has a site root other than "/" configured, then the site root is removed from the beginning of
// * the given vfsPath
// * @param module the module the path belongs to
// * @param vfsPath the VFS path to be stripped of the site root
// * @return the given vfsPath with the site root removed
// */
// public static String stripVfsSiteRootFromVfsPath(OpenCmsModule module, String vfsPath) {
// String localPath;
// if ("/".equals(module.getExportImportSiteRoot())) {
// localPath = vfsPath;
// }
// else {
// localPath = vfsPath.replaceFirst("^" + module.getExportImportSiteRoot(), "");
// }
// return localPath;
// }
//
//
// /**
// * If the module has a site root other than "/" configured, then the site root is added to the beginning of
// * the given local path
// *
// * @param module the module the path belongs to
// * @param localPath the local path that the site root should be added to
// * @return the given local path with the site root added as prefix
// */
// public static String addVfsSiteRootToLocalPath(OpenCmsModule module, String localPath) {
// String vfsRootPath = localPath;
// if (!"/".equals(module.getExportImportSiteRoot())) {
// vfsRootPath = module.getExportImportSiteRoot() + vfsRootPath;
// }
// return vfsRootPath;
//
// }
// }
// Path: src/com/mediaworx/intellij/opencmsplugin/opencms/OpenCmsModuleResource.java
import com.mediaworx.intellij.opencmsplugin.tools.PluginTools;
/*
* This file is part of the OpenCms plugin for IntelliJ by mediaworx.
*
* For further information about the OpenCms plugin for IntelliJ, please
* see the project website at GitHub:
* https://github.com/mediaworx/opencms-intellijplugin
*
* Copyright (C) 2007-2016 mediaworx berlin AG (http://www.mediaworx.com)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.mediaworx.intellij.opencmsplugin.opencms;
/**
* Bean linking a resource path to its corresponding OpenCms module
*/
public class OpenCmsModuleResource {
private OpenCmsModule openCmsModule;
private String resourcePath;
/**
* @param openCmsModule the OpenCms module this resource belongs to
* @param resourcePath the resource path (VFS relative path)
*/
public OpenCmsModuleResource(OpenCmsModule openCmsModule, String resourcePath) {
this.openCmsModule = openCmsModule; | this.resourcePath = PluginTools.ensureUnixPath(resourcePath); |
mediaworx/opencms-intellijplugin | src/com/mediaworx/intellij/opencmsplugin/connector/OpenCmsPluginConnector.java | // Path: src/com/mediaworx/intellij/opencmsplugin/exceptions/OpenCmsConnectorException.java
// public class OpenCmsConnectorException extends Exception {
//
// /**
// * Creates a new OpenCmsConnectorException with the given message
// * @param message the error message
// */
// public OpenCmsConnectorException(String message) {
// super(message);
// }
//
// /**
// * Creates a new OpenCmsConnectorException with the given message
// * @param message the error message
// * @param cause Original Exception/Throwable that led to the exception
// */
// public OpenCmsConnectorException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/com/mediaworx/intellij/opencmsplugin/opencms/OpenCmsModuleResource.java
// public class OpenCmsModuleResource {
//
// private OpenCmsModule openCmsModule;
// private String resourcePath;
//
// /**
// * @param openCmsModule the OpenCms module this resource belongs to
// * @param resourcePath the resource path (VFS relative path)
// */
// public OpenCmsModuleResource(OpenCmsModule openCmsModule, String resourcePath) {
// this.openCmsModule = openCmsModule;
// this.resourcePath = PluginTools.ensureUnixPath(resourcePath);
// }
//
// /**
// * @return the OpenCms module this resource belongs to
// */
// public OpenCmsModule getOpenCmsModule() {
// return openCmsModule;
// }
//
// /**
// * @return the resource path (VFS relative path)
// */
// public String getResourcePath() {
// String resourcePath = this.resourcePath.replaceFirst("/$", ""); // strip trailing slash
// return PluginTools.addVfsSiteRootToLocalPath(openCmsModule, resourcePath);
// }
//
// }
| import com.intellij.openapi.diagnostic.Logger;
import com.mediaworx.intellij.opencmsplugin.exceptions.OpenCmsConnectorException;
import com.mediaworx.intellij.opencmsplugin.opencms.OpenCmsModuleResource;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | resetClient();
}
}
/**
* Sets the flag denoting if using placeholders instead of dates in resource meta data is enabled
* @param useMetaDateVariables <code>true</code> if using date placeholders should be enabled, <code>false</code>
* otherwise
*/
public void setUseMetaDateVariables(boolean useMetaDateVariables) {
this.useMetaDateVariables = useMetaDateVariables;
}
/**
* Sets the flag denoting if using placeholders instead of UUIDs in resource meta data is enabled
* @param useMetaIdVariables <code>true</code> if using UUID placeholders should be enabled, <code>false</code>
* otherwise
*/
public void setUseMetaIdVariables(boolean useMetaIdVariables) {
this.useMetaIdVariables = useMetaIdVariables;
}
/**
* Gets the resource meta data for the given module resources
* @param moduleResources a list of module resources for which meta data is to be retrieved
* @return a map containing the resource path as key and the corresponding resource meta data (XML String) as value
* @throws IOException if something went wrong with the HttpClient
* @throws OpenCmsConnectorException if the connector was not found at the given Url or if the connector returned
* an invalid http status
*/ | // Path: src/com/mediaworx/intellij/opencmsplugin/exceptions/OpenCmsConnectorException.java
// public class OpenCmsConnectorException extends Exception {
//
// /**
// * Creates a new OpenCmsConnectorException with the given message
// * @param message the error message
// */
// public OpenCmsConnectorException(String message) {
// super(message);
// }
//
// /**
// * Creates a new OpenCmsConnectorException with the given message
// * @param message the error message
// * @param cause Original Exception/Throwable that led to the exception
// */
// public OpenCmsConnectorException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/com/mediaworx/intellij/opencmsplugin/opencms/OpenCmsModuleResource.java
// public class OpenCmsModuleResource {
//
// private OpenCmsModule openCmsModule;
// private String resourcePath;
//
// /**
// * @param openCmsModule the OpenCms module this resource belongs to
// * @param resourcePath the resource path (VFS relative path)
// */
// public OpenCmsModuleResource(OpenCmsModule openCmsModule, String resourcePath) {
// this.openCmsModule = openCmsModule;
// this.resourcePath = PluginTools.ensureUnixPath(resourcePath);
// }
//
// /**
// * @return the OpenCms module this resource belongs to
// */
// public OpenCmsModule getOpenCmsModule() {
// return openCmsModule;
// }
//
// /**
// * @return the resource path (VFS relative path)
// */
// public String getResourcePath() {
// String resourcePath = this.resourcePath.replaceFirst("/$", ""); // strip trailing slash
// return PluginTools.addVfsSiteRootToLocalPath(openCmsModule, resourcePath);
// }
//
// }
// Path: src/com/mediaworx/intellij/opencmsplugin/connector/OpenCmsPluginConnector.java
import com.intellij.openapi.diagnostic.Logger;
import com.mediaworx.intellij.opencmsplugin.exceptions.OpenCmsConnectorException;
import com.mediaworx.intellij.opencmsplugin.opencms.OpenCmsModuleResource;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
resetClient();
}
}
/**
* Sets the flag denoting if using placeholders instead of dates in resource meta data is enabled
* @param useMetaDateVariables <code>true</code> if using date placeholders should be enabled, <code>false</code>
* otherwise
*/
public void setUseMetaDateVariables(boolean useMetaDateVariables) {
this.useMetaDateVariables = useMetaDateVariables;
}
/**
* Sets the flag denoting if using placeholders instead of UUIDs in resource meta data is enabled
* @param useMetaIdVariables <code>true</code> if using UUID placeholders should be enabled, <code>false</code>
* otherwise
*/
public void setUseMetaIdVariables(boolean useMetaIdVariables) {
this.useMetaIdVariables = useMetaIdVariables;
}
/**
* Gets the resource meta data for the given module resources
* @param moduleResources a list of module resources for which meta data is to be retrieved
* @return a map containing the resource path as key and the corresponding resource meta data (XML String) as value
* @throws IOException if something went wrong with the HttpClient
* @throws OpenCmsConnectorException if the connector was not found at the given Url or if the connector returned
* an invalid http status
*/ | public HashMap<String, String> getModuleResourceInfos(List<OpenCmsModuleResource> moduleResources) throws IOException, OpenCmsConnectorException { |
mediaworx/opencms-intellijplugin | src/com/mediaworx/intellij/opencmsplugin/connector/OpenCmsPluginConnector.java | // Path: src/com/mediaworx/intellij/opencmsplugin/exceptions/OpenCmsConnectorException.java
// public class OpenCmsConnectorException extends Exception {
//
// /**
// * Creates a new OpenCmsConnectorException with the given message
// * @param message the error message
// */
// public OpenCmsConnectorException(String message) {
// super(message);
// }
//
// /**
// * Creates a new OpenCmsConnectorException with the given message
// * @param message the error message
// * @param cause Original Exception/Throwable that led to the exception
// */
// public OpenCmsConnectorException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/com/mediaworx/intellij/opencmsplugin/opencms/OpenCmsModuleResource.java
// public class OpenCmsModuleResource {
//
// private OpenCmsModule openCmsModule;
// private String resourcePath;
//
// /**
// * @param openCmsModule the OpenCms module this resource belongs to
// * @param resourcePath the resource path (VFS relative path)
// */
// public OpenCmsModuleResource(OpenCmsModule openCmsModule, String resourcePath) {
// this.openCmsModule = openCmsModule;
// this.resourcePath = PluginTools.ensureUnixPath(resourcePath);
// }
//
// /**
// * @return the OpenCms module this resource belongs to
// */
// public OpenCmsModule getOpenCmsModule() {
// return openCmsModule;
// }
//
// /**
// * @return the resource path (VFS relative path)
// */
// public String getResourcePath() {
// String resourcePath = this.resourcePath.replaceFirst("/$", ""); // strip trailing slash
// return PluginTools.addVfsSiteRootToLocalPath(openCmsModule, resourcePath);
// }
//
// }
| import com.intellij.openapi.diagnostic.Logger;
import com.mediaworx.intellij.opencmsplugin.exceptions.OpenCmsConnectorException;
import com.mediaworx.intellij.opencmsplugin.opencms.OpenCmsModuleResource;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | resetClient();
}
}
/**
* Sets the flag denoting if using placeholders instead of dates in resource meta data is enabled
* @param useMetaDateVariables <code>true</code> if using date placeholders should be enabled, <code>false</code>
* otherwise
*/
public void setUseMetaDateVariables(boolean useMetaDateVariables) {
this.useMetaDateVariables = useMetaDateVariables;
}
/**
* Sets the flag denoting if using placeholders instead of UUIDs in resource meta data is enabled
* @param useMetaIdVariables <code>true</code> if using UUID placeholders should be enabled, <code>false</code>
* otherwise
*/
public void setUseMetaIdVariables(boolean useMetaIdVariables) {
this.useMetaIdVariables = useMetaIdVariables;
}
/**
* Gets the resource meta data for the given module resources
* @param moduleResources a list of module resources for which meta data is to be retrieved
* @return a map containing the resource path as key and the corresponding resource meta data (XML String) as value
* @throws IOException if something went wrong with the HttpClient
* @throws OpenCmsConnectorException if the connector was not found at the given Url or if the connector returned
* an invalid http status
*/ | // Path: src/com/mediaworx/intellij/opencmsplugin/exceptions/OpenCmsConnectorException.java
// public class OpenCmsConnectorException extends Exception {
//
// /**
// * Creates a new OpenCmsConnectorException with the given message
// * @param message the error message
// */
// public OpenCmsConnectorException(String message) {
// super(message);
// }
//
// /**
// * Creates a new OpenCmsConnectorException with the given message
// * @param message the error message
// * @param cause Original Exception/Throwable that led to the exception
// */
// public OpenCmsConnectorException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/com/mediaworx/intellij/opencmsplugin/opencms/OpenCmsModuleResource.java
// public class OpenCmsModuleResource {
//
// private OpenCmsModule openCmsModule;
// private String resourcePath;
//
// /**
// * @param openCmsModule the OpenCms module this resource belongs to
// * @param resourcePath the resource path (VFS relative path)
// */
// public OpenCmsModuleResource(OpenCmsModule openCmsModule, String resourcePath) {
// this.openCmsModule = openCmsModule;
// this.resourcePath = PluginTools.ensureUnixPath(resourcePath);
// }
//
// /**
// * @return the OpenCms module this resource belongs to
// */
// public OpenCmsModule getOpenCmsModule() {
// return openCmsModule;
// }
//
// /**
// * @return the resource path (VFS relative path)
// */
// public String getResourcePath() {
// String resourcePath = this.resourcePath.replaceFirst("/$", ""); // strip trailing slash
// return PluginTools.addVfsSiteRootToLocalPath(openCmsModule, resourcePath);
// }
//
// }
// Path: src/com/mediaworx/intellij/opencmsplugin/connector/OpenCmsPluginConnector.java
import com.intellij.openapi.diagnostic.Logger;
import com.mediaworx.intellij.opencmsplugin.exceptions.OpenCmsConnectorException;
import com.mediaworx.intellij.opencmsplugin.opencms.OpenCmsModuleResource;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
resetClient();
}
}
/**
* Sets the flag denoting if using placeholders instead of dates in resource meta data is enabled
* @param useMetaDateVariables <code>true</code> if using date placeholders should be enabled, <code>false</code>
* otherwise
*/
public void setUseMetaDateVariables(boolean useMetaDateVariables) {
this.useMetaDateVariables = useMetaDateVariables;
}
/**
* Sets the flag denoting if using placeholders instead of UUIDs in resource meta data is enabled
* @param useMetaIdVariables <code>true</code> if using UUID placeholders should be enabled, <code>false</code>
* otherwise
*/
public void setUseMetaIdVariables(boolean useMetaIdVariables) {
this.useMetaIdVariables = useMetaIdVariables;
}
/**
* Gets the resource meta data for the given module resources
* @param moduleResources a list of module resources for which meta data is to be retrieved
* @return a map containing the resource path as key and the corresponding resource meta data (XML String) as value
* @throws IOException if something went wrong with the HttpClient
* @throws OpenCmsConnectorException if the connector was not found at the given Url or if the connector returned
* an invalid http status
*/ | public HashMap<String, String> getModuleResourceInfos(List<OpenCmsModuleResource> moduleResources) throws IOException, OpenCmsConnectorException { |
mediaworx/opencms-intellijplugin | src/com/mediaworx/intellij/opencmsplugin/configuration/OpenCmsPluginConfigurationData.java | // Path: src/com/mediaworx/intellij/opencmsplugin/connector/AutoPublishMode.java
// public enum AutoPublishMode {
// OFF,
// FILECHANGE,
// ALL
// }
//
// Path: src/com/mediaworx/intellij/opencmsplugin/sync/SyncMode.java
// public enum SyncMode {
// PUSH,
// SYNC,
// PULL
// }
| import com.mediaworx.intellij.opencmsplugin.connector.AutoPublishMode;
import com.mediaworx.intellij.opencmsplugin.sync.SyncMode;
import org.apache.commons.lang.StringUtils; | /*
* This file is part of the OpenCms plugin for IntelliJ by mediaworx.
*
* For further information about the OpenCms plugin for IntelliJ, please
* see the project website at GitHub:
* https://github.com/mediaworx/opencms-intellijplugin
*
* Copyright (C) 2007-2016 mediaworx berlin AG (http://www.mediaworx.com)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.mediaworx.intellij.opencmsplugin.configuration;
/**
* Configuration data container for the project level configuration of the OpenCms plugin for IntelliJ.
*/
public class OpenCmsPluginConfigurationData {
private boolean openCmsPluginEnabled = false;
private String repository;
private String username;
private String password;
private String webappRoot;
private String defaultLocalVfsRoot;
private String moduleNamingScheme; | // Path: src/com/mediaworx/intellij/opencmsplugin/connector/AutoPublishMode.java
// public enum AutoPublishMode {
// OFF,
// FILECHANGE,
// ALL
// }
//
// Path: src/com/mediaworx/intellij/opencmsplugin/sync/SyncMode.java
// public enum SyncMode {
// PUSH,
// SYNC,
// PULL
// }
// Path: src/com/mediaworx/intellij/opencmsplugin/configuration/OpenCmsPluginConfigurationData.java
import com.mediaworx.intellij.opencmsplugin.connector.AutoPublishMode;
import com.mediaworx.intellij.opencmsplugin.sync.SyncMode;
import org.apache.commons.lang.StringUtils;
/*
* This file is part of the OpenCms plugin for IntelliJ by mediaworx.
*
* For further information about the OpenCms plugin for IntelliJ, please
* see the project website at GitHub:
* https://github.com/mediaworx/opencms-intellijplugin
*
* Copyright (C) 2007-2016 mediaworx berlin AG (http://www.mediaworx.com)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.mediaworx.intellij.opencmsplugin.configuration;
/**
* Configuration data container for the project level configuration of the OpenCms plugin for IntelliJ.
*/
public class OpenCmsPluginConfigurationData {
private boolean openCmsPluginEnabled = false;
private String repository;
private String username;
private String password;
private String webappRoot;
private String defaultLocalVfsRoot;
private String moduleNamingScheme; | private SyncMode defaultSyncMode; |
mediaworx/opencms-intellijplugin | src/com/mediaworx/intellij/opencmsplugin/configuration/OpenCmsPluginConfigurationData.java | // Path: src/com/mediaworx/intellij/opencmsplugin/connector/AutoPublishMode.java
// public enum AutoPublishMode {
// OFF,
// FILECHANGE,
// ALL
// }
//
// Path: src/com/mediaworx/intellij/opencmsplugin/sync/SyncMode.java
// public enum SyncMode {
// PUSH,
// SYNC,
// PULL
// }
| import com.mediaworx.intellij.opencmsplugin.connector.AutoPublishMode;
import com.mediaworx.intellij.opencmsplugin.sync.SyncMode;
import org.apache.commons.lang.StringUtils; | /*
* This file is part of the OpenCms plugin for IntelliJ by mediaworx.
*
* For further information about the OpenCms plugin for IntelliJ, please
* see the project website at GitHub:
* https://github.com/mediaworx/opencms-intellijplugin
*
* Copyright (C) 2007-2016 mediaworx berlin AG (http://www.mediaworx.com)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.mediaworx.intellij.opencmsplugin.configuration;
/**
* Configuration data container for the project level configuration of the OpenCms plugin for IntelliJ.
*/
public class OpenCmsPluginConfigurationData {
private boolean openCmsPluginEnabled = false;
private String repository;
private String username;
private String password;
private String webappRoot;
private String defaultLocalVfsRoot;
private String moduleNamingScheme;
private SyncMode defaultSyncMode;
private String ignoredFiles;
private String[] ignoredFilesArray;
private String ignoredPaths;
private String[] ignoredPathsArray;
private String moduleZipTargetFolderPath;
private boolean pluginConnectorEnabled;
private String connectorUrl;
private boolean pluginConnectorServiceEnabled;
private String connectorServiceUrl; | // Path: src/com/mediaworx/intellij/opencmsplugin/connector/AutoPublishMode.java
// public enum AutoPublishMode {
// OFF,
// FILECHANGE,
// ALL
// }
//
// Path: src/com/mediaworx/intellij/opencmsplugin/sync/SyncMode.java
// public enum SyncMode {
// PUSH,
// SYNC,
// PULL
// }
// Path: src/com/mediaworx/intellij/opencmsplugin/configuration/OpenCmsPluginConfigurationData.java
import com.mediaworx.intellij.opencmsplugin.connector.AutoPublishMode;
import com.mediaworx.intellij.opencmsplugin.sync.SyncMode;
import org.apache.commons.lang.StringUtils;
/*
* This file is part of the OpenCms plugin for IntelliJ by mediaworx.
*
* For further information about the OpenCms plugin for IntelliJ, please
* see the project website at GitHub:
* https://github.com/mediaworx/opencms-intellijplugin
*
* Copyright (C) 2007-2016 mediaworx berlin AG (http://www.mediaworx.com)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.mediaworx.intellij.opencmsplugin.configuration;
/**
* Configuration data container for the project level configuration of the OpenCms plugin for IntelliJ.
*/
public class OpenCmsPluginConfigurationData {
private boolean openCmsPluginEnabled = false;
private String repository;
private String username;
private String password;
private String webappRoot;
private String defaultLocalVfsRoot;
private String moduleNamingScheme;
private SyncMode defaultSyncMode;
private String ignoredFiles;
private String[] ignoredFilesArray;
private String ignoredPaths;
private String[] ignoredPathsArray;
private String moduleZipTargetFolderPath;
private boolean pluginConnectorEnabled;
private String connectorUrl;
private boolean pluginConnectorServiceEnabled;
private String connectorServiceUrl; | private AutoPublishMode autoPublishMode; |
mediaworx/opencms-intellijplugin | src/com/mediaworx/intellij/opencmsplugin/configuration/OpenCmsModuleConfigurationData.java | // Path: src/com/mediaworx/intellij/opencmsplugin/sync/SyncMode.java
// public enum SyncMode {
// PUSH,
// SYNC,
// PULL
// }
| import com.mediaworx.intellij.opencmsplugin.sync.SyncMode; | /*
* This file is part of the OpenCms plugin for IntelliJ by mediaworx.
*
* For further information about the OpenCms plugin for IntelliJ, please
* see the project website at GitHub:
* https://github.com/mediaworx/opencms-intellijplugin
*
* Copyright (C) 2007-2016 mediaworx berlin AG (http://www.mediaworx.com)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.mediaworx.intellij.opencmsplugin.configuration;
/**
* Configuration data container for the module level configuration of the OpenCms plugin for IntelliJ.
*/
public class OpenCmsModuleConfigurationData {
private boolean openCmsModuleEnabled = false;
private boolean useProjectDefaultModuleNameEnabled = true;
private String moduleName;
private boolean useProjectDefaultVfsRootEnabled = true;
private String localVfsRoot;
private String exportImportSiteRoot;
private boolean useProjectDefaultSyncModeEnabled = true; | // Path: src/com/mediaworx/intellij/opencmsplugin/sync/SyncMode.java
// public enum SyncMode {
// PUSH,
// SYNC,
// PULL
// }
// Path: src/com/mediaworx/intellij/opencmsplugin/configuration/OpenCmsModuleConfigurationData.java
import com.mediaworx.intellij.opencmsplugin.sync.SyncMode;
/*
* This file is part of the OpenCms plugin for IntelliJ by mediaworx.
*
* For further information about the OpenCms plugin for IntelliJ, please
* see the project website at GitHub:
* https://github.com/mediaworx/opencms-intellijplugin
*
* Copyright (C) 2007-2016 mediaworx berlin AG (http://www.mediaworx.com)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.mediaworx.intellij.opencmsplugin.configuration;
/**
* Configuration data container for the module level configuration of the OpenCms plugin for IntelliJ.
*/
public class OpenCmsModuleConfigurationData {
private boolean openCmsModuleEnabled = false;
private boolean useProjectDefaultModuleNameEnabled = true;
private String moduleName;
private boolean useProjectDefaultVfsRootEnabled = true;
private String localVfsRoot;
private String exportImportSiteRoot;
private boolean useProjectDefaultSyncModeEnabled = true; | private SyncMode syncMode; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.