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
|
---|---|---|---|---|---|---|
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/HttpUrlSource.java | // Path: library/src/main/java/com/danikula/videocache/headers/EmptyHeadersInjector.java
// public class EmptyHeadersInjector implements HeaderInjector {
//
// @Override
// public Map<String, String> addHeaders(String url) {
// return new HashMap<>();
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorageFactory.java
// public class SourceInfoStorageFactory {
//
// public static SourceInfoStorage newSourceInfoStorage(Context context) {
// return new DatabaseSourceInfoStorage(context);
// }
//
// public static SourceInfoStorage newEmptySourceInfoStorage() {
// return new NoSourceInfoStorage();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheUtils.java
// static final int DEFAULT_BUFFER_SIZE = 8 * 1024;
| import android.text.TextUtils;
import com.danikula.videocache.headers.EmptyHeadersInjector;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import com.danikula.videocache.sourcestorage.SourceInfoStorageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import static com.danikula.videocache.Preconditions.checkNotNull;
import static com.danikula.videocache.ProxyCacheUtils.DEFAULT_BUFFER_SIZE;
import static java.net.HttpURLConnection.HTTP_MOVED_PERM;
import static java.net.HttpURLConnection.HTTP_MOVED_TEMP;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.HttpURLConnection.HTTP_PARTIAL;
import static java.net.HttpURLConnection.HTTP_SEE_OTHER; | package com.danikula.videocache;
/**
* {@link Source} that uses http resource as source for {@link ProxyCache}.
*
* @author Alexey Danilov ([email protected]).
*/
public class HttpUrlSource implements Source {
private static final Logger LOG = LoggerFactory.getLogger("HttpUrlSource");
private static final int MAX_REDIRECTS = 5;
private final SourceInfoStorage sourceInfoStorage;
private final HeaderInjector headerInjector;
private SourceInfo sourceInfo;
private HttpURLConnection connection;
private InputStream inputStream;
public HttpUrlSource(String url) { | // Path: library/src/main/java/com/danikula/videocache/headers/EmptyHeadersInjector.java
// public class EmptyHeadersInjector implements HeaderInjector {
//
// @Override
// public Map<String, String> addHeaders(String url) {
// return new HashMap<>();
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorageFactory.java
// public class SourceInfoStorageFactory {
//
// public static SourceInfoStorage newSourceInfoStorage(Context context) {
// return new DatabaseSourceInfoStorage(context);
// }
//
// public static SourceInfoStorage newEmptySourceInfoStorage() {
// return new NoSourceInfoStorage();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheUtils.java
// static final int DEFAULT_BUFFER_SIZE = 8 * 1024;
// Path: library/src/main/java/com/danikula/videocache/HttpUrlSource.java
import android.text.TextUtils;
import com.danikula.videocache.headers.EmptyHeadersInjector;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import com.danikula.videocache.sourcestorage.SourceInfoStorageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import static com.danikula.videocache.Preconditions.checkNotNull;
import static com.danikula.videocache.ProxyCacheUtils.DEFAULT_BUFFER_SIZE;
import static java.net.HttpURLConnection.HTTP_MOVED_PERM;
import static java.net.HttpURLConnection.HTTP_MOVED_TEMP;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.HttpURLConnection.HTTP_PARTIAL;
import static java.net.HttpURLConnection.HTTP_SEE_OTHER;
package com.danikula.videocache;
/**
* {@link Source} that uses http resource as source for {@link ProxyCache}.
*
* @author Alexey Danilov ([email protected]).
*/
public class HttpUrlSource implements Source {
private static final Logger LOG = LoggerFactory.getLogger("HttpUrlSource");
private static final int MAX_REDIRECTS = 5;
private final SourceInfoStorage sourceInfoStorage;
private final HeaderInjector headerInjector;
private SourceInfo sourceInfo;
private HttpURLConnection connection;
private InputStream inputStream;
public HttpUrlSource(String url) { | this(url, SourceInfoStorageFactory.newEmptySourceInfoStorage()); |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/HttpUrlSource.java | // Path: library/src/main/java/com/danikula/videocache/headers/EmptyHeadersInjector.java
// public class EmptyHeadersInjector implements HeaderInjector {
//
// @Override
// public Map<String, String> addHeaders(String url) {
// return new HashMap<>();
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorageFactory.java
// public class SourceInfoStorageFactory {
//
// public static SourceInfoStorage newSourceInfoStorage(Context context) {
// return new DatabaseSourceInfoStorage(context);
// }
//
// public static SourceInfoStorage newEmptySourceInfoStorage() {
// return new NoSourceInfoStorage();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheUtils.java
// static final int DEFAULT_BUFFER_SIZE = 8 * 1024;
| import android.text.TextUtils;
import com.danikula.videocache.headers.EmptyHeadersInjector;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import com.danikula.videocache.sourcestorage.SourceInfoStorageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import static com.danikula.videocache.Preconditions.checkNotNull;
import static com.danikula.videocache.ProxyCacheUtils.DEFAULT_BUFFER_SIZE;
import static java.net.HttpURLConnection.HTTP_MOVED_PERM;
import static java.net.HttpURLConnection.HTTP_MOVED_TEMP;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.HttpURLConnection.HTTP_PARTIAL;
import static java.net.HttpURLConnection.HTTP_SEE_OTHER; | package com.danikula.videocache;
/**
* {@link Source} that uses http resource as source for {@link ProxyCache}.
*
* @author Alexey Danilov ([email protected]).
*/
public class HttpUrlSource implements Source {
private static final Logger LOG = LoggerFactory.getLogger("HttpUrlSource");
private static final int MAX_REDIRECTS = 5;
private final SourceInfoStorage sourceInfoStorage;
private final HeaderInjector headerInjector;
private SourceInfo sourceInfo;
private HttpURLConnection connection;
private InputStream inputStream;
public HttpUrlSource(String url) {
this(url, SourceInfoStorageFactory.newEmptySourceInfoStorage());
}
public HttpUrlSource(String url, SourceInfoStorage sourceInfoStorage) { | // Path: library/src/main/java/com/danikula/videocache/headers/EmptyHeadersInjector.java
// public class EmptyHeadersInjector implements HeaderInjector {
//
// @Override
// public Map<String, String> addHeaders(String url) {
// return new HashMap<>();
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorageFactory.java
// public class SourceInfoStorageFactory {
//
// public static SourceInfoStorage newSourceInfoStorage(Context context) {
// return new DatabaseSourceInfoStorage(context);
// }
//
// public static SourceInfoStorage newEmptySourceInfoStorage() {
// return new NoSourceInfoStorage();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheUtils.java
// static final int DEFAULT_BUFFER_SIZE = 8 * 1024;
// Path: library/src/main/java/com/danikula/videocache/HttpUrlSource.java
import android.text.TextUtils;
import com.danikula.videocache.headers.EmptyHeadersInjector;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import com.danikula.videocache.sourcestorage.SourceInfoStorageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import static com.danikula.videocache.Preconditions.checkNotNull;
import static com.danikula.videocache.ProxyCacheUtils.DEFAULT_BUFFER_SIZE;
import static java.net.HttpURLConnection.HTTP_MOVED_PERM;
import static java.net.HttpURLConnection.HTTP_MOVED_TEMP;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.HttpURLConnection.HTTP_PARTIAL;
import static java.net.HttpURLConnection.HTTP_SEE_OTHER;
package com.danikula.videocache;
/**
* {@link Source} that uses http resource as source for {@link ProxyCache}.
*
* @author Alexey Danilov ([email protected]).
*/
public class HttpUrlSource implements Source {
private static final Logger LOG = LoggerFactory.getLogger("HttpUrlSource");
private static final int MAX_REDIRECTS = 5;
private final SourceInfoStorage sourceInfoStorage;
private final HeaderInjector headerInjector;
private SourceInfo sourceInfo;
private HttpURLConnection connection;
private InputStream inputStream;
public HttpUrlSource(String url) {
this(url, SourceInfoStorageFactory.newEmptySourceInfoStorage());
}
public HttpUrlSource(String url, SourceInfoStorage sourceInfoStorage) { | this(url, sourceInfoStorage, new EmptyHeadersInjector()); |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/HttpUrlSource.java | // Path: library/src/main/java/com/danikula/videocache/headers/EmptyHeadersInjector.java
// public class EmptyHeadersInjector implements HeaderInjector {
//
// @Override
// public Map<String, String> addHeaders(String url) {
// return new HashMap<>();
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorageFactory.java
// public class SourceInfoStorageFactory {
//
// public static SourceInfoStorage newSourceInfoStorage(Context context) {
// return new DatabaseSourceInfoStorage(context);
// }
//
// public static SourceInfoStorage newEmptySourceInfoStorage() {
// return new NoSourceInfoStorage();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheUtils.java
// static final int DEFAULT_BUFFER_SIZE = 8 * 1024;
| import android.text.TextUtils;
import com.danikula.videocache.headers.EmptyHeadersInjector;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import com.danikula.videocache.sourcestorage.SourceInfoStorageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import static com.danikula.videocache.Preconditions.checkNotNull;
import static com.danikula.videocache.ProxyCacheUtils.DEFAULT_BUFFER_SIZE;
import static java.net.HttpURLConnection.HTTP_MOVED_PERM;
import static java.net.HttpURLConnection.HTTP_MOVED_TEMP;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.HttpURLConnection.HTTP_PARTIAL;
import static java.net.HttpURLConnection.HTTP_SEE_OTHER; | package com.danikula.videocache;
/**
* {@link Source} that uses http resource as source for {@link ProxyCache}.
*
* @author Alexey Danilov ([email protected]).
*/
public class HttpUrlSource implements Source {
private static final Logger LOG = LoggerFactory.getLogger("HttpUrlSource");
private static final int MAX_REDIRECTS = 5;
private final SourceInfoStorage sourceInfoStorage;
private final HeaderInjector headerInjector;
private SourceInfo sourceInfo;
private HttpURLConnection connection;
private InputStream inputStream;
public HttpUrlSource(String url) {
this(url, SourceInfoStorageFactory.newEmptySourceInfoStorage());
}
public HttpUrlSource(String url, SourceInfoStorage sourceInfoStorage) {
this(url, sourceInfoStorage, new EmptyHeadersInjector());
}
public HttpUrlSource(String url, SourceInfoStorage sourceInfoStorage, HeaderInjector headerInjector) { | // Path: library/src/main/java/com/danikula/videocache/headers/EmptyHeadersInjector.java
// public class EmptyHeadersInjector implements HeaderInjector {
//
// @Override
// public Map<String, String> addHeaders(String url) {
// return new HashMap<>();
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorageFactory.java
// public class SourceInfoStorageFactory {
//
// public static SourceInfoStorage newSourceInfoStorage(Context context) {
// return new DatabaseSourceInfoStorage(context);
// }
//
// public static SourceInfoStorage newEmptySourceInfoStorage() {
// return new NoSourceInfoStorage();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheUtils.java
// static final int DEFAULT_BUFFER_SIZE = 8 * 1024;
// Path: library/src/main/java/com/danikula/videocache/HttpUrlSource.java
import android.text.TextUtils;
import com.danikula.videocache.headers.EmptyHeadersInjector;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import com.danikula.videocache.sourcestorage.SourceInfoStorageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import static com.danikula.videocache.Preconditions.checkNotNull;
import static com.danikula.videocache.ProxyCacheUtils.DEFAULT_BUFFER_SIZE;
import static java.net.HttpURLConnection.HTTP_MOVED_PERM;
import static java.net.HttpURLConnection.HTTP_MOVED_TEMP;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.HttpURLConnection.HTTP_PARTIAL;
import static java.net.HttpURLConnection.HTTP_SEE_OTHER;
package com.danikula.videocache;
/**
* {@link Source} that uses http resource as source for {@link ProxyCache}.
*
* @author Alexey Danilov ([email protected]).
*/
public class HttpUrlSource implements Source {
private static final Logger LOG = LoggerFactory.getLogger("HttpUrlSource");
private static final int MAX_REDIRECTS = 5;
private final SourceInfoStorage sourceInfoStorage;
private final HeaderInjector headerInjector;
private SourceInfo sourceInfo;
private HttpURLConnection connection;
private InputStream inputStream;
public HttpUrlSource(String url) {
this(url, SourceInfoStorageFactory.newEmptySourceInfoStorage());
}
public HttpUrlSource(String url, SourceInfoStorage sourceInfoStorage) {
this(url, sourceInfoStorage, new EmptyHeadersInjector());
}
public HttpUrlSource(String url, SourceInfoStorage sourceInfoStorage, HeaderInjector headerInjector) { | this.sourceInfoStorage = checkNotNull(sourceInfoStorage); |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/HttpUrlSource.java | // Path: library/src/main/java/com/danikula/videocache/headers/EmptyHeadersInjector.java
// public class EmptyHeadersInjector implements HeaderInjector {
//
// @Override
// public Map<String, String> addHeaders(String url) {
// return new HashMap<>();
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorageFactory.java
// public class SourceInfoStorageFactory {
//
// public static SourceInfoStorage newSourceInfoStorage(Context context) {
// return new DatabaseSourceInfoStorage(context);
// }
//
// public static SourceInfoStorage newEmptySourceInfoStorage() {
// return new NoSourceInfoStorage();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheUtils.java
// static final int DEFAULT_BUFFER_SIZE = 8 * 1024;
| import android.text.TextUtils;
import com.danikula.videocache.headers.EmptyHeadersInjector;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import com.danikula.videocache.sourcestorage.SourceInfoStorageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import static com.danikula.videocache.Preconditions.checkNotNull;
import static com.danikula.videocache.ProxyCacheUtils.DEFAULT_BUFFER_SIZE;
import static java.net.HttpURLConnection.HTTP_MOVED_PERM;
import static java.net.HttpURLConnection.HTTP_MOVED_TEMP;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.HttpURLConnection.HTTP_PARTIAL;
import static java.net.HttpURLConnection.HTTP_SEE_OTHER; | this(url, sourceInfoStorage, new EmptyHeadersInjector());
}
public HttpUrlSource(String url, SourceInfoStorage sourceInfoStorage, HeaderInjector headerInjector) {
this.sourceInfoStorage = checkNotNull(sourceInfoStorage);
this.headerInjector = checkNotNull(headerInjector);
SourceInfo sourceInfo = sourceInfoStorage.get(url);
this.sourceInfo = sourceInfo != null ? sourceInfo :
new SourceInfo(url, Integer.MIN_VALUE, ProxyCacheUtils.getSupposablyMime(url));
}
public HttpUrlSource(HttpUrlSource source) {
this.sourceInfo = source.sourceInfo;
this.sourceInfoStorage = source.sourceInfoStorage;
this.headerInjector = source.headerInjector;
}
@Override
public synchronized long length() throws ProxyCacheException {
if (sourceInfo.length == Integer.MIN_VALUE) {
fetchContentInfo();
}
return sourceInfo.length;
}
@Override
public void open(long offset) throws ProxyCacheException {
try {
connection = openConnection(offset, -1);
String mime = connection.getContentType(); | // Path: library/src/main/java/com/danikula/videocache/headers/EmptyHeadersInjector.java
// public class EmptyHeadersInjector implements HeaderInjector {
//
// @Override
// public Map<String, String> addHeaders(String url) {
// return new HashMap<>();
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorageFactory.java
// public class SourceInfoStorageFactory {
//
// public static SourceInfoStorage newSourceInfoStorage(Context context) {
// return new DatabaseSourceInfoStorage(context);
// }
//
// public static SourceInfoStorage newEmptySourceInfoStorage() {
// return new NoSourceInfoStorage();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheUtils.java
// static final int DEFAULT_BUFFER_SIZE = 8 * 1024;
// Path: library/src/main/java/com/danikula/videocache/HttpUrlSource.java
import android.text.TextUtils;
import com.danikula.videocache.headers.EmptyHeadersInjector;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import com.danikula.videocache.sourcestorage.SourceInfoStorageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import static com.danikula.videocache.Preconditions.checkNotNull;
import static com.danikula.videocache.ProxyCacheUtils.DEFAULT_BUFFER_SIZE;
import static java.net.HttpURLConnection.HTTP_MOVED_PERM;
import static java.net.HttpURLConnection.HTTP_MOVED_TEMP;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.HttpURLConnection.HTTP_PARTIAL;
import static java.net.HttpURLConnection.HTTP_SEE_OTHER;
this(url, sourceInfoStorage, new EmptyHeadersInjector());
}
public HttpUrlSource(String url, SourceInfoStorage sourceInfoStorage, HeaderInjector headerInjector) {
this.sourceInfoStorage = checkNotNull(sourceInfoStorage);
this.headerInjector = checkNotNull(headerInjector);
SourceInfo sourceInfo = sourceInfoStorage.get(url);
this.sourceInfo = sourceInfo != null ? sourceInfo :
new SourceInfo(url, Integer.MIN_VALUE, ProxyCacheUtils.getSupposablyMime(url));
}
public HttpUrlSource(HttpUrlSource source) {
this.sourceInfo = source.sourceInfo;
this.sourceInfoStorage = source.sourceInfoStorage;
this.headerInjector = source.headerInjector;
}
@Override
public synchronized long length() throws ProxyCacheException {
if (sourceInfo.length == Integer.MIN_VALUE) {
fetchContentInfo();
}
return sourceInfo.length;
}
@Override
public void open(long offset) throws ProxyCacheException {
try {
connection = openConnection(offset, -1);
String mime = connection.getContentType(); | inputStream = new BufferedInputStream(connection.getInputStream(), DEFAULT_BUFFER_SIZE); |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/IgnoreHostProxySelector.java | // Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
| import java.io.IOException;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import static com.danikula.videocache.Preconditions.checkNotNull; | package com.danikula.videocache;
/**
* {@link ProxySelector} that ignore system default proxies for concrete host.
* <p>
* It is important to <a href="https://github.com/danikula/AndroidVideoCache/issues/28">ignore system proxy</a> for localhost connection.
*
* @author Alexey Danilov ([email protected]).
*/
class IgnoreHostProxySelector extends ProxySelector {
private static final List<Proxy> NO_PROXY_LIST = Arrays.asList(Proxy.NO_PROXY);
private final ProxySelector defaultProxySelector;
private final String hostToIgnore;
private final int portToIgnore;
IgnoreHostProxySelector(ProxySelector defaultProxySelector, String hostToIgnore, int portToIgnore) { | // Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
// Path: library/src/main/java/com/danikula/videocache/IgnoreHostProxySelector.java
import java.io.IOException;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import static com.danikula.videocache.Preconditions.checkNotNull;
package com.danikula.videocache;
/**
* {@link ProxySelector} that ignore system default proxies for concrete host.
* <p>
* It is important to <a href="https://github.com/danikula/AndroidVideoCache/issues/28">ignore system proxy</a> for localhost connection.
*
* @author Alexey Danilov ([email protected]).
*/
class IgnoreHostProxySelector extends ProxySelector {
private static final List<Proxy> NO_PROXY_LIST = Arrays.asList(Proxy.NO_PROXY);
private final ProxySelector defaultProxySelector;
private final String hostToIgnore;
private final int portToIgnore;
IgnoreHostProxySelector(ProxySelector defaultProxySelector, String hostToIgnore, int portToIgnore) { | this.defaultProxySelector = checkNotNull(defaultProxySelector); |
danikula/AndroidVideoCache | test/src/test/java/com/danikula/videocache/PingerTest.java | // Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static int getPort(HttpProxyCacheServer server) {
// String proxyUrl = server.getProxyUrl("test");
// Pattern pattern = Pattern.compile("http://127.0.0.1:(\\d*)/test");
// Matcher matcher = pattern.matcher(proxyUrl);
// assertThat(matcher.find()).isTrue();
// String portAsString = matcher.group(1);
// return Integer.parseInt(portAsString);
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static int getPortWithoutPing(HttpProxyCacheServer server) {
// return (Integer) ReflectUtil.getField(server, "port");
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static void installExternalSystemProxy() {
// // see proxies list at http://proxylist.hidemyass.com/
// Proxy systemProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("162.8.230.7", 11180));
// ProxySelector mockedProxySelector = Mockito.mock(ProxySelector.class);
// when(mockedProxySelector.select(Mockito.<URI>any())).thenReturn(Lists.newArrayList(systemProxy));
// ProxySelector.setDefault(mockedProxySelector);
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static void resetSystemProxy() {
// ProxySelector mockedProxySelector = Mockito.mock(ProxySelector.class);
// when(mockedProxySelector.select(Mockito.<URI>any())).thenReturn(Lists.newArrayList(Proxy.NO_PROXY));
// ProxySelector.setDefault(mockedProxySelector);
// }
| import org.junit.Before;
import org.junit.Test;
import org.robolectric.RuntimeEnvironment;
import java.io.ByteArrayOutputStream;
import java.net.Socket;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getPort;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getPortWithoutPing;
import static com.danikula.videocache.support.ProxyCacheTestUtils.installExternalSystemProxy;
import static com.danikula.videocache.support.ProxyCacheTestUtils.resetSystemProxy;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; | package com.danikula.videocache;
/**
* Tests {@link Pinger}.
*
* @author Alexey Danilov ([email protected]).
*/
public class PingerTest extends BaseTest {
@Before
public void setup() throws Exception { | // Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static int getPort(HttpProxyCacheServer server) {
// String proxyUrl = server.getProxyUrl("test");
// Pattern pattern = Pattern.compile("http://127.0.0.1:(\\d*)/test");
// Matcher matcher = pattern.matcher(proxyUrl);
// assertThat(matcher.find()).isTrue();
// String portAsString = matcher.group(1);
// return Integer.parseInt(portAsString);
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static int getPortWithoutPing(HttpProxyCacheServer server) {
// return (Integer) ReflectUtil.getField(server, "port");
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static void installExternalSystemProxy() {
// // see proxies list at http://proxylist.hidemyass.com/
// Proxy systemProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("162.8.230.7", 11180));
// ProxySelector mockedProxySelector = Mockito.mock(ProxySelector.class);
// when(mockedProxySelector.select(Mockito.<URI>any())).thenReturn(Lists.newArrayList(systemProxy));
// ProxySelector.setDefault(mockedProxySelector);
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static void resetSystemProxy() {
// ProxySelector mockedProxySelector = Mockito.mock(ProxySelector.class);
// when(mockedProxySelector.select(Mockito.<URI>any())).thenReturn(Lists.newArrayList(Proxy.NO_PROXY));
// ProxySelector.setDefault(mockedProxySelector);
// }
// Path: test/src/test/java/com/danikula/videocache/PingerTest.java
import org.junit.Before;
import org.junit.Test;
import org.robolectric.RuntimeEnvironment;
import java.io.ByteArrayOutputStream;
import java.net.Socket;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getPort;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getPortWithoutPing;
import static com.danikula.videocache.support.ProxyCacheTestUtils.installExternalSystemProxy;
import static com.danikula.videocache.support.ProxyCacheTestUtils.resetSystemProxy;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
package com.danikula.videocache;
/**
* Tests {@link Pinger}.
*
* @author Alexey Danilov ([email protected]).
*/
public class PingerTest extends BaseTest {
@Before
public void setup() throws Exception { | resetSystemProxy(); |
danikula/AndroidVideoCache | test/src/test/java/com/danikula/videocache/PingerTest.java | // Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static int getPort(HttpProxyCacheServer server) {
// String proxyUrl = server.getProxyUrl("test");
// Pattern pattern = Pattern.compile("http://127.0.0.1:(\\d*)/test");
// Matcher matcher = pattern.matcher(proxyUrl);
// assertThat(matcher.find()).isTrue();
// String portAsString = matcher.group(1);
// return Integer.parseInt(portAsString);
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static int getPortWithoutPing(HttpProxyCacheServer server) {
// return (Integer) ReflectUtil.getField(server, "port");
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static void installExternalSystemProxy() {
// // see proxies list at http://proxylist.hidemyass.com/
// Proxy systemProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("162.8.230.7", 11180));
// ProxySelector mockedProxySelector = Mockito.mock(ProxySelector.class);
// when(mockedProxySelector.select(Mockito.<URI>any())).thenReturn(Lists.newArrayList(systemProxy));
// ProxySelector.setDefault(mockedProxySelector);
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static void resetSystemProxy() {
// ProxySelector mockedProxySelector = Mockito.mock(ProxySelector.class);
// when(mockedProxySelector.select(Mockito.<URI>any())).thenReturn(Lists.newArrayList(Proxy.NO_PROXY));
// ProxySelector.setDefault(mockedProxySelector);
// }
| import org.junit.Before;
import org.junit.Test;
import org.robolectric.RuntimeEnvironment;
import java.io.ByteArrayOutputStream;
import java.net.Socket;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getPort;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getPortWithoutPing;
import static com.danikula.videocache.support.ProxyCacheTestUtils.installExternalSystemProxy;
import static com.danikula.videocache.support.ProxyCacheTestUtils.resetSystemProxy;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; | package com.danikula.videocache;
/**
* Tests {@link Pinger}.
*
* @author Alexey Danilov ([email protected]).
*/
public class PingerTest extends BaseTest {
@Before
public void setup() throws Exception {
resetSystemProxy();
}
@Test
public void testPingSuccess() throws Exception {
HttpProxyCacheServer server = new HttpProxyCacheServer(RuntimeEnvironment.application); | // Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static int getPort(HttpProxyCacheServer server) {
// String proxyUrl = server.getProxyUrl("test");
// Pattern pattern = Pattern.compile("http://127.0.0.1:(\\d*)/test");
// Matcher matcher = pattern.matcher(proxyUrl);
// assertThat(matcher.find()).isTrue();
// String portAsString = matcher.group(1);
// return Integer.parseInt(portAsString);
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static int getPortWithoutPing(HttpProxyCacheServer server) {
// return (Integer) ReflectUtil.getField(server, "port");
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static void installExternalSystemProxy() {
// // see proxies list at http://proxylist.hidemyass.com/
// Proxy systemProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("162.8.230.7", 11180));
// ProxySelector mockedProxySelector = Mockito.mock(ProxySelector.class);
// when(mockedProxySelector.select(Mockito.<URI>any())).thenReturn(Lists.newArrayList(systemProxy));
// ProxySelector.setDefault(mockedProxySelector);
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static void resetSystemProxy() {
// ProxySelector mockedProxySelector = Mockito.mock(ProxySelector.class);
// when(mockedProxySelector.select(Mockito.<URI>any())).thenReturn(Lists.newArrayList(Proxy.NO_PROXY));
// ProxySelector.setDefault(mockedProxySelector);
// }
// Path: test/src/test/java/com/danikula/videocache/PingerTest.java
import org.junit.Before;
import org.junit.Test;
import org.robolectric.RuntimeEnvironment;
import java.io.ByteArrayOutputStream;
import java.net.Socket;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getPort;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getPortWithoutPing;
import static com.danikula.videocache.support.ProxyCacheTestUtils.installExternalSystemProxy;
import static com.danikula.videocache.support.ProxyCacheTestUtils.resetSystemProxy;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
package com.danikula.videocache;
/**
* Tests {@link Pinger}.
*
* @author Alexey Danilov ([email protected]).
*/
public class PingerTest extends BaseTest {
@Before
public void setup() throws Exception {
resetSystemProxy();
}
@Test
public void testPingSuccess() throws Exception {
HttpProxyCacheServer server = new HttpProxyCacheServer(RuntimeEnvironment.application); | Pinger pinger = new Pinger("127.0.0.1", getPort(server)); |
danikula/AndroidVideoCache | test/src/test/java/com/danikula/videocache/PingerTest.java | // Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static int getPort(HttpProxyCacheServer server) {
// String proxyUrl = server.getProxyUrl("test");
// Pattern pattern = Pattern.compile("http://127.0.0.1:(\\d*)/test");
// Matcher matcher = pattern.matcher(proxyUrl);
// assertThat(matcher.find()).isTrue();
// String portAsString = matcher.group(1);
// return Integer.parseInt(portAsString);
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static int getPortWithoutPing(HttpProxyCacheServer server) {
// return (Integer) ReflectUtil.getField(server, "port");
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static void installExternalSystemProxy() {
// // see proxies list at http://proxylist.hidemyass.com/
// Proxy systemProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("162.8.230.7", 11180));
// ProxySelector mockedProxySelector = Mockito.mock(ProxySelector.class);
// when(mockedProxySelector.select(Mockito.<URI>any())).thenReturn(Lists.newArrayList(systemProxy));
// ProxySelector.setDefault(mockedProxySelector);
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static void resetSystemProxy() {
// ProxySelector mockedProxySelector = Mockito.mock(ProxySelector.class);
// when(mockedProxySelector.select(Mockito.<URI>any())).thenReturn(Lists.newArrayList(Proxy.NO_PROXY));
// ProxySelector.setDefault(mockedProxySelector);
// }
| import org.junit.Before;
import org.junit.Test;
import org.robolectric.RuntimeEnvironment;
import java.io.ByteArrayOutputStream;
import java.net.Socket;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getPort;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getPortWithoutPing;
import static com.danikula.videocache.support.ProxyCacheTestUtils.installExternalSystemProxy;
import static com.danikula.videocache.support.ProxyCacheTestUtils.resetSystemProxy;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; |
server.shutdown();
}
@Test
public void testPingFail() throws Exception {
Pinger pinger = new Pinger("127.0.0.1", 33);
boolean pinged = pinger.ping(3, 70);
assertThat(pinged).isFalse();
}
@Test
public void testIsPingRequest() throws Exception {
Pinger pinger = new Pinger("127.0.0.1", 1);
assertThat(pinger.isPingRequest("ping")).isTrue();
assertThat(pinger.isPingRequest("notPing")).isFalse();
}
@Test
public void testResponseToPing() throws Exception {
Pinger pinger = new Pinger("127.0.0.1", 1);
ByteArrayOutputStream out = new ByteArrayOutputStream();
Socket socket = mock(Socket.class);
when(socket.getOutputStream()).thenReturn(out);
pinger.responseToPing(socket);
assertThat(out.toString()).isEqualTo("HTTP/1.1 200 OK\n\nping ok");
}
@Test // https://github.com/danikula/AndroidVideoCache/issues/28
public void testPingedWithExternalProxy() throws Exception { | // Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static int getPort(HttpProxyCacheServer server) {
// String proxyUrl = server.getProxyUrl("test");
// Pattern pattern = Pattern.compile("http://127.0.0.1:(\\d*)/test");
// Matcher matcher = pattern.matcher(proxyUrl);
// assertThat(matcher.find()).isTrue();
// String portAsString = matcher.group(1);
// return Integer.parseInt(portAsString);
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static int getPortWithoutPing(HttpProxyCacheServer server) {
// return (Integer) ReflectUtil.getField(server, "port");
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static void installExternalSystemProxy() {
// // see proxies list at http://proxylist.hidemyass.com/
// Proxy systemProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("162.8.230.7", 11180));
// ProxySelector mockedProxySelector = Mockito.mock(ProxySelector.class);
// when(mockedProxySelector.select(Mockito.<URI>any())).thenReturn(Lists.newArrayList(systemProxy));
// ProxySelector.setDefault(mockedProxySelector);
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static void resetSystemProxy() {
// ProxySelector mockedProxySelector = Mockito.mock(ProxySelector.class);
// when(mockedProxySelector.select(Mockito.<URI>any())).thenReturn(Lists.newArrayList(Proxy.NO_PROXY));
// ProxySelector.setDefault(mockedProxySelector);
// }
// Path: test/src/test/java/com/danikula/videocache/PingerTest.java
import org.junit.Before;
import org.junit.Test;
import org.robolectric.RuntimeEnvironment;
import java.io.ByteArrayOutputStream;
import java.net.Socket;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getPort;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getPortWithoutPing;
import static com.danikula.videocache.support.ProxyCacheTestUtils.installExternalSystemProxy;
import static com.danikula.videocache.support.ProxyCacheTestUtils.resetSystemProxy;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
server.shutdown();
}
@Test
public void testPingFail() throws Exception {
Pinger pinger = new Pinger("127.0.0.1", 33);
boolean pinged = pinger.ping(3, 70);
assertThat(pinged).isFalse();
}
@Test
public void testIsPingRequest() throws Exception {
Pinger pinger = new Pinger("127.0.0.1", 1);
assertThat(pinger.isPingRequest("ping")).isTrue();
assertThat(pinger.isPingRequest("notPing")).isFalse();
}
@Test
public void testResponseToPing() throws Exception {
Pinger pinger = new Pinger("127.0.0.1", 1);
ByteArrayOutputStream out = new ByteArrayOutputStream();
Socket socket = mock(Socket.class);
when(socket.getOutputStream()).thenReturn(out);
pinger.responseToPing(socket);
assertThat(out.toString()).isEqualTo("HTTP/1.1 200 OK\n\nping ok");
}
@Test // https://github.com/danikula/AndroidVideoCache/issues/28
public void testPingedWithExternalProxy() throws Exception { | installExternalSystemProxy(); |
danikula/AndroidVideoCache | test/src/test/java/com/danikula/videocache/PingerTest.java | // Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static int getPort(HttpProxyCacheServer server) {
// String proxyUrl = server.getProxyUrl("test");
// Pattern pattern = Pattern.compile("http://127.0.0.1:(\\d*)/test");
// Matcher matcher = pattern.matcher(proxyUrl);
// assertThat(matcher.find()).isTrue();
// String portAsString = matcher.group(1);
// return Integer.parseInt(portAsString);
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static int getPortWithoutPing(HttpProxyCacheServer server) {
// return (Integer) ReflectUtil.getField(server, "port");
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static void installExternalSystemProxy() {
// // see proxies list at http://proxylist.hidemyass.com/
// Proxy systemProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("162.8.230.7", 11180));
// ProxySelector mockedProxySelector = Mockito.mock(ProxySelector.class);
// when(mockedProxySelector.select(Mockito.<URI>any())).thenReturn(Lists.newArrayList(systemProxy));
// ProxySelector.setDefault(mockedProxySelector);
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static void resetSystemProxy() {
// ProxySelector mockedProxySelector = Mockito.mock(ProxySelector.class);
// when(mockedProxySelector.select(Mockito.<URI>any())).thenReturn(Lists.newArrayList(Proxy.NO_PROXY));
// ProxySelector.setDefault(mockedProxySelector);
// }
| import org.junit.Before;
import org.junit.Test;
import org.robolectric.RuntimeEnvironment;
import java.io.ByteArrayOutputStream;
import java.net.Socket;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getPort;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getPortWithoutPing;
import static com.danikula.videocache.support.ProxyCacheTestUtils.installExternalSystemProxy;
import static com.danikula.videocache.support.ProxyCacheTestUtils.resetSystemProxy;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; |
@Test
public void testPingFail() throws Exception {
Pinger pinger = new Pinger("127.0.0.1", 33);
boolean pinged = pinger.ping(3, 70);
assertThat(pinged).isFalse();
}
@Test
public void testIsPingRequest() throws Exception {
Pinger pinger = new Pinger("127.0.0.1", 1);
assertThat(pinger.isPingRequest("ping")).isTrue();
assertThat(pinger.isPingRequest("notPing")).isFalse();
}
@Test
public void testResponseToPing() throws Exception {
Pinger pinger = new Pinger("127.0.0.1", 1);
ByteArrayOutputStream out = new ByteArrayOutputStream();
Socket socket = mock(Socket.class);
when(socket.getOutputStream()).thenReturn(out);
pinger.responseToPing(socket);
assertThat(out.toString()).isEqualTo("HTTP/1.1 200 OK\n\nping ok");
}
@Test // https://github.com/danikula/AndroidVideoCache/issues/28
public void testPingedWithExternalProxy() throws Exception {
installExternalSystemProxy();
HttpProxyCacheServer server = new HttpProxyCacheServer(RuntimeEnvironment.application); | // Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static int getPort(HttpProxyCacheServer server) {
// String proxyUrl = server.getProxyUrl("test");
// Pattern pattern = Pattern.compile("http://127.0.0.1:(\\d*)/test");
// Matcher matcher = pattern.matcher(proxyUrl);
// assertThat(matcher.find()).isTrue();
// String portAsString = matcher.group(1);
// return Integer.parseInt(portAsString);
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static int getPortWithoutPing(HttpProxyCacheServer server) {
// return (Integer) ReflectUtil.getField(server, "port");
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static void installExternalSystemProxy() {
// // see proxies list at http://proxylist.hidemyass.com/
// Proxy systemProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("162.8.230.7", 11180));
// ProxySelector mockedProxySelector = Mockito.mock(ProxySelector.class);
// when(mockedProxySelector.select(Mockito.<URI>any())).thenReturn(Lists.newArrayList(systemProxy));
// ProxySelector.setDefault(mockedProxySelector);
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static void resetSystemProxy() {
// ProxySelector mockedProxySelector = Mockito.mock(ProxySelector.class);
// when(mockedProxySelector.select(Mockito.<URI>any())).thenReturn(Lists.newArrayList(Proxy.NO_PROXY));
// ProxySelector.setDefault(mockedProxySelector);
// }
// Path: test/src/test/java/com/danikula/videocache/PingerTest.java
import org.junit.Before;
import org.junit.Test;
import org.robolectric.RuntimeEnvironment;
import java.io.ByteArrayOutputStream;
import java.net.Socket;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getPort;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getPortWithoutPing;
import static com.danikula.videocache.support.ProxyCacheTestUtils.installExternalSystemProxy;
import static com.danikula.videocache.support.ProxyCacheTestUtils.resetSystemProxy;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@Test
public void testPingFail() throws Exception {
Pinger pinger = new Pinger("127.0.0.1", 33);
boolean pinged = pinger.ping(3, 70);
assertThat(pinged).isFalse();
}
@Test
public void testIsPingRequest() throws Exception {
Pinger pinger = new Pinger("127.0.0.1", 1);
assertThat(pinger.isPingRequest("ping")).isTrue();
assertThat(pinger.isPingRequest("notPing")).isFalse();
}
@Test
public void testResponseToPing() throws Exception {
Pinger pinger = new Pinger("127.0.0.1", 1);
ByteArrayOutputStream out = new ByteArrayOutputStream();
Socket socket = mock(Socket.class);
when(socket.getOutputStream()).thenReturn(out);
pinger.responseToPing(socket);
assertThat(out.toString()).isEqualTo("HTTP/1.1 200 OK\n\nping ok");
}
@Test // https://github.com/danikula/AndroidVideoCache/issues/28
public void testPingedWithExternalProxy() throws Exception {
installExternalSystemProxy();
HttpProxyCacheServer server = new HttpProxyCacheServer(RuntimeEnvironment.application); | Pinger pinger = new Pinger("127.0.0.1", getPortWithoutPing(server)); |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/sourcestorage/NoSourceInfoStorage.java | // Path: library/src/main/java/com/danikula/videocache/SourceInfo.java
// public class SourceInfo {
//
// public final String url;
// public final long length;
// public final String mime;
//
// public SourceInfo(String url, long length, String mime) {
// this.url = url;
// this.length = length;
// this.mime = mime;
// }
//
// @Override
// public String toString() {
// return "SourceInfo{" +
// "url='" + url + '\'' +
// ", length=" + length +
// ", mime='" + mime + '\'' +
// '}';
// }
// }
| import com.danikula.videocache.SourceInfo; | package com.danikula.videocache.sourcestorage;
/**
* {@link SourceInfoStorage} that does nothing.
*
* @author Alexey Danilov ([email protected]).
*/
public class NoSourceInfoStorage implements SourceInfoStorage {
@Override | // Path: library/src/main/java/com/danikula/videocache/SourceInfo.java
// public class SourceInfo {
//
// public final String url;
// public final long length;
// public final String mime;
//
// public SourceInfo(String url, long length, String mime) {
// this.url = url;
// this.length = length;
// this.mime = mime;
// }
//
// @Override
// public String toString() {
// return "SourceInfo{" +
// "url='" + url + '\'' +
// ", length=" + length +
// ", mime='" + mime + '\'' +
// '}';
// }
// }
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/NoSourceInfoStorage.java
import com.danikula.videocache.SourceInfo;
package com.danikula.videocache.sourcestorage;
/**
* {@link SourceInfoStorage} that does nothing.
*
* @author Alexey Danilov ([email protected]).
*/
public class NoSourceInfoStorage implements SourceInfoStorage {
@Override | public SourceInfo get(String url) { |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/HttpProxyCache.java | // Path: library/src/main/java/com/danikula/videocache/file/FileCache.java
// public class FileCache implements Cache {
//
// private static final String TEMP_POSTFIX = ".download";
//
// private final DiskUsage diskUsage;
// public File file;
// private RandomAccessFile dataFile;
//
// public FileCache(File file) throws ProxyCacheException {
// this(file, new UnlimitedDiskUsage());
// }
//
// public FileCache(File file, DiskUsage diskUsage) throws ProxyCacheException {
// try {
// if (diskUsage == null) {
// throw new NullPointerException();
// }
// this.diskUsage = diskUsage;
// File directory = file.getParentFile();
// Files.makeDir(directory);
// boolean completed = file.exists();
// this.file = completed ? file : new File(file.getParentFile(), file.getName() + TEMP_POSTFIX);
// this.dataFile = new RandomAccessFile(this.file, completed ? "r" : "rw");
// } catch (IOException e) {
// throw new ProxyCacheException("Error using file " + file + " as disc cache", e);
// }
// }
//
// @Override
// public synchronized long available() throws ProxyCacheException {
// try {
// return (int) dataFile.length();
// } catch (IOException e) {
// throw new ProxyCacheException("Error reading length of file " + file, e);
// }
// }
//
// @Override
// public synchronized int read(byte[] buffer, long offset, int length) throws ProxyCacheException {
// try {
// dataFile.seek(offset);
// return dataFile.read(buffer, 0, length);
// } catch (IOException e) {
// String format = "Error reading %d bytes with offset %d from file[%d bytes] to buffer[%d bytes]";
// throw new ProxyCacheException(String.format(format, length, offset, available(), buffer.length), e);
// }
// }
//
// @Override
// public synchronized void append(byte[] data, int length) throws ProxyCacheException {
// try {
// if (isCompleted()) {
// throw new ProxyCacheException("Error append cache: cache file " + file + " is completed!");
// }
// dataFile.seek(available());
// dataFile.write(data, 0, length);
// } catch (IOException e) {
// String format = "Error writing %d bytes to %s from buffer with size %d";
// throw new ProxyCacheException(String.format(format, length, dataFile, data.length), e);
// }
// }
//
// @Override
// public synchronized void close() throws ProxyCacheException {
// try {
// dataFile.close();
// diskUsage.touch(file);
// } catch (IOException e) {
// throw new ProxyCacheException("Error closing file " + file, e);
// }
// }
//
// @Override
// public synchronized void complete() throws ProxyCacheException {
// if (isCompleted()) {
// return;
// }
//
// close();
// String fileName = file.getName().substring(0, file.getName().length() - TEMP_POSTFIX.length());
// File completedFile = new File(file.getParentFile(), fileName);
// boolean renamed = file.renameTo(completedFile);
// if (!renamed) {
// throw new ProxyCacheException("Error renaming file " + file + " to " + completedFile + " for completion!");
// }
// file = completedFile;
// try {
// dataFile = new RandomAccessFile(file, "r");
// diskUsage.touch(file);
// } catch (IOException e) {
// throw new ProxyCacheException("Error opening " + file + " as disc cache", e);
// }
// }
//
// @Override
// public synchronized boolean isCompleted() {
// return !isTempFile(file);
// }
//
// /**
// * Returns file to be used fo caching. It may as original file passed in constructor as some temp file for not completed cache.
// *
// * @return file for caching.
// */
// public File getFile() {
// return file;
// }
//
// private boolean isTempFile(File file) {
// return file.getName().endsWith(TEMP_POSTFIX);
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheUtils.java
// static final int DEFAULT_BUFFER_SIZE = 8 * 1024;
| import android.text.TextUtils;
import com.danikula.videocache.file.FileCache;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Locale;
import static com.danikula.videocache.ProxyCacheUtils.DEFAULT_BUFFER_SIZE; | package com.danikula.videocache;
/**
* {@link ProxyCache} that read http url and writes data to {@link Socket}
*
* @author Alexey Danilov ([email protected]).
*/
class HttpProxyCache extends ProxyCache {
private static final float NO_CACHE_BARRIER = .2f;
private final HttpUrlSource source; | // Path: library/src/main/java/com/danikula/videocache/file/FileCache.java
// public class FileCache implements Cache {
//
// private static final String TEMP_POSTFIX = ".download";
//
// private final DiskUsage diskUsage;
// public File file;
// private RandomAccessFile dataFile;
//
// public FileCache(File file) throws ProxyCacheException {
// this(file, new UnlimitedDiskUsage());
// }
//
// public FileCache(File file, DiskUsage diskUsage) throws ProxyCacheException {
// try {
// if (diskUsage == null) {
// throw new NullPointerException();
// }
// this.diskUsage = diskUsage;
// File directory = file.getParentFile();
// Files.makeDir(directory);
// boolean completed = file.exists();
// this.file = completed ? file : new File(file.getParentFile(), file.getName() + TEMP_POSTFIX);
// this.dataFile = new RandomAccessFile(this.file, completed ? "r" : "rw");
// } catch (IOException e) {
// throw new ProxyCacheException("Error using file " + file + " as disc cache", e);
// }
// }
//
// @Override
// public synchronized long available() throws ProxyCacheException {
// try {
// return (int) dataFile.length();
// } catch (IOException e) {
// throw new ProxyCacheException("Error reading length of file " + file, e);
// }
// }
//
// @Override
// public synchronized int read(byte[] buffer, long offset, int length) throws ProxyCacheException {
// try {
// dataFile.seek(offset);
// return dataFile.read(buffer, 0, length);
// } catch (IOException e) {
// String format = "Error reading %d bytes with offset %d from file[%d bytes] to buffer[%d bytes]";
// throw new ProxyCacheException(String.format(format, length, offset, available(), buffer.length), e);
// }
// }
//
// @Override
// public synchronized void append(byte[] data, int length) throws ProxyCacheException {
// try {
// if (isCompleted()) {
// throw new ProxyCacheException("Error append cache: cache file " + file + " is completed!");
// }
// dataFile.seek(available());
// dataFile.write(data, 0, length);
// } catch (IOException e) {
// String format = "Error writing %d bytes to %s from buffer with size %d";
// throw new ProxyCacheException(String.format(format, length, dataFile, data.length), e);
// }
// }
//
// @Override
// public synchronized void close() throws ProxyCacheException {
// try {
// dataFile.close();
// diskUsage.touch(file);
// } catch (IOException e) {
// throw new ProxyCacheException("Error closing file " + file, e);
// }
// }
//
// @Override
// public synchronized void complete() throws ProxyCacheException {
// if (isCompleted()) {
// return;
// }
//
// close();
// String fileName = file.getName().substring(0, file.getName().length() - TEMP_POSTFIX.length());
// File completedFile = new File(file.getParentFile(), fileName);
// boolean renamed = file.renameTo(completedFile);
// if (!renamed) {
// throw new ProxyCacheException("Error renaming file " + file + " to " + completedFile + " for completion!");
// }
// file = completedFile;
// try {
// dataFile = new RandomAccessFile(file, "r");
// diskUsage.touch(file);
// } catch (IOException e) {
// throw new ProxyCacheException("Error opening " + file + " as disc cache", e);
// }
// }
//
// @Override
// public synchronized boolean isCompleted() {
// return !isTempFile(file);
// }
//
// /**
// * Returns file to be used fo caching. It may as original file passed in constructor as some temp file for not completed cache.
// *
// * @return file for caching.
// */
// public File getFile() {
// return file;
// }
//
// private boolean isTempFile(File file) {
// return file.getName().endsWith(TEMP_POSTFIX);
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheUtils.java
// static final int DEFAULT_BUFFER_SIZE = 8 * 1024;
// Path: library/src/main/java/com/danikula/videocache/HttpProxyCache.java
import android.text.TextUtils;
import com.danikula.videocache.file.FileCache;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Locale;
import static com.danikula.videocache.ProxyCacheUtils.DEFAULT_BUFFER_SIZE;
package com.danikula.videocache;
/**
* {@link ProxyCache} that read http url and writes data to {@link Socket}
*
* @author Alexey Danilov ([email protected]).
*/
class HttpProxyCache extends ProxyCache {
private static final float NO_CACHE_BARRIER = .2f;
private final HttpUrlSource source; | private final FileCache cache; |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/HttpProxyCache.java | // Path: library/src/main/java/com/danikula/videocache/file/FileCache.java
// public class FileCache implements Cache {
//
// private static final String TEMP_POSTFIX = ".download";
//
// private final DiskUsage diskUsage;
// public File file;
// private RandomAccessFile dataFile;
//
// public FileCache(File file) throws ProxyCacheException {
// this(file, new UnlimitedDiskUsage());
// }
//
// public FileCache(File file, DiskUsage diskUsage) throws ProxyCacheException {
// try {
// if (diskUsage == null) {
// throw new NullPointerException();
// }
// this.diskUsage = diskUsage;
// File directory = file.getParentFile();
// Files.makeDir(directory);
// boolean completed = file.exists();
// this.file = completed ? file : new File(file.getParentFile(), file.getName() + TEMP_POSTFIX);
// this.dataFile = new RandomAccessFile(this.file, completed ? "r" : "rw");
// } catch (IOException e) {
// throw new ProxyCacheException("Error using file " + file + " as disc cache", e);
// }
// }
//
// @Override
// public synchronized long available() throws ProxyCacheException {
// try {
// return (int) dataFile.length();
// } catch (IOException e) {
// throw new ProxyCacheException("Error reading length of file " + file, e);
// }
// }
//
// @Override
// public synchronized int read(byte[] buffer, long offset, int length) throws ProxyCacheException {
// try {
// dataFile.seek(offset);
// return dataFile.read(buffer, 0, length);
// } catch (IOException e) {
// String format = "Error reading %d bytes with offset %d from file[%d bytes] to buffer[%d bytes]";
// throw new ProxyCacheException(String.format(format, length, offset, available(), buffer.length), e);
// }
// }
//
// @Override
// public synchronized void append(byte[] data, int length) throws ProxyCacheException {
// try {
// if (isCompleted()) {
// throw new ProxyCacheException("Error append cache: cache file " + file + " is completed!");
// }
// dataFile.seek(available());
// dataFile.write(data, 0, length);
// } catch (IOException e) {
// String format = "Error writing %d bytes to %s from buffer with size %d";
// throw new ProxyCacheException(String.format(format, length, dataFile, data.length), e);
// }
// }
//
// @Override
// public synchronized void close() throws ProxyCacheException {
// try {
// dataFile.close();
// diskUsage.touch(file);
// } catch (IOException e) {
// throw new ProxyCacheException("Error closing file " + file, e);
// }
// }
//
// @Override
// public synchronized void complete() throws ProxyCacheException {
// if (isCompleted()) {
// return;
// }
//
// close();
// String fileName = file.getName().substring(0, file.getName().length() - TEMP_POSTFIX.length());
// File completedFile = new File(file.getParentFile(), fileName);
// boolean renamed = file.renameTo(completedFile);
// if (!renamed) {
// throw new ProxyCacheException("Error renaming file " + file + " to " + completedFile + " for completion!");
// }
// file = completedFile;
// try {
// dataFile = new RandomAccessFile(file, "r");
// diskUsage.touch(file);
// } catch (IOException e) {
// throw new ProxyCacheException("Error opening " + file + " as disc cache", e);
// }
// }
//
// @Override
// public synchronized boolean isCompleted() {
// return !isTempFile(file);
// }
//
// /**
// * Returns file to be used fo caching. It may as original file passed in constructor as some temp file for not completed cache.
// *
// * @return file for caching.
// */
// public File getFile() {
// return file;
// }
//
// private boolean isTempFile(File file) {
// return file.getName().endsWith(TEMP_POSTFIX);
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheUtils.java
// static final int DEFAULT_BUFFER_SIZE = 8 * 1024;
| import android.text.TextUtils;
import com.danikula.videocache.file.FileCache;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Locale;
import static com.danikula.videocache.ProxyCacheUtils.DEFAULT_BUFFER_SIZE; | responseWithoutCache(out, offset);
}
}
private boolean isUseCache(GetRequest request) throws ProxyCacheException {
long sourceLength = source.length();
boolean sourceLengthKnown = sourceLength > 0;
long cacheAvailable = cache.available();
// do not use cache for partial requests which too far from available cache. It seems user seek video.
return !sourceLengthKnown || !request.partial || request.rangeOffset <= cacheAvailable + sourceLength * NO_CACHE_BARRIER;
}
private String newResponseHeaders(GetRequest request) throws IOException, ProxyCacheException {
String mime = source.getMime();
boolean mimeKnown = !TextUtils.isEmpty(mime);
long length = cache.isCompleted() ? cache.available() : source.length();
boolean lengthKnown = length >= 0;
long contentLength = request.partial ? length - request.rangeOffset : length;
boolean addRange = lengthKnown && request.partial;
return new StringBuilder()
.append(request.partial ? "HTTP/1.1 206 PARTIAL CONTENT\n" : "HTTP/1.1 200 OK\n")
.append("Accept-Ranges: bytes\n")
.append(lengthKnown ? format("Content-Length: %d\n", contentLength) : "")
.append(addRange ? format("Content-Range: bytes %d-%d/%d\n", request.rangeOffset, length - 1, length) : "")
.append(mimeKnown ? format("Content-Type: %s\n", mime) : "")
.append("\n") // headers end
.toString();
}
private void responseWithCache(OutputStream out, long offset) throws ProxyCacheException, IOException { | // Path: library/src/main/java/com/danikula/videocache/file/FileCache.java
// public class FileCache implements Cache {
//
// private static final String TEMP_POSTFIX = ".download";
//
// private final DiskUsage diskUsage;
// public File file;
// private RandomAccessFile dataFile;
//
// public FileCache(File file) throws ProxyCacheException {
// this(file, new UnlimitedDiskUsage());
// }
//
// public FileCache(File file, DiskUsage diskUsage) throws ProxyCacheException {
// try {
// if (diskUsage == null) {
// throw new NullPointerException();
// }
// this.diskUsage = diskUsage;
// File directory = file.getParentFile();
// Files.makeDir(directory);
// boolean completed = file.exists();
// this.file = completed ? file : new File(file.getParentFile(), file.getName() + TEMP_POSTFIX);
// this.dataFile = new RandomAccessFile(this.file, completed ? "r" : "rw");
// } catch (IOException e) {
// throw new ProxyCacheException("Error using file " + file + " as disc cache", e);
// }
// }
//
// @Override
// public synchronized long available() throws ProxyCacheException {
// try {
// return (int) dataFile.length();
// } catch (IOException e) {
// throw new ProxyCacheException("Error reading length of file " + file, e);
// }
// }
//
// @Override
// public synchronized int read(byte[] buffer, long offset, int length) throws ProxyCacheException {
// try {
// dataFile.seek(offset);
// return dataFile.read(buffer, 0, length);
// } catch (IOException e) {
// String format = "Error reading %d bytes with offset %d from file[%d bytes] to buffer[%d bytes]";
// throw new ProxyCacheException(String.format(format, length, offset, available(), buffer.length), e);
// }
// }
//
// @Override
// public synchronized void append(byte[] data, int length) throws ProxyCacheException {
// try {
// if (isCompleted()) {
// throw new ProxyCacheException("Error append cache: cache file " + file + " is completed!");
// }
// dataFile.seek(available());
// dataFile.write(data, 0, length);
// } catch (IOException e) {
// String format = "Error writing %d bytes to %s from buffer with size %d";
// throw new ProxyCacheException(String.format(format, length, dataFile, data.length), e);
// }
// }
//
// @Override
// public synchronized void close() throws ProxyCacheException {
// try {
// dataFile.close();
// diskUsage.touch(file);
// } catch (IOException e) {
// throw new ProxyCacheException("Error closing file " + file, e);
// }
// }
//
// @Override
// public synchronized void complete() throws ProxyCacheException {
// if (isCompleted()) {
// return;
// }
//
// close();
// String fileName = file.getName().substring(0, file.getName().length() - TEMP_POSTFIX.length());
// File completedFile = new File(file.getParentFile(), fileName);
// boolean renamed = file.renameTo(completedFile);
// if (!renamed) {
// throw new ProxyCacheException("Error renaming file " + file + " to " + completedFile + " for completion!");
// }
// file = completedFile;
// try {
// dataFile = new RandomAccessFile(file, "r");
// diskUsage.touch(file);
// } catch (IOException e) {
// throw new ProxyCacheException("Error opening " + file + " as disc cache", e);
// }
// }
//
// @Override
// public synchronized boolean isCompleted() {
// return !isTempFile(file);
// }
//
// /**
// * Returns file to be used fo caching. It may as original file passed in constructor as some temp file for not completed cache.
// *
// * @return file for caching.
// */
// public File getFile() {
// return file;
// }
//
// private boolean isTempFile(File file) {
// return file.getName().endsWith(TEMP_POSTFIX);
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheUtils.java
// static final int DEFAULT_BUFFER_SIZE = 8 * 1024;
// Path: library/src/main/java/com/danikula/videocache/HttpProxyCache.java
import android.text.TextUtils;
import com.danikula.videocache.file.FileCache;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Locale;
import static com.danikula.videocache.ProxyCacheUtils.DEFAULT_BUFFER_SIZE;
responseWithoutCache(out, offset);
}
}
private boolean isUseCache(GetRequest request) throws ProxyCacheException {
long sourceLength = source.length();
boolean sourceLengthKnown = sourceLength > 0;
long cacheAvailable = cache.available();
// do not use cache for partial requests which too far from available cache. It seems user seek video.
return !sourceLengthKnown || !request.partial || request.rangeOffset <= cacheAvailable + sourceLength * NO_CACHE_BARRIER;
}
private String newResponseHeaders(GetRequest request) throws IOException, ProxyCacheException {
String mime = source.getMime();
boolean mimeKnown = !TextUtils.isEmpty(mime);
long length = cache.isCompleted() ? cache.available() : source.length();
boolean lengthKnown = length >= 0;
long contentLength = request.partial ? length - request.rangeOffset : length;
boolean addRange = lengthKnown && request.partial;
return new StringBuilder()
.append(request.partial ? "HTTP/1.1 206 PARTIAL CONTENT\n" : "HTTP/1.1 200 OK\n")
.append("Accept-Ranges: bytes\n")
.append(lengthKnown ? format("Content-Length: %d\n", contentLength) : "")
.append(addRange ? format("Content-Range: bytes %d-%d/%d\n", request.rangeOffset, length - 1, length) : "")
.append(mimeKnown ? format("Content-Type: %s\n", mime) : "")
.append("\n") // headers end
.toString();
}
private void responseWithCache(OutputStream out, long offset) throws ProxyCacheException, IOException { | byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/file/FileCache.java | // Path: library/src/main/java/com/danikula/videocache/Cache.java
// public interface Cache {
//
// long available() throws ProxyCacheException;
//
// int read(byte[] buffer, long offset, int length) throws ProxyCacheException;
//
// void append(byte[] data, int length) throws ProxyCacheException;
//
// void close() throws ProxyCacheException;
//
// void complete() throws ProxyCacheException;
//
// boolean isCompleted();
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheException.java
// public class ProxyCacheException extends Exception {
//
// private static final String LIBRARY_VERSION = ". Version: " + BuildConfig.VERSION_NAME;
//
// public ProxyCacheException(String message) {
// super(message + LIBRARY_VERSION);
// }
//
// public ProxyCacheException(String message, Throwable cause) {
// super(message + LIBRARY_VERSION, cause);
// }
//
// public ProxyCacheException(Throwable cause) {
// super("No explanation error" + LIBRARY_VERSION, cause);
// }
// }
| import com.danikula.videocache.Cache;
import com.danikula.videocache.ProxyCacheException;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile; | package com.danikula.videocache.file;
/**
* {@link Cache} that uses file for storing data.
*
* @author Alexey Danilov ([email protected]).
*/
public class FileCache implements Cache {
private static final String TEMP_POSTFIX = ".download";
private final DiskUsage diskUsage;
public File file;
private RandomAccessFile dataFile;
| // Path: library/src/main/java/com/danikula/videocache/Cache.java
// public interface Cache {
//
// long available() throws ProxyCacheException;
//
// int read(byte[] buffer, long offset, int length) throws ProxyCacheException;
//
// void append(byte[] data, int length) throws ProxyCacheException;
//
// void close() throws ProxyCacheException;
//
// void complete() throws ProxyCacheException;
//
// boolean isCompleted();
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheException.java
// public class ProxyCacheException extends Exception {
//
// private static final String LIBRARY_VERSION = ". Version: " + BuildConfig.VERSION_NAME;
//
// public ProxyCacheException(String message) {
// super(message + LIBRARY_VERSION);
// }
//
// public ProxyCacheException(String message, Throwable cause) {
// super(message + LIBRARY_VERSION, cause);
// }
//
// public ProxyCacheException(Throwable cause) {
// super("No explanation error" + LIBRARY_VERSION, cause);
// }
// }
// Path: library/src/main/java/com/danikula/videocache/file/FileCache.java
import com.danikula.videocache.Cache;
import com.danikula.videocache.ProxyCacheException;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
package com.danikula.videocache.file;
/**
* {@link Cache} that uses file for storing data.
*
* @author Alexey Danilov ([email protected]).
*/
public class FileCache implements Cache {
private static final String TEMP_POSTFIX = ".download";
private final DiskUsage diskUsage;
public File file;
private RandomAccessFile dataFile;
| public FileCache(File file) throws ProxyCacheException { |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/ProxyCache.java | // Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.atomic.AtomicInteger;
import static com.danikula.videocache.Preconditions.checkNotNull; | package com.danikula.videocache;
/**
* Proxy for {@link Source} with caching support ({@link Cache}).
* <p/>
* Can be used only for sources with persistent data (that doesn't change with time).
* Method {@link #read(byte[], long, int)} will be blocked while fetching data from source.
* Useful for streaming something with caching e.g. streaming video/audio etc.
*
* @author Alexey Danilov ([email protected]).
*/
class ProxyCache {
private static final Logger LOG = LoggerFactory.getLogger("ProxyCache");
private static final int MAX_READ_SOURCE_ATTEMPTS = 1;
private final Source source;
private final Cache cache;
private final Object wc = new Object();
private final Object stopLock = new Object();
private final AtomicInteger readSourceErrorsCount;
private volatile Thread sourceReaderThread;
private volatile boolean stopped;
private volatile int percentsAvailable = -1;
public ProxyCache(Source source, Cache cache) { | // Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
// Path: library/src/main/java/com/danikula/videocache/ProxyCache.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.atomic.AtomicInteger;
import static com.danikula.videocache.Preconditions.checkNotNull;
package com.danikula.videocache;
/**
* Proxy for {@link Source} with caching support ({@link Cache}).
* <p/>
* Can be used only for sources with persistent data (that doesn't change with time).
* Method {@link #read(byte[], long, int)} will be blocked while fetching data from source.
* Useful for streaming something with caching e.g. streaming video/audio etc.
*
* @author Alexey Danilov ([email protected]).
*/
class ProxyCache {
private static final Logger LOG = LoggerFactory.getLogger("ProxyCache");
private static final int MAX_READ_SOURCE_ATTEMPTS = 1;
private final Source source;
private final Cache cache;
private final Object wc = new Object();
private final Object stopLock = new Object();
private final AtomicInteger readSourceErrorsCount;
private volatile Thread sourceReaderThread;
private volatile boolean stopped;
private volatile int percentsAvailable = -1;
public ProxyCache(Source source, Cache cache) { | this.source = checkNotNull(source); |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/HttpProxyCacheServer.java | // Path: library/src/main/java/com/danikula/videocache/file/FileNameGenerator.java
// public interface FileNameGenerator {
//
// String generate(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/EmptyHeadersInjector.java
// public class EmptyHeadersInjector implements HeaderInjector {
//
// @Override
// public Map<String, String> addHeaders(String url) {
// return new HashMap<>();
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorageFactory.java
// public class SourceInfoStorageFactory {
//
// public static SourceInfoStorage newSourceInfoStorage(Context context) {
// return new DatabaseSourceInfoStorage(context);
// }
//
// public static SourceInfoStorage newEmptySourceInfoStorage() {
// return new NoSourceInfoStorage();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static void checkAllNotNull(Object... references) {
// for (Object reference : references) {
// if (reference == null) {
// throw new NullPointerException();
// }
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
| import android.content.Context;
import android.net.Uri;
import com.danikula.videocache.file.DiskUsage;
import com.danikula.videocache.file.FileNameGenerator;
import com.danikula.videocache.file.Md5FileNameGenerator;
import com.danikula.videocache.file.TotalCountLruDiskUsage;
import com.danikula.videocache.file.TotalSizeLruDiskUsage;
import com.danikula.videocache.headers.EmptyHeadersInjector;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import com.danikula.videocache.sourcestorage.SourceInfoStorageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.danikula.videocache.Preconditions.checkAllNotNull;
import static com.danikula.videocache.Preconditions.checkNotNull; | package com.danikula.videocache;
/**
* Simple lightweight proxy server with file caching support that handles HTTP requests.
* Typical usage:
* <pre><code>
* public onCreate(Bundle state) {
* super.onCreate(state);
*
* HttpProxyCacheServer proxy = getProxy();
* String proxyUrl = proxy.getProxyUrl(VIDEO_URL);
* videoView.setVideoPath(proxyUrl);
* }
*
* private HttpProxyCacheServer getProxy() {
* // should return single instance of HttpProxyCacheServer shared for whole app.
* }
* </code></pre>
*
* @author Alexey Danilov ([email protected]).
*/
public class HttpProxyCacheServer {
private static final Logger LOG = LoggerFactory.getLogger("HttpProxyCacheServer");
private static final String PROXY_HOST = "127.0.0.1";
private final Object clientsLock = new Object();
private final ExecutorService socketProcessor = Executors.newFixedThreadPool(8);
private final Map<String, HttpProxyCacheServerClients> clientsMap = new ConcurrentHashMap<>();
private final ServerSocket serverSocket;
private final int port;
private final Thread waitConnectionThread;
private final Config config;
private final Pinger pinger;
public HttpProxyCacheServer(Context context) {
this(new Builder(context).buildConfig());
}
private HttpProxyCacheServer(Config config) { | // Path: library/src/main/java/com/danikula/videocache/file/FileNameGenerator.java
// public interface FileNameGenerator {
//
// String generate(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/EmptyHeadersInjector.java
// public class EmptyHeadersInjector implements HeaderInjector {
//
// @Override
// public Map<String, String> addHeaders(String url) {
// return new HashMap<>();
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorageFactory.java
// public class SourceInfoStorageFactory {
//
// public static SourceInfoStorage newSourceInfoStorage(Context context) {
// return new DatabaseSourceInfoStorage(context);
// }
//
// public static SourceInfoStorage newEmptySourceInfoStorage() {
// return new NoSourceInfoStorage();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static void checkAllNotNull(Object... references) {
// for (Object reference : references) {
// if (reference == null) {
// throw new NullPointerException();
// }
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
// Path: library/src/main/java/com/danikula/videocache/HttpProxyCacheServer.java
import android.content.Context;
import android.net.Uri;
import com.danikula.videocache.file.DiskUsage;
import com.danikula.videocache.file.FileNameGenerator;
import com.danikula.videocache.file.Md5FileNameGenerator;
import com.danikula.videocache.file.TotalCountLruDiskUsage;
import com.danikula.videocache.file.TotalSizeLruDiskUsage;
import com.danikula.videocache.headers.EmptyHeadersInjector;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import com.danikula.videocache.sourcestorage.SourceInfoStorageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.danikula.videocache.Preconditions.checkAllNotNull;
import static com.danikula.videocache.Preconditions.checkNotNull;
package com.danikula.videocache;
/**
* Simple lightweight proxy server with file caching support that handles HTTP requests.
* Typical usage:
* <pre><code>
* public onCreate(Bundle state) {
* super.onCreate(state);
*
* HttpProxyCacheServer proxy = getProxy();
* String proxyUrl = proxy.getProxyUrl(VIDEO_URL);
* videoView.setVideoPath(proxyUrl);
* }
*
* private HttpProxyCacheServer getProxy() {
* // should return single instance of HttpProxyCacheServer shared for whole app.
* }
* </code></pre>
*
* @author Alexey Danilov ([email protected]).
*/
public class HttpProxyCacheServer {
private static final Logger LOG = LoggerFactory.getLogger("HttpProxyCacheServer");
private static final String PROXY_HOST = "127.0.0.1";
private final Object clientsLock = new Object();
private final ExecutorService socketProcessor = Executors.newFixedThreadPool(8);
private final Map<String, HttpProxyCacheServerClients> clientsMap = new ConcurrentHashMap<>();
private final ServerSocket serverSocket;
private final int port;
private final Thread waitConnectionThread;
private final Config config;
private final Pinger pinger;
public HttpProxyCacheServer(Context context) {
this(new Builder(context).buildConfig());
}
private HttpProxyCacheServer(Config config) { | this.config = checkNotNull(config); |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/HttpProxyCacheServer.java | // Path: library/src/main/java/com/danikula/videocache/file/FileNameGenerator.java
// public interface FileNameGenerator {
//
// String generate(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/EmptyHeadersInjector.java
// public class EmptyHeadersInjector implements HeaderInjector {
//
// @Override
// public Map<String, String> addHeaders(String url) {
// return new HashMap<>();
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorageFactory.java
// public class SourceInfoStorageFactory {
//
// public static SourceInfoStorage newSourceInfoStorage(Context context) {
// return new DatabaseSourceInfoStorage(context);
// }
//
// public static SourceInfoStorage newEmptySourceInfoStorage() {
// return new NoSourceInfoStorage();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static void checkAllNotNull(Object... references) {
// for (Object reference : references) {
// if (reference == null) {
// throw new NullPointerException();
// }
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
| import android.content.Context;
import android.net.Uri;
import com.danikula.videocache.file.DiskUsage;
import com.danikula.videocache.file.FileNameGenerator;
import com.danikula.videocache.file.Md5FileNameGenerator;
import com.danikula.videocache.file.TotalCountLruDiskUsage;
import com.danikula.videocache.file.TotalSizeLruDiskUsage;
import com.danikula.videocache.headers.EmptyHeadersInjector;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import com.danikula.videocache.sourcestorage.SourceInfoStorageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.danikula.videocache.Preconditions.checkAllNotNull;
import static com.danikula.videocache.Preconditions.checkNotNull; | * <p>
* Calling this method has same effect as calling {@link #getProxyUrl(String, boolean)} with 2nd parameter set to {@code true}.
*
* @param url a url to file that should be cached.
* @return a wrapped by proxy url if file is not fully cached or url pointed to cache file otherwise.
*/
public String getProxyUrl(String url) {
return getProxyUrl(url, true);
}
/**
* Returns url that wrap original url and should be used for client (MediaPlayer, ExoPlayer, etc).
* <p>
* If parameter {@code allowCachedFileUri} is {@code true} and file for this url is fully cached
* (it means method {@link #isCached(String)} returns {@code true}) then file:// uri to cached file will be returned.
*
* @param url a url to file that should be cached.
* @param allowCachedFileUri {@code true} if allow to return file:// uri if url is fully cached
* @return a wrapped by proxy url if file is not fully cached or url pointed to cache file otherwise (if {@code allowCachedFileUri} is {@code true}).
*/
public String getProxyUrl(String url, boolean allowCachedFileUri) {
if (allowCachedFileUri && isCached(url)) {
File cacheFile = getCacheFile(url);
touchFileSafely(cacheFile);
return Uri.fromFile(cacheFile).toString();
}
return isAlive() ? appendToProxyUrl(url) : url;
}
public void registerCacheListener(CacheListener cacheListener, String url) { | // Path: library/src/main/java/com/danikula/videocache/file/FileNameGenerator.java
// public interface FileNameGenerator {
//
// String generate(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/EmptyHeadersInjector.java
// public class EmptyHeadersInjector implements HeaderInjector {
//
// @Override
// public Map<String, String> addHeaders(String url) {
// return new HashMap<>();
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorageFactory.java
// public class SourceInfoStorageFactory {
//
// public static SourceInfoStorage newSourceInfoStorage(Context context) {
// return new DatabaseSourceInfoStorage(context);
// }
//
// public static SourceInfoStorage newEmptySourceInfoStorage() {
// return new NoSourceInfoStorage();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static void checkAllNotNull(Object... references) {
// for (Object reference : references) {
// if (reference == null) {
// throw new NullPointerException();
// }
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
// Path: library/src/main/java/com/danikula/videocache/HttpProxyCacheServer.java
import android.content.Context;
import android.net.Uri;
import com.danikula.videocache.file.DiskUsage;
import com.danikula.videocache.file.FileNameGenerator;
import com.danikula.videocache.file.Md5FileNameGenerator;
import com.danikula.videocache.file.TotalCountLruDiskUsage;
import com.danikula.videocache.file.TotalSizeLruDiskUsage;
import com.danikula.videocache.headers.EmptyHeadersInjector;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import com.danikula.videocache.sourcestorage.SourceInfoStorageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.danikula.videocache.Preconditions.checkAllNotNull;
import static com.danikula.videocache.Preconditions.checkNotNull;
* <p>
* Calling this method has same effect as calling {@link #getProxyUrl(String, boolean)} with 2nd parameter set to {@code true}.
*
* @param url a url to file that should be cached.
* @return a wrapped by proxy url if file is not fully cached or url pointed to cache file otherwise.
*/
public String getProxyUrl(String url) {
return getProxyUrl(url, true);
}
/**
* Returns url that wrap original url and should be used for client (MediaPlayer, ExoPlayer, etc).
* <p>
* If parameter {@code allowCachedFileUri} is {@code true} and file for this url is fully cached
* (it means method {@link #isCached(String)} returns {@code true}) then file:// uri to cached file will be returned.
*
* @param url a url to file that should be cached.
* @param allowCachedFileUri {@code true} if allow to return file:// uri if url is fully cached
* @return a wrapped by proxy url if file is not fully cached or url pointed to cache file otherwise (if {@code allowCachedFileUri} is {@code true}).
*/
public String getProxyUrl(String url, boolean allowCachedFileUri) {
if (allowCachedFileUri && isCached(url)) {
File cacheFile = getCacheFile(url);
touchFileSafely(cacheFile);
return Uri.fromFile(cacheFile).toString();
}
return isAlive() ? appendToProxyUrl(url) : url;
}
public void registerCacheListener(CacheListener cacheListener, String url) { | checkAllNotNull(cacheListener, url); |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/HttpProxyCacheServer.java | // Path: library/src/main/java/com/danikula/videocache/file/FileNameGenerator.java
// public interface FileNameGenerator {
//
// String generate(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/EmptyHeadersInjector.java
// public class EmptyHeadersInjector implements HeaderInjector {
//
// @Override
// public Map<String, String> addHeaders(String url) {
// return new HashMap<>();
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorageFactory.java
// public class SourceInfoStorageFactory {
//
// public static SourceInfoStorage newSourceInfoStorage(Context context) {
// return new DatabaseSourceInfoStorage(context);
// }
//
// public static SourceInfoStorage newEmptySourceInfoStorage() {
// return new NoSourceInfoStorage();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static void checkAllNotNull(Object... references) {
// for (Object reference : references) {
// if (reference == null) {
// throw new NullPointerException();
// }
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
| import android.content.Context;
import android.net.Uri;
import com.danikula.videocache.file.DiskUsage;
import com.danikula.videocache.file.FileNameGenerator;
import com.danikula.videocache.file.Md5FileNameGenerator;
import com.danikula.videocache.file.TotalCountLruDiskUsage;
import com.danikula.videocache.file.TotalSizeLruDiskUsage;
import com.danikula.videocache.headers.EmptyHeadersInjector;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import com.danikula.videocache.sourcestorage.SourceInfoStorageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.danikula.videocache.Preconditions.checkAllNotNull;
import static com.danikula.videocache.Preconditions.checkNotNull; |
@Override
public void run() {
startSignal.countDown();
waitForRequest();
}
}
private final class SocketProcessorRunnable implements Runnable {
private final Socket socket;
public SocketProcessorRunnable(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
processSocket(socket);
}
}
/**
* Builder for {@link HttpProxyCacheServer}.
*/
public static final class Builder {
private static final long DEFAULT_MAX_SIZE = 512 * 1024 * 1024;
private File cacheRoot; | // Path: library/src/main/java/com/danikula/videocache/file/FileNameGenerator.java
// public interface FileNameGenerator {
//
// String generate(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/EmptyHeadersInjector.java
// public class EmptyHeadersInjector implements HeaderInjector {
//
// @Override
// public Map<String, String> addHeaders(String url) {
// return new HashMap<>();
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorageFactory.java
// public class SourceInfoStorageFactory {
//
// public static SourceInfoStorage newSourceInfoStorage(Context context) {
// return new DatabaseSourceInfoStorage(context);
// }
//
// public static SourceInfoStorage newEmptySourceInfoStorage() {
// return new NoSourceInfoStorage();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static void checkAllNotNull(Object... references) {
// for (Object reference : references) {
// if (reference == null) {
// throw new NullPointerException();
// }
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
// Path: library/src/main/java/com/danikula/videocache/HttpProxyCacheServer.java
import android.content.Context;
import android.net.Uri;
import com.danikula.videocache.file.DiskUsage;
import com.danikula.videocache.file.FileNameGenerator;
import com.danikula.videocache.file.Md5FileNameGenerator;
import com.danikula.videocache.file.TotalCountLruDiskUsage;
import com.danikula.videocache.file.TotalSizeLruDiskUsage;
import com.danikula.videocache.headers.EmptyHeadersInjector;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import com.danikula.videocache.sourcestorage.SourceInfoStorageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.danikula.videocache.Preconditions.checkAllNotNull;
import static com.danikula.videocache.Preconditions.checkNotNull;
@Override
public void run() {
startSignal.countDown();
waitForRequest();
}
}
private final class SocketProcessorRunnable implements Runnable {
private final Socket socket;
public SocketProcessorRunnable(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
processSocket(socket);
}
}
/**
* Builder for {@link HttpProxyCacheServer}.
*/
public static final class Builder {
private static final long DEFAULT_MAX_SIZE = 512 * 1024 * 1024;
private File cacheRoot; | private FileNameGenerator fileNameGenerator; |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/HttpProxyCacheServer.java | // Path: library/src/main/java/com/danikula/videocache/file/FileNameGenerator.java
// public interface FileNameGenerator {
//
// String generate(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/EmptyHeadersInjector.java
// public class EmptyHeadersInjector implements HeaderInjector {
//
// @Override
// public Map<String, String> addHeaders(String url) {
// return new HashMap<>();
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorageFactory.java
// public class SourceInfoStorageFactory {
//
// public static SourceInfoStorage newSourceInfoStorage(Context context) {
// return new DatabaseSourceInfoStorage(context);
// }
//
// public static SourceInfoStorage newEmptySourceInfoStorage() {
// return new NoSourceInfoStorage();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static void checkAllNotNull(Object... references) {
// for (Object reference : references) {
// if (reference == null) {
// throw new NullPointerException();
// }
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
| import android.content.Context;
import android.net.Uri;
import com.danikula.videocache.file.DiskUsage;
import com.danikula.videocache.file.FileNameGenerator;
import com.danikula.videocache.file.Md5FileNameGenerator;
import com.danikula.videocache.file.TotalCountLruDiskUsage;
import com.danikula.videocache.file.TotalSizeLruDiskUsage;
import com.danikula.videocache.headers.EmptyHeadersInjector;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import com.danikula.videocache.sourcestorage.SourceInfoStorageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.danikula.videocache.Preconditions.checkAllNotNull;
import static com.danikula.videocache.Preconditions.checkNotNull; | public void run() {
startSignal.countDown();
waitForRequest();
}
}
private final class SocketProcessorRunnable implements Runnable {
private final Socket socket;
public SocketProcessorRunnable(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
processSocket(socket);
}
}
/**
* Builder for {@link HttpProxyCacheServer}.
*/
public static final class Builder {
private static final long DEFAULT_MAX_SIZE = 512 * 1024 * 1024;
private File cacheRoot;
private FileNameGenerator fileNameGenerator;
private DiskUsage diskUsage; | // Path: library/src/main/java/com/danikula/videocache/file/FileNameGenerator.java
// public interface FileNameGenerator {
//
// String generate(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/EmptyHeadersInjector.java
// public class EmptyHeadersInjector implements HeaderInjector {
//
// @Override
// public Map<String, String> addHeaders(String url) {
// return new HashMap<>();
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorageFactory.java
// public class SourceInfoStorageFactory {
//
// public static SourceInfoStorage newSourceInfoStorage(Context context) {
// return new DatabaseSourceInfoStorage(context);
// }
//
// public static SourceInfoStorage newEmptySourceInfoStorage() {
// return new NoSourceInfoStorage();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static void checkAllNotNull(Object... references) {
// for (Object reference : references) {
// if (reference == null) {
// throw new NullPointerException();
// }
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
// Path: library/src/main/java/com/danikula/videocache/HttpProxyCacheServer.java
import android.content.Context;
import android.net.Uri;
import com.danikula.videocache.file.DiskUsage;
import com.danikula.videocache.file.FileNameGenerator;
import com.danikula.videocache.file.Md5FileNameGenerator;
import com.danikula.videocache.file.TotalCountLruDiskUsage;
import com.danikula.videocache.file.TotalSizeLruDiskUsage;
import com.danikula.videocache.headers.EmptyHeadersInjector;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import com.danikula.videocache.sourcestorage.SourceInfoStorageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.danikula.videocache.Preconditions.checkAllNotNull;
import static com.danikula.videocache.Preconditions.checkNotNull;
public void run() {
startSignal.countDown();
waitForRequest();
}
}
private final class SocketProcessorRunnable implements Runnable {
private final Socket socket;
public SocketProcessorRunnable(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
processSocket(socket);
}
}
/**
* Builder for {@link HttpProxyCacheServer}.
*/
public static final class Builder {
private static final long DEFAULT_MAX_SIZE = 512 * 1024 * 1024;
private File cacheRoot;
private FileNameGenerator fileNameGenerator;
private DiskUsage diskUsage; | private SourceInfoStorage sourceInfoStorage; |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/HttpProxyCacheServer.java | // Path: library/src/main/java/com/danikula/videocache/file/FileNameGenerator.java
// public interface FileNameGenerator {
//
// String generate(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/EmptyHeadersInjector.java
// public class EmptyHeadersInjector implements HeaderInjector {
//
// @Override
// public Map<String, String> addHeaders(String url) {
// return new HashMap<>();
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorageFactory.java
// public class SourceInfoStorageFactory {
//
// public static SourceInfoStorage newSourceInfoStorage(Context context) {
// return new DatabaseSourceInfoStorage(context);
// }
//
// public static SourceInfoStorage newEmptySourceInfoStorage() {
// return new NoSourceInfoStorage();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static void checkAllNotNull(Object... references) {
// for (Object reference : references) {
// if (reference == null) {
// throw new NullPointerException();
// }
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
| import android.content.Context;
import android.net.Uri;
import com.danikula.videocache.file.DiskUsage;
import com.danikula.videocache.file.FileNameGenerator;
import com.danikula.videocache.file.Md5FileNameGenerator;
import com.danikula.videocache.file.TotalCountLruDiskUsage;
import com.danikula.videocache.file.TotalSizeLruDiskUsage;
import com.danikula.videocache.headers.EmptyHeadersInjector;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import com.danikula.videocache.sourcestorage.SourceInfoStorageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.danikula.videocache.Preconditions.checkAllNotNull;
import static com.danikula.videocache.Preconditions.checkNotNull; | startSignal.countDown();
waitForRequest();
}
}
private final class SocketProcessorRunnable implements Runnable {
private final Socket socket;
public SocketProcessorRunnable(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
processSocket(socket);
}
}
/**
* Builder for {@link HttpProxyCacheServer}.
*/
public static final class Builder {
private static final long DEFAULT_MAX_SIZE = 512 * 1024 * 1024;
private File cacheRoot;
private FileNameGenerator fileNameGenerator;
private DiskUsage diskUsage;
private SourceInfoStorage sourceInfoStorage; | // Path: library/src/main/java/com/danikula/videocache/file/FileNameGenerator.java
// public interface FileNameGenerator {
//
// String generate(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/EmptyHeadersInjector.java
// public class EmptyHeadersInjector implements HeaderInjector {
//
// @Override
// public Map<String, String> addHeaders(String url) {
// return new HashMap<>();
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorageFactory.java
// public class SourceInfoStorageFactory {
//
// public static SourceInfoStorage newSourceInfoStorage(Context context) {
// return new DatabaseSourceInfoStorage(context);
// }
//
// public static SourceInfoStorage newEmptySourceInfoStorage() {
// return new NoSourceInfoStorage();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static void checkAllNotNull(Object... references) {
// for (Object reference : references) {
// if (reference == null) {
// throw new NullPointerException();
// }
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
// Path: library/src/main/java/com/danikula/videocache/HttpProxyCacheServer.java
import android.content.Context;
import android.net.Uri;
import com.danikula.videocache.file.DiskUsage;
import com.danikula.videocache.file.FileNameGenerator;
import com.danikula.videocache.file.Md5FileNameGenerator;
import com.danikula.videocache.file.TotalCountLruDiskUsage;
import com.danikula.videocache.file.TotalSizeLruDiskUsage;
import com.danikula.videocache.headers.EmptyHeadersInjector;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import com.danikula.videocache.sourcestorage.SourceInfoStorageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.danikula.videocache.Preconditions.checkAllNotNull;
import static com.danikula.videocache.Preconditions.checkNotNull;
startSignal.countDown();
waitForRequest();
}
}
private final class SocketProcessorRunnable implements Runnable {
private final Socket socket;
public SocketProcessorRunnable(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
processSocket(socket);
}
}
/**
* Builder for {@link HttpProxyCacheServer}.
*/
public static final class Builder {
private static final long DEFAULT_MAX_SIZE = 512 * 1024 * 1024;
private File cacheRoot;
private FileNameGenerator fileNameGenerator;
private DiskUsage diskUsage;
private SourceInfoStorage sourceInfoStorage; | private HeaderInjector headerInjector; |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/HttpProxyCacheServer.java | // Path: library/src/main/java/com/danikula/videocache/file/FileNameGenerator.java
// public interface FileNameGenerator {
//
// String generate(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/EmptyHeadersInjector.java
// public class EmptyHeadersInjector implements HeaderInjector {
//
// @Override
// public Map<String, String> addHeaders(String url) {
// return new HashMap<>();
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorageFactory.java
// public class SourceInfoStorageFactory {
//
// public static SourceInfoStorage newSourceInfoStorage(Context context) {
// return new DatabaseSourceInfoStorage(context);
// }
//
// public static SourceInfoStorage newEmptySourceInfoStorage() {
// return new NoSourceInfoStorage();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static void checkAllNotNull(Object... references) {
// for (Object reference : references) {
// if (reference == null) {
// throw new NullPointerException();
// }
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
| import android.content.Context;
import android.net.Uri;
import com.danikula.videocache.file.DiskUsage;
import com.danikula.videocache.file.FileNameGenerator;
import com.danikula.videocache.file.Md5FileNameGenerator;
import com.danikula.videocache.file.TotalCountLruDiskUsage;
import com.danikula.videocache.file.TotalSizeLruDiskUsage;
import com.danikula.videocache.headers.EmptyHeadersInjector;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import com.danikula.videocache.sourcestorage.SourceInfoStorageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.danikula.videocache.Preconditions.checkAllNotNull;
import static com.danikula.videocache.Preconditions.checkNotNull; | }
private final class SocketProcessorRunnable implements Runnable {
private final Socket socket;
public SocketProcessorRunnable(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
processSocket(socket);
}
}
/**
* Builder for {@link HttpProxyCacheServer}.
*/
public static final class Builder {
private static final long DEFAULT_MAX_SIZE = 512 * 1024 * 1024;
private File cacheRoot;
private FileNameGenerator fileNameGenerator;
private DiskUsage diskUsage;
private SourceInfoStorage sourceInfoStorage;
private HeaderInjector headerInjector;
public Builder(Context context) { | // Path: library/src/main/java/com/danikula/videocache/file/FileNameGenerator.java
// public interface FileNameGenerator {
//
// String generate(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/EmptyHeadersInjector.java
// public class EmptyHeadersInjector implements HeaderInjector {
//
// @Override
// public Map<String, String> addHeaders(String url) {
// return new HashMap<>();
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorageFactory.java
// public class SourceInfoStorageFactory {
//
// public static SourceInfoStorage newSourceInfoStorage(Context context) {
// return new DatabaseSourceInfoStorage(context);
// }
//
// public static SourceInfoStorage newEmptySourceInfoStorage() {
// return new NoSourceInfoStorage();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static void checkAllNotNull(Object... references) {
// for (Object reference : references) {
// if (reference == null) {
// throw new NullPointerException();
// }
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
// Path: library/src/main/java/com/danikula/videocache/HttpProxyCacheServer.java
import android.content.Context;
import android.net.Uri;
import com.danikula.videocache.file.DiskUsage;
import com.danikula.videocache.file.FileNameGenerator;
import com.danikula.videocache.file.Md5FileNameGenerator;
import com.danikula.videocache.file.TotalCountLruDiskUsage;
import com.danikula.videocache.file.TotalSizeLruDiskUsage;
import com.danikula.videocache.headers.EmptyHeadersInjector;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import com.danikula.videocache.sourcestorage.SourceInfoStorageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.danikula.videocache.Preconditions.checkAllNotNull;
import static com.danikula.videocache.Preconditions.checkNotNull;
}
private final class SocketProcessorRunnable implements Runnable {
private final Socket socket;
public SocketProcessorRunnable(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
processSocket(socket);
}
}
/**
* Builder for {@link HttpProxyCacheServer}.
*/
public static final class Builder {
private static final long DEFAULT_MAX_SIZE = 512 * 1024 * 1024;
private File cacheRoot;
private FileNameGenerator fileNameGenerator;
private DiskUsage diskUsage;
private SourceInfoStorage sourceInfoStorage;
private HeaderInjector headerInjector;
public Builder(Context context) { | this.sourceInfoStorage = SourceInfoStorageFactory.newSourceInfoStorage(context); |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/HttpProxyCacheServer.java | // Path: library/src/main/java/com/danikula/videocache/file/FileNameGenerator.java
// public interface FileNameGenerator {
//
// String generate(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/EmptyHeadersInjector.java
// public class EmptyHeadersInjector implements HeaderInjector {
//
// @Override
// public Map<String, String> addHeaders(String url) {
// return new HashMap<>();
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorageFactory.java
// public class SourceInfoStorageFactory {
//
// public static SourceInfoStorage newSourceInfoStorage(Context context) {
// return new DatabaseSourceInfoStorage(context);
// }
//
// public static SourceInfoStorage newEmptySourceInfoStorage() {
// return new NoSourceInfoStorage();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static void checkAllNotNull(Object... references) {
// for (Object reference : references) {
// if (reference == null) {
// throw new NullPointerException();
// }
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
| import android.content.Context;
import android.net.Uri;
import com.danikula.videocache.file.DiskUsage;
import com.danikula.videocache.file.FileNameGenerator;
import com.danikula.videocache.file.Md5FileNameGenerator;
import com.danikula.videocache.file.TotalCountLruDiskUsage;
import com.danikula.videocache.file.TotalSizeLruDiskUsage;
import com.danikula.videocache.headers.EmptyHeadersInjector;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import com.danikula.videocache.sourcestorage.SourceInfoStorageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.danikula.videocache.Preconditions.checkAllNotNull;
import static com.danikula.videocache.Preconditions.checkNotNull; | private final Socket socket;
public SocketProcessorRunnable(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
processSocket(socket);
}
}
/**
* Builder for {@link HttpProxyCacheServer}.
*/
public static final class Builder {
private static final long DEFAULT_MAX_SIZE = 512 * 1024 * 1024;
private File cacheRoot;
private FileNameGenerator fileNameGenerator;
private DiskUsage diskUsage;
private SourceInfoStorage sourceInfoStorage;
private HeaderInjector headerInjector;
public Builder(Context context) {
this.sourceInfoStorage = SourceInfoStorageFactory.newSourceInfoStorage(context);
this.cacheRoot = StorageUtils.getIndividualCacheDirectory(context);
this.diskUsage = new TotalSizeLruDiskUsage(DEFAULT_MAX_SIZE);
this.fileNameGenerator = new Md5FileNameGenerator(); | // Path: library/src/main/java/com/danikula/videocache/file/FileNameGenerator.java
// public interface FileNameGenerator {
//
// String generate(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/EmptyHeadersInjector.java
// public class EmptyHeadersInjector implements HeaderInjector {
//
// @Override
// public Map<String, String> addHeaders(String url) {
// return new HashMap<>();
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorageFactory.java
// public class SourceInfoStorageFactory {
//
// public static SourceInfoStorage newSourceInfoStorage(Context context) {
// return new DatabaseSourceInfoStorage(context);
// }
//
// public static SourceInfoStorage newEmptySourceInfoStorage() {
// return new NoSourceInfoStorage();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static void checkAllNotNull(Object... references) {
// for (Object reference : references) {
// if (reference == null) {
// throw new NullPointerException();
// }
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
// Path: library/src/main/java/com/danikula/videocache/HttpProxyCacheServer.java
import android.content.Context;
import android.net.Uri;
import com.danikula.videocache.file.DiskUsage;
import com.danikula.videocache.file.FileNameGenerator;
import com.danikula.videocache.file.Md5FileNameGenerator;
import com.danikula.videocache.file.TotalCountLruDiskUsage;
import com.danikula.videocache.file.TotalSizeLruDiskUsage;
import com.danikula.videocache.headers.EmptyHeadersInjector;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import com.danikula.videocache.sourcestorage.SourceInfoStorageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.danikula.videocache.Preconditions.checkAllNotNull;
import static com.danikula.videocache.Preconditions.checkNotNull;
private final Socket socket;
public SocketProcessorRunnable(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
processSocket(socket);
}
}
/**
* Builder for {@link HttpProxyCacheServer}.
*/
public static final class Builder {
private static final long DEFAULT_MAX_SIZE = 512 * 1024 * 1024;
private File cacheRoot;
private FileNameGenerator fileNameGenerator;
private DiskUsage diskUsage;
private SourceInfoStorage sourceInfoStorage;
private HeaderInjector headerInjector;
public Builder(Context context) {
this.sourceInfoStorage = SourceInfoStorageFactory.newSourceInfoStorage(context);
this.cacheRoot = StorageUtils.getIndividualCacheDirectory(context);
this.diskUsage = new TotalSizeLruDiskUsage(DEFAULT_MAX_SIZE);
this.fileNameGenerator = new Md5FileNameGenerator(); | this.headerInjector = new EmptyHeadersInjector(); |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/sourcestorage/DatabaseSourceInfoStorage.java | // Path: library/src/main/java/com/danikula/videocache/SourceInfo.java
// public class SourceInfo {
//
// public final String url;
// public final long length;
// public final String mime;
//
// public SourceInfo(String url, long length, String mime) {
// this.url = url;
// this.length = length;
// this.mime = mime;
// }
//
// @Override
// public String toString() {
// return "SourceInfo{" +
// "url='" + url + '\'' +
// ", length=" + length +
// ", mime='" + mime + '\'' +
// '}';
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static void checkAllNotNull(Object... references) {
// for (Object reference : references) {
// if (reference == null) {
// throw new NullPointerException();
// }
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
| import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.danikula.videocache.SourceInfo;
import static com.danikula.videocache.Preconditions.checkAllNotNull;
import static com.danikula.videocache.Preconditions.checkNotNull; | package com.danikula.videocache.sourcestorage;
/**
* Database based {@link SourceInfoStorage}.
*
* @author Alexey Danilov ([email protected]).
*/
class DatabaseSourceInfoStorage extends SQLiteOpenHelper implements SourceInfoStorage {
private static final String TABLE = "SourceInfo";
private static final String COLUMN_ID = "_id";
private static final String COLUMN_URL = "url";
private static final String COLUMN_LENGTH = "length";
private static final String COLUMN_MIME = "mime";
private static final String[] ALL_COLUMNS = new String[]{COLUMN_ID, COLUMN_URL, COLUMN_LENGTH, COLUMN_MIME};
private static final String CREATE_SQL =
"CREATE TABLE " + TABLE + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," +
COLUMN_URL + " TEXT NOT NULL," +
COLUMN_MIME + " TEXT," +
COLUMN_LENGTH + " INTEGER" +
");";
DatabaseSourceInfoStorage(Context context) {
super(context, "AndroidVideoCache.db", null, 1); | // Path: library/src/main/java/com/danikula/videocache/SourceInfo.java
// public class SourceInfo {
//
// public final String url;
// public final long length;
// public final String mime;
//
// public SourceInfo(String url, long length, String mime) {
// this.url = url;
// this.length = length;
// this.mime = mime;
// }
//
// @Override
// public String toString() {
// return "SourceInfo{" +
// "url='" + url + '\'' +
// ", length=" + length +
// ", mime='" + mime + '\'' +
// '}';
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static void checkAllNotNull(Object... references) {
// for (Object reference : references) {
// if (reference == null) {
// throw new NullPointerException();
// }
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/DatabaseSourceInfoStorage.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.danikula.videocache.SourceInfo;
import static com.danikula.videocache.Preconditions.checkAllNotNull;
import static com.danikula.videocache.Preconditions.checkNotNull;
package com.danikula.videocache.sourcestorage;
/**
* Database based {@link SourceInfoStorage}.
*
* @author Alexey Danilov ([email protected]).
*/
class DatabaseSourceInfoStorage extends SQLiteOpenHelper implements SourceInfoStorage {
private static final String TABLE = "SourceInfo";
private static final String COLUMN_ID = "_id";
private static final String COLUMN_URL = "url";
private static final String COLUMN_LENGTH = "length";
private static final String COLUMN_MIME = "mime";
private static final String[] ALL_COLUMNS = new String[]{COLUMN_ID, COLUMN_URL, COLUMN_LENGTH, COLUMN_MIME};
private static final String CREATE_SQL =
"CREATE TABLE " + TABLE + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," +
COLUMN_URL + " TEXT NOT NULL," +
COLUMN_MIME + " TEXT," +
COLUMN_LENGTH + " INTEGER" +
");";
DatabaseSourceInfoStorage(Context context) {
super(context, "AndroidVideoCache.db", null, 1); | checkNotNull(context); |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/sourcestorage/DatabaseSourceInfoStorage.java | // Path: library/src/main/java/com/danikula/videocache/SourceInfo.java
// public class SourceInfo {
//
// public final String url;
// public final long length;
// public final String mime;
//
// public SourceInfo(String url, long length, String mime) {
// this.url = url;
// this.length = length;
// this.mime = mime;
// }
//
// @Override
// public String toString() {
// return "SourceInfo{" +
// "url='" + url + '\'' +
// ", length=" + length +
// ", mime='" + mime + '\'' +
// '}';
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static void checkAllNotNull(Object... references) {
// for (Object reference : references) {
// if (reference == null) {
// throw new NullPointerException();
// }
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
| import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.danikula.videocache.SourceInfo;
import static com.danikula.videocache.Preconditions.checkAllNotNull;
import static com.danikula.videocache.Preconditions.checkNotNull; | checkNotNull(context);
}
@Override
public void onCreate(SQLiteDatabase db) {
checkNotNull(db);
db.execSQL(CREATE_SQL);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
throw new IllegalStateException("Should not be called. There is no any migration");
}
@Override
public SourceInfo get(String url) {
checkNotNull(url);
Cursor cursor = null;
try {
cursor = getReadableDatabase().query(TABLE, ALL_COLUMNS, COLUMN_URL + "=?", new String[]{url}, null, null, null);
return cursor == null || !cursor.moveToFirst() ? null : convert(cursor);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
@Override
public void put(String url, SourceInfo sourceInfo) { | // Path: library/src/main/java/com/danikula/videocache/SourceInfo.java
// public class SourceInfo {
//
// public final String url;
// public final long length;
// public final String mime;
//
// public SourceInfo(String url, long length, String mime) {
// this.url = url;
// this.length = length;
// this.mime = mime;
// }
//
// @Override
// public String toString() {
// return "SourceInfo{" +
// "url='" + url + '\'' +
// ", length=" + length +
// ", mime='" + mime + '\'' +
// '}';
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static void checkAllNotNull(Object... references) {
// for (Object reference : references) {
// if (reference == null) {
// throw new NullPointerException();
// }
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/DatabaseSourceInfoStorage.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.danikula.videocache.SourceInfo;
import static com.danikula.videocache.Preconditions.checkAllNotNull;
import static com.danikula.videocache.Preconditions.checkNotNull;
checkNotNull(context);
}
@Override
public void onCreate(SQLiteDatabase db) {
checkNotNull(db);
db.execSQL(CREATE_SQL);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
throw new IllegalStateException("Should not be called. There is no any migration");
}
@Override
public SourceInfo get(String url) {
checkNotNull(url);
Cursor cursor = null;
try {
cursor = getReadableDatabase().query(TABLE, ALL_COLUMNS, COLUMN_URL + "=?", new String[]{url}, null, null, null);
return cursor == null || !cursor.moveToFirst() ? null : convert(cursor);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
@Override
public void put(String url, SourceInfo sourceInfo) { | checkAllNotNull(url, sourceInfo); |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/Config.java | // Path: library/src/main/java/com/danikula/videocache/file/FileNameGenerator.java
// public interface FileNameGenerator {
//
// String generate(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
| import com.danikula.videocache.file.DiskUsage;
import com.danikula.videocache.file.FileNameGenerator;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import java.io.File; | package com.danikula.videocache;
/**
* Configuration for proxy cache.
*
* @author Alexey Danilov ([email protected]).
*/
class Config {
public final File cacheRoot; | // Path: library/src/main/java/com/danikula/videocache/file/FileNameGenerator.java
// public interface FileNameGenerator {
//
// String generate(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
// Path: library/src/main/java/com/danikula/videocache/Config.java
import com.danikula.videocache.file.DiskUsage;
import com.danikula.videocache.file.FileNameGenerator;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import java.io.File;
package com.danikula.videocache;
/**
* Configuration for proxy cache.
*
* @author Alexey Danilov ([email protected]).
*/
class Config {
public final File cacheRoot; | public final FileNameGenerator fileNameGenerator; |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/Config.java | // Path: library/src/main/java/com/danikula/videocache/file/FileNameGenerator.java
// public interface FileNameGenerator {
//
// String generate(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
| import com.danikula.videocache.file.DiskUsage;
import com.danikula.videocache.file.FileNameGenerator;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import java.io.File; | package com.danikula.videocache;
/**
* Configuration for proxy cache.
*
* @author Alexey Danilov ([email protected]).
*/
class Config {
public final File cacheRoot;
public final FileNameGenerator fileNameGenerator;
public final DiskUsage diskUsage; | // Path: library/src/main/java/com/danikula/videocache/file/FileNameGenerator.java
// public interface FileNameGenerator {
//
// String generate(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
// Path: library/src/main/java/com/danikula/videocache/Config.java
import com.danikula.videocache.file.DiskUsage;
import com.danikula.videocache.file.FileNameGenerator;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import java.io.File;
package com.danikula.videocache;
/**
* Configuration for proxy cache.
*
* @author Alexey Danilov ([email protected]).
*/
class Config {
public final File cacheRoot;
public final FileNameGenerator fileNameGenerator;
public final DiskUsage diskUsage; | public final SourceInfoStorage sourceInfoStorage; |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/Config.java | // Path: library/src/main/java/com/danikula/videocache/file/FileNameGenerator.java
// public interface FileNameGenerator {
//
// String generate(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
| import com.danikula.videocache.file.DiskUsage;
import com.danikula.videocache.file.FileNameGenerator;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import java.io.File; | package com.danikula.videocache;
/**
* Configuration for proxy cache.
*
* @author Alexey Danilov ([email protected]).
*/
class Config {
public final File cacheRoot;
public final FileNameGenerator fileNameGenerator;
public final DiskUsage diskUsage;
public final SourceInfoStorage sourceInfoStorage; | // Path: library/src/main/java/com/danikula/videocache/file/FileNameGenerator.java
// public interface FileNameGenerator {
//
// String generate(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/headers/HeaderInjector.java
// public interface HeaderInjector {
//
// /**
// * Adds headers to server's requests for corresponding url.
// *
// * @param url an url headers will be added for
// * @return a map with headers, where keys are header's names, and values are header's values. {@code null} is not acceptable!
// */
// Map<String, String> addHeaders(String url);
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/sourcestorage/SourceInfoStorage.java
// public interface SourceInfoStorage {
//
// SourceInfo get(String url);
//
// void put(String url, SourceInfo sourceInfo);
//
// void release();
// }
// Path: library/src/main/java/com/danikula/videocache/Config.java
import com.danikula.videocache.file.DiskUsage;
import com.danikula.videocache.file.FileNameGenerator;
import com.danikula.videocache.headers.HeaderInjector;
import com.danikula.videocache.sourcestorage.SourceInfoStorage;
import java.io.File;
package com.danikula.videocache;
/**
* Configuration for proxy cache.
*
* @author Alexey Danilov ([email protected]).
*/
class Config {
public final File cacheRoot;
public final FileNameGenerator fileNameGenerator;
public final DiskUsage diskUsage;
public final SourceInfoStorage sourceInfoStorage; | public final HeaderInjector headerInjector; |
danikula/AndroidVideoCache | test/src/test/java/com/danikula/videocache/sourcestorage/SourceInfoStorageTest.java | // Path: test/src/test/java/com/danikula/videocache/BaseTest.java
// @RunWith(RobolectricTestRunner.class)
// @Config(constants = BuildConfig.class)
// public abstract class BaseTest {
//
// static {
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/SourceInfo.java
// public class SourceInfo {
//
// public final String url;
// public final long length;
// public final String mime;
//
// public SourceInfo(String url, long length, String mime) {
// this.url = url;
// this.length = length;
// this.mime = mime;
// }
//
// @Override
// public String toString() {
// return "SourceInfo{" +
// "url='" + url + '\'' +
// ", length=" + length +
// ", mime='" + mime + '\'' +
// '}';
// }
// }
| import com.danikula.videocache.BaseTest;
import com.danikula.videocache.SourceInfo;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.robolectric.RuntimeEnvironment;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.fail; | package com.danikula.videocache.sourcestorage;
/**
* Tests for {@link SourceInfoStorage}.
*
* @author Alexey Danilov ([email protected]).
*/
public class SourceInfoStorageTest extends BaseTest {
private SourceInfoStorage storage;
@Before
public void setUp() throws Exception {
storage = SourceInfoStorageFactory.newSourceInfoStorage(RuntimeEnvironment.application);
}
@After
public void tearDown() throws Exception {
storage.release();
}
@Test
public void testGetAbsent() throws Exception { | // Path: test/src/test/java/com/danikula/videocache/BaseTest.java
// @RunWith(RobolectricTestRunner.class)
// @Config(constants = BuildConfig.class)
// public abstract class BaseTest {
//
// static {
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/SourceInfo.java
// public class SourceInfo {
//
// public final String url;
// public final long length;
// public final String mime;
//
// public SourceInfo(String url, long length, String mime) {
// this.url = url;
// this.length = length;
// this.mime = mime;
// }
//
// @Override
// public String toString() {
// return "SourceInfo{" +
// "url='" + url + '\'' +
// ", length=" + length +
// ", mime='" + mime + '\'' +
// '}';
// }
// }
// Path: test/src/test/java/com/danikula/videocache/sourcestorage/SourceInfoStorageTest.java
import com.danikula.videocache.BaseTest;
import com.danikula.videocache.SourceInfo;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.robolectric.RuntimeEnvironment;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.fail;
package com.danikula.videocache.sourcestorage;
/**
* Tests for {@link SourceInfoStorage}.
*
* @author Alexey Danilov ([email protected]).
*/
public class SourceInfoStorageTest extends BaseTest {
private SourceInfoStorage storage;
@Before
public void setUp() throws Exception {
storage = SourceInfoStorageFactory.newSourceInfoStorage(RuntimeEnvironment.application);
}
@After
public void tearDown() throws Exception {
storage.release();
}
@Test
public void testGetAbsent() throws Exception { | SourceInfo sourceInfo = storage.get(":-)"); |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/HttpProxyCacheServerClients.java | // Path: library/src/main/java/com/danikula/videocache/file/FileCache.java
// public class FileCache implements Cache {
//
// private static final String TEMP_POSTFIX = ".download";
//
// private final DiskUsage diskUsage;
// public File file;
// private RandomAccessFile dataFile;
//
// public FileCache(File file) throws ProxyCacheException {
// this(file, new UnlimitedDiskUsage());
// }
//
// public FileCache(File file, DiskUsage diskUsage) throws ProxyCacheException {
// try {
// if (diskUsage == null) {
// throw new NullPointerException();
// }
// this.diskUsage = diskUsage;
// File directory = file.getParentFile();
// Files.makeDir(directory);
// boolean completed = file.exists();
// this.file = completed ? file : new File(file.getParentFile(), file.getName() + TEMP_POSTFIX);
// this.dataFile = new RandomAccessFile(this.file, completed ? "r" : "rw");
// } catch (IOException e) {
// throw new ProxyCacheException("Error using file " + file + " as disc cache", e);
// }
// }
//
// @Override
// public synchronized long available() throws ProxyCacheException {
// try {
// return (int) dataFile.length();
// } catch (IOException e) {
// throw new ProxyCacheException("Error reading length of file " + file, e);
// }
// }
//
// @Override
// public synchronized int read(byte[] buffer, long offset, int length) throws ProxyCacheException {
// try {
// dataFile.seek(offset);
// return dataFile.read(buffer, 0, length);
// } catch (IOException e) {
// String format = "Error reading %d bytes with offset %d from file[%d bytes] to buffer[%d bytes]";
// throw new ProxyCacheException(String.format(format, length, offset, available(), buffer.length), e);
// }
// }
//
// @Override
// public synchronized void append(byte[] data, int length) throws ProxyCacheException {
// try {
// if (isCompleted()) {
// throw new ProxyCacheException("Error append cache: cache file " + file + " is completed!");
// }
// dataFile.seek(available());
// dataFile.write(data, 0, length);
// } catch (IOException e) {
// String format = "Error writing %d bytes to %s from buffer with size %d";
// throw new ProxyCacheException(String.format(format, length, dataFile, data.length), e);
// }
// }
//
// @Override
// public synchronized void close() throws ProxyCacheException {
// try {
// dataFile.close();
// diskUsage.touch(file);
// } catch (IOException e) {
// throw new ProxyCacheException("Error closing file " + file, e);
// }
// }
//
// @Override
// public synchronized void complete() throws ProxyCacheException {
// if (isCompleted()) {
// return;
// }
//
// close();
// String fileName = file.getName().substring(0, file.getName().length() - TEMP_POSTFIX.length());
// File completedFile = new File(file.getParentFile(), fileName);
// boolean renamed = file.renameTo(completedFile);
// if (!renamed) {
// throw new ProxyCacheException("Error renaming file " + file + " to " + completedFile + " for completion!");
// }
// file = completedFile;
// try {
// dataFile = new RandomAccessFile(file, "r");
// diskUsage.touch(file);
// } catch (IOException e) {
// throw new ProxyCacheException("Error opening " + file + " as disc cache", e);
// }
// }
//
// @Override
// public synchronized boolean isCompleted() {
// return !isTempFile(file);
// }
//
// /**
// * Returns file to be used fo caching. It may as original file passed in constructor as some temp file for not completed cache.
// *
// * @return file for caching.
// */
// public File getFile() {
// return file;
// }
//
// private boolean isTempFile(File file) {
// return file.getName().endsWith(TEMP_POSTFIX);
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
| import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import com.danikula.videocache.file.FileCache;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import static com.danikula.videocache.Preconditions.checkNotNull; | package com.danikula.videocache;
/**
* Client for {@link HttpProxyCacheServer}
*
* @author Alexey Danilov ([email protected]).
*/
final class HttpProxyCacheServerClients {
private final AtomicInteger clientsCount = new AtomicInteger(0);
private final String url;
private volatile HttpProxyCache proxyCache;
private final List<CacheListener> listeners = new CopyOnWriteArrayList<>();
private final CacheListener uiCacheListener;
private final Config config;
public HttpProxyCacheServerClients(String url, Config config) { | // Path: library/src/main/java/com/danikula/videocache/file/FileCache.java
// public class FileCache implements Cache {
//
// private static final String TEMP_POSTFIX = ".download";
//
// private final DiskUsage diskUsage;
// public File file;
// private RandomAccessFile dataFile;
//
// public FileCache(File file) throws ProxyCacheException {
// this(file, new UnlimitedDiskUsage());
// }
//
// public FileCache(File file, DiskUsage diskUsage) throws ProxyCacheException {
// try {
// if (diskUsage == null) {
// throw new NullPointerException();
// }
// this.diskUsage = diskUsage;
// File directory = file.getParentFile();
// Files.makeDir(directory);
// boolean completed = file.exists();
// this.file = completed ? file : new File(file.getParentFile(), file.getName() + TEMP_POSTFIX);
// this.dataFile = new RandomAccessFile(this.file, completed ? "r" : "rw");
// } catch (IOException e) {
// throw new ProxyCacheException("Error using file " + file + " as disc cache", e);
// }
// }
//
// @Override
// public synchronized long available() throws ProxyCacheException {
// try {
// return (int) dataFile.length();
// } catch (IOException e) {
// throw new ProxyCacheException("Error reading length of file " + file, e);
// }
// }
//
// @Override
// public synchronized int read(byte[] buffer, long offset, int length) throws ProxyCacheException {
// try {
// dataFile.seek(offset);
// return dataFile.read(buffer, 0, length);
// } catch (IOException e) {
// String format = "Error reading %d bytes with offset %d from file[%d bytes] to buffer[%d bytes]";
// throw new ProxyCacheException(String.format(format, length, offset, available(), buffer.length), e);
// }
// }
//
// @Override
// public synchronized void append(byte[] data, int length) throws ProxyCacheException {
// try {
// if (isCompleted()) {
// throw new ProxyCacheException("Error append cache: cache file " + file + " is completed!");
// }
// dataFile.seek(available());
// dataFile.write(data, 0, length);
// } catch (IOException e) {
// String format = "Error writing %d bytes to %s from buffer with size %d";
// throw new ProxyCacheException(String.format(format, length, dataFile, data.length), e);
// }
// }
//
// @Override
// public synchronized void close() throws ProxyCacheException {
// try {
// dataFile.close();
// diskUsage.touch(file);
// } catch (IOException e) {
// throw new ProxyCacheException("Error closing file " + file, e);
// }
// }
//
// @Override
// public synchronized void complete() throws ProxyCacheException {
// if (isCompleted()) {
// return;
// }
//
// close();
// String fileName = file.getName().substring(0, file.getName().length() - TEMP_POSTFIX.length());
// File completedFile = new File(file.getParentFile(), fileName);
// boolean renamed = file.renameTo(completedFile);
// if (!renamed) {
// throw new ProxyCacheException("Error renaming file " + file + " to " + completedFile + " for completion!");
// }
// file = completedFile;
// try {
// dataFile = new RandomAccessFile(file, "r");
// diskUsage.touch(file);
// } catch (IOException e) {
// throw new ProxyCacheException("Error opening " + file + " as disc cache", e);
// }
// }
//
// @Override
// public synchronized boolean isCompleted() {
// return !isTempFile(file);
// }
//
// /**
// * Returns file to be used fo caching. It may as original file passed in constructor as some temp file for not completed cache.
// *
// * @return file for caching.
// */
// public File getFile() {
// return file;
// }
//
// private boolean isTempFile(File file) {
// return file.getName().endsWith(TEMP_POSTFIX);
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
// Path: library/src/main/java/com/danikula/videocache/HttpProxyCacheServerClients.java
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import com.danikula.videocache.file.FileCache;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import static com.danikula.videocache.Preconditions.checkNotNull;
package com.danikula.videocache;
/**
* Client for {@link HttpProxyCacheServer}
*
* @author Alexey Danilov ([email protected]).
*/
final class HttpProxyCacheServerClients {
private final AtomicInteger clientsCount = new AtomicInteger(0);
private final String url;
private volatile HttpProxyCache proxyCache;
private final List<CacheListener> listeners = new CopyOnWriteArrayList<>();
private final CacheListener uiCacheListener;
private final Config config;
public HttpProxyCacheServerClients(String url, Config config) { | this.url = checkNotNull(url); |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/HttpProxyCacheServerClients.java | // Path: library/src/main/java/com/danikula/videocache/file/FileCache.java
// public class FileCache implements Cache {
//
// private static final String TEMP_POSTFIX = ".download";
//
// private final DiskUsage diskUsage;
// public File file;
// private RandomAccessFile dataFile;
//
// public FileCache(File file) throws ProxyCacheException {
// this(file, new UnlimitedDiskUsage());
// }
//
// public FileCache(File file, DiskUsage diskUsage) throws ProxyCacheException {
// try {
// if (diskUsage == null) {
// throw new NullPointerException();
// }
// this.diskUsage = diskUsage;
// File directory = file.getParentFile();
// Files.makeDir(directory);
// boolean completed = file.exists();
// this.file = completed ? file : new File(file.getParentFile(), file.getName() + TEMP_POSTFIX);
// this.dataFile = new RandomAccessFile(this.file, completed ? "r" : "rw");
// } catch (IOException e) {
// throw new ProxyCacheException("Error using file " + file + " as disc cache", e);
// }
// }
//
// @Override
// public synchronized long available() throws ProxyCacheException {
// try {
// return (int) dataFile.length();
// } catch (IOException e) {
// throw new ProxyCacheException("Error reading length of file " + file, e);
// }
// }
//
// @Override
// public synchronized int read(byte[] buffer, long offset, int length) throws ProxyCacheException {
// try {
// dataFile.seek(offset);
// return dataFile.read(buffer, 0, length);
// } catch (IOException e) {
// String format = "Error reading %d bytes with offset %d from file[%d bytes] to buffer[%d bytes]";
// throw new ProxyCacheException(String.format(format, length, offset, available(), buffer.length), e);
// }
// }
//
// @Override
// public synchronized void append(byte[] data, int length) throws ProxyCacheException {
// try {
// if (isCompleted()) {
// throw new ProxyCacheException("Error append cache: cache file " + file + " is completed!");
// }
// dataFile.seek(available());
// dataFile.write(data, 0, length);
// } catch (IOException e) {
// String format = "Error writing %d bytes to %s from buffer with size %d";
// throw new ProxyCacheException(String.format(format, length, dataFile, data.length), e);
// }
// }
//
// @Override
// public synchronized void close() throws ProxyCacheException {
// try {
// dataFile.close();
// diskUsage.touch(file);
// } catch (IOException e) {
// throw new ProxyCacheException("Error closing file " + file, e);
// }
// }
//
// @Override
// public synchronized void complete() throws ProxyCacheException {
// if (isCompleted()) {
// return;
// }
//
// close();
// String fileName = file.getName().substring(0, file.getName().length() - TEMP_POSTFIX.length());
// File completedFile = new File(file.getParentFile(), fileName);
// boolean renamed = file.renameTo(completedFile);
// if (!renamed) {
// throw new ProxyCacheException("Error renaming file " + file + " to " + completedFile + " for completion!");
// }
// file = completedFile;
// try {
// dataFile = new RandomAccessFile(file, "r");
// diskUsage.touch(file);
// } catch (IOException e) {
// throw new ProxyCacheException("Error opening " + file + " as disc cache", e);
// }
// }
//
// @Override
// public synchronized boolean isCompleted() {
// return !isTempFile(file);
// }
//
// /**
// * Returns file to be used fo caching. It may as original file passed in constructor as some temp file for not completed cache.
// *
// * @return file for caching.
// */
// public File getFile() {
// return file;
// }
//
// private boolean isTempFile(File file) {
// return file.getName().endsWith(TEMP_POSTFIX);
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
| import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import com.danikula.videocache.file.FileCache;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import static com.danikula.videocache.Preconditions.checkNotNull; | if (clientsCount.decrementAndGet() <= 0) {
proxyCache.shutdown();
proxyCache = null;
}
}
public void registerCacheListener(CacheListener cacheListener) {
listeners.add(cacheListener);
}
public void unregisterCacheListener(CacheListener cacheListener) {
listeners.remove(cacheListener);
}
public void shutdown() {
listeners.clear();
if (proxyCache != null) {
proxyCache.registerCacheListener(null);
proxyCache.shutdown();
proxyCache = null;
}
clientsCount.set(0);
}
public int getClientsCount() {
return clientsCount.get();
}
private HttpProxyCache newHttpProxyCache() throws ProxyCacheException {
HttpUrlSource source = new HttpUrlSource(url, config.sourceInfoStorage, config.headerInjector); | // Path: library/src/main/java/com/danikula/videocache/file/FileCache.java
// public class FileCache implements Cache {
//
// private static final String TEMP_POSTFIX = ".download";
//
// private final DiskUsage diskUsage;
// public File file;
// private RandomAccessFile dataFile;
//
// public FileCache(File file) throws ProxyCacheException {
// this(file, new UnlimitedDiskUsage());
// }
//
// public FileCache(File file, DiskUsage diskUsage) throws ProxyCacheException {
// try {
// if (diskUsage == null) {
// throw new NullPointerException();
// }
// this.diskUsage = diskUsage;
// File directory = file.getParentFile();
// Files.makeDir(directory);
// boolean completed = file.exists();
// this.file = completed ? file : new File(file.getParentFile(), file.getName() + TEMP_POSTFIX);
// this.dataFile = new RandomAccessFile(this.file, completed ? "r" : "rw");
// } catch (IOException e) {
// throw new ProxyCacheException("Error using file " + file + " as disc cache", e);
// }
// }
//
// @Override
// public synchronized long available() throws ProxyCacheException {
// try {
// return (int) dataFile.length();
// } catch (IOException e) {
// throw new ProxyCacheException("Error reading length of file " + file, e);
// }
// }
//
// @Override
// public synchronized int read(byte[] buffer, long offset, int length) throws ProxyCacheException {
// try {
// dataFile.seek(offset);
// return dataFile.read(buffer, 0, length);
// } catch (IOException e) {
// String format = "Error reading %d bytes with offset %d from file[%d bytes] to buffer[%d bytes]";
// throw new ProxyCacheException(String.format(format, length, offset, available(), buffer.length), e);
// }
// }
//
// @Override
// public synchronized void append(byte[] data, int length) throws ProxyCacheException {
// try {
// if (isCompleted()) {
// throw new ProxyCacheException("Error append cache: cache file " + file + " is completed!");
// }
// dataFile.seek(available());
// dataFile.write(data, 0, length);
// } catch (IOException e) {
// String format = "Error writing %d bytes to %s from buffer with size %d";
// throw new ProxyCacheException(String.format(format, length, dataFile, data.length), e);
// }
// }
//
// @Override
// public synchronized void close() throws ProxyCacheException {
// try {
// dataFile.close();
// diskUsage.touch(file);
// } catch (IOException e) {
// throw new ProxyCacheException("Error closing file " + file, e);
// }
// }
//
// @Override
// public synchronized void complete() throws ProxyCacheException {
// if (isCompleted()) {
// return;
// }
//
// close();
// String fileName = file.getName().substring(0, file.getName().length() - TEMP_POSTFIX.length());
// File completedFile = new File(file.getParentFile(), fileName);
// boolean renamed = file.renameTo(completedFile);
// if (!renamed) {
// throw new ProxyCacheException("Error renaming file " + file + " to " + completedFile + " for completion!");
// }
// file = completedFile;
// try {
// dataFile = new RandomAccessFile(file, "r");
// diskUsage.touch(file);
// } catch (IOException e) {
// throw new ProxyCacheException("Error opening " + file + " as disc cache", e);
// }
// }
//
// @Override
// public synchronized boolean isCompleted() {
// return !isTempFile(file);
// }
//
// /**
// * Returns file to be used fo caching. It may as original file passed in constructor as some temp file for not completed cache.
// *
// * @return file for caching.
// */
// public File getFile() {
// return file;
// }
//
// private boolean isTempFile(File file) {
// return file.getName().endsWith(TEMP_POSTFIX);
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
// Path: library/src/main/java/com/danikula/videocache/HttpProxyCacheServerClients.java
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import com.danikula.videocache.file.FileCache;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import static com.danikula.videocache.Preconditions.checkNotNull;
if (clientsCount.decrementAndGet() <= 0) {
proxyCache.shutdown();
proxyCache = null;
}
}
public void registerCacheListener(CacheListener cacheListener) {
listeners.add(cacheListener);
}
public void unregisterCacheListener(CacheListener cacheListener) {
listeners.remove(cacheListener);
}
public void shutdown() {
listeners.clear();
if (proxyCache != null) {
proxyCache.registerCacheListener(null);
proxyCache.shutdown();
proxyCache = null;
}
clientsCount.set(0);
}
public int getClientsCount() {
return clientsCount.get();
}
private HttpProxyCache newHttpProxyCache() throws ProxyCacheException {
HttpUrlSource source = new HttpUrlSource(url, config.sourceInfoStorage, config.headerInjector); | FileCache cache = new FileCache(config.generateCacheFile(url), config.diskUsage); |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/ProxyCacheUtils.java | // Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// static void checkArgument(boolean expression) {
// if (!expression) {
// throw new IllegalArgumentException();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
| import android.text.TextUtils;
import android.webkit.MimeTypeMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import static com.danikula.videocache.Preconditions.checkArgument;
import static com.danikula.videocache.Preconditions.checkNotNull; | package com.danikula.videocache;
/**
* Just simple utils.
*
* @author Alexey Danilov ([email protected]).
*/
public class ProxyCacheUtils {
private static final Logger LOG = LoggerFactory.getLogger("ProxyCacheUtils");
static final int DEFAULT_BUFFER_SIZE = 8 * 1024;
static final int MAX_ARRAY_PREVIEW = 16;
static String getSupposablyMime(String url) {
MimeTypeMap mimes = MimeTypeMap.getSingleton();
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
return TextUtils.isEmpty(extension) ? null : mimes.getMimeTypeFromExtension(extension);
}
static void assertBuffer(byte[] buffer, long offset, int length) { | // Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// static void checkArgument(boolean expression) {
// if (!expression) {
// throw new IllegalArgumentException();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheUtils.java
import android.text.TextUtils;
import android.webkit.MimeTypeMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import static com.danikula.videocache.Preconditions.checkArgument;
import static com.danikula.videocache.Preconditions.checkNotNull;
package com.danikula.videocache;
/**
* Just simple utils.
*
* @author Alexey Danilov ([email protected]).
*/
public class ProxyCacheUtils {
private static final Logger LOG = LoggerFactory.getLogger("ProxyCacheUtils");
static final int DEFAULT_BUFFER_SIZE = 8 * 1024;
static final int MAX_ARRAY_PREVIEW = 16;
static String getSupposablyMime(String url) {
MimeTypeMap mimes = MimeTypeMap.getSingleton();
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
return TextUtils.isEmpty(extension) ? null : mimes.getMimeTypeFromExtension(extension);
}
static void assertBuffer(byte[] buffer, long offset, int length) { | checkNotNull(buffer, "Buffer must be not null!"); |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/ProxyCacheUtils.java | // Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// static void checkArgument(boolean expression) {
// if (!expression) {
// throw new IllegalArgumentException();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
| import android.text.TextUtils;
import android.webkit.MimeTypeMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import static com.danikula.videocache.Preconditions.checkArgument;
import static com.danikula.videocache.Preconditions.checkNotNull; | package com.danikula.videocache;
/**
* Just simple utils.
*
* @author Alexey Danilov ([email protected]).
*/
public class ProxyCacheUtils {
private static final Logger LOG = LoggerFactory.getLogger("ProxyCacheUtils");
static final int DEFAULT_BUFFER_SIZE = 8 * 1024;
static final int MAX_ARRAY_PREVIEW = 16;
static String getSupposablyMime(String url) {
MimeTypeMap mimes = MimeTypeMap.getSingleton();
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
return TextUtils.isEmpty(extension) ? null : mimes.getMimeTypeFromExtension(extension);
}
static void assertBuffer(byte[] buffer, long offset, int length) {
checkNotNull(buffer, "Buffer must be not null!"); | // Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// static void checkArgument(boolean expression) {
// if (!expression) {
// throw new IllegalArgumentException();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheUtils.java
import android.text.TextUtils;
import android.webkit.MimeTypeMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import static com.danikula.videocache.Preconditions.checkArgument;
import static com.danikula.videocache.Preconditions.checkNotNull;
package com.danikula.videocache;
/**
* Just simple utils.
*
* @author Alexey Danilov ([email protected]).
*/
public class ProxyCacheUtils {
private static final Logger LOG = LoggerFactory.getLogger("ProxyCacheUtils");
static final int DEFAULT_BUFFER_SIZE = 8 * 1024;
static final int MAX_ARRAY_PREVIEW = 16;
static String getSupposablyMime(String url) {
MimeTypeMap mimes = MimeTypeMap.getSingleton();
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
return TextUtils.isEmpty(extension) ? null : mimes.getMimeTypeFromExtension(extension);
}
static void assertBuffer(byte[] buffer, long offset, int length) {
checkNotNull(buffer, "Buffer must be not null!"); | checkArgument(offset >= 0, "Data offset must be positive!"); |
danikula/AndroidVideoCache | test/src/test/java/com/danikula/videocache/FileNameGeneratorTest.java | // Path: library/src/main/java/com/danikula/videocache/file/FileNameGenerator.java
// public interface FileNameGenerator {
//
// String generate(String url);
//
// }
| import com.danikula.videocache.file.FileNameGenerator;
import com.danikula.videocache.file.Md5FileNameGenerator;
import org.junit.Test;
import java.io.File;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.fail; | assertThat(path).isEqualTo(expected);
}
@Test
public void testMd5TooLongExtension() throws Exception {
String url = "http://host.com/videos/video-with-dot-.12345";
String path = generateMd5Name("/home", url);
String expected = "/home/" + ProxyCacheUtils.computeMD5(url);
assertThat(path).isEqualTo(expected);
}
@Test
public void testMd5InvalidExtension() throws Exception {
String url = "http://host.com/videos/video.mp4?token=-648729473536183645";
String path = generateMd5Name("/home", url);
String expected = "/home/" + ProxyCacheUtils.computeMD5(url);
assertThat(path).isEqualTo(expected);
}
@Test
public void testMd5ExtraLongExtension() throws Exception {
// https://github.com/danikula/AndroidVideoCache/issues/14
String url = "https://d1wst0behutosd.cloudfront.net/videos/4367900/10807247.480p.mp4?Expires=1442849176&Signature=JXV~3AoI0rWcGuZBywg3-ukf6Ycw2X8v7Htog3lyvuFwp8o6VUEDFUsTC9-XtIGu-ULxCd7dP3fvB306lRyGFxdvf-sXLX~ar~HCQ7lullNyeLtp8BJOT5Y~W5rJE7X-AZaueNcycGtLFRhRtr5ySTguwtmJNaO3T1apX~-oVrFh1dWStEKbuPoXY04RgkmhMHoFgtwgXMC1ctIDeQHxZeXLi6LLyZnQsgzlUDffCx4P16iiW0uh2-Z~HUOi9BLBwHMQ5k5lYwZqdQ6DhhYoWlniRfQz6mp1IEiMgr4L3Z1ijgGITV4cYeF31CmFzCxaJTE7IIAC5tMDQSTt7M9Q4A__&Key-Pair-Id=APKAJJ6WELAPEP47UKWQ";
String path = generateMd5Name("/home", url);
String expected = "/home/" + ProxyCacheUtils.computeMD5(url);
assertThat(path).isEqualTo(expected);
}
@Test(expected = NullPointerException.class)
public void testAssertNullUrl() throws Exception { | // Path: library/src/main/java/com/danikula/videocache/file/FileNameGenerator.java
// public interface FileNameGenerator {
//
// String generate(String url);
//
// }
// Path: test/src/test/java/com/danikula/videocache/FileNameGeneratorTest.java
import com.danikula.videocache.file.FileNameGenerator;
import com.danikula.videocache.file.Md5FileNameGenerator;
import org.junit.Test;
import java.io.File;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.fail;
assertThat(path).isEqualTo(expected);
}
@Test
public void testMd5TooLongExtension() throws Exception {
String url = "http://host.com/videos/video-with-dot-.12345";
String path = generateMd5Name("/home", url);
String expected = "/home/" + ProxyCacheUtils.computeMD5(url);
assertThat(path).isEqualTo(expected);
}
@Test
public void testMd5InvalidExtension() throws Exception {
String url = "http://host.com/videos/video.mp4?token=-648729473536183645";
String path = generateMd5Name("/home", url);
String expected = "/home/" + ProxyCacheUtils.computeMD5(url);
assertThat(path).isEqualTo(expected);
}
@Test
public void testMd5ExtraLongExtension() throws Exception {
// https://github.com/danikula/AndroidVideoCache/issues/14
String url = "https://d1wst0behutosd.cloudfront.net/videos/4367900/10807247.480p.mp4?Expires=1442849176&Signature=JXV~3AoI0rWcGuZBywg3-ukf6Ycw2X8v7Htog3lyvuFwp8o6VUEDFUsTC9-XtIGu-ULxCd7dP3fvB306lRyGFxdvf-sXLX~ar~HCQ7lullNyeLtp8BJOT5Y~W5rJE7X-AZaueNcycGtLFRhRtr5ySTguwtmJNaO3T1apX~-oVrFh1dWStEKbuPoXY04RgkmhMHoFgtwgXMC1ctIDeQHxZeXLi6LLyZnQsgzlUDffCx4P16iiW0uh2-Z~HUOi9BLBwHMQ5k5lYwZqdQ6DhhYoWlniRfQz6mp1IEiMgr4L3Z1ijgGITV4cYeF31CmFzCxaJTE7IIAC5tMDQSTt7M9Q4A__&Key-Pair-Id=APKAJJ6WELAPEP47UKWQ";
String path = generateMd5Name("/home", url);
String expected = "/home/" + ProxyCacheUtils.computeMD5(url);
assertThat(path).isEqualTo(expected);
}
@Test(expected = NullPointerException.class)
public void testAssertNullUrl() throws Exception { | FileNameGenerator nameGenerator = new Md5FileNameGenerator(); |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/Pinger.java | // Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// static void checkArgument(boolean expression) {
// if (!expression) {
// throw new IllegalArgumentException();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
import static com.danikula.videocache.Preconditions.checkArgument;
import static com.danikula.videocache.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS; | package com.danikula.videocache;
/**
* Pings {@link HttpProxyCacheServer} to make sure it works.
*
* @author Alexey Danilov ([email protected]).
*/
class Pinger {
private static final Logger LOG = LoggerFactory.getLogger("Pinger");
private static final String PING_REQUEST = "ping";
private static final String PING_RESPONSE = "ping ok";
private final ExecutorService pingExecutor = Executors.newSingleThreadExecutor();
private final String host;
private final int port;
Pinger(String host, int port) { | // Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// static void checkArgument(boolean expression) {
// if (!expression) {
// throw new IllegalArgumentException();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
// Path: library/src/main/java/com/danikula/videocache/Pinger.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
import static com.danikula.videocache.Preconditions.checkArgument;
import static com.danikula.videocache.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
package com.danikula.videocache;
/**
* Pings {@link HttpProxyCacheServer} to make sure it works.
*
* @author Alexey Danilov ([email protected]).
*/
class Pinger {
private static final Logger LOG = LoggerFactory.getLogger("Pinger");
private static final String PING_REQUEST = "ping";
private static final String PING_RESPONSE = "ping ok";
private final ExecutorService pingExecutor = Executors.newSingleThreadExecutor();
private final String host;
private final int port;
Pinger(String host, int port) { | this.host = checkNotNull(host); |
danikula/AndroidVideoCache | library/src/main/java/com/danikula/videocache/Pinger.java | // Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// static void checkArgument(boolean expression) {
// if (!expression) {
// throw new IllegalArgumentException();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
import static com.danikula.videocache.Preconditions.checkArgument;
import static com.danikula.videocache.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS; | package com.danikula.videocache;
/**
* Pings {@link HttpProxyCacheServer} to make sure it works.
*
* @author Alexey Danilov ([email protected]).
*/
class Pinger {
private static final Logger LOG = LoggerFactory.getLogger("Pinger");
private static final String PING_REQUEST = "ping";
private static final String PING_RESPONSE = "ping ok";
private final ExecutorService pingExecutor = Executors.newSingleThreadExecutor();
private final String host;
private final int port;
Pinger(String host, int port) {
this.host = checkNotNull(host);
this.port = port;
}
boolean ping(int maxAttempts, int startTimeout) { | // Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// static void checkArgument(boolean expression) {
// if (!expression) {
// throw new IllegalArgumentException();
// }
// }
//
// Path: library/src/main/java/com/danikula/videocache/Preconditions.java
// public static <T> T checkNotNull(T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
// Path: library/src/main/java/com/danikula/videocache/Pinger.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
import static com.danikula.videocache.Preconditions.checkArgument;
import static com.danikula.videocache.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
package com.danikula.videocache;
/**
* Pings {@link HttpProxyCacheServer} to make sure it works.
*
* @author Alexey Danilov ([email protected]).
*/
class Pinger {
private static final Logger LOG = LoggerFactory.getLogger("Pinger");
private static final String PING_REQUEST = "ping";
private static final String PING_RESPONSE = "ping ok";
private final ExecutorService pingExecutor = Executors.newSingleThreadExecutor();
private final String host;
private final int port;
Pinger(String host, int port) {
this.host = checkNotNull(host);
this.port = port;
}
boolean ping(int maxAttempts, int startTimeout) { | checkArgument(maxAttempts >= 1); |
danikula/AndroidVideoCache | test/src/test/java/com/danikula/videocache/file/FileCacheTest.java | // Path: test/src/test/java/com/danikula/videocache/BaseTest.java
// @RunWith(RobolectricTestRunner.class)
// @Config(constants = BuildConfig.class)
// public abstract class BaseTest {
//
// static {
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/Cache.java
// public interface Cache {
//
// long available() throws ProxyCacheException;
//
// int read(byte[] buffer, long offset, int length) throws ProxyCacheException;
//
// void append(byte[] data, int length) throws ProxyCacheException;
//
// void close() throws ProxyCacheException;
//
// void complete() throws ProxyCacheException;
//
// boolean isCompleted();
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheException.java
// public class ProxyCacheException extends Exception {
//
// private static final String LIBRARY_VERSION = ". Version: " + BuildConfig.VERSION_NAME;
//
// public ProxyCacheException(String message) {
// super(message + LIBRARY_VERSION);
// }
//
// public ProxyCacheException(String message, Throwable cause) {
// super(message + LIBRARY_VERSION, cause);
// }
//
// public ProxyCacheException(Throwable cause) {
// super("No explanation error" + LIBRARY_VERSION, cause);
// }
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static final String ASSETS_DATA_NAME = "android.jpg";
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] generate(int capacity) {
// Random random = new Random(System.currentTimeMillis());
// byte[] result = new byte[capacity];
// random.nextBytes(result);
// return result;
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] getFileContent(File file) throws IOException {
// return Files.asByteSource(file).read();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File getTempFile(File file) {
// return new File(file.getParentFile(), file.getName() + ".download");
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] loadAssetFile(String name) throws IOException {
// InputStream in = RuntimeEnvironment.application.getResources().getAssets().open(name);
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// IoUtils.copy(in, out);
// IoUtils.closeSilently(in);
// IoUtils.closeSilently(out);
// return out.toByteArray();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File newCacheFile() {
// return new File(RuntimeEnvironment.application.getCacheDir(), UUID.randomUUID().toString());
// }
| import com.danikula.android.garden.io.Files;
import com.danikula.videocache.BaseTest;
import com.danikula.videocache.Cache;
import com.danikula.videocache.ProxyCacheException;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import static com.danikula.videocache.support.ProxyCacheTestUtils.ASSETS_DATA_NAME;
import static com.danikula.videocache.support.ProxyCacheTestUtils.generate;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getFileContent;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getTempFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.loadAssetFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.newCacheFile;
import static com.google.common.io.Files.write;
import static org.fest.assertions.api.Assertions.assertThat; | package com.danikula.videocache.file;
/**
* @author Alexey Danilov ([email protected]).
*/
public class FileCacheTest extends BaseTest {
@Test
public void testWriteReadDiscCache() throws Exception {
int firstPortionLength = 10000; | // Path: test/src/test/java/com/danikula/videocache/BaseTest.java
// @RunWith(RobolectricTestRunner.class)
// @Config(constants = BuildConfig.class)
// public abstract class BaseTest {
//
// static {
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/Cache.java
// public interface Cache {
//
// long available() throws ProxyCacheException;
//
// int read(byte[] buffer, long offset, int length) throws ProxyCacheException;
//
// void append(byte[] data, int length) throws ProxyCacheException;
//
// void close() throws ProxyCacheException;
//
// void complete() throws ProxyCacheException;
//
// boolean isCompleted();
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheException.java
// public class ProxyCacheException extends Exception {
//
// private static final String LIBRARY_VERSION = ". Version: " + BuildConfig.VERSION_NAME;
//
// public ProxyCacheException(String message) {
// super(message + LIBRARY_VERSION);
// }
//
// public ProxyCacheException(String message, Throwable cause) {
// super(message + LIBRARY_VERSION, cause);
// }
//
// public ProxyCacheException(Throwable cause) {
// super("No explanation error" + LIBRARY_VERSION, cause);
// }
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static final String ASSETS_DATA_NAME = "android.jpg";
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] generate(int capacity) {
// Random random = new Random(System.currentTimeMillis());
// byte[] result = new byte[capacity];
// random.nextBytes(result);
// return result;
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] getFileContent(File file) throws IOException {
// return Files.asByteSource(file).read();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File getTempFile(File file) {
// return new File(file.getParentFile(), file.getName() + ".download");
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] loadAssetFile(String name) throws IOException {
// InputStream in = RuntimeEnvironment.application.getResources().getAssets().open(name);
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// IoUtils.copy(in, out);
// IoUtils.closeSilently(in);
// IoUtils.closeSilently(out);
// return out.toByteArray();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File newCacheFile() {
// return new File(RuntimeEnvironment.application.getCacheDir(), UUID.randomUUID().toString());
// }
// Path: test/src/test/java/com/danikula/videocache/file/FileCacheTest.java
import com.danikula.android.garden.io.Files;
import com.danikula.videocache.BaseTest;
import com.danikula.videocache.Cache;
import com.danikula.videocache.ProxyCacheException;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import static com.danikula.videocache.support.ProxyCacheTestUtils.ASSETS_DATA_NAME;
import static com.danikula.videocache.support.ProxyCacheTestUtils.generate;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getFileContent;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getTempFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.loadAssetFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.newCacheFile;
import static com.google.common.io.Files.write;
import static org.fest.assertions.api.Assertions.assertThat;
package com.danikula.videocache.file;
/**
* @author Alexey Danilov ([email protected]).
*/
public class FileCacheTest extends BaseTest {
@Test
public void testWriteReadDiscCache() throws Exception {
int firstPortionLength = 10000; | byte[] firstDataPortion = generate(firstPortionLength); |
danikula/AndroidVideoCache | test/src/test/java/com/danikula/videocache/file/FileCacheTest.java | // Path: test/src/test/java/com/danikula/videocache/BaseTest.java
// @RunWith(RobolectricTestRunner.class)
// @Config(constants = BuildConfig.class)
// public abstract class BaseTest {
//
// static {
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/Cache.java
// public interface Cache {
//
// long available() throws ProxyCacheException;
//
// int read(byte[] buffer, long offset, int length) throws ProxyCacheException;
//
// void append(byte[] data, int length) throws ProxyCacheException;
//
// void close() throws ProxyCacheException;
//
// void complete() throws ProxyCacheException;
//
// boolean isCompleted();
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheException.java
// public class ProxyCacheException extends Exception {
//
// private static final String LIBRARY_VERSION = ". Version: " + BuildConfig.VERSION_NAME;
//
// public ProxyCacheException(String message) {
// super(message + LIBRARY_VERSION);
// }
//
// public ProxyCacheException(String message, Throwable cause) {
// super(message + LIBRARY_VERSION, cause);
// }
//
// public ProxyCacheException(Throwable cause) {
// super("No explanation error" + LIBRARY_VERSION, cause);
// }
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static final String ASSETS_DATA_NAME = "android.jpg";
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] generate(int capacity) {
// Random random = new Random(System.currentTimeMillis());
// byte[] result = new byte[capacity];
// random.nextBytes(result);
// return result;
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] getFileContent(File file) throws IOException {
// return Files.asByteSource(file).read();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File getTempFile(File file) {
// return new File(file.getParentFile(), file.getName() + ".download");
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] loadAssetFile(String name) throws IOException {
// InputStream in = RuntimeEnvironment.application.getResources().getAssets().open(name);
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// IoUtils.copy(in, out);
// IoUtils.closeSilently(in);
// IoUtils.closeSilently(out);
// return out.toByteArray();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File newCacheFile() {
// return new File(RuntimeEnvironment.application.getCacheDir(), UUID.randomUUID().toString());
// }
| import com.danikula.android.garden.io.Files;
import com.danikula.videocache.BaseTest;
import com.danikula.videocache.Cache;
import com.danikula.videocache.ProxyCacheException;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import static com.danikula.videocache.support.ProxyCacheTestUtils.ASSETS_DATA_NAME;
import static com.danikula.videocache.support.ProxyCacheTestUtils.generate;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getFileContent;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getTempFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.loadAssetFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.newCacheFile;
import static com.google.common.io.Files.write;
import static org.fest.assertions.api.Assertions.assertThat; | package com.danikula.videocache.file;
/**
* @author Alexey Danilov ([email protected]).
*/
public class FileCacheTest extends BaseTest {
@Test
public void testWriteReadDiscCache() throws Exception {
int firstPortionLength = 10000;
byte[] firstDataPortion = generate(firstPortionLength); | // Path: test/src/test/java/com/danikula/videocache/BaseTest.java
// @RunWith(RobolectricTestRunner.class)
// @Config(constants = BuildConfig.class)
// public abstract class BaseTest {
//
// static {
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/Cache.java
// public interface Cache {
//
// long available() throws ProxyCacheException;
//
// int read(byte[] buffer, long offset, int length) throws ProxyCacheException;
//
// void append(byte[] data, int length) throws ProxyCacheException;
//
// void close() throws ProxyCacheException;
//
// void complete() throws ProxyCacheException;
//
// boolean isCompleted();
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheException.java
// public class ProxyCacheException extends Exception {
//
// private static final String LIBRARY_VERSION = ". Version: " + BuildConfig.VERSION_NAME;
//
// public ProxyCacheException(String message) {
// super(message + LIBRARY_VERSION);
// }
//
// public ProxyCacheException(String message, Throwable cause) {
// super(message + LIBRARY_VERSION, cause);
// }
//
// public ProxyCacheException(Throwable cause) {
// super("No explanation error" + LIBRARY_VERSION, cause);
// }
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static final String ASSETS_DATA_NAME = "android.jpg";
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] generate(int capacity) {
// Random random = new Random(System.currentTimeMillis());
// byte[] result = new byte[capacity];
// random.nextBytes(result);
// return result;
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] getFileContent(File file) throws IOException {
// return Files.asByteSource(file).read();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File getTempFile(File file) {
// return new File(file.getParentFile(), file.getName() + ".download");
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] loadAssetFile(String name) throws IOException {
// InputStream in = RuntimeEnvironment.application.getResources().getAssets().open(name);
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// IoUtils.copy(in, out);
// IoUtils.closeSilently(in);
// IoUtils.closeSilently(out);
// return out.toByteArray();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File newCacheFile() {
// return new File(RuntimeEnvironment.application.getCacheDir(), UUID.randomUUID().toString());
// }
// Path: test/src/test/java/com/danikula/videocache/file/FileCacheTest.java
import com.danikula.android.garden.io.Files;
import com.danikula.videocache.BaseTest;
import com.danikula.videocache.Cache;
import com.danikula.videocache.ProxyCacheException;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import static com.danikula.videocache.support.ProxyCacheTestUtils.ASSETS_DATA_NAME;
import static com.danikula.videocache.support.ProxyCacheTestUtils.generate;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getFileContent;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getTempFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.loadAssetFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.newCacheFile;
import static com.google.common.io.Files.write;
import static org.fest.assertions.api.Assertions.assertThat;
package com.danikula.videocache.file;
/**
* @author Alexey Danilov ([email protected]).
*/
public class FileCacheTest extends BaseTest {
@Test
public void testWriteReadDiscCache() throws Exception {
int firstPortionLength = 10000;
byte[] firstDataPortion = generate(firstPortionLength); | File file = newCacheFile(); |
danikula/AndroidVideoCache | test/src/test/java/com/danikula/videocache/file/FileCacheTest.java | // Path: test/src/test/java/com/danikula/videocache/BaseTest.java
// @RunWith(RobolectricTestRunner.class)
// @Config(constants = BuildConfig.class)
// public abstract class BaseTest {
//
// static {
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/Cache.java
// public interface Cache {
//
// long available() throws ProxyCacheException;
//
// int read(byte[] buffer, long offset, int length) throws ProxyCacheException;
//
// void append(byte[] data, int length) throws ProxyCacheException;
//
// void close() throws ProxyCacheException;
//
// void complete() throws ProxyCacheException;
//
// boolean isCompleted();
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheException.java
// public class ProxyCacheException extends Exception {
//
// private static final String LIBRARY_VERSION = ". Version: " + BuildConfig.VERSION_NAME;
//
// public ProxyCacheException(String message) {
// super(message + LIBRARY_VERSION);
// }
//
// public ProxyCacheException(String message, Throwable cause) {
// super(message + LIBRARY_VERSION, cause);
// }
//
// public ProxyCacheException(Throwable cause) {
// super("No explanation error" + LIBRARY_VERSION, cause);
// }
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static final String ASSETS_DATA_NAME = "android.jpg";
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] generate(int capacity) {
// Random random = new Random(System.currentTimeMillis());
// byte[] result = new byte[capacity];
// random.nextBytes(result);
// return result;
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] getFileContent(File file) throws IOException {
// return Files.asByteSource(file).read();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File getTempFile(File file) {
// return new File(file.getParentFile(), file.getName() + ".download");
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] loadAssetFile(String name) throws IOException {
// InputStream in = RuntimeEnvironment.application.getResources().getAssets().open(name);
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// IoUtils.copy(in, out);
// IoUtils.closeSilently(in);
// IoUtils.closeSilently(out);
// return out.toByteArray();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File newCacheFile() {
// return new File(RuntimeEnvironment.application.getCacheDir(), UUID.randomUUID().toString());
// }
| import com.danikula.android.garden.io.Files;
import com.danikula.videocache.BaseTest;
import com.danikula.videocache.Cache;
import com.danikula.videocache.ProxyCacheException;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import static com.danikula.videocache.support.ProxyCacheTestUtils.ASSETS_DATA_NAME;
import static com.danikula.videocache.support.ProxyCacheTestUtils.generate;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getFileContent;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getTempFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.loadAssetFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.newCacheFile;
import static com.google.common.io.Files.write;
import static org.fest.assertions.api.Assertions.assertThat; | package com.danikula.videocache.file;
/**
* @author Alexey Danilov ([email protected]).
*/
public class FileCacheTest extends BaseTest {
@Test
public void testWriteReadDiscCache() throws Exception {
int firstPortionLength = 10000;
byte[] firstDataPortion = generate(firstPortionLength);
File file = newCacheFile(); | // Path: test/src/test/java/com/danikula/videocache/BaseTest.java
// @RunWith(RobolectricTestRunner.class)
// @Config(constants = BuildConfig.class)
// public abstract class BaseTest {
//
// static {
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/Cache.java
// public interface Cache {
//
// long available() throws ProxyCacheException;
//
// int read(byte[] buffer, long offset, int length) throws ProxyCacheException;
//
// void append(byte[] data, int length) throws ProxyCacheException;
//
// void close() throws ProxyCacheException;
//
// void complete() throws ProxyCacheException;
//
// boolean isCompleted();
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheException.java
// public class ProxyCacheException extends Exception {
//
// private static final String LIBRARY_VERSION = ". Version: " + BuildConfig.VERSION_NAME;
//
// public ProxyCacheException(String message) {
// super(message + LIBRARY_VERSION);
// }
//
// public ProxyCacheException(String message, Throwable cause) {
// super(message + LIBRARY_VERSION, cause);
// }
//
// public ProxyCacheException(Throwable cause) {
// super("No explanation error" + LIBRARY_VERSION, cause);
// }
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static final String ASSETS_DATA_NAME = "android.jpg";
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] generate(int capacity) {
// Random random = new Random(System.currentTimeMillis());
// byte[] result = new byte[capacity];
// random.nextBytes(result);
// return result;
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] getFileContent(File file) throws IOException {
// return Files.asByteSource(file).read();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File getTempFile(File file) {
// return new File(file.getParentFile(), file.getName() + ".download");
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] loadAssetFile(String name) throws IOException {
// InputStream in = RuntimeEnvironment.application.getResources().getAssets().open(name);
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// IoUtils.copy(in, out);
// IoUtils.closeSilently(in);
// IoUtils.closeSilently(out);
// return out.toByteArray();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File newCacheFile() {
// return new File(RuntimeEnvironment.application.getCacheDir(), UUID.randomUUID().toString());
// }
// Path: test/src/test/java/com/danikula/videocache/file/FileCacheTest.java
import com.danikula.android.garden.io.Files;
import com.danikula.videocache.BaseTest;
import com.danikula.videocache.Cache;
import com.danikula.videocache.ProxyCacheException;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import static com.danikula.videocache.support.ProxyCacheTestUtils.ASSETS_DATA_NAME;
import static com.danikula.videocache.support.ProxyCacheTestUtils.generate;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getFileContent;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getTempFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.loadAssetFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.newCacheFile;
import static com.google.common.io.Files.write;
import static org.fest.assertions.api.Assertions.assertThat;
package com.danikula.videocache.file;
/**
* @author Alexey Danilov ([email protected]).
*/
public class FileCacheTest extends BaseTest {
@Test
public void testWriteReadDiscCache() throws Exception {
int firstPortionLength = 10000;
byte[] firstDataPortion = generate(firstPortionLength);
File file = newCacheFile(); | Cache fileCache = new FileCache(file); |
danikula/AndroidVideoCache | test/src/test/java/com/danikula/videocache/file/FileCacheTest.java | // Path: test/src/test/java/com/danikula/videocache/BaseTest.java
// @RunWith(RobolectricTestRunner.class)
// @Config(constants = BuildConfig.class)
// public abstract class BaseTest {
//
// static {
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/Cache.java
// public interface Cache {
//
// long available() throws ProxyCacheException;
//
// int read(byte[] buffer, long offset, int length) throws ProxyCacheException;
//
// void append(byte[] data, int length) throws ProxyCacheException;
//
// void close() throws ProxyCacheException;
//
// void complete() throws ProxyCacheException;
//
// boolean isCompleted();
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheException.java
// public class ProxyCacheException extends Exception {
//
// private static final String LIBRARY_VERSION = ". Version: " + BuildConfig.VERSION_NAME;
//
// public ProxyCacheException(String message) {
// super(message + LIBRARY_VERSION);
// }
//
// public ProxyCacheException(String message, Throwable cause) {
// super(message + LIBRARY_VERSION, cause);
// }
//
// public ProxyCacheException(Throwable cause) {
// super("No explanation error" + LIBRARY_VERSION, cause);
// }
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static final String ASSETS_DATA_NAME = "android.jpg";
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] generate(int capacity) {
// Random random = new Random(System.currentTimeMillis());
// byte[] result = new byte[capacity];
// random.nextBytes(result);
// return result;
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] getFileContent(File file) throws IOException {
// return Files.asByteSource(file).read();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File getTempFile(File file) {
// return new File(file.getParentFile(), file.getName() + ".download");
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] loadAssetFile(String name) throws IOException {
// InputStream in = RuntimeEnvironment.application.getResources().getAssets().open(name);
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// IoUtils.copy(in, out);
// IoUtils.closeSilently(in);
// IoUtils.closeSilently(out);
// return out.toByteArray();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File newCacheFile() {
// return new File(RuntimeEnvironment.application.getCacheDir(), UUID.randomUUID().toString());
// }
| import com.danikula.android.garden.io.Files;
import com.danikula.videocache.BaseTest;
import com.danikula.videocache.Cache;
import com.danikula.videocache.ProxyCacheException;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import static com.danikula.videocache.support.ProxyCacheTestUtils.ASSETS_DATA_NAME;
import static com.danikula.videocache.support.ProxyCacheTestUtils.generate;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getFileContent;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getTempFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.loadAssetFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.newCacheFile;
import static com.google.common.io.Files.write;
import static org.fest.assertions.api.Assertions.assertThat; | package com.danikula.videocache.file;
/**
* @author Alexey Danilov ([email protected]).
*/
public class FileCacheTest extends BaseTest {
@Test
public void testWriteReadDiscCache() throws Exception {
int firstPortionLength = 10000;
byte[] firstDataPortion = generate(firstPortionLength);
File file = newCacheFile();
Cache fileCache = new FileCache(file);
fileCache.append(firstDataPortion, firstDataPortion.length);
byte[] readData = new byte[firstPortionLength];
fileCache.read(readData, 0, firstPortionLength);
assertThat(readData).isEqualTo(firstDataPortion); | // Path: test/src/test/java/com/danikula/videocache/BaseTest.java
// @RunWith(RobolectricTestRunner.class)
// @Config(constants = BuildConfig.class)
// public abstract class BaseTest {
//
// static {
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/Cache.java
// public interface Cache {
//
// long available() throws ProxyCacheException;
//
// int read(byte[] buffer, long offset, int length) throws ProxyCacheException;
//
// void append(byte[] data, int length) throws ProxyCacheException;
//
// void close() throws ProxyCacheException;
//
// void complete() throws ProxyCacheException;
//
// boolean isCompleted();
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheException.java
// public class ProxyCacheException extends Exception {
//
// private static final String LIBRARY_VERSION = ". Version: " + BuildConfig.VERSION_NAME;
//
// public ProxyCacheException(String message) {
// super(message + LIBRARY_VERSION);
// }
//
// public ProxyCacheException(String message, Throwable cause) {
// super(message + LIBRARY_VERSION, cause);
// }
//
// public ProxyCacheException(Throwable cause) {
// super("No explanation error" + LIBRARY_VERSION, cause);
// }
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static final String ASSETS_DATA_NAME = "android.jpg";
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] generate(int capacity) {
// Random random = new Random(System.currentTimeMillis());
// byte[] result = new byte[capacity];
// random.nextBytes(result);
// return result;
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] getFileContent(File file) throws IOException {
// return Files.asByteSource(file).read();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File getTempFile(File file) {
// return new File(file.getParentFile(), file.getName() + ".download");
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] loadAssetFile(String name) throws IOException {
// InputStream in = RuntimeEnvironment.application.getResources().getAssets().open(name);
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// IoUtils.copy(in, out);
// IoUtils.closeSilently(in);
// IoUtils.closeSilently(out);
// return out.toByteArray();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File newCacheFile() {
// return new File(RuntimeEnvironment.application.getCacheDir(), UUID.randomUUID().toString());
// }
// Path: test/src/test/java/com/danikula/videocache/file/FileCacheTest.java
import com.danikula.android.garden.io.Files;
import com.danikula.videocache.BaseTest;
import com.danikula.videocache.Cache;
import com.danikula.videocache.ProxyCacheException;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import static com.danikula.videocache.support.ProxyCacheTestUtils.ASSETS_DATA_NAME;
import static com.danikula.videocache.support.ProxyCacheTestUtils.generate;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getFileContent;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getTempFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.loadAssetFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.newCacheFile;
import static com.google.common.io.Files.write;
import static org.fest.assertions.api.Assertions.assertThat;
package com.danikula.videocache.file;
/**
* @author Alexey Danilov ([email protected]).
*/
public class FileCacheTest extends BaseTest {
@Test
public void testWriteReadDiscCache() throws Exception {
int firstPortionLength = 10000;
byte[] firstDataPortion = generate(firstPortionLength);
File file = newCacheFile();
Cache fileCache = new FileCache(file);
fileCache.append(firstDataPortion, firstDataPortion.length);
byte[] readData = new byte[firstPortionLength];
fileCache.read(readData, 0, firstPortionLength);
assertThat(readData).isEqualTo(firstDataPortion); | byte[] fileContent = getFileContent(getTempFile(file)); |
danikula/AndroidVideoCache | test/src/test/java/com/danikula/videocache/file/FileCacheTest.java | // Path: test/src/test/java/com/danikula/videocache/BaseTest.java
// @RunWith(RobolectricTestRunner.class)
// @Config(constants = BuildConfig.class)
// public abstract class BaseTest {
//
// static {
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/Cache.java
// public interface Cache {
//
// long available() throws ProxyCacheException;
//
// int read(byte[] buffer, long offset, int length) throws ProxyCacheException;
//
// void append(byte[] data, int length) throws ProxyCacheException;
//
// void close() throws ProxyCacheException;
//
// void complete() throws ProxyCacheException;
//
// boolean isCompleted();
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheException.java
// public class ProxyCacheException extends Exception {
//
// private static final String LIBRARY_VERSION = ". Version: " + BuildConfig.VERSION_NAME;
//
// public ProxyCacheException(String message) {
// super(message + LIBRARY_VERSION);
// }
//
// public ProxyCacheException(String message, Throwable cause) {
// super(message + LIBRARY_VERSION, cause);
// }
//
// public ProxyCacheException(Throwable cause) {
// super("No explanation error" + LIBRARY_VERSION, cause);
// }
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static final String ASSETS_DATA_NAME = "android.jpg";
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] generate(int capacity) {
// Random random = new Random(System.currentTimeMillis());
// byte[] result = new byte[capacity];
// random.nextBytes(result);
// return result;
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] getFileContent(File file) throws IOException {
// return Files.asByteSource(file).read();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File getTempFile(File file) {
// return new File(file.getParentFile(), file.getName() + ".download");
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] loadAssetFile(String name) throws IOException {
// InputStream in = RuntimeEnvironment.application.getResources().getAssets().open(name);
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// IoUtils.copy(in, out);
// IoUtils.closeSilently(in);
// IoUtils.closeSilently(out);
// return out.toByteArray();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File newCacheFile() {
// return new File(RuntimeEnvironment.application.getCacheDir(), UUID.randomUUID().toString());
// }
| import com.danikula.android.garden.io.Files;
import com.danikula.videocache.BaseTest;
import com.danikula.videocache.Cache;
import com.danikula.videocache.ProxyCacheException;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import static com.danikula.videocache.support.ProxyCacheTestUtils.ASSETS_DATA_NAME;
import static com.danikula.videocache.support.ProxyCacheTestUtils.generate;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getFileContent;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getTempFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.loadAssetFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.newCacheFile;
import static com.google.common.io.Files.write;
import static org.fest.assertions.api.Assertions.assertThat; | package com.danikula.videocache.file;
/**
* @author Alexey Danilov ([email protected]).
*/
public class FileCacheTest extends BaseTest {
@Test
public void testWriteReadDiscCache() throws Exception {
int firstPortionLength = 10000;
byte[] firstDataPortion = generate(firstPortionLength);
File file = newCacheFile();
Cache fileCache = new FileCache(file);
fileCache.append(firstDataPortion, firstDataPortion.length);
byte[] readData = new byte[firstPortionLength];
fileCache.read(readData, 0, firstPortionLength);
assertThat(readData).isEqualTo(firstDataPortion); | // Path: test/src/test/java/com/danikula/videocache/BaseTest.java
// @RunWith(RobolectricTestRunner.class)
// @Config(constants = BuildConfig.class)
// public abstract class BaseTest {
//
// static {
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/Cache.java
// public interface Cache {
//
// long available() throws ProxyCacheException;
//
// int read(byte[] buffer, long offset, int length) throws ProxyCacheException;
//
// void append(byte[] data, int length) throws ProxyCacheException;
//
// void close() throws ProxyCacheException;
//
// void complete() throws ProxyCacheException;
//
// boolean isCompleted();
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheException.java
// public class ProxyCacheException extends Exception {
//
// private static final String LIBRARY_VERSION = ". Version: " + BuildConfig.VERSION_NAME;
//
// public ProxyCacheException(String message) {
// super(message + LIBRARY_VERSION);
// }
//
// public ProxyCacheException(String message, Throwable cause) {
// super(message + LIBRARY_VERSION, cause);
// }
//
// public ProxyCacheException(Throwable cause) {
// super("No explanation error" + LIBRARY_VERSION, cause);
// }
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static final String ASSETS_DATA_NAME = "android.jpg";
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] generate(int capacity) {
// Random random = new Random(System.currentTimeMillis());
// byte[] result = new byte[capacity];
// random.nextBytes(result);
// return result;
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] getFileContent(File file) throws IOException {
// return Files.asByteSource(file).read();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File getTempFile(File file) {
// return new File(file.getParentFile(), file.getName() + ".download");
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] loadAssetFile(String name) throws IOException {
// InputStream in = RuntimeEnvironment.application.getResources().getAssets().open(name);
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// IoUtils.copy(in, out);
// IoUtils.closeSilently(in);
// IoUtils.closeSilently(out);
// return out.toByteArray();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File newCacheFile() {
// return new File(RuntimeEnvironment.application.getCacheDir(), UUID.randomUUID().toString());
// }
// Path: test/src/test/java/com/danikula/videocache/file/FileCacheTest.java
import com.danikula.android.garden.io.Files;
import com.danikula.videocache.BaseTest;
import com.danikula.videocache.Cache;
import com.danikula.videocache.ProxyCacheException;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import static com.danikula.videocache.support.ProxyCacheTestUtils.ASSETS_DATA_NAME;
import static com.danikula.videocache.support.ProxyCacheTestUtils.generate;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getFileContent;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getTempFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.loadAssetFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.newCacheFile;
import static com.google.common.io.Files.write;
import static org.fest.assertions.api.Assertions.assertThat;
package com.danikula.videocache.file;
/**
* @author Alexey Danilov ([email protected]).
*/
public class FileCacheTest extends BaseTest {
@Test
public void testWriteReadDiscCache() throws Exception {
int firstPortionLength = 10000;
byte[] firstDataPortion = generate(firstPortionLength);
File file = newCacheFile();
Cache fileCache = new FileCache(file);
fileCache.append(firstDataPortion, firstDataPortion.length);
byte[] readData = new byte[firstPortionLength];
fileCache.read(readData, 0, firstPortionLength);
assertThat(readData).isEqualTo(firstDataPortion); | byte[] fileContent = getFileContent(getTempFile(file)); |
danikula/AndroidVideoCache | test/src/test/java/com/danikula/videocache/file/FileCacheTest.java | // Path: test/src/test/java/com/danikula/videocache/BaseTest.java
// @RunWith(RobolectricTestRunner.class)
// @Config(constants = BuildConfig.class)
// public abstract class BaseTest {
//
// static {
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/Cache.java
// public interface Cache {
//
// long available() throws ProxyCacheException;
//
// int read(byte[] buffer, long offset, int length) throws ProxyCacheException;
//
// void append(byte[] data, int length) throws ProxyCacheException;
//
// void close() throws ProxyCacheException;
//
// void complete() throws ProxyCacheException;
//
// boolean isCompleted();
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheException.java
// public class ProxyCacheException extends Exception {
//
// private static final String LIBRARY_VERSION = ". Version: " + BuildConfig.VERSION_NAME;
//
// public ProxyCacheException(String message) {
// super(message + LIBRARY_VERSION);
// }
//
// public ProxyCacheException(String message, Throwable cause) {
// super(message + LIBRARY_VERSION, cause);
// }
//
// public ProxyCacheException(Throwable cause) {
// super("No explanation error" + LIBRARY_VERSION, cause);
// }
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static final String ASSETS_DATA_NAME = "android.jpg";
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] generate(int capacity) {
// Random random = new Random(System.currentTimeMillis());
// byte[] result = new byte[capacity];
// random.nextBytes(result);
// return result;
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] getFileContent(File file) throws IOException {
// return Files.asByteSource(file).read();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File getTempFile(File file) {
// return new File(file.getParentFile(), file.getName() + ".download");
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] loadAssetFile(String name) throws IOException {
// InputStream in = RuntimeEnvironment.application.getResources().getAssets().open(name);
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// IoUtils.copy(in, out);
// IoUtils.closeSilently(in);
// IoUtils.closeSilently(out);
// return out.toByteArray();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File newCacheFile() {
// return new File(RuntimeEnvironment.application.getCacheDir(), UUID.randomUUID().toString());
// }
| import com.danikula.android.garden.io.Files;
import com.danikula.videocache.BaseTest;
import com.danikula.videocache.Cache;
import com.danikula.videocache.ProxyCacheException;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import static com.danikula.videocache.support.ProxyCacheTestUtils.ASSETS_DATA_NAME;
import static com.danikula.videocache.support.ProxyCacheTestUtils.generate;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getFileContent;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getTempFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.loadAssetFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.newCacheFile;
import static com.google.common.io.Files.write;
import static org.fest.assertions.api.Assertions.assertThat; | package com.danikula.videocache.file;
/**
* @author Alexey Danilov ([email protected]).
*/
public class FileCacheTest extends BaseTest {
@Test
public void testWriteReadDiscCache() throws Exception {
int firstPortionLength = 10000;
byte[] firstDataPortion = generate(firstPortionLength);
File file = newCacheFile();
Cache fileCache = new FileCache(file);
fileCache.append(firstDataPortion, firstDataPortion.length);
byte[] readData = new byte[firstPortionLength];
fileCache.read(readData, 0, firstPortionLength);
assertThat(readData).isEqualTo(firstDataPortion);
byte[] fileContent = getFileContent(getTempFile(file));
assertThat(readData).isEqualTo(fileContent);
}
@Test
public void testFileCacheCompletion() throws Exception {
File file = newCacheFile();
File tempFile = getTempFile(file);
Cache fileCache = new FileCache(file);
assertThat(file.exists()).isFalse();
assertThat(tempFile.exists()).isTrue();
int dataSize = 345;
fileCache.append(generate(dataSize), dataSize);
fileCache.complete();
assertThat(file.exists()).isTrue();
assertThat(tempFile.exists()).isFalse();
assertThat(file.length()).isEqualTo(dataSize);
}
| // Path: test/src/test/java/com/danikula/videocache/BaseTest.java
// @RunWith(RobolectricTestRunner.class)
// @Config(constants = BuildConfig.class)
// public abstract class BaseTest {
//
// static {
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/Cache.java
// public interface Cache {
//
// long available() throws ProxyCacheException;
//
// int read(byte[] buffer, long offset, int length) throws ProxyCacheException;
//
// void append(byte[] data, int length) throws ProxyCacheException;
//
// void close() throws ProxyCacheException;
//
// void complete() throws ProxyCacheException;
//
// boolean isCompleted();
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheException.java
// public class ProxyCacheException extends Exception {
//
// private static final String LIBRARY_VERSION = ". Version: " + BuildConfig.VERSION_NAME;
//
// public ProxyCacheException(String message) {
// super(message + LIBRARY_VERSION);
// }
//
// public ProxyCacheException(String message, Throwable cause) {
// super(message + LIBRARY_VERSION, cause);
// }
//
// public ProxyCacheException(Throwable cause) {
// super("No explanation error" + LIBRARY_VERSION, cause);
// }
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static final String ASSETS_DATA_NAME = "android.jpg";
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] generate(int capacity) {
// Random random = new Random(System.currentTimeMillis());
// byte[] result = new byte[capacity];
// random.nextBytes(result);
// return result;
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] getFileContent(File file) throws IOException {
// return Files.asByteSource(file).read();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File getTempFile(File file) {
// return new File(file.getParentFile(), file.getName() + ".download");
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] loadAssetFile(String name) throws IOException {
// InputStream in = RuntimeEnvironment.application.getResources().getAssets().open(name);
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// IoUtils.copy(in, out);
// IoUtils.closeSilently(in);
// IoUtils.closeSilently(out);
// return out.toByteArray();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File newCacheFile() {
// return new File(RuntimeEnvironment.application.getCacheDir(), UUID.randomUUID().toString());
// }
// Path: test/src/test/java/com/danikula/videocache/file/FileCacheTest.java
import com.danikula.android.garden.io.Files;
import com.danikula.videocache.BaseTest;
import com.danikula.videocache.Cache;
import com.danikula.videocache.ProxyCacheException;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import static com.danikula.videocache.support.ProxyCacheTestUtils.ASSETS_DATA_NAME;
import static com.danikula.videocache.support.ProxyCacheTestUtils.generate;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getFileContent;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getTempFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.loadAssetFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.newCacheFile;
import static com.google.common.io.Files.write;
import static org.fest.assertions.api.Assertions.assertThat;
package com.danikula.videocache.file;
/**
* @author Alexey Danilov ([email protected]).
*/
public class FileCacheTest extends BaseTest {
@Test
public void testWriteReadDiscCache() throws Exception {
int firstPortionLength = 10000;
byte[] firstDataPortion = generate(firstPortionLength);
File file = newCacheFile();
Cache fileCache = new FileCache(file);
fileCache.append(firstDataPortion, firstDataPortion.length);
byte[] readData = new byte[firstPortionLength];
fileCache.read(readData, 0, firstPortionLength);
assertThat(readData).isEqualTo(firstDataPortion);
byte[] fileContent = getFileContent(getTempFile(file));
assertThat(readData).isEqualTo(fileContent);
}
@Test
public void testFileCacheCompletion() throws Exception {
File file = newCacheFile();
File tempFile = getTempFile(file);
Cache fileCache = new FileCache(file);
assertThat(file.exists()).isFalse();
assertThat(tempFile.exists()).isTrue();
int dataSize = 345;
fileCache.append(generate(dataSize), dataSize);
fileCache.complete();
assertThat(file.exists()).isTrue();
assertThat(tempFile.exists()).isFalse();
assertThat(file.length()).isEqualTo(dataSize);
}
| @Test(expected = ProxyCacheException.class) |
danikula/AndroidVideoCache | test/src/test/java/com/danikula/videocache/file/FileCacheTest.java | // Path: test/src/test/java/com/danikula/videocache/BaseTest.java
// @RunWith(RobolectricTestRunner.class)
// @Config(constants = BuildConfig.class)
// public abstract class BaseTest {
//
// static {
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/Cache.java
// public interface Cache {
//
// long available() throws ProxyCacheException;
//
// int read(byte[] buffer, long offset, int length) throws ProxyCacheException;
//
// void append(byte[] data, int length) throws ProxyCacheException;
//
// void close() throws ProxyCacheException;
//
// void complete() throws ProxyCacheException;
//
// boolean isCompleted();
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheException.java
// public class ProxyCacheException extends Exception {
//
// private static final String LIBRARY_VERSION = ". Version: " + BuildConfig.VERSION_NAME;
//
// public ProxyCacheException(String message) {
// super(message + LIBRARY_VERSION);
// }
//
// public ProxyCacheException(String message, Throwable cause) {
// super(message + LIBRARY_VERSION, cause);
// }
//
// public ProxyCacheException(Throwable cause) {
// super("No explanation error" + LIBRARY_VERSION, cause);
// }
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static final String ASSETS_DATA_NAME = "android.jpg";
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] generate(int capacity) {
// Random random = new Random(System.currentTimeMillis());
// byte[] result = new byte[capacity];
// random.nextBytes(result);
// return result;
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] getFileContent(File file) throws IOException {
// return Files.asByteSource(file).read();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File getTempFile(File file) {
// return new File(file.getParentFile(), file.getName() + ".download");
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] loadAssetFile(String name) throws IOException {
// InputStream in = RuntimeEnvironment.application.getResources().getAssets().open(name);
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// IoUtils.copy(in, out);
// IoUtils.closeSilently(in);
// IoUtils.closeSilently(out);
// return out.toByteArray();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File newCacheFile() {
// return new File(RuntimeEnvironment.application.getCacheDir(), UUID.randomUUID().toString());
// }
| import com.danikula.android.garden.io.Files;
import com.danikula.videocache.BaseTest;
import com.danikula.videocache.Cache;
import com.danikula.videocache.ProxyCacheException;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import static com.danikula.videocache.support.ProxyCacheTestUtils.ASSETS_DATA_NAME;
import static com.danikula.videocache.support.ProxyCacheTestUtils.generate;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getFileContent;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getTempFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.loadAssetFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.newCacheFile;
import static com.google.common.io.Files.write;
import static org.fest.assertions.api.Assertions.assertThat; | }
@Test
public void testAppendDiscCache() throws Exception {
File file = newCacheFile();
Cache fileCache = new FileCache(file);
int firstPortionLength = 10000;
byte[] firstDataPortion = generate(firstPortionLength);
fileCache.append(firstDataPortion, firstDataPortion.length);
int secondPortionLength = 30000;
byte[] secondDataPortion = generate(secondPortionLength * 2);
fileCache.append(secondDataPortion, secondPortionLength);
byte[] wroteSecondPortion = Arrays.copyOfRange(secondDataPortion, 0, secondPortionLength);
byte[] readData = new byte[secondPortionLength];
fileCache.read(readData, firstPortionLength, secondPortionLength);
assertThat(readData).isEqualTo(wroteSecondPortion);
readData = new byte[(int)fileCache.available()];
fileCache.read(readData, 0, readData.length);
byte[] fileContent = getFileContent(getTempFile(file));
assertThat(readData).isEqualTo(fileContent);
}
@Test
public void testIsFileCacheCompleted() throws Exception {
File file = newCacheFile();
File partialFile = new File(file.getParentFile(), file.getName() + ".download"); | // Path: test/src/test/java/com/danikula/videocache/BaseTest.java
// @RunWith(RobolectricTestRunner.class)
// @Config(constants = BuildConfig.class)
// public abstract class BaseTest {
//
// static {
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/Cache.java
// public interface Cache {
//
// long available() throws ProxyCacheException;
//
// int read(byte[] buffer, long offset, int length) throws ProxyCacheException;
//
// void append(byte[] data, int length) throws ProxyCacheException;
//
// void close() throws ProxyCacheException;
//
// void complete() throws ProxyCacheException;
//
// boolean isCompleted();
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheException.java
// public class ProxyCacheException extends Exception {
//
// private static final String LIBRARY_VERSION = ". Version: " + BuildConfig.VERSION_NAME;
//
// public ProxyCacheException(String message) {
// super(message + LIBRARY_VERSION);
// }
//
// public ProxyCacheException(String message, Throwable cause) {
// super(message + LIBRARY_VERSION, cause);
// }
//
// public ProxyCacheException(Throwable cause) {
// super("No explanation error" + LIBRARY_VERSION, cause);
// }
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static final String ASSETS_DATA_NAME = "android.jpg";
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] generate(int capacity) {
// Random random = new Random(System.currentTimeMillis());
// byte[] result = new byte[capacity];
// random.nextBytes(result);
// return result;
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] getFileContent(File file) throws IOException {
// return Files.asByteSource(file).read();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File getTempFile(File file) {
// return new File(file.getParentFile(), file.getName() + ".download");
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] loadAssetFile(String name) throws IOException {
// InputStream in = RuntimeEnvironment.application.getResources().getAssets().open(name);
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// IoUtils.copy(in, out);
// IoUtils.closeSilently(in);
// IoUtils.closeSilently(out);
// return out.toByteArray();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File newCacheFile() {
// return new File(RuntimeEnvironment.application.getCacheDir(), UUID.randomUUID().toString());
// }
// Path: test/src/test/java/com/danikula/videocache/file/FileCacheTest.java
import com.danikula.android.garden.io.Files;
import com.danikula.videocache.BaseTest;
import com.danikula.videocache.Cache;
import com.danikula.videocache.ProxyCacheException;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import static com.danikula.videocache.support.ProxyCacheTestUtils.ASSETS_DATA_NAME;
import static com.danikula.videocache.support.ProxyCacheTestUtils.generate;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getFileContent;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getTempFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.loadAssetFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.newCacheFile;
import static com.google.common.io.Files.write;
import static org.fest.assertions.api.Assertions.assertThat;
}
@Test
public void testAppendDiscCache() throws Exception {
File file = newCacheFile();
Cache fileCache = new FileCache(file);
int firstPortionLength = 10000;
byte[] firstDataPortion = generate(firstPortionLength);
fileCache.append(firstDataPortion, firstDataPortion.length);
int secondPortionLength = 30000;
byte[] secondDataPortion = generate(secondPortionLength * 2);
fileCache.append(secondDataPortion, secondPortionLength);
byte[] wroteSecondPortion = Arrays.copyOfRange(secondDataPortion, 0, secondPortionLength);
byte[] readData = new byte[secondPortionLength];
fileCache.read(readData, firstPortionLength, secondPortionLength);
assertThat(readData).isEqualTo(wroteSecondPortion);
readData = new byte[(int)fileCache.available()];
fileCache.read(readData, 0, readData.length);
byte[] fileContent = getFileContent(getTempFile(file));
assertThat(readData).isEqualTo(fileContent);
}
@Test
public void testIsFileCacheCompleted() throws Exception {
File file = newCacheFile();
File partialFile = new File(file.getParentFile(), file.getName() + ".download"); | write(loadAssetFile(ASSETS_DATA_NAME), partialFile); |
danikula/AndroidVideoCache | test/src/test/java/com/danikula/videocache/file/FileCacheTest.java | // Path: test/src/test/java/com/danikula/videocache/BaseTest.java
// @RunWith(RobolectricTestRunner.class)
// @Config(constants = BuildConfig.class)
// public abstract class BaseTest {
//
// static {
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/Cache.java
// public interface Cache {
//
// long available() throws ProxyCacheException;
//
// int read(byte[] buffer, long offset, int length) throws ProxyCacheException;
//
// void append(byte[] data, int length) throws ProxyCacheException;
//
// void close() throws ProxyCacheException;
//
// void complete() throws ProxyCacheException;
//
// boolean isCompleted();
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheException.java
// public class ProxyCacheException extends Exception {
//
// private static final String LIBRARY_VERSION = ". Version: " + BuildConfig.VERSION_NAME;
//
// public ProxyCacheException(String message) {
// super(message + LIBRARY_VERSION);
// }
//
// public ProxyCacheException(String message, Throwable cause) {
// super(message + LIBRARY_VERSION, cause);
// }
//
// public ProxyCacheException(Throwable cause) {
// super("No explanation error" + LIBRARY_VERSION, cause);
// }
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static final String ASSETS_DATA_NAME = "android.jpg";
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] generate(int capacity) {
// Random random = new Random(System.currentTimeMillis());
// byte[] result = new byte[capacity];
// random.nextBytes(result);
// return result;
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] getFileContent(File file) throws IOException {
// return Files.asByteSource(file).read();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File getTempFile(File file) {
// return new File(file.getParentFile(), file.getName() + ".download");
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] loadAssetFile(String name) throws IOException {
// InputStream in = RuntimeEnvironment.application.getResources().getAssets().open(name);
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// IoUtils.copy(in, out);
// IoUtils.closeSilently(in);
// IoUtils.closeSilently(out);
// return out.toByteArray();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File newCacheFile() {
// return new File(RuntimeEnvironment.application.getCacheDir(), UUID.randomUUID().toString());
// }
| import com.danikula.android.garden.io.Files;
import com.danikula.videocache.BaseTest;
import com.danikula.videocache.Cache;
import com.danikula.videocache.ProxyCacheException;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import static com.danikula.videocache.support.ProxyCacheTestUtils.ASSETS_DATA_NAME;
import static com.danikula.videocache.support.ProxyCacheTestUtils.generate;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getFileContent;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getTempFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.loadAssetFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.newCacheFile;
import static com.google.common.io.Files.write;
import static org.fest.assertions.api.Assertions.assertThat; | }
@Test
public void testAppendDiscCache() throws Exception {
File file = newCacheFile();
Cache fileCache = new FileCache(file);
int firstPortionLength = 10000;
byte[] firstDataPortion = generate(firstPortionLength);
fileCache.append(firstDataPortion, firstDataPortion.length);
int secondPortionLength = 30000;
byte[] secondDataPortion = generate(secondPortionLength * 2);
fileCache.append(secondDataPortion, secondPortionLength);
byte[] wroteSecondPortion = Arrays.copyOfRange(secondDataPortion, 0, secondPortionLength);
byte[] readData = new byte[secondPortionLength];
fileCache.read(readData, firstPortionLength, secondPortionLength);
assertThat(readData).isEqualTo(wroteSecondPortion);
readData = new byte[(int)fileCache.available()];
fileCache.read(readData, 0, readData.length);
byte[] fileContent = getFileContent(getTempFile(file));
assertThat(readData).isEqualTo(fileContent);
}
@Test
public void testIsFileCacheCompleted() throws Exception {
File file = newCacheFile();
File partialFile = new File(file.getParentFile(), file.getName() + ".download"); | // Path: test/src/test/java/com/danikula/videocache/BaseTest.java
// @RunWith(RobolectricTestRunner.class)
// @Config(constants = BuildConfig.class)
// public abstract class BaseTest {
//
// static {
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// }
//
// }
//
// Path: library/src/main/java/com/danikula/videocache/Cache.java
// public interface Cache {
//
// long available() throws ProxyCacheException;
//
// int read(byte[] buffer, long offset, int length) throws ProxyCacheException;
//
// void append(byte[] data, int length) throws ProxyCacheException;
//
// void close() throws ProxyCacheException;
//
// void complete() throws ProxyCacheException;
//
// boolean isCompleted();
// }
//
// Path: library/src/main/java/com/danikula/videocache/ProxyCacheException.java
// public class ProxyCacheException extends Exception {
//
// private static final String LIBRARY_VERSION = ". Version: " + BuildConfig.VERSION_NAME;
//
// public ProxyCacheException(String message) {
// super(message + LIBRARY_VERSION);
// }
//
// public ProxyCacheException(String message, Throwable cause) {
// super(message + LIBRARY_VERSION, cause);
// }
//
// public ProxyCacheException(Throwable cause) {
// super("No explanation error" + LIBRARY_VERSION, cause);
// }
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static final String ASSETS_DATA_NAME = "android.jpg";
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] generate(int capacity) {
// Random random = new Random(System.currentTimeMillis());
// byte[] result = new byte[capacity];
// random.nextBytes(result);
// return result;
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] getFileContent(File file) throws IOException {
// return Files.asByteSource(file).read();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File getTempFile(File file) {
// return new File(file.getParentFile(), file.getName() + ".download");
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static byte[] loadAssetFile(String name) throws IOException {
// InputStream in = RuntimeEnvironment.application.getResources().getAssets().open(name);
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// IoUtils.copy(in, out);
// IoUtils.closeSilently(in);
// IoUtils.closeSilently(out);
// return out.toByteArray();
// }
//
// Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static File newCacheFile() {
// return new File(RuntimeEnvironment.application.getCacheDir(), UUID.randomUUID().toString());
// }
// Path: test/src/test/java/com/danikula/videocache/file/FileCacheTest.java
import com.danikula.android.garden.io.Files;
import com.danikula.videocache.BaseTest;
import com.danikula.videocache.Cache;
import com.danikula.videocache.ProxyCacheException;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import static com.danikula.videocache.support.ProxyCacheTestUtils.ASSETS_DATA_NAME;
import static com.danikula.videocache.support.ProxyCacheTestUtils.generate;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getFileContent;
import static com.danikula.videocache.support.ProxyCacheTestUtils.getTempFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.loadAssetFile;
import static com.danikula.videocache.support.ProxyCacheTestUtils.newCacheFile;
import static com.google.common.io.Files.write;
import static org.fest.assertions.api.Assertions.assertThat;
}
@Test
public void testAppendDiscCache() throws Exception {
File file = newCacheFile();
Cache fileCache = new FileCache(file);
int firstPortionLength = 10000;
byte[] firstDataPortion = generate(firstPortionLength);
fileCache.append(firstDataPortion, firstDataPortion.length);
int secondPortionLength = 30000;
byte[] secondDataPortion = generate(secondPortionLength * 2);
fileCache.append(secondDataPortion, secondPortionLength);
byte[] wroteSecondPortion = Arrays.copyOfRange(secondDataPortion, 0, secondPortionLength);
byte[] readData = new byte[secondPortionLength];
fileCache.read(readData, firstPortionLength, secondPortionLength);
assertThat(readData).isEqualTo(wroteSecondPortion);
readData = new byte[(int)fileCache.available()];
fileCache.read(readData, 0, readData.length);
byte[] fileContent = getFileContent(getTempFile(file));
assertThat(readData).isEqualTo(fileContent);
}
@Test
public void testIsFileCacheCompleted() throws Exception {
File file = newCacheFile();
File partialFile = new File(file.getParentFile(), file.getName() + ".download"); | write(loadAssetFile(ASSETS_DATA_NAME), partialFile); |
danikula/AndroidVideoCache | test/src/test/java/com/danikula/videocache/ProxySelectorTest.java | // Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static void resetSystemProxy() {
// ProxySelector mockedProxySelector = Mockito.mock(ProxySelector.class);
// when(mockedProxySelector.select(Mockito.<URI>any())).thenReturn(Lists.newArrayList(Proxy.NO_PROXY));
// ProxySelector.setDefault(mockedProxySelector);
// }
| import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URI;
import java.util.List;
import static com.danikula.videocache.support.ProxyCacheTestUtils.resetSystemProxy;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Mockito.when; | package com.danikula.videocache;
/**
* Tests {@link IgnoreHostProxySelector}.
*
* @author Alexey Danilov ([email protected]).
*/
public class ProxySelectorTest extends BaseTest {
@Before
public void setup() throws Exception { | // Path: test/src/test/java/com/danikula/videocache/support/ProxyCacheTestUtils.java
// public static void resetSystemProxy() {
// ProxySelector mockedProxySelector = Mockito.mock(ProxySelector.class);
// when(mockedProxySelector.select(Mockito.<URI>any())).thenReturn(Lists.newArrayList(Proxy.NO_PROXY));
// ProxySelector.setDefault(mockedProxySelector);
// }
// Path: test/src/test/java/com/danikula/videocache/ProxySelectorTest.java
import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URI;
import java.util.List;
import static com.danikula.videocache.support.ProxyCacheTestUtils.resetSystemProxy;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
package com.danikula.videocache;
/**
* Tests {@link IgnoreHostProxySelector}.
*
* @author Alexey Danilov ([email protected]).
*/
public class ProxySelectorTest extends BaseTest {
@Before
public void setup() throws Exception { | resetSystemProxy(); |
gdfm/sssj | src/test/java/sssj/io/ParserFactoryTest.java | // Path: src/main/java/sssj/io/Format.java
// public enum Format {
// SSSJ {
// @Override
// public Function<String, Vector> getRecordParser() {
// return new Function<String, Vector>() {
// public Vector apply(String input) {
// String[] tokens = input.split("\\s");
// long ts = Long.parseLong(tokens[0]);
// Vector result = new Vector(ts);
// for (int i = 1; i < tokens.length; i++) {
// String[] parts = tokens[i].split(":");
// int key = Integer.parseInt(parts[0]);
// double val = Double.parseDouble(parts[1]);
// result.put(key, val);
// }
// return result;
// }
// };
// }
// },
//
// SVMLIB {
// @Override
// public Function<String, Vector> getRecordParser() {
// return new Function<String, Vector>() {
// public Vector apply(String input) {
// String[] tokens = input.split("\\s");
// // ignore class label tokens[0]
// Vector result = new Vector();
// for (int i = 1; i < tokens.length; i++) {
// String[] parts = tokens[i].split(":");
// int key = Integer.parseInt(parts[0]);
// double val = Double.parseDouble(parts[1]);
// result.put(key, val);
// }
// return result;
// }
// };
// }
// },
//
// VW {
// @Override
// public Function<String, Vector> getRecordParser() {
// return new Function<String, Vector>() {
// public Vector apply(String input) {
// String[] tokens = input.split("\\s");
// // ignore class label tokens[0] and namespace tokens[1]
// Vector result = new Vector();
// for (int i = 2; i < tokens.length; i++) {
// String[] parts = tokens[i].split(":");
// int key = Integer.parseInt(parts[0]);
// double val = Double.parseDouble(parts[1]);
// result.put(key, val);
// }
// return result;
// }
// };
// }
// },
//
// BINARY {
// @Override
// public Function<String, Vector> getRecordParser() {
// throw new UnsupportedOperationException("Binary format does not need a parser");
// }
// };
//
// abstract public Function<String, Vector> getRecordParser();
// }
| import static org.junit.Assert.assertEquals;
import org.junit.Test;
import sssj.io.Format; | package sssj.io;
public class ParserFactoryTest {
private static final String vw_example = "-1 3018:0.30226897258187 4028:0.21384332469612 8145:0.162488218352206 8617:0.143218756157527 8656:0.269024762292572 11646:0.25355901006852 13549:0.127390094515473 14143:0.142682425043427 15430:0.142445657672089 18150:0.0866057074792051 19585:0.114039541131034 21010:0.245524202230314 24428:0.20251364605078 27170:0.230395320302119 27307:0.112952537620285 29568:0.539073784182882 33035:0.146617340760801 35684:0.135815231166287 37664:0.0856990106295996 39724:0.108603031289468 42362:0.0762167284131916 42841:0.0876971237607474 43330:0.172808060913155 44957:0.155120603794981 46694:0.133042224445797";
@Test
public void testVW() { | // Path: src/main/java/sssj/io/Format.java
// public enum Format {
// SSSJ {
// @Override
// public Function<String, Vector> getRecordParser() {
// return new Function<String, Vector>() {
// public Vector apply(String input) {
// String[] tokens = input.split("\\s");
// long ts = Long.parseLong(tokens[0]);
// Vector result = new Vector(ts);
// for (int i = 1; i < tokens.length; i++) {
// String[] parts = tokens[i].split(":");
// int key = Integer.parseInt(parts[0]);
// double val = Double.parseDouble(parts[1]);
// result.put(key, val);
// }
// return result;
// }
// };
// }
// },
//
// SVMLIB {
// @Override
// public Function<String, Vector> getRecordParser() {
// return new Function<String, Vector>() {
// public Vector apply(String input) {
// String[] tokens = input.split("\\s");
// // ignore class label tokens[0]
// Vector result = new Vector();
// for (int i = 1; i < tokens.length; i++) {
// String[] parts = tokens[i].split(":");
// int key = Integer.parseInt(parts[0]);
// double val = Double.parseDouble(parts[1]);
// result.put(key, val);
// }
// return result;
// }
// };
// }
// },
//
// VW {
// @Override
// public Function<String, Vector> getRecordParser() {
// return new Function<String, Vector>() {
// public Vector apply(String input) {
// String[] tokens = input.split("\\s");
// // ignore class label tokens[0] and namespace tokens[1]
// Vector result = new Vector();
// for (int i = 2; i < tokens.length; i++) {
// String[] parts = tokens[i].split(":");
// int key = Integer.parseInt(parts[0]);
// double val = Double.parseDouble(parts[1]);
// result.put(key, val);
// }
// return result;
// }
// };
// }
// },
//
// BINARY {
// @Override
// public Function<String, Vector> getRecordParser() {
// throw new UnsupportedOperationException("Binary format does not need a parser");
// }
// };
//
// abstract public Function<String, Vector> getRecordParser();
// }
// Path: src/test/java/sssj/io/ParserFactoryTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import sssj.io.Format;
package sssj.io;
public class ParserFactoryTest {
private static final String vw_example = "-1 3018:0.30226897258187 4028:0.21384332469612 8145:0.162488218352206 8617:0.143218756157527 8656:0.269024762292572 11646:0.25355901006852 13549:0.127390094515473 14143:0.142682425043427 15430:0.142445657672089 18150:0.0866057074792051 19585:0.114039541131034 21010:0.245524202230314 24428:0.20251364605078 27170:0.230395320302119 27307:0.112952537620285 29568:0.539073784182882 33035:0.146617340760801 35684:0.135815231166287 37664:0.0856990106295996 39724:0.108603031289468 42362:0.0762167284131916 42841:0.0876971237607474 43330:0.172808060913155 44957:0.155120603794981 46694:0.133042224445797";
@Test
public void testVW() { | Format f = Format.SVMLIB; |
gdfm/sssj | src/main/java/sssj/index/minibatch/component/VectorWindow.java | // Path: src/main/java/sssj/io/Vector.java
// public class Vector { // entries are returned in the same order they are added
// public static final Vector EMPTY_VECTOR = new Vector(Long.MIN_VALUE);
// protected Int2DoubleLinkedOpenHashMap data = new Int2DoubleLinkedOpenHashMap();
// protected long timestamp;
// protected double maxValue;
// protected double sumValues;
//
// public Vector() {
// this(0);
// }
//
// public Vector(long timestamp) {
// this.timestamp = timestamp;
// this.maxValue = 0;
// this.sumValues = 0;
// }
//
// /**
// * Copy constructor. The values are deep copied.
// *
// * @param other the vector to copy
// */
// public Vector(Vector other) {
// this.timestamp = other.timestamp;
// this.maxValue = other.maxValue;
// this.sumValues = other.sumValues;
// data.putAll(other.data);
// }
//
// public double put(int k, double v) {
// this.maxValue = Math.max(maxValue, v);
// this.sumValues += v;
// return data.put(k, v);
// }
//
// public double get(int k) {
// return data.get(k);
// }
//
// public FastSortedEntrySet int2DoubleEntrySet() {
// return data.int2DoubleEntrySet();
// }
//
// public int size() {
// return data.size();
// }
//
// public double maxValue() {
// return maxValue;
// }
//
// public double sumValues() {
// return sumValues;
// }
//
// public long timestamp() {
// return timestamp;
// }
//
// public void setTimestamp(long timestamp) {
// this.timestamp = timestamp;
// }
//
// @Override
// public String toString() {
// return timestamp + "\t" + super.toString();
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((data == null) ? 0 : data.hashCode());
// result = prime * result + (int) (timestamp ^ (timestamp >>> 32));
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Vector))
// return false;
// Vector other = (Vector) obj;
// if (data == null) {
// if (other.data != null)
// return false;
// } else if (!data.equals(other.data))
// return false;
// if (timestamp != other.timestamp)
// return false;
// return true;
// }
//
// public double magnitude() {
// double magnitude = 0;
// for (double d : data.values())
// magnitude += d * d;
// magnitude = Math.sqrt(magnitude);
// return magnitude;
// }
//
// public void read(ByteBuffer in) throws IOException {
// data.clear();
// int numElements = in.getInt();
// this.setTimestamp(in.getLong());
// for (int i = 0; i < numElements; i++) {
// int dim = in.getInt();
// double val = in.getDouble();
// this.put(dim, val);
// }
// }
//
// public void write(ByteBuffer out) throws IOException {
// out.putInt(this.size());
// out.putLong(this.timestamp());
// for (Int2DoubleMap.Entry e : this.int2DoubleEntrySet()) {
// out.putInt(e.getIntKey());
// out.putDouble(e.getDoubleValue());
// }
// }
//
// public void read(DataInput in) throws IOException {
// data.clear();
// int numElements = in.readInt();
// this.setTimestamp(in.readLong());
// for (int i = 0; i < numElements; i++) {
// int dim = in.readInt();
// double val = in.readDouble();
// this.put(dim, val);
// }
// }
//
// public void write(DataOutput out) throws IOException {
// out.writeInt(this.size());
// out.writeLong(this.timestamp());
// for (Int2DoubleMap.Entry e : this.int2DoubleEntrySet()) {
// out.writeInt(e.getIntKey());
// out.writeDouble(e.getDoubleValue());
// }
// }
//
// public static Vector l2normalize(Vector v) {
// Vector result;
// double magnitude = v.magnitude();
// if (Double.compare(1.0, magnitude) != 0) {
// result = new Vector(v.timestamp());
// for (Int2DoubleMap.Entry e : v.int2DoubleEntrySet())
// result.put(e.getIntKey(), e.getDoubleValue() / magnitude);
// } else {
// result = v;
// }
// return result;
// }
//
// public static double similarity(Vector query, Vector target) {
// double result = 0;
// for (Int2DoubleMap.Entry e : query.int2DoubleEntrySet()) {
// result += e.getDoubleValue() * target.get(e.getIntKey());
// }
// return result;
// }
// }
| import java.util.ArrayDeque;
import java.util.Iterator;
import java.util.Queue;
import sssj.io.Vector;
import com.google.common.base.Preconditions; | package sssj.index.minibatch.component;
/**
* A buffer for Vectors. The buffer keeps the order of the vectors as they are added, and optionally maintains the maximum vector. Assumes vectors are added in
* increasing order of timestamp.
*/
public class VectorWindow {
private MaxVector max1 = new MaxVector();
private MaxVector max2 = new MaxVector(); | // Path: src/main/java/sssj/io/Vector.java
// public class Vector { // entries are returned in the same order they are added
// public static final Vector EMPTY_VECTOR = new Vector(Long.MIN_VALUE);
// protected Int2DoubleLinkedOpenHashMap data = new Int2DoubleLinkedOpenHashMap();
// protected long timestamp;
// protected double maxValue;
// protected double sumValues;
//
// public Vector() {
// this(0);
// }
//
// public Vector(long timestamp) {
// this.timestamp = timestamp;
// this.maxValue = 0;
// this.sumValues = 0;
// }
//
// /**
// * Copy constructor. The values are deep copied.
// *
// * @param other the vector to copy
// */
// public Vector(Vector other) {
// this.timestamp = other.timestamp;
// this.maxValue = other.maxValue;
// this.sumValues = other.sumValues;
// data.putAll(other.data);
// }
//
// public double put(int k, double v) {
// this.maxValue = Math.max(maxValue, v);
// this.sumValues += v;
// return data.put(k, v);
// }
//
// public double get(int k) {
// return data.get(k);
// }
//
// public FastSortedEntrySet int2DoubleEntrySet() {
// return data.int2DoubleEntrySet();
// }
//
// public int size() {
// return data.size();
// }
//
// public double maxValue() {
// return maxValue;
// }
//
// public double sumValues() {
// return sumValues;
// }
//
// public long timestamp() {
// return timestamp;
// }
//
// public void setTimestamp(long timestamp) {
// this.timestamp = timestamp;
// }
//
// @Override
// public String toString() {
// return timestamp + "\t" + super.toString();
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((data == null) ? 0 : data.hashCode());
// result = prime * result + (int) (timestamp ^ (timestamp >>> 32));
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Vector))
// return false;
// Vector other = (Vector) obj;
// if (data == null) {
// if (other.data != null)
// return false;
// } else if (!data.equals(other.data))
// return false;
// if (timestamp != other.timestamp)
// return false;
// return true;
// }
//
// public double magnitude() {
// double magnitude = 0;
// for (double d : data.values())
// magnitude += d * d;
// magnitude = Math.sqrt(magnitude);
// return magnitude;
// }
//
// public void read(ByteBuffer in) throws IOException {
// data.clear();
// int numElements = in.getInt();
// this.setTimestamp(in.getLong());
// for (int i = 0; i < numElements; i++) {
// int dim = in.getInt();
// double val = in.getDouble();
// this.put(dim, val);
// }
// }
//
// public void write(ByteBuffer out) throws IOException {
// out.putInt(this.size());
// out.putLong(this.timestamp());
// for (Int2DoubleMap.Entry e : this.int2DoubleEntrySet()) {
// out.putInt(e.getIntKey());
// out.putDouble(e.getDoubleValue());
// }
// }
//
// public void read(DataInput in) throws IOException {
// data.clear();
// int numElements = in.readInt();
// this.setTimestamp(in.readLong());
// for (int i = 0; i < numElements; i++) {
// int dim = in.readInt();
// double val = in.readDouble();
// this.put(dim, val);
// }
// }
//
// public void write(DataOutput out) throws IOException {
// out.writeInt(this.size());
// out.writeLong(this.timestamp());
// for (Int2DoubleMap.Entry e : this.int2DoubleEntrySet()) {
// out.writeInt(e.getIntKey());
// out.writeDouble(e.getDoubleValue());
// }
// }
//
// public static Vector l2normalize(Vector v) {
// Vector result;
// double magnitude = v.magnitude();
// if (Double.compare(1.0, magnitude) != 0) {
// result = new Vector(v.timestamp());
// for (Int2DoubleMap.Entry e : v.int2DoubleEntrySet())
// result.put(e.getIntKey(), e.getDoubleValue() / magnitude);
// } else {
// result = v;
// }
// return result;
// }
//
// public static double similarity(Vector query, Vector target) {
// double result = 0;
// for (Int2DoubleMap.Entry e : query.int2DoubleEntrySet()) {
// result += e.getDoubleValue() * target.get(e.getIntKey());
// }
// return result;
// }
// }
// Path: src/main/java/sssj/index/minibatch/component/VectorWindow.java
import java.util.ArrayDeque;
import java.util.Iterator;
import java.util.Queue;
import sssj.io.Vector;
import com.google.common.base.Preconditions;
package sssj.index.minibatch.component;
/**
* A buffer for Vectors. The buffer keeps the order of the vectors as they are added, and optionally maintains the maximum vector. Assumes vectors are added in
* increasing order of timestamp.
*/
public class VectorWindow {
private MaxVector max1 = new MaxVector();
private MaxVector max2 = new MaxVector(); | private Queue<Vector> q1 = new ArrayDeque<>(); |
gdfm/sssj | src/test/java/sssj/util/CommonsTest.java | // Path: src/main/java/sssj/util/Commons.java
// public class Commons {
// public static final double DEFAULT_THETA = 0.5;
// public static final double DEFAULT_LAMBDA = 0.01;
// public static final int DEFAULT_REPORT_PERIOD = 100_000;
//
// private static double[] FF; // precomputed values for the forgetting factor
//
// public static double tau(final double theta, final double lambda) {
// Preconditions.checkArgument(theta > 0 && theta < 1);
// Preconditions.checkArgument(lambda > 0);
// double tau = 1 / lambda * Math.log(1 / theta);
// return tau;
// }
//
// public static void precomputeFFTable(final double lambda, final int tau) {
// FF = new double[tau];
// for (int i = 0; i < tau; i++)
// FF[i] = FastMath.exp(-lambda * i);
// }
//
// public static double forgettingFactor(final double lambda, final long deltaT) {
// assert (FF != null);
// if (deltaT >= FF.length)
// return FastMath.exp(-lambda * deltaT);
// assert (deltaT >= 0 && deltaT < FF.length);
// return FF[(int) deltaT];
// }
//
// public static String formatMap(final Map<Long, Double> map) {
// StringBuilder sb = new StringBuilder();
// sb.append('{');
// Iterator<Entry<Long, Double>> iter = map.entrySet().iterator();
// while (iter.hasNext()) {
// Entry<Long, Double> entry = iter.next();
// sb.append(entry.getKey()).append(':').append(String.format("%.5f", entry.getValue()));
// if (iter.hasNext())
// sb.append(", ");
// }
// sb.append('}');
// return sb.toString();
// }
// }
| import org.apache.commons.math3.util.FastMath;
import org.junit.Test;
import sssj.util.Commons; | package sssj.util;
@SuppressWarnings("unused")
public class CommonsTest {
// @Test
public void testExpSpeed() {
long start, finish;
int i, N = 10_000_000;
final double l = 0.1;
double d;
start = System.currentTimeMillis(); | // Path: src/main/java/sssj/util/Commons.java
// public class Commons {
// public static final double DEFAULT_THETA = 0.5;
// public static final double DEFAULT_LAMBDA = 0.01;
// public static final int DEFAULT_REPORT_PERIOD = 100_000;
//
// private static double[] FF; // precomputed values for the forgetting factor
//
// public static double tau(final double theta, final double lambda) {
// Preconditions.checkArgument(theta > 0 && theta < 1);
// Preconditions.checkArgument(lambda > 0);
// double tau = 1 / lambda * Math.log(1 / theta);
// return tau;
// }
//
// public static void precomputeFFTable(final double lambda, final int tau) {
// FF = new double[tau];
// for (int i = 0; i < tau; i++)
// FF[i] = FastMath.exp(-lambda * i);
// }
//
// public static double forgettingFactor(final double lambda, final long deltaT) {
// assert (FF != null);
// if (deltaT >= FF.length)
// return FastMath.exp(-lambda * deltaT);
// assert (deltaT >= 0 && deltaT < FF.length);
// return FF[(int) deltaT];
// }
//
// public static String formatMap(final Map<Long, Double> map) {
// StringBuilder sb = new StringBuilder();
// sb.append('{');
// Iterator<Entry<Long, Double>> iter = map.entrySet().iterator();
// while (iter.hasNext()) {
// Entry<Long, Double> entry = iter.next();
// sb.append(entry.getKey()).append(':').append(String.format("%.5f", entry.getValue()));
// if (iter.hasNext())
// sb.append(", ");
// }
// sb.append('}');
// return sb.toString();
// }
// }
// Path: src/test/java/sssj/util/CommonsTest.java
import org.apache.commons.math3.util.FastMath;
import org.junit.Test;
import sssj.util.Commons;
package sssj.util;
@SuppressWarnings("unused")
public class CommonsTest {
// @Test
public void testExpSpeed() {
long start, finish;
int i, N = 10_000_000;
final double l = 0.1;
double d;
start = System.currentTimeMillis(); | Commons.precomputeFFTable(l, N); |
gdfm/sssj | src/test/java/sssj/io/BinaryVectorStreamReaderTest.java | // Path: src/main/java/sssj/time/Timeline.java
// public interface Timeline {
// long nextTimestamp();
//
// public static class Sequential implements Timeline {
// private long current = 0;
//
// @Override
// public long nextTimestamp() {
// return current++;
// }
//
// @Override
// public String toString() {
// return "Sequential";
// }
// }
//
// public static class Poisson implements Timeline {
// private long current = 0;
// private ExponentialDistribution p;
//
// public Poisson(double rate) {
// // exponential interarrival times with mean = 1/lambda
// p = new ExponentialDistribution(1 / rate);
// }
//
// @Override
// public long nextTimestamp() {
// current += Math.max(1, p.sample()); // ensure unique timestamps
// return current;
// }
//
// @Override
// public String toString() {
// return "Poisson(" + 1.0 / p.getMean() + ")";
// }
// }
// }
| import static org.junit.Assert.*;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import sssj.time.Timeline; |
@Test
public void testOnData() throws FileNotFoundException, IOException {
File file = new File(this.getClass().getResource(EXAMPLE_FILENAME).getPath());
VectorStream reader = new BinaryVectorStreamReader(file);
assertEquals(804414, reader.numVectors());
Vector v = reader.iterator().next();
Vector r = Vector.l2normalize(Format.VW.getRecordParser().apply(vw_example));
assertEquals(r, v);
}
// @Test
public void testSpeed() throws IOException {
File file;
VectorStream reader;
int nnz;
long start, finish;
file = new File("data/RCV1-seq.bin");
reader = new BinaryVectorStreamReader(file);
nnz = 0;
start = System.currentTimeMillis();
for (Vector v : reader) {
nnz += v.size();
}
finish = System.currentTimeMillis();
System.out.println("nnz=" + nnz);
System.out.println("BINARY READER - Total time taken: " + TimeUnit.MILLISECONDS.toMillis(finish - start) + " ms.");
file = new File("data/RCV1.vw"); | // Path: src/main/java/sssj/time/Timeline.java
// public interface Timeline {
// long nextTimestamp();
//
// public static class Sequential implements Timeline {
// private long current = 0;
//
// @Override
// public long nextTimestamp() {
// return current++;
// }
//
// @Override
// public String toString() {
// return "Sequential";
// }
// }
//
// public static class Poisson implements Timeline {
// private long current = 0;
// private ExponentialDistribution p;
//
// public Poisson(double rate) {
// // exponential interarrival times with mean = 1/lambda
// p = new ExponentialDistribution(1 / rate);
// }
//
// @Override
// public long nextTimestamp() {
// current += Math.max(1, p.sample()); // ensure unique timestamps
// return current;
// }
//
// @Override
// public String toString() {
// return "Poisson(" + 1.0 / p.getMean() + ")";
// }
// }
// }
// Path: src/test/java/sssj/io/BinaryVectorStreamReaderTest.java
import static org.junit.Assert.*;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import sssj.time.Timeline;
@Test
public void testOnData() throws FileNotFoundException, IOException {
File file = new File(this.getClass().getResource(EXAMPLE_FILENAME).getPath());
VectorStream reader = new BinaryVectorStreamReader(file);
assertEquals(804414, reader.numVectors());
Vector v = reader.iterator().next();
Vector r = Vector.l2normalize(Format.VW.getRecordParser().apply(vw_example));
assertEquals(r, v);
}
// @Test
public void testSpeed() throws IOException {
File file;
VectorStream reader;
int nnz;
long start, finish;
file = new File("data/RCV1-seq.bin");
reader = new BinaryVectorStreamReader(file);
nnz = 0;
start = System.currentTimeMillis();
for (Vector v : reader) {
nnz += v.size();
}
finish = System.currentTimeMillis();
System.out.println("nnz=" + nnz);
System.out.println("BINARY READER - Total time taken: " + TimeUnit.MILLISECONDS.toMillis(finish - start) + " ms.");
file = new File("data/RCV1.vw"); | reader = new VectorStreamReader(file, Format.VW, new Timeline.Sequential()); |
gdfm/sssj | src/test/java/sssj/io/VectorStreamReaderTest.java | // Path: src/main/java/sssj/io/Format.java
// public enum Format {
// SSSJ {
// @Override
// public Function<String, Vector> getRecordParser() {
// return new Function<String, Vector>() {
// public Vector apply(String input) {
// String[] tokens = input.split("\\s");
// long ts = Long.parseLong(tokens[0]);
// Vector result = new Vector(ts);
// for (int i = 1; i < tokens.length; i++) {
// String[] parts = tokens[i].split(":");
// int key = Integer.parseInt(parts[0]);
// double val = Double.parseDouble(parts[1]);
// result.put(key, val);
// }
// return result;
// }
// };
// }
// },
//
// SVMLIB {
// @Override
// public Function<String, Vector> getRecordParser() {
// return new Function<String, Vector>() {
// public Vector apply(String input) {
// String[] tokens = input.split("\\s");
// // ignore class label tokens[0]
// Vector result = new Vector();
// for (int i = 1; i < tokens.length; i++) {
// String[] parts = tokens[i].split(":");
// int key = Integer.parseInt(parts[0]);
// double val = Double.parseDouble(parts[1]);
// result.put(key, val);
// }
// return result;
// }
// };
// }
// },
//
// VW {
// @Override
// public Function<String, Vector> getRecordParser() {
// return new Function<String, Vector>() {
// public Vector apply(String input) {
// String[] tokens = input.split("\\s");
// // ignore class label tokens[0] and namespace tokens[1]
// Vector result = new Vector();
// for (int i = 2; i < tokens.length; i++) {
// String[] parts = tokens[i].split(":");
// int key = Integer.parseInt(parts[0]);
// double val = Double.parseDouble(parts[1]);
// result.put(key, val);
// }
// return result;
// }
// };
// }
// },
//
// BINARY {
// @Override
// public Function<String, Vector> getRecordParser() {
// throw new UnsupportedOperationException("Binary format does not need a parser");
// }
// };
//
// abstract public Function<String, Vector> getRecordParser();
// }
//
// Path: src/main/java/sssj/io/VectorStreamReader.java
// public class VectorStreamReader implements VectorStream {
// private final LineIterable it;
// private final Format format;
// private final TimeStamper ts;
// private final int numVectors;
//
// public VectorStreamReader(File file, Format format) throws FileNotFoundException, IOException {
// this(file, format, null);
// Preconditions.checkArgument(format == Format.SSSJ); // the format needs to have a timestamp
// }
//
// public VectorStreamReader(File file, Format format, Timeline timeline) throws FileNotFoundException, IOException {
// this.numVectors = IOUtils.getNumberOfLines(new FileReader(file));
// this.it = new LineIterable(file);
// this.format = format;
// Preconditions.checkArgument(timeline != null || format == Format.SSSJ,
// "Specify a timeline or an input format with timestamp information. Timeline=%s, Format=%s.", timeline, format);
// this.ts = timeline != null ? new TimeStamper(timeline) : null;
// }
//
// @Override
// public long numVectors() {
// return numVectors;
// }
//
// @Override
// public Iterator<Vector> iterator() {
// Iterator<Vector> result = Iterators.transform(it.iterator(), format.getRecordParser()); // parser
// result = Iterators.transform(result, new Function<Vector, Vector>() { // decorator normalizer
// @Override
// public Vector apply(Vector input) {
// return Vector.l2normalize(input);
// }
// });
// if (ts != null)
// result = Iterators.transform(result, ts); // decorator timestamper
// return result;
// }
// }
| import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import org.junit.Test;
import sssj.io.Format;
import sssj.io.VectorStreamReader; | package sssj.io;
public class VectorStreamReaderTest {
public static final String EXAMPLE_FILENAME = "/example.txt";
@Test
public void test() throws IOException {
File file = new File(this.getClass().getResource(EXAMPLE_FILENAME).getPath()); | // Path: src/main/java/sssj/io/Format.java
// public enum Format {
// SSSJ {
// @Override
// public Function<String, Vector> getRecordParser() {
// return new Function<String, Vector>() {
// public Vector apply(String input) {
// String[] tokens = input.split("\\s");
// long ts = Long.parseLong(tokens[0]);
// Vector result = new Vector(ts);
// for (int i = 1; i < tokens.length; i++) {
// String[] parts = tokens[i].split(":");
// int key = Integer.parseInt(parts[0]);
// double val = Double.parseDouble(parts[1]);
// result.put(key, val);
// }
// return result;
// }
// };
// }
// },
//
// SVMLIB {
// @Override
// public Function<String, Vector> getRecordParser() {
// return new Function<String, Vector>() {
// public Vector apply(String input) {
// String[] tokens = input.split("\\s");
// // ignore class label tokens[0]
// Vector result = new Vector();
// for (int i = 1; i < tokens.length; i++) {
// String[] parts = tokens[i].split(":");
// int key = Integer.parseInt(parts[0]);
// double val = Double.parseDouble(parts[1]);
// result.put(key, val);
// }
// return result;
// }
// };
// }
// },
//
// VW {
// @Override
// public Function<String, Vector> getRecordParser() {
// return new Function<String, Vector>() {
// public Vector apply(String input) {
// String[] tokens = input.split("\\s");
// // ignore class label tokens[0] and namespace tokens[1]
// Vector result = new Vector();
// for (int i = 2; i < tokens.length; i++) {
// String[] parts = tokens[i].split(":");
// int key = Integer.parseInt(parts[0]);
// double val = Double.parseDouble(parts[1]);
// result.put(key, val);
// }
// return result;
// }
// };
// }
// },
//
// BINARY {
// @Override
// public Function<String, Vector> getRecordParser() {
// throw new UnsupportedOperationException("Binary format does not need a parser");
// }
// };
//
// abstract public Function<String, Vector> getRecordParser();
// }
//
// Path: src/main/java/sssj/io/VectorStreamReader.java
// public class VectorStreamReader implements VectorStream {
// private final LineIterable it;
// private final Format format;
// private final TimeStamper ts;
// private final int numVectors;
//
// public VectorStreamReader(File file, Format format) throws FileNotFoundException, IOException {
// this(file, format, null);
// Preconditions.checkArgument(format == Format.SSSJ); // the format needs to have a timestamp
// }
//
// public VectorStreamReader(File file, Format format, Timeline timeline) throws FileNotFoundException, IOException {
// this.numVectors = IOUtils.getNumberOfLines(new FileReader(file));
// this.it = new LineIterable(file);
// this.format = format;
// Preconditions.checkArgument(timeline != null || format == Format.SSSJ,
// "Specify a timeline or an input format with timestamp information. Timeline=%s, Format=%s.", timeline, format);
// this.ts = timeline != null ? new TimeStamper(timeline) : null;
// }
//
// @Override
// public long numVectors() {
// return numVectors;
// }
//
// @Override
// public Iterator<Vector> iterator() {
// Iterator<Vector> result = Iterators.transform(it.iterator(), format.getRecordParser()); // parser
// result = Iterators.transform(result, new Function<Vector, Vector>() { // decorator normalizer
// @Override
// public Vector apply(Vector input) {
// return Vector.l2normalize(input);
// }
// });
// if (ts != null)
// result = Iterators.transform(result, ts); // decorator timestamper
// return result;
// }
// }
// Path: src/test/java/sssj/io/VectorStreamReaderTest.java
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import org.junit.Test;
import sssj.io.Format;
import sssj.io.VectorStreamReader;
package sssj.io;
public class VectorStreamReaderTest {
public static final String EXAMPLE_FILENAME = "/example.txt";
@Test
public void test() throws IOException {
File file = new File(this.getClass().getResource(EXAMPLE_FILENAME).getPath()); | VectorStreamReader stream = new VectorStreamReader(file, Format.SSSJ); |
gdfm/sssj | src/test/java/sssj/io/VectorStreamReaderTest.java | // Path: src/main/java/sssj/io/Format.java
// public enum Format {
// SSSJ {
// @Override
// public Function<String, Vector> getRecordParser() {
// return new Function<String, Vector>() {
// public Vector apply(String input) {
// String[] tokens = input.split("\\s");
// long ts = Long.parseLong(tokens[0]);
// Vector result = new Vector(ts);
// for (int i = 1; i < tokens.length; i++) {
// String[] parts = tokens[i].split(":");
// int key = Integer.parseInt(parts[0]);
// double val = Double.parseDouble(parts[1]);
// result.put(key, val);
// }
// return result;
// }
// };
// }
// },
//
// SVMLIB {
// @Override
// public Function<String, Vector> getRecordParser() {
// return new Function<String, Vector>() {
// public Vector apply(String input) {
// String[] tokens = input.split("\\s");
// // ignore class label tokens[0]
// Vector result = new Vector();
// for (int i = 1; i < tokens.length; i++) {
// String[] parts = tokens[i].split(":");
// int key = Integer.parseInt(parts[0]);
// double val = Double.parseDouble(parts[1]);
// result.put(key, val);
// }
// return result;
// }
// };
// }
// },
//
// VW {
// @Override
// public Function<String, Vector> getRecordParser() {
// return new Function<String, Vector>() {
// public Vector apply(String input) {
// String[] tokens = input.split("\\s");
// // ignore class label tokens[0] and namespace tokens[1]
// Vector result = new Vector();
// for (int i = 2; i < tokens.length; i++) {
// String[] parts = tokens[i].split(":");
// int key = Integer.parseInt(parts[0]);
// double val = Double.parseDouble(parts[1]);
// result.put(key, val);
// }
// return result;
// }
// };
// }
// },
//
// BINARY {
// @Override
// public Function<String, Vector> getRecordParser() {
// throw new UnsupportedOperationException("Binary format does not need a parser");
// }
// };
//
// abstract public Function<String, Vector> getRecordParser();
// }
//
// Path: src/main/java/sssj/io/VectorStreamReader.java
// public class VectorStreamReader implements VectorStream {
// private final LineIterable it;
// private final Format format;
// private final TimeStamper ts;
// private final int numVectors;
//
// public VectorStreamReader(File file, Format format) throws FileNotFoundException, IOException {
// this(file, format, null);
// Preconditions.checkArgument(format == Format.SSSJ); // the format needs to have a timestamp
// }
//
// public VectorStreamReader(File file, Format format, Timeline timeline) throws FileNotFoundException, IOException {
// this.numVectors = IOUtils.getNumberOfLines(new FileReader(file));
// this.it = new LineIterable(file);
// this.format = format;
// Preconditions.checkArgument(timeline != null || format == Format.SSSJ,
// "Specify a timeline or an input format with timestamp information. Timeline=%s, Format=%s.", timeline, format);
// this.ts = timeline != null ? new TimeStamper(timeline) : null;
// }
//
// @Override
// public long numVectors() {
// return numVectors;
// }
//
// @Override
// public Iterator<Vector> iterator() {
// Iterator<Vector> result = Iterators.transform(it.iterator(), format.getRecordParser()); // parser
// result = Iterators.transform(result, new Function<Vector, Vector>() { // decorator normalizer
// @Override
// public Vector apply(Vector input) {
// return Vector.l2normalize(input);
// }
// });
// if (ts != null)
// result = Iterators.transform(result, ts); // decorator timestamper
// return result;
// }
// }
| import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import org.junit.Test;
import sssj.io.Format;
import sssj.io.VectorStreamReader; | package sssj.io;
public class VectorStreamReaderTest {
public static final String EXAMPLE_FILENAME = "/example.txt";
@Test
public void test() throws IOException {
File file = new File(this.getClass().getResource(EXAMPLE_FILENAME).getPath()); | // Path: src/main/java/sssj/io/Format.java
// public enum Format {
// SSSJ {
// @Override
// public Function<String, Vector> getRecordParser() {
// return new Function<String, Vector>() {
// public Vector apply(String input) {
// String[] tokens = input.split("\\s");
// long ts = Long.parseLong(tokens[0]);
// Vector result = new Vector(ts);
// for (int i = 1; i < tokens.length; i++) {
// String[] parts = tokens[i].split(":");
// int key = Integer.parseInt(parts[0]);
// double val = Double.parseDouble(parts[1]);
// result.put(key, val);
// }
// return result;
// }
// };
// }
// },
//
// SVMLIB {
// @Override
// public Function<String, Vector> getRecordParser() {
// return new Function<String, Vector>() {
// public Vector apply(String input) {
// String[] tokens = input.split("\\s");
// // ignore class label tokens[0]
// Vector result = new Vector();
// for (int i = 1; i < tokens.length; i++) {
// String[] parts = tokens[i].split(":");
// int key = Integer.parseInt(parts[0]);
// double val = Double.parseDouble(parts[1]);
// result.put(key, val);
// }
// return result;
// }
// };
// }
// },
//
// VW {
// @Override
// public Function<String, Vector> getRecordParser() {
// return new Function<String, Vector>() {
// public Vector apply(String input) {
// String[] tokens = input.split("\\s");
// // ignore class label tokens[0] and namespace tokens[1]
// Vector result = new Vector();
// for (int i = 2; i < tokens.length; i++) {
// String[] parts = tokens[i].split(":");
// int key = Integer.parseInt(parts[0]);
// double val = Double.parseDouble(parts[1]);
// result.put(key, val);
// }
// return result;
// }
// };
// }
// },
//
// BINARY {
// @Override
// public Function<String, Vector> getRecordParser() {
// throw new UnsupportedOperationException("Binary format does not need a parser");
// }
// };
//
// abstract public Function<String, Vector> getRecordParser();
// }
//
// Path: src/main/java/sssj/io/VectorStreamReader.java
// public class VectorStreamReader implements VectorStream {
// private final LineIterable it;
// private final Format format;
// private final TimeStamper ts;
// private final int numVectors;
//
// public VectorStreamReader(File file, Format format) throws FileNotFoundException, IOException {
// this(file, format, null);
// Preconditions.checkArgument(format == Format.SSSJ); // the format needs to have a timestamp
// }
//
// public VectorStreamReader(File file, Format format, Timeline timeline) throws FileNotFoundException, IOException {
// this.numVectors = IOUtils.getNumberOfLines(new FileReader(file));
// this.it = new LineIterable(file);
// this.format = format;
// Preconditions.checkArgument(timeline != null || format == Format.SSSJ,
// "Specify a timeline or an input format with timestamp information. Timeline=%s, Format=%s.", timeline, format);
// this.ts = timeline != null ? new TimeStamper(timeline) : null;
// }
//
// @Override
// public long numVectors() {
// return numVectors;
// }
//
// @Override
// public Iterator<Vector> iterator() {
// Iterator<Vector> result = Iterators.transform(it.iterator(), format.getRecordParser()); // parser
// result = Iterators.transform(result, new Function<Vector, Vector>() { // decorator normalizer
// @Override
// public Vector apply(Vector input) {
// return Vector.l2normalize(input);
// }
// });
// if (ts != null)
// result = Iterators.transform(result, ts); // decorator timestamper
// return result;
// }
// }
// Path: src/test/java/sssj/io/VectorStreamReaderTest.java
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import org.junit.Test;
import sssj.io.Format;
import sssj.io.VectorStreamReader;
package sssj.io;
public class VectorStreamReaderTest {
public static final String EXAMPLE_FILENAME = "/example.txt";
@Test
public void test() throws IOException {
File file = new File(this.getClass().getResource(EXAMPLE_FILENAME).getPath()); | VectorStreamReader stream = new VectorStreamReader(file, Format.SSSJ); |
gdfm/sssj | src/test/java/sssj/io/VectorTest.java | // Path: src/main/java/sssj/io/Vector.java
// public class Vector { // entries are returned in the same order they are added
// public static final Vector EMPTY_VECTOR = new Vector(Long.MIN_VALUE);
// protected Int2DoubleLinkedOpenHashMap data = new Int2DoubleLinkedOpenHashMap();
// protected long timestamp;
// protected double maxValue;
// protected double sumValues;
//
// public Vector() {
// this(0);
// }
//
// public Vector(long timestamp) {
// this.timestamp = timestamp;
// this.maxValue = 0;
// this.sumValues = 0;
// }
//
// /**
// * Copy constructor. The values are deep copied.
// *
// * @param other the vector to copy
// */
// public Vector(Vector other) {
// this.timestamp = other.timestamp;
// this.maxValue = other.maxValue;
// this.sumValues = other.sumValues;
// data.putAll(other.data);
// }
//
// public double put(int k, double v) {
// this.maxValue = Math.max(maxValue, v);
// this.sumValues += v;
// return data.put(k, v);
// }
//
// public double get(int k) {
// return data.get(k);
// }
//
// public FastSortedEntrySet int2DoubleEntrySet() {
// return data.int2DoubleEntrySet();
// }
//
// public int size() {
// return data.size();
// }
//
// public double maxValue() {
// return maxValue;
// }
//
// public double sumValues() {
// return sumValues;
// }
//
// public long timestamp() {
// return timestamp;
// }
//
// public void setTimestamp(long timestamp) {
// this.timestamp = timestamp;
// }
//
// @Override
// public String toString() {
// return timestamp + "\t" + super.toString();
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((data == null) ? 0 : data.hashCode());
// result = prime * result + (int) (timestamp ^ (timestamp >>> 32));
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Vector))
// return false;
// Vector other = (Vector) obj;
// if (data == null) {
// if (other.data != null)
// return false;
// } else if (!data.equals(other.data))
// return false;
// if (timestamp != other.timestamp)
// return false;
// return true;
// }
//
// public double magnitude() {
// double magnitude = 0;
// for (double d : data.values())
// magnitude += d * d;
// magnitude = Math.sqrt(magnitude);
// return magnitude;
// }
//
// public void read(ByteBuffer in) throws IOException {
// data.clear();
// int numElements = in.getInt();
// this.setTimestamp(in.getLong());
// for (int i = 0; i < numElements; i++) {
// int dim = in.getInt();
// double val = in.getDouble();
// this.put(dim, val);
// }
// }
//
// public void write(ByteBuffer out) throws IOException {
// out.putInt(this.size());
// out.putLong(this.timestamp());
// for (Int2DoubleMap.Entry e : this.int2DoubleEntrySet()) {
// out.putInt(e.getIntKey());
// out.putDouble(e.getDoubleValue());
// }
// }
//
// public void read(DataInput in) throws IOException {
// data.clear();
// int numElements = in.readInt();
// this.setTimestamp(in.readLong());
// for (int i = 0; i < numElements; i++) {
// int dim = in.readInt();
// double val = in.readDouble();
// this.put(dim, val);
// }
// }
//
// public void write(DataOutput out) throws IOException {
// out.writeInt(this.size());
// out.writeLong(this.timestamp());
// for (Int2DoubleMap.Entry e : this.int2DoubleEntrySet()) {
// out.writeInt(e.getIntKey());
// out.writeDouble(e.getDoubleValue());
// }
// }
//
// public static Vector l2normalize(Vector v) {
// Vector result;
// double magnitude = v.magnitude();
// if (Double.compare(1.0, magnitude) != 0) {
// result = new Vector(v.timestamp());
// for (Int2DoubleMap.Entry e : v.int2DoubleEntrySet())
// result.put(e.getIntKey(), e.getDoubleValue() / magnitude);
// } else {
// result = v;
// }
// return result;
// }
//
// public static double similarity(Vector query, Vector target) {
// double result = 0;
// for (Int2DoubleMap.Entry e : query.int2DoubleEntrySet()) {
// result += e.getDoubleValue() * target.get(e.getIntKey());
// }
// return result;
// }
// }
| import static org.junit.Assert.*;
import it.unimi.dsi.fastutil.BidirectionalIterator;
import it.unimi.dsi.fastutil.ints.Int2DoubleMap;
import it.unimi.dsi.fastutil.ints.Int2DoubleMap.Entry;
import java.util.Iterator;
import org.junit.Test;
import sssj.io.Vector; | package sssj.io;
public class VectorTest {
@Test
public void testNotContains() { | // Path: src/main/java/sssj/io/Vector.java
// public class Vector { // entries are returned in the same order they are added
// public static final Vector EMPTY_VECTOR = new Vector(Long.MIN_VALUE);
// protected Int2DoubleLinkedOpenHashMap data = new Int2DoubleLinkedOpenHashMap();
// protected long timestamp;
// protected double maxValue;
// protected double sumValues;
//
// public Vector() {
// this(0);
// }
//
// public Vector(long timestamp) {
// this.timestamp = timestamp;
// this.maxValue = 0;
// this.sumValues = 0;
// }
//
// /**
// * Copy constructor. The values are deep copied.
// *
// * @param other the vector to copy
// */
// public Vector(Vector other) {
// this.timestamp = other.timestamp;
// this.maxValue = other.maxValue;
// this.sumValues = other.sumValues;
// data.putAll(other.data);
// }
//
// public double put(int k, double v) {
// this.maxValue = Math.max(maxValue, v);
// this.sumValues += v;
// return data.put(k, v);
// }
//
// public double get(int k) {
// return data.get(k);
// }
//
// public FastSortedEntrySet int2DoubleEntrySet() {
// return data.int2DoubleEntrySet();
// }
//
// public int size() {
// return data.size();
// }
//
// public double maxValue() {
// return maxValue;
// }
//
// public double sumValues() {
// return sumValues;
// }
//
// public long timestamp() {
// return timestamp;
// }
//
// public void setTimestamp(long timestamp) {
// this.timestamp = timestamp;
// }
//
// @Override
// public String toString() {
// return timestamp + "\t" + super.toString();
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((data == null) ? 0 : data.hashCode());
// result = prime * result + (int) (timestamp ^ (timestamp >>> 32));
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Vector))
// return false;
// Vector other = (Vector) obj;
// if (data == null) {
// if (other.data != null)
// return false;
// } else if (!data.equals(other.data))
// return false;
// if (timestamp != other.timestamp)
// return false;
// return true;
// }
//
// public double magnitude() {
// double magnitude = 0;
// for (double d : data.values())
// magnitude += d * d;
// magnitude = Math.sqrt(magnitude);
// return magnitude;
// }
//
// public void read(ByteBuffer in) throws IOException {
// data.clear();
// int numElements = in.getInt();
// this.setTimestamp(in.getLong());
// for (int i = 0; i < numElements; i++) {
// int dim = in.getInt();
// double val = in.getDouble();
// this.put(dim, val);
// }
// }
//
// public void write(ByteBuffer out) throws IOException {
// out.putInt(this.size());
// out.putLong(this.timestamp());
// for (Int2DoubleMap.Entry e : this.int2DoubleEntrySet()) {
// out.putInt(e.getIntKey());
// out.putDouble(e.getDoubleValue());
// }
// }
//
// public void read(DataInput in) throws IOException {
// data.clear();
// int numElements = in.readInt();
// this.setTimestamp(in.readLong());
// for (int i = 0; i < numElements; i++) {
// int dim = in.readInt();
// double val = in.readDouble();
// this.put(dim, val);
// }
// }
//
// public void write(DataOutput out) throws IOException {
// out.writeInt(this.size());
// out.writeLong(this.timestamp());
// for (Int2DoubleMap.Entry e : this.int2DoubleEntrySet()) {
// out.writeInt(e.getIntKey());
// out.writeDouble(e.getDoubleValue());
// }
// }
//
// public static Vector l2normalize(Vector v) {
// Vector result;
// double magnitude = v.magnitude();
// if (Double.compare(1.0, magnitude) != 0) {
// result = new Vector(v.timestamp());
// for (Int2DoubleMap.Entry e : v.int2DoubleEntrySet())
// result.put(e.getIntKey(), e.getDoubleValue() / magnitude);
// } else {
// result = v;
// }
// return result;
// }
//
// public static double similarity(Vector query, Vector target) {
// double result = 0;
// for (Int2DoubleMap.Entry e : query.int2DoubleEntrySet()) {
// result += e.getDoubleValue() * target.get(e.getIntKey());
// }
// return result;
// }
// }
// Path: src/test/java/sssj/io/VectorTest.java
import static org.junit.Assert.*;
import it.unimi.dsi.fastutil.BidirectionalIterator;
import it.unimi.dsi.fastutil.ints.Int2DoubleMap;
import it.unimi.dsi.fastutil.ints.Int2DoubleMap.Entry;
import java.util.Iterator;
import org.junit.Test;
import sssj.io.Vector;
package sssj.io;
public class VectorTest {
@Test
public void testNotContains() { | Vector v = new Vector(); |
gdfm/sssj | src/main/java/sssj/io/BinaryConverter.java | // Path: src/main/java/sssj/time/Timeline.java
// public interface Timeline {
// long nextTimestamp();
//
// public static class Sequential implements Timeline {
// private long current = 0;
//
// @Override
// public long nextTimestamp() {
// return current++;
// }
//
// @Override
// public String toString() {
// return "Sequential";
// }
// }
//
// public static class Poisson implements Timeline {
// private long current = 0;
// private ExponentialDistribution p;
//
// public Poisson(double rate) {
// // exponential interarrival times with mean = 1/lambda
// p = new ExponentialDistribution(1 / rate);
// }
//
// @Override
// public long nextTimestamp() {
// current += Math.max(1, p.sample()); // ensure unique timestamps
// return current;
// }
//
// @Override
// public String toString() {
// return "Poisson(" + 1.0 / p.getMean() + ")";
// }
// }
// }
| import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.Namespace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sssj.time.Timeline;
import com.google.common.base.Preconditions; | package sssj.io;
public class BinaryConverter {
private static final Logger log = LoggerFactory.getLogger(BinaryConverter.class);
public static void main(String[] args) throws Exception {
ArgumentParser parser = ArgumentParsers.newArgumentParser("Convert")
.description("Convert files to binary SSSJ format.").defaultHelp(true);
parser.addArgument("-f", "--format").type(Format.class).choices(Format.values()).setDefault(Format.SSSJ)
.help("input format");
parser.addArgument("-t", "--timeline").choices("sequential", "poisson").help("timeline to apply");
parser.addArgument("-r", "--rate").type(Double.class).setDefault(0.01)
.help("rate for the Poisson timeline (events/ms)");
parser.addArgument("input").metavar("input")
.type(Arguments.fileType().verifyExists().verifyIsFile().verifyCanRead()).help("input file");
parser.addArgument("output").metavar("output").type(Arguments.fileType().verifyCanCreate()).help("output file");
Namespace opts = parser.parseArgsOrFail(args);
final double rate = opts.getDouble("rate");
final Format fmt = opts.<Format>get("format");
final String tmls = opts.get("timeline"); | // Path: src/main/java/sssj/time/Timeline.java
// public interface Timeline {
// long nextTimestamp();
//
// public static class Sequential implements Timeline {
// private long current = 0;
//
// @Override
// public long nextTimestamp() {
// return current++;
// }
//
// @Override
// public String toString() {
// return "Sequential";
// }
// }
//
// public static class Poisson implements Timeline {
// private long current = 0;
// private ExponentialDistribution p;
//
// public Poisson(double rate) {
// // exponential interarrival times with mean = 1/lambda
// p = new ExponentialDistribution(1 / rate);
// }
//
// @Override
// public long nextTimestamp() {
// current += Math.max(1, p.sample()); // ensure unique timestamps
// return current;
// }
//
// @Override
// public String toString() {
// return "Poisson(" + 1.0 / p.getMean() + ")";
// }
// }
// }
// Path: src/main/java/sssj/io/BinaryConverter.java
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.Namespace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sssj.time.Timeline;
import com.google.common.base.Preconditions;
package sssj.io;
public class BinaryConverter {
private static final Logger log = LoggerFactory.getLogger(BinaryConverter.class);
public static void main(String[] args) throws Exception {
ArgumentParser parser = ArgumentParsers.newArgumentParser("Convert")
.description("Convert files to binary SSSJ format.").defaultHelp(true);
parser.addArgument("-f", "--format").type(Format.class).choices(Format.values()).setDefault(Format.SSSJ)
.help("input format");
parser.addArgument("-t", "--timeline").choices("sequential", "poisson").help("timeline to apply");
parser.addArgument("-r", "--rate").type(Double.class).setDefault(0.01)
.help("rate for the Poisson timeline (events/ms)");
parser.addArgument("input").metavar("input")
.type(Arguments.fileType().verifyExists().verifyIsFile().verifyCanRead()).help("input file");
parser.addArgument("output").metavar("output").type(Arguments.fileType().verifyCanCreate()).help("output file");
Namespace opts = parser.parseArgsOrFail(args);
final double rate = opts.getDouble("rate");
final Format fmt = opts.<Format>get("format");
final String tmls = opts.get("timeline"); | final Timeline tml; |
gdfm/sssj | src/main/java/sssj/io/VectorStreamReader.java | // Path: src/main/java/sssj/time/TimeStamper.java
// public class TimeStamper implements Function<Vector, Vector> {
// private Timeline timeline;
//
// public TimeStamper(Timeline timeline) {
// this.timeline = timeline;
// }
//
// @Override
// public Vector apply(Vector input) {
// input.setTimestamp(timeline.nextTimestamp());
// return input;
// }
// }
//
// Path: src/main/java/sssj/time/Timeline.java
// public interface Timeline {
// long nextTimestamp();
//
// public static class Sequential implements Timeline {
// private long current = 0;
//
// @Override
// public long nextTimestamp() {
// return current++;
// }
//
// @Override
// public String toString() {
// return "Sequential";
// }
// }
//
// public static class Poisson implements Timeline {
// private long current = 0;
// private ExponentialDistribution p;
//
// public Poisson(double rate) {
// // exponential interarrival times with mean = 1/lambda
// p = new ExponentialDistribution(1 / rate);
// }
//
// @Override
// public long nextTimestamp() {
// current += Math.max(1, p.sample()); // ensure unique timestamps
// return current;
// }
//
// @Override
// public String toString() {
// return "Poisson(" + 1.0 / p.getMean() + ")";
// }
// }
// }
| import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import sssj.time.TimeStamper;
import sssj.time.Timeline;
import com.github.gdfm.shobaidogu.IOUtils;
import com.github.gdfm.shobaidogu.LineIterable;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterators; | package sssj.io;
public class VectorStreamReader implements VectorStream {
private final LineIterable it;
private final Format format; | // Path: src/main/java/sssj/time/TimeStamper.java
// public class TimeStamper implements Function<Vector, Vector> {
// private Timeline timeline;
//
// public TimeStamper(Timeline timeline) {
// this.timeline = timeline;
// }
//
// @Override
// public Vector apply(Vector input) {
// input.setTimestamp(timeline.nextTimestamp());
// return input;
// }
// }
//
// Path: src/main/java/sssj/time/Timeline.java
// public interface Timeline {
// long nextTimestamp();
//
// public static class Sequential implements Timeline {
// private long current = 0;
//
// @Override
// public long nextTimestamp() {
// return current++;
// }
//
// @Override
// public String toString() {
// return "Sequential";
// }
// }
//
// public static class Poisson implements Timeline {
// private long current = 0;
// private ExponentialDistribution p;
//
// public Poisson(double rate) {
// // exponential interarrival times with mean = 1/lambda
// p = new ExponentialDistribution(1 / rate);
// }
//
// @Override
// public long nextTimestamp() {
// current += Math.max(1, p.sample()); // ensure unique timestamps
// return current;
// }
//
// @Override
// public String toString() {
// return "Poisson(" + 1.0 / p.getMean() + ")";
// }
// }
// }
// Path: src/main/java/sssj/io/VectorStreamReader.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import sssj.time.TimeStamper;
import sssj.time.Timeline;
import com.github.gdfm.shobaidogu.IOUtils;
import com.github.gdfm.shobaidogu.LineIterable;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterators;
package sssj.io;
public class VectorStreamReader implements VectorStream {
private final LineIterable it;
private final Format format; | private final TimeStamper ts; |
gdfm/sssj | src/main/java/sssj/io/VectorStreamReader.java | // Path: src/main/java/sssj/time/TimeStamper.java
// public class TimeStamper implements Function<Vector, Vector> {
// private Timeline timeline;
//
// public TimeStamper(Timeline timeline) {
// this.timeline = timeline;
// }
//
// @Override
// public Vector apply(Vector input) {
// input.setTimestamp(timeline.nextTimestamp());
// return input;
// }
// }
//
// Path: src/main/java/sssj/time/Timeline.java
// public interface Timeline {
// long nextTimestamp();
//
// public static class Sequential implements Timeline {
// private long current = 0;
//
// @Override
// public long nextTimestamp() {
// return current++;
// }
//
// @Override
// public String toString() {
// return "Sequential";
// }
// }
//
// public static class Poisson implements Timeline {
// private long current = 0;
// private ExponentialDistribution p;
//
// public Poisson(double rate) {
// // exponential interarrival times with mean = 1/lambda
// p = new ExponentialDistribution(1 / rate);
// }
//
// @Override
// public long nextTimestamp() {
// current += Math.max(1, p.sample()); // ensure unique timestamps
// return current;
// }
//
// @Override
// public String toString() {
// return "Poisson(" + 1.0 / p.getMean() + ")";
// }
// }
// }
| import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import sssj.time.TimeStamper;
import sssj.time.Timeline;
import com.github.gdfm.shobaidogu.IOUtils;
import com.github.gdfm.shobaidogu.LineIterable;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterators; | package sssj.io;
public class VectorStreamReader implements VectorStream {
private final LineIterable it;
private final Format format;
private final TimeStamper ts;
private final int numVectors;
public VectorStreamReader(File file, Format format) throws FileNotFoundException, IOException {
this(file, format, null);
Preconditions.checkArgument(format == Format.SSSJ); // the format needs to have a timestamp
}
| // Path: src/main/java/sssj/time/TimeStamper.java
// public class TimeStamper implements Function<Vector, Vector> {
// private Timeline timeline;
//
// public TimeStamper(Timeline timeline) {
// this.timeline = timeline;
// }
//
// @Override
// public Vector apply(Vector input) {
// input.setTimestamp(timeline.nextTimestamp());
// return input;
// }
// }
//
// Path: src/main/java/sssj/time/Timeline.java
// public interface Timeline {
// long nextTimestamp();
//
// public static class Sequential implements Timeline {
// private long current = 0;
//
// @Override
// public long nextTimestamp() {
// return current++;
// }
//
// @Override
// public String toString() {
// return "Sequential";
// }
// }
//
// public static class Poisson implements Timeline {
// private long current = 0;
// private ExponentialDistribution p;
//
// public Poisson(double rate) {
// // exponential interarrival times with mean = 1/lambda
// p = new ExponentialDistribution(1 / rate);
// }
//
// @Override
// public long nextTimestamp() {
// current += Math.max(1, p.sample()); // ensure unique timestamps
// return current;
// }
//
// @Override
// public String toString() {
// return "Poisson(" + 1.0 / p.getMean() + ")";
// }
// }
// }
// Path: src/main/java/sssj/io/VectorStreamReader.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import sssj.time.TimeStamper;
import sssj.time.Timeline;
import com.github.gdfm.shobaidogu.IOUtils;
import com.github.gdfm.shobaidogu.LineIterable;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterators;
package sssj.io;
public class VectorStreamReader implements VectorStream {
private final LineIterable it;
private final Format format;
private final TimeStamper ts;
private final int numVectors;
public VectorStreamReader(File file, Format format) throws FileNotFoundException, IOException {
this(file, format, null);
Preconditions.checkArgument(format == Format.SSSJ); // the format needs to have a timestamp
}
| public VectorStreamReader(File file, Format format, Timeline timeline) throws FileNotFoundException, IOException { |
bazaarvoice/dropwizard-caching-bundle | example/src/main/java/com/bazaarvoice/dropwizard/caching/example/ExampleApplication.java | // Path: bundle/src/main/java/com/bazaarvoice/dropwizard/caching/CachingBundle.java
// public class CachingBundle implements ConfiguredBundle<CachingBundleConfiguration> {
// private static final Set<String> SINGLETON_HEADERS = HttpHeaderUtils.headerNames(
// // Jetty sets the Date header automatically to the current time after the request has been
// // processed. Any other attempts to set the date header result in duplicate date headers. The
// // caching layer needs to be able to set the date header to the date the cached response was
// // generated. Duplicate headers are unexpected, confusing, and will likely result in problems
// // for clients.
// HttpHeaders.DATE
// );
//
// public void initialize(Bootstrap<?> bootstrap) {
// // Nothing to do
// }
//
// @Override
// public void run(CachingBundleConfiguration configuration, Environment environment) {
// Function<String, Optional<String>> cacheControlMapper = configuration.getCacheControl().buildMapper();
// ResponseCache responseCache = configuration.getCache().buildCache(environment.metrics());
//
// environment.jersey().register(new CacheResourceMethodDispatchAdapter(responseCache, cacheControlMapper));
//
// environment.servlets().addFilter("dropwizard-cache", new Filter() {
// @Override
// public void init(FilterConfig filterConfig) throws ServletException {
// // Nothing to do
// }
//
// @Override
// public void doFilter(ServletRequest request, final ServletResponse response, FilterChain chain) throws IOException, ServletException {
// HttpServletResponse httpResponse = (HttpServletResponse) response;
//
// chain.doFilter(request, new HttpServletResponseWrapper(httpResponse) {
// @Override
// public void addHeader(String name, String value) {
// if (SINGLETON_HEADERS.contains(name)) {
// super.setHeader(name, value);
// } else {
// super.addHeader(name, value);
// }
// }
// });
// }
//
// @Override
// public void destroy() {
// // Nothing to do
// }
// }).addMappingForUrlPatterns(null, false, "*");
// }
// }
| import com.bazaarvoice.dropwizard.caching.CachingBundle;
import io.dropwizard.Application;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment; | /*
* Copyright 2014 Bazaarvoice, 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.bazaarvoice.dropwizard.caching.example;
public class ExampleApplication extends Application<ExampleConfiguration> {
@Override
public void initialize(Bootstrap<ExampleConfiguration> bootstrap) { | // Path: bundle/src/main/java/com/bazaarvoice/dropwizard/caching/CachingBundle.java
// public class CachingBundle implements ConfiguredBundle<CachingBundleConfiguration> {
// private static final Set<String> SINGLETON_HEADERS = HttpHeaderUtils.headerNames(
// // Jetty sets the Date header automatically to the current time after the request has been
// // processed. Any other attempts to set the date header result in duplicate date headers. The
// // caching layer needs to be able to set the date header to the date the cached response was
// // generated. Duplicate headers are unexpected, confusing, and will likely result in problems
// // for clients.
// HttpHeaders.DATE
// );
//
// public void initialize(Bootstrap<?> bootstrap) {
// // Nothing to do
// }
//
// @Override
// public void run(CachingBundleConfiguration configuration, Environment environment) {
// Function<String, Optional<String>> cacheControlMapper = configuration.getCacheControl().buildMapper();
// ResponseCache responseCache = configuration.getCache().buildCache(environment.metrics());
//
// environment.jersey().register(new CacheResourceMethodDispatchAdapter(responseCache, cacheControlMapper));
//
// environment.servlets().addFilter("dropwizard-cache", new Filter() {
// @Override
// public void init(FilterConfig filterConfig) throws ServletException {
// // Nothing to do
// }
//
// @Override
// public void doFilter(ServletRequest request, final ServletResponse response, FilterChain chain) throws IOException, ServletException {
// HttpServletResponse httpResponse = (HttpServletResponse) response;
//
// chain.doFilter(request, new HttpServletResponseWrapper(httpResponse) {
// @Override
// public void addHeader(String name, String value) {
// if (SINGLETON_HEADERS.contains(name)) {
// super.setHeader(name, value);
// } else {
// super.addHeader(name, value);
// }
// }
// });
// }
//
// @Override
// public void destroy() {
// // Nothing to do
// }
// }).addMappingForUrlPatterns(null, false, "*");
// }
// }
// Path: example/src/main/java/com/bazaarvoice/dropwizard/caching/example/ExampleApplication.java
import com.bazaarvoice.dropwizard.caching.CachingBundle;
import io.dropwizard.Application;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
/*
* Copyright 2014 Bazaarvoice, 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.bazaarvoice.dropwizard.caching.example;
public class ExampleApplication extends Application<ExampleConfiguration> {
@Override
public void initialize(Bootstrap<ExampleConfiguration> bootstrap) { | bootstrap.addBundle(new CachingBundle()); |
bazaarvoice/dropwizard-caching-bundle | example/src/main/java/com/bazaarvoice/dropwizard/caching/example/ExampleConfiguration.java | // Path: bundle/src/main/java/com/bazaarvoice/dropwizard/caching/CacheControlConfiguration.java
// public class CacheControlConfiguration {
// private List<CacheControlConfigurationItem> _items = ImmutableList.of();
//
// public CacheControlConfiguration() {
// // Do nothing
// }
//
// @JsonCreator
// public CacheControlConfiguration(List<CacheControlConfigurationItem> items) {
// checkNotNull(items);
// _items = ImmutableList.copyOf(items);
// }
//
// @JsonValue
// public List<CacheControlConfigurationItem> getItems() {
// return _items;
// }
//
// public Function<String, Optional<String>> buildMapper() {
// if (_items.size() == 0) {
// return new Function<String, Optional<String>>() {
// public Optional<String> apply(@Nullable String input) {
// return Optional.absent();
// }
// };
// }
//
// final List<CacheControlMap> maps = FluentIterable
// .from(_items)
// .transform(new Function<CacheControlConfigurationItem, CacheControlMap>() {
// public CacheControlMap apply(CacheControlConfigurationItem input) {
// return new CacheControlMap(input);
// }
// })
// .toList();
//
// return CacheBuilder.newBuilder()
// .maximumSize(100)
// .build(
// new CacheLoader<String, Optional<String>>() {
// @Override
// public Optional<String> load(String key) throws Exception {
// for (CacheControlMap map : maps) {
// if (map.groupMatcher.apply(key)) {
// return Optional.of(map.options);
// }
// }
//
// return Optional.absent();
// }
// }
// );
// }
//
// private static class CacheControlMap {
// public final Predicate<String> groupMatcher;
// public final String options;
//
// public CacheControlMap(CacheControlConfigurationItem item) {
// this.groupMatcher = item.buildGroupMatcher();
// this.options = item.buildCacheControl().toString();
// }
// }
// }
//
// Path: bundle/src/main/java/com/bazaarvoice/dropwizard/caching/CachingBundleConfiguration.java
// public interface CachingBundleConfiguration {
// CachingConfiguration getCache();
//
// CacheControlConfiguration getCacheControl();
// }
//
// Path: bundle/src/main/java/com/bazaarvoice/dropwizard/caching/CachingConfiguration.java
// public class CachingConfiguration {
// private LocalCacheConfiguration _local = new LocalCacheConfiguration();
// private ResponseStoreFactory _storeFactory = ResponseStoreFactory.NULL_STORE_FACTORY;
//
// public LocalCacheConfiguration getLocal() {
// return _local;
// }
//
// @JsonProperty
// public void setLocal(LocalCacheConfiguration local) {
// _local = checkNotNull(local);
// }
//
// public ResponseStoreFactory getStoreFactory() {
// return _storeFactory;
// }
//
// @JsonProperty("store")
// public void setStoreFactory(ResponseStoreFactory storeFactory) {
// _storeFactory = checkNotNull(storeFactory);
// }
//
// public ResponseCache buildCache(MetricRegistry metricRegistry) {
// return new ResponseCache(_local.buildCache(), _storeFactory.createStore(), metricRegistry);
// }
// }
| import com.bazaarvoice.dropwizard.caching.CacheControlConfiguration;
import com.bazaarvoice.dropwizard.caching.CachingBundleConfiguration;
import com.bazaarvoice.dropwizard.caching.CachingConfiguration;
import io.dropwizard.Configuration; | /*
* Copyright 2014 Bazaarvoice, 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.bazaarvoice.dropwizard.caching.example;
public class ExampleConfiguration extends Configuration implements CachingBundleConfiguration {
private CachingConfiguration cache = new CachingConfiguration(); | // Path: bundle/src/main/java/com/bazaarvoice/dropwizard/caching/CacheControlConfiguration.java
// public class CacheControlConfiguration {
// private List<CacheControlConfigurationItem> _items = ImmutableList.of();
//
// public CacheControlConfiguration() {
// // Do nothing
// }
//
// @JsonCreator
// public CacheControlConfiguration(List<CacheControlConfigurationItem> items) {
// checkNotNull(items);
// _items = ImmutableList.copyOf(items);
// }
//
// @JsonValue
// public List<CacheControlConfigurationItem> getItems() {
// return _items;
// }
//
// public Function<String, Optional<String>> buildMapper() {
// if (_items.size() == 0) {
// return new Function<String, Optional<String>>() {
// public Optional<String> apply(@Nullable String input) {
// return Optional.absent();
// }
// };
// }
//
// final List<CacheControlMap> maps = FluentIterable
// .from(_items)
// .transform(new Function<CacheControlConfigurationItem, CacheControlMap>() {
// public CacheControlMap apply(CacheControlConfigurationItem input) {
// return new CacheControlMap(input);
// }
// })
// .toList();
//
// return CacheBuilder.newBuilder()
// .maximumSize(100)
// .build(
// new CacheLoader<String, Optional<String>>() {
// @Override
// public Optional<String> load(String key) throws Exception {
// for (CacheControlMap map : maps) {
// if (map.groupMatcher.apply(key)) {
// return Optional.of(map.options);
// }
// }
//
// return Optional.absent();
// }
// }
// );
// }
//
// private static class CacheControlMap {
// public final Predicate<String> groupMatcher;
// public final String options;
//
// public CacheControlMap(CacheControlConfigurationItem item) {
// this.groupMatcher = item.buildGroupMatcher();
// this.options = item.buildCacheControl().toString();
// }
// }
// }
//
// Path: bundle/src/main/java/com/bazaarvoice/dropwizard/caching/CachingBundleConfiguration.java
// public interface CachingBundleConfiguration {
// CachingConfiguration getCache();
//
// CacheControlConfiguration getCacheControl();
// }
//
// Path: bundle/src/main/java/com/bazaarvoice/dropwizard/caching/CachingConfiguration.java
// public class CachingConfiguration {
// private LocalCacheConfiguration _local = new LocalCacheConfiguration();
// private ResponseStoreFactory _storeFactory = ResponseStoreFactory.NULL_STORE_FACTORY;
//
// public LocalCacheConfiguration getLocal() {
// return _local;
// }
//
// @JsonProperty
// public void setLocal(LocalCacheConfiguration local) {
// _local = checkNotNull(local);
// }
//
// public ResponseStoreFactory getStoreFactory() {
// return _storeFactory;
// }
//
// @JsonProperty("store")
// public void setStoreFactory(ResponseStoreFactory storeFactory) {
// _storeFactory = checkNotNull(storeFactory);
// }
//
// public ResponseCache buildCache(MetricRegistry metricRegistry) {
// return new ResponseCache(_local.buildCache(), _storeFactory.createStore(), metricRegistry);
// }
// }
// Path: example/src/main/java/com/bazaarvoice/dropwizard/caching/example/ExampleConfiguration.java
import com.bazaarvoice.dropwizard.caching.CacheControlConfiguration;
import com.bazaarvoice.dropwizard.caching.CachingBundleConfiguration;
import com.bazaarvoice.dropwizard.caching.CachingConfiguration;
import io.dropwizard.Configuration;
/*
* Copyright 2014 Bazaarvoice, 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.bazaarvoice.dropwizard.caching.example;
public class ExampleConfiguration extends Configuration implements CachingBundleConfiguration {
private CachingConfiguration cache = new CachingConfiguration(); | public CacheControlConfiguration cacheControl = new CacheControlConfiguration(); |
bazaarvoice/dropwizard-caching-bundle | memcached/src/main/java/com/bazaarvoice/dropwizard/caching/memcached/MemcachedResponseStoreFactory.java | // Path: bundle/src/main/java/com/bazaarvoice/dropwizard/caching/ResponseStore.java
// public abstract class ResponseStore {
// public static final ResponseStore NULL_STORE = new ResponseStore() {
// @Override
// public Optional<CachedResponse> get(String key) {
// return Optional.absent();
// }
//
// @Override
// public void put(String key, CachedResponse response) {
// // Do nothing
// }
//
// @Override
// public void invalidate(String key) {
// // Do nothing
// }
// };
//
// public abstract Optional<CachedResponse> get(String key);
//
// public abstract void put(String key, CachedResponse response);
//
// public abstract void invalidate(String key);
// }
//
// Path: bundle/src/main/java/com/bazaarvoice/dropwizard/caching/ResponseStoreFactory.java
// @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
// public interface ResponseStoreFactory extends Discoverable {
// public static final ResponseStoreFactory NULL_STORE_FACTORY = new ResponseStoreFactory() {
// @Override
// public ResponseStore createStore() {
// return ResponseStore.NULL_STORE;
// }
// };
//
// public abstract ResponseStore createStore();
// }
| import java.util.Arrays;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
import com.bazaarvoice.dropwizard.caching.ResponseStore;
import com.bazaarvoice.dropwizard.caching.ResponseStoreFactory;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.net.HostAndPort;
import net.spy.memcached.BinaryConnectionFactory;
import net.spy.memcached.MemcachedClient;
import java.io.IOException;
import java.net.InetSocketAddress; | public List<InetSocketAddress> getServers() {
return _servers;
}
@JsonIgnore
public void setServers(List<InetSocketAddress> servers) {
checkNotNull(servers);
_servers = ImmutableList.copyOf(servers);
}
/**
* InetSocketAddress deserialization is broken in jackson 2.3.3, so using HostAndPort instead.
* See: https://github.com/FasterXML/jackson-databind/issues/444
* Fix will be in 2.3.4, but not released yet (as of 2014-Jul-10).
*/
@JsonProperty
void setServers(HostAndPort[] servers) {
checkNotNull(servers);
_servers = FluentIterable
.from(Arrays.asList(servers))
.transform(new Function<HostAndPort, InetSocketAddress>() {
public InetSocketAddress apply(HostAndPort input) {
return new InetSocketAddress(input.getHostText(), input.getPort());
}
})
.toList();
}
@Override | // Path: bundle/src/main/java/com/bazaarvoice/dropwizard/caching/ResponseStore.java
// public abstract class ResponseStore {
// public static final ResponseStore NULL_STORE = new ResponseStore() {
// @Override
// public Optional<CachedResponse> get(String key) {
// return Optional.absent();
// }
//
// @Override
// public void put(String key, CachedResponse response) {
// // Do nothing
// }
//
// @Override
// public void invalidate(String key) {
// // Do nothing
// }
// };
//
// public abstract Optional<CachedResponse> get(String key);
//
// public abstract void put(String key, CachedResponse response);
//
// public abstract void invalidate(String key);
// }
//
// Path: bundle/src/main/java/com/bazaarvoice/dropwizard/caching/ResponseStoreFactory.java
// @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
// public interface ResponseStoreFactory extends Discoverable {
// public static final ResponseStoreFactory NULL_STORE_FACTORY = new ResponseStoreFactory() {
// @Override
// public ResponseStore createStore() {
// return ResponseStore.NULL_STORE;
// }
// };
//
// public abstract ResponseStore createStore();
// }
// Path: memcached/src/main/java/com/bazaarvoice/dropwizard/caching/memcached/MemcachedResponseStoreFactory.java
import java.util.Arrays;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
import com.bazaarvoice.dropwizard.caching.ResponseStore;
import com.bazaarvoice.dropwizard.caching.ResponseStoreFactory;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.net.HostAndPort;
import net.spy.memcached.BinaryConnectionFactory;
import net.spy.memcached.MemcachedClient;
import java.io.IOException;
import java.net.InetSocketAddress;
public List<InetSocketAddress> getServers() {
return _servers;
}
@JsonIgnore
public void setServers(List<InetSocketAddress> servers) {
checkNotNull(servers);
_servers = ImmutableList.copyOf(servers);
}
/**
* InetSocketAddress deserialization is broken in jackson 2.3.3, so using HostAndPort instead.
* See: https://github.com/FasterXML/jackson-databind/issues/444
* Fix will be in 2.3.4, but not released yet (as of 2014-Jul-10).
*/
@JsonProperty
void setServers(HostAndPort[] servers) {
checkNotNull(servers);
_servers = FluentIterable
.from(Arrays.asList(servers))
.transform(new Function<HostAndPort, InetSocketAddress>() {
public InetSocketAddress apply(HostAndPort input) {
return new InetSocketAddress(input.getHostText(), input.getPort());
}
})
.toList();
}
@Override | public ResponseStore createStore() { |
sbouclier/kraken-java-api-client | src/test/java/com/github/sbouclier/result/TradesInformationResultTest.java | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith; | package com.github.sbouclier.result;
/**
* TradesInformationResult test
*
* @author Stéphane Bouclier
*/
public class TradesInformationResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
// Path: src/test/java/com/github/sbouclier/result/TradesInformationResultTest.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith;
package com.github.sbouclier.result;
/**
* TradesInformationResult test
*
* @author Stéphane Bouclier
*/
public class TradesInformationResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | final String jsonResult = StreamUtils.getResourceAsString(this.getClass(), "json/trades_information.mock.json"); |
sbouclier/kraken-java-api-client | src/test/java/com/github/sbouclier/result/OrdersInformationResultTest.java | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith; | package com.github.sbouclier.result;
/**
* ClosedOrdersResult test
*
* @author Stéphane Bouclier
*/
public class OrdersInformationResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
// Path: src/test/java/com/github/sbouclier/result/OrdersInformationResultTest.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith;
package com.github.sbouclier.result;
/**
* ClosedOrdersResult test
*
* @author Stéphane Bouclier
*/
public class OrdersInformationResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | final String jsonResult = StreamUtils.getResourceAsString(this.getClass(), "json/orders_information.mock.json"); |
sbouclier/kraken-java-api-client | src/main/java/com/github/sbouclier/result/ClosedOrdersResult.java | // Path: src/main/java/com/github/sbouclier/result/common/OrderDirection.java
// public enum OrderDirection {
//
// BUY("buy"),
// SELL("sell");
//
// private String value;
//
// OrderDirection(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/common/OrderType.java
// public enum OrderType {
// MARKET("market"),
// LIMIT("limit"),
// STOP_LOSS("stop-loss"),
// TAKE_PROFIT("take-profit"),
// STOP_LOSS_PROFIT("stop-loss-profit"),
// STOP_LOSS_PROFIT_LIMIT("stop-loss-profit-limit"),
// STOP_LOSS_LIMIT("stop-loss-limit"),
// TAKE_PROFIT_LIMIT("take-profit-limit"),
// TRAILING_STOP("trailing-stop"),
// TRAILING_STOP_LIMIT("trailing-stop-limit"),
// STOP_LOSS_AND_LIMIT("stop-loss-and-limit"),
// SETTLE_POSITION("settle-position");
//
// private String value;
//
// OrderType(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.github.sbouclier.result.common.OrderDirection;
import com.github.sbouclier.result.common.OrderType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
import java.util.Map; | }
}
public static class ClosedOrder {
public enum Status {
PENDING("pending"),
OPEN("open"),
CLOSED("closed"),
CANCELED("canceled"),
EXPIRED("expired");
private String value;
Status(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
}
public static class Description {
@JsonProperty("pair")
public String assetPair;
@JsonProperty("type") | // Path: src/main/java/com/github/sbouclier/result/common/OrderDirection.java
// public enum OrderDirection {
//
// BUY("buy"),
// SELL("sell");
//
// private String value;
//
// OrderDirection(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/common/OrderType.java
// public enum OrderType {
// MARKET("market"),
// LIMIT("limit"),
// STOP_LOSS("stop-loss"),
// TAKE_PROFIT("take-profit"),
// STOP_LOSS_PROFIT("stop-loss-profit"),
// STOP_LOSS_PROFIT_LIMIT("stop-loss-profit-limit"),
// STOP_LOSS_LIMIT("stop-loss-limit"),
// TAKE_PROFIT_LIMIT("take-profit-limit"),
// TRAILING_STOP("trailing-stop"),
// TRAILING_STOP_LIMIT("trailing-stop-limit"),
// STOP_LOSS_AND_LIMIT("stop-loss-and-limit"),
// SETTLE_POSITION("settle-position");
//
// private String value;
//
// OrderType(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
// Path: src/main/java/com/github/sbouclier/result/ClosedOrdersResult.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.github.sbouclier.result.common.OrderDirection;
import com.github.sbouclier.result.common.OrderType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
import java.util.Map;
}
}
public static class ClosedOrder {
public enum Status {
PENDING("pending"),
OPEN("open"),
CLOSED("closed"),
CANCELED("canceled"),
EXPIRED("expired");
private String value;
Status(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
}
public static class Description {
@JsonProperty("pair")
public String assetPair;
@JsonProperty("type") | public OrderDirection orderDirection; |
sbouclier/kraken-java-api-client | src/main/java/com/github/sbouclier/result/ClosedOrdersResult.java | // Path: src/main/java/com/github/sbouclier/result/common/OrderDirection.java
// public enum OrderDirection {
//
// BUY("buy"),
// SELL("sell");
//
// private String value;
//
// OrderDirection(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/common/OrderType.java
// public enum OrderType {
// MARKET("market"),
// LIMIT("limit"),
// STOP_LOSS("stop-loss"),
// TAKE_PROFIT("take-profit"),
// STOP_LOSS_PROFIT("stop-loss-profit"),
// STOP_LOSS_PROFIT_LIMIT("stop-loss-profit-limit"),
// STOP_LOSS_LIMIT("stop-loss-limit"),
// TAKE_PROFIT_LIMIT("take-profit-limit"),
// TRAILING_STOP("trailing-stop"),
// TRAILING_STOP_LIMIT("trailing-stop-limit"),
// STOP_LOSS_AND_LIMIT("stop-loss-and-limit"),
// SETTLE_POSITION("settle-position");
//
// private String value;
//
// OrderType(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.github.sbouclier.result.common.OrderDirection;
import com.github.sbouclier.result.common.OrderType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
import java.util.Map; | public static class ClosedOrder {
public enum Status {
PENDING("pending"),
OPEN("open"),
CLOSED("closed"),
CANCELED("canceled"),
EXPIRED("expired");
private String value;
Status(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
}
public static class Description {
@JsonProperty("pair")
public String assetPair;
@JsonProperty("type")
public OrderDirection orderDirection;
@JsonProperty("ordertype") | // Path: src/main/java/com/github/sbouclier/result/common/OrderDirection.java
// public enum OrderDirection {
//
// BUY("buy"),
// SELL("sell");
//
// private String value;
//
// OrderDirection(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/common/OrderType.java
// public enum OrderType {
// MARKET("market"),
// LIMIT("limit"),
// STOP_LOSS("stop-loss"),
// TAKE_PROFIT("take-profit"),
// STOP_LOSS_PROFIT("stop-loss-profit"),
// STOP_LOSS_PROFIT_LIMIT("stop-loss-profit-limit"),
// STOP_LOSS_LIMIT("stop-loss-limit"),
// TAKE_PROFIT_LIMIT("take-profit-limit"),
// TRAILING_STOP("trailing-stop"),
// TRAILING_STOP_LIMIT("trailing-stop-limit"),
// STOP_LOSS_AND_LIMIT("stop-loss-and-limit"),
// SETTLE_POSITION("settle-position");
//
// private String value;
//
// OrderType(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
// Path: src/main/java/com/github/sbouclier/result/ClosedOrdersResult.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.github.sbouclier.result.common.OrderDirection;
import com.github.sbouclier.result.common.OrderType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
import java.util.Map;
public static class ClosedOrder {
public enum Status {
PENDING("pending"),
OPEN("open"),
CLOSED("closed"),
CANCELED("canceled"),
EXPIRED("expired");
private String value;
Status(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
}
public static class Description {
@JsonProperty("pair")
public String assetPair;
@JsonProperty("type")
public OrderDirection orderDirection;
@JsonProperty("ordertype") | public OrderType orderType; |
sbouclier/kraken-java-api-client | src/main/java/com/github/sbouclier/HttpJsonClient.java | // Path: src/main/java/com/github/sbouclier/utils/Base64Utils.java
// public final class Base64Utils {
//
// /**
// * Private constructor
// */
// private Base64Utils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Decode from Base64
// *
// * @param input data to decode
// * @return decoded data
// */
// public static byte[] base64Decode(String input) {
// return Base64.getDecoder().decode(input);
// }
//
// /**
// * Encode into Base64
// *
// * @param data to encode
// * @return encoded data
// */
// public static String base64Encode(byte[] data) {
// return Base64.getEncoder().encodeToString(data);
// }
// }
//
// Path: src/main/java/com/github/sbouclier/utils/ByteUtils.java
// public class ByteUtils {
//
// private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
//
// /**
// * Private constructor
// */
// private ByteUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Convert string to bytes using UTF-8 charset
// *
// * @param input to convert
// * @return converted string to bytes array
// */
// public static byte[] stringToBytes(String input) {
// return input.getBytes(UTF8_CHARSET);
// }
//
// /**
// * Convert bytes array to string using UTF-8 charset
// *
// * @param bytes array to convert
// * @return converted bytes array to string
// */
// public static String bytesToString(byte[] bytes) {
// return new String(bytes, UTF8_CHARSET);
// }
//
// /**
// * Concatenate arrays of bytes into one
// *
// * @param a first array
// * @param b second array
// * @return array of bytes concatenated
// */
// public static byte[] concatArrays(byte[] a, byte[] b) throws IOException {
// ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// outputStream.write(a);
// outputStream.write(b);
//
// return outputStream.toByteArray();
// }
// }
//
// Path: src/main/java/com/github/sbouclier/utils/CryptoUtils.java
// public class CryptoUtils {
//
// /**
// * Private constructor
// */
// private CryptoUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Encode message to SHA-256 cryptographic hash algorithm
// *
// * @param message to encod
// * @return message encoded
// * @throws NoSuchAlgorithmException
// */
// public static byte[] sha256(String message) throws NoSuchAlgorithmException {
// MessageDigest md = MessageDigest.getInstance("SHA-256");
// return md.digest(ByteUtils.stringToBytes(message));
// }
//
// /**
// * Compute HMAC-SHA512 with secret key
// *
// * @param key secret key
// * @param message to encod
// * @return generated HMAC-SHA512
// * @throws InvalidKeyException
// * @throws NoSuchAlgorithmException
// */
// public static byte[] hmacSha512(byte[] key, byte[] message) throws InvalidKeyException, NoSuchAlgorithmException {
// Mac mac = Mac.getInstance("HmacSHA512");
// mac.init(new SecretKeySpec(key, "HmacSHA512"));
// return mac.doFinal(message);
// }
// }
| import com.github.sbouclier.utils.Base64Utils;
import com.github.sbouclier.utils.ByteUtils;
import com.github.sbouclier.utils.CryptoUtils;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.Map; | private String buildPostData(Map<String, String> params, String nonce) {
final StringBuilder postData = new StringBuilder();
if (params != null && !params.isEmpty()) {
params.forEach((k, v) -> {
postData.append(k).append("=").append(v).append("&");
});
}
postData.append("nonce=").append(nonce);
return postData.toString();
}
public String generateNonce() {
return String.valueOf(System.currentTimeMillis() * 1000);
}
/**
* Generate signature
*
* @param path URI path
* @param nonce
* @param postData POST data
* @return generated signature
* @throws KrakenApiException
*/
private String generateSignature(String path, String nonce, String postData) throws KrakenApiException {
// Algorithm: HMAC-SHA512 of (URI path + SHA256(nonce + POST data)) and base64 decoded secret API key
String hmacDigest = null;
try { | // Path: src/main/java/com/github/sbouclier/utils/Base64Utils.java
// public final class Base64Utils {
//
// /**
// * Private constructor
// */
// private Base64Utils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Decode from Base64
// *
// * @param input data to decode
// * @return decoded data
// */
// public static byte[] base64Decode(String input) {
// return Base64.getDecoder().decode(input);
// }
//
// /**
// * Encode into Base64
// *
// * @param data to encode
// * @return encoded data
// */
// public static String base64Encode(byte[] data) {
// return Base64.getEncoder().encodeToString(data);
// }
// }
//
// Path: src/main/java/com/github/sbouclier/utils/ByteUtils.java
// public class ByteUtils {
//
// private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
//
// /**
// * Private constructor
// */
// private ByteUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Convert string to bytes using UTF-8 charset
// *
// * @param input to convert
// * @return converted string to bytes array
// */
// public static byte[] stringToBytes(String input) {
// return input.getBytes(UTF8_CHARSET);
// }
//
// /**
// * Convert bytes array to string using UTF-8 charset
// *
// * @param bytes array to convert
// * @return converted bytes array to string
// */
// public static String bytesToString(byte[] bytes) {
// return new String(bytes, UTF8_CHARSET);
// }
//
// /**
// * Concatenate arrays of bytes into one
// *
// * @param a first array
// * @param b second array
// * @return array of bytes concatenated
// */
// public static byte[] concatArrays(byte[] a, byte[] b) throws IOException {
// ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// outputStream.write(a);
// outputStream.write(b);
//
// return outputStream.toByteArray();
// }
// }
//
// Path: src/main/java/com/github/sbouclier/utils/CryptoUtils.java
// public class CryptoUtils {
//
// /**
// * Private constructor
// */
// private CryptoUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Encode message to SHA-256 cryptographic hash algorithm
// *
// * @param message to encod
// * @return message encoded
// * @throws NoSuchAlgorithmException
// */
// public static byte[] sha256(String message) throws NoSuchAlgorithmException {
// MessageDigest md = MessageDigest.getInstance("SHA-256");
// return md.digest(ByteUtils.stringToBytes(message));
// }
//
// /**
// * Compute HMAC-SHA512 with secret key
// *
// * @param key secret key
// * @param message to encod
// * @return generated HMAC-SHA512
// * @throws InvalidKeyException
// * @throws NoSuchAlgorithmException
// */
// public static byte[] hmacSha512(byte[] key, byte[] message) throws InvalidKeyException, NoSuchAlgorithmException {
// Mac mac = Mac.getInstance("HmacSHA512");
// mac.init(new SecretKeySpec(key, "HmacSHA512"));
// return mac.doFinal(message);
// }
// }
// Path: src/main/java/com/github/sbouclier/HttpJsonClient.java
import com.github.sbouclier.utils.Base64Utils;
import com.github.sbouclier.utils.ByteUtils;
import com.github.sbouclier.utils.CryptoUtils;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.Map;
private String buildPostData(Map<String, String> params, String nonce) {
final StringBuilder postData = new StringBuilder();
if (params != null && !params.isEmpty()) {
params.forEach((k, v) -> {
postData.append(k).append("=").append(v).append("&");
});
}
postData.append("nonce=").append(nonce);
return postData.toString();
}
public String generateNonce() {
return String.valueOf(System.currentTimeMillis() * 1000);
}
/**
* Generate signature
*
* @param path URI path
* @param nonce
* @param postData POST data
* @return generated signature
* @throws KrakenApiException
*/
private String generateSignature(String path, String nonce, String postData) throws KrakenApiException {
// Algorithm: HMAC-SHA512 of (URI path + SHA256(nonce + POST data)) and base64 decoded secret API key
String hmacDigest = null;
try { | byte[] bytePath = ByteUtils.stringToBytes(path); |
sbouclier/kraken-java-api-client | src/main/java/com/github/sbouclier/HttpJsonClient.java | // Path: src/main/java/com/github/sbouclier/utils/Base64Utils.java
// public final class Base64Utils {
//
// /**
// * Private constructor
// */
// private Base64Utils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Decode from Base64
// *
// * @param input data to decode
// * @return decoded data
// */
// public static byte[] base64Decode(String input) {
// return Base64.getDecoder().decode(input);
// }
//
// /**
// * Encode into Base64
// *
// * @param data to encode
// * @return encoded data
// */
// public static String base64Encode(byte[] data) {
// return Base64.getEncoder().encodeToString(data);
// }
// }
//
// Path: src/main/java/com/github/sbouclier/utils/ByteUtils.java
// public class ByteUtils {
//
// private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
//
// /**
// * Private constructor
// */
// private ByteUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Convert string to bytes using UTF-8 charset
// *
// * @param input to convert
// * @return converted string to bytes array
// */
// public static byte[] stringToBytes(String input) {
// return input.getBytes(UTF8_CHARSET);
// }
//
// /**
// * Convert bytes array to string using UTF-8 charset
// *
// * @param bytes array to convert
// * @return converted bytes array to string
// */
// public static String bytesToString(byte[] bytes) {
// return new String(bytes, UTF8_CHARSET);
// }
//
// /**
// * Concatenate arrays of bytes into one
// *
// * @param a first array
// * @param b second array
// * @return array of bytes concatenated
// */
// public static byte[] concatArrays(byte[] a, byte[] b) throws IOException {
// ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// outputStream.write(a);
// outputStream.write(b);
//
// return outputStream.toByteArray();
// }
// }
//
// Path: src/main/java/com/github/sbouclier/utils/CryptoUtils.java
// public class CryptoUtils {
//
// /**
// * Private constructor
// */
// private CryptoUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Encode message to SHA-256 cryptographic hash algorithm
// *
// * @param message to encod
// * @return message encoded
// * @throws NoSuchAlgorithmException
// */
// public static byte[] sha256(String message) throws NoSuchAlgorithmException {
// MessageDigest md = MessageDigest.getInstance("SHA-256");
// return md.digest(ByteUtils.stringToBytes(message));
// }
//
// /**
// * Compute HMAC-SHA512 with secret key
// *
// * @param key secret key
// * @param message to encod
// * @return generated HMAC-SHA512
// * @throws InvalidKeyException
// * @throws NoSuchAlgorithmException
// */
// public static byte[] hmacSha512(byte[] key, byte[] message) throws InvalidKeyException, NoSuchAlgorithmException {
// Mac mac = Mac.getInstance("HmacSHA512");
// mac.init(new SecretKeySpec(key, "HmacSHA512"));
// return mac.doFinal(message);
// }
// }
| import com.github.sbouclier.utils.Base64Utils;
import com.github.sbouclier.utils.ByteUtils;
import com.github.sbouclier.utils.CryptoUtils;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.Map; | final StringBuilder postData = new StringBuilder();
if (params != null && !params.isEmpty()) {
params.forEach((k, v) -> {
postData.append(k).append("=").append(v).append("&");
});
}
postData.append("nonce=").append(nonce);
return postData.toString();
}
public String generateNonce() {
return String.valueOf(System.currentTimeMillis() * 1000);
}
/**
* Generate signature
*
* @param path URI path
* @param nonce
* @param postData POST data
* @return generated signature
* @throws KrakenApiException
*/
private String generateSignature(String path, String nonce, String postData) throws KrakenApiException {
// Algorithm: HMAC-SHA512 of (URI path + SHA256(nonce + POST data)) and base64 decoded secret API key
String hmacDigest = null;
try {
byte[] bytePath = ByteUtils.stringToBytes(path); | // Path: src/main/java/com/github/sbouclier/utils/Base64Utils.java
// public final class Base64Utils {
//
// /**
// * Private constructor
// */
// private Base64Utils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Decode from Base64
// *
// * @param input data to decode
// * @return decoded data
// */
// public static byte[] base64Decode(String input) {
// return Base64.getDecoder().decode(input);
// }
//
// /**
// * Encode into Base64
// *
// * @param data to encode
// * @return encoded data
// */
// public static String base64Encode(byte[] data) {
// return Base64.getEncoder().encodeToString(data);
// }
// }
//
// Path: src/main/java/com/github/sbouclier/utils/ByteUtils.java
// public class ByteUtils {
//
// private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
//
// /**
// * Private constructor
// */
// private ByteUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Convert string to bytes using UTF-8 charset
// *
// * @param input to convert
// * @return converted string to bytes array
// */
// public static byte[] stringToBytes(String input) {
// return input.getBytes(UTF8_CHARSET);
// }
//
// /**
// * Convert bytes array to string using UTF-8 charset
// *
// * @param bytes array to convert
// * @return converted bytes array to string
// */
// public static String bytesToString(byte[] bytes) {
// return new String(bytes, UTF8_CHARSET);
// }
//
// /**
// * Concatenate arrays of bytes into one
// *
// * @param a first array
// * @param b second array
// * @return array of bytes concatenated
// */
// public static byte[] concatArrays(byte[] a, byte[] b) throws IOException {
// ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// outputStream.write(a);
// outputStream.write(b);
//
// return outputStream.toByteArray();
// }
// }
//
// Path: src/main/java/com/github/sbouclier/utils/CryptoUtils.java
// public class CryptoUtils {
//
// /**
// * Private constructor
// */
// private CryptoUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Encode message to SHA-256 cryptographic hash algorithm
// *
// * @param message to encod
// * @return message encoded
// * @throws NoSuchAlgorithmException
// */
// public static byte[] sha256(String message) throws NoSuchAlgorithmException {
// MessageDigest md = MessageDigest.getInstance("SHA-256");
// return md.digest(ByteUtils.stringToBytes(message));
// }
//
// /**
// * Compute HMAC-SHA512 with secret key
// *
// * @param key secret key
// * @param message to encod
// * @return generated HMAC-SHA512
// * @throws InvalidKeyException
// * @throws NoSuchAlgorithmException
// */
// public static byte[] hmacSha512(byte[] key, byte[] message) throws InvalidKeyException, NoSuchAlgorithmException {
// Mac mac = Mac.getInstance("HmacSHA512");
// mac.init(new SecretKeySpec(key, "HmacSHA512"));
// return mac.doFinal(message);
// }
// }
// Path: src/main/java/com/github/sbouclier/HttpJsonClient.java
import com.github.sbouclier.utils.Base64Utils;
import com.github.sbouclier.utils.ByteUtils;
import com.github.sbouclier.utils.CryptoUtils;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.Map;
final StringBuilder postData = new StringBuilder();
if (params != null && !params.isEmpty()) {
params.forEach((k, v) -> {
postData.append(k).append("=").append(v).append("&");
});
}
postData.append("nonce=").append(nonce);
return postData.toString();
}
public String generateNonce() {
return String.valueOf(System.currentTimeMillis() * 1000);
}
/**
* Generate signature
*
* @param path URI path
* @param nonce
* @param postData POST data
* @return generated signature
* @throws KrakenApiException
*/
private String generateSignature(String path, String nonce, String postData) throws KrakenApiException {
// Algorithm: HMAC-SHA512 of (URI path + SHA256(nonce + POST data)) and base64 decoded secret API key
String hmacDigest = null;
try {
byte[] bytePath = ByteUtils.stringToBytes(path); | byte[] sha256 = CryptoUtils.sha256(nonce + postData); |
sbouclier/kraken-java-api-client | src/main/java/com/github/sbouclier/HttpJsonClient.java | // Path: src/main/java/com/github/sbouclier/utils/Base64Utils.java
// public final class Base64Utils {
//
// /**
// * Private constructor
// */
// private Base64Utils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Decode from Base64
// *
// * @param input data to decode
// * @return decoded data
// */
// public static byte[] base64Decode(String input) {
// return Base64.getDecoder().decode(input);
// }
//
// /**
// * Encode into Base64
// *
// * @param data to encode
// * @return encoded data
// */
// public static String base64Encode(byte[] data) {
// return Base64.getEncoder().encodeToString(data);
// }
// }
//
// Path: src/main/java/com/github/sbouclier/utils/ByteUtils.java
// public class ByteUtils {
//
// private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
//
// /**
// * Private constructor
// */
// private ByteUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Convert string to bytes using UTF-8 charset
// *
// * @param input to convert
// * @return converted string to bytes array
// */
// public static byte[] stringToBytes(String input) {
// return input.getBytes(UTF8_CHARSET);
// }
//
// /**
// * Convert bytes array to string using UTF-8 charset
// *
// * @param bytes array to convert
// * @return converted bytes array to string
// */
// public static String bytesToString(byte[] bytes) {
// return new String(bytes, UTF8_CHARSET);
// }
//
// /**
// * Concatenate arrays of bytes into one
// *
// * @param a first array
// * @param b second array
// * @return array of bytes concatenated
// */
// public static byte[] concatArrays(byte[] a, byte[] b) throws IOException {
// ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// outputStream.write(a);
// outputStream.write(b);
//
// return outputStream.toByteArray();
// }
// }
//
// Path: src/main/java/com/github/sbouclier/utils/CryptoUtils.java
// public class CryptoUtils {
//
// /**
// * Private constructor
// */
// private CryptoUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Encode message to SHA-256 cryptographic hash algorithm
// *
// * @param message to encod
// * @return message encoded
// * @throws NoSuchAlgorithmException
// */
// public static byte[] sha256(String message) throws NoSuchAlgorithmException {
// MessageDigest md = MessageDigest.getInstance("SHA-256");
// return md.digest(ByteUtils.stringToBytes(message));
// }
//
// /**
// * Compute HMAC-SHA512 with secret key
// *
// * @param key secret key
// * @param message to encod
// * @return generated HMAC-SHA512
// * @throws InvalidKeyException
// * @throws NoSuchAlgorithmException
// */
// public static byte[] hmacSha512(byte[] key, byte[] message) throws InvalidKeyException, NoSuchAlgorithmException {
// Mac mac = Mac.getInstance("HmacSHA512");
// mac.init(new SecretKeySpec(key, "HmacSHA512"));
// return mac.doFinal(message);
// }
// }
| import com.github.sbouclier.utils.Base64Utils;
import com.github.sbouclier.utils.ByteUtils;
import com.github.sbouclier.utils.CryptoUtils;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.Map; | postData.append(k).append("=").append(v).append("&");
});
}
postData.append("nonce=").append(nonce);
return postData.toString();
}
public String generateNonce() {
return String.valueOf(System.currentTimeMillis() * 1000);
}
/**
* Generate signature
*
* @param path URI path
* @param nonce
* @param postData POST data
* @return generated signature
* @throws KrakenApiException
*/
private String generateSignature(String path, String nonce, String postData) throws KrakenApiException {
// Algorithm: HMAC-SHA512 of (URI path + SHA256(nonce + POST data)) and base64 decoded secret API key
String hmacDigest = null;
try {
byte[] bytePath = ByteUtils.stringToBytes(path);
byte[] sha256 = CryptoUtils.sha256(nonce + postData);
byte[] hmacMessage = ByteUtils.concatArrays(bytePath, sha256);
| // Path: src/main/java/com/github/sbouclier/utils/Base64Utils.java
// public final class Base64Utils {
//
// /**
// * Private constructor
// */
// private Base64Utils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Decode from Base64
// *
// * @param input data to decode
// * @return decoded data
// */
// public static byte[] base64Decode(String input) {
// return Base64.getDecoder().decode(input);
// }
//
// /**
// * Encode into Base64
// *
// * @param data to encode
// * @return encoded data
// */
// public static String base64Encode(byte[] data) {
// return Base64.getEncoder().encodeToString(data);
// }
// }
//
// Path: src/main/java/com/github/sbouclier/utils/ByteUtils.java
// public class ByteUtils {
//
// private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
//
// /**
// * Private constructor
// */
// private ByteUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Convert string to bytes using UTF-8 charset
// *
// * @param input to convert
// * @return converted string to bytes array
// */
// public static byte[] stringToBytes(String input) {
// return input.getBytes(UTF8_CHARSET);
// }
//
// /**
// * Convert bytes array to string using UTF-8 charset
// *
// * @param bytes array to convert
// * @return converted bytes array to string
// */
// public static String bytesToString(byte[] bytes) {
// return new String(bytes, UTF8_CHARSET);
// }
//
// /**
// * Concatenate arrays of bytes into one
// *
// * @param a first array
// * @param b second array
// * @return array of bytes concatenated
// */
// public static byte[] concatArrays(byte[] a, byte[] b) throws IOException {
// ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// outputStream.write(a);
// outputStream.write(b);
//
// return outputStream.toByteArray();
// }
// }
//
// Path: src/main/java/com/github/sbouclier/utils/CryptoUtils.java
// public class CryptoUtils {
//
// /**
// * Private constructor
// */
// private CryptoUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Encode message to SHA-256 cryptographic hash algorithm
// *
// * @param message to encod
// * @return message encoded
// * @throws NoSuchAlgorithmException
// */
// public static byte[] sha256(String message) throws NoSuchAlgorithmException {
// MessageDigest md = MessageDigest.getInstance("SHA-256");
// return md.digest(ByteUtils.stringToBytes(message));
// }
//
// /**
// * Compute HMAC-SHA512 with secret key
// *
// * @param key secret key
// * @param message to encod
// * @return generated HMAC-SHA512
// * @throws InvalidKeyException
// * @throws NoSuchAlgorithmException
// */
// public static byte[] hmacSha512(byte[] key, byte[] message) throws InvalidKeyException, NoSuchAlgorithmException {
// Mac mac = Mac.getInstance("HmacSHA512");
// mac.init(new SecretKeySpec(key, "HmacSHA512"));
// return mac.doFinal(message);
// }
// }
// Path: src/main/java/com/github/sbouclier/HttpJsonClient.java
import com.github.sbouclier.utils.Base64Utils;
import com.github.sbouclier.utils.ByteUtils;
import com.github.sbouclier.utils.CryptoUtils;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.Map;
postData.append(k).append("=").append(v).append("&");
});
}
postData.append("nonce=").append(nonce);
return postData.toString();
}
public String generateNonce() {
return String.valueOf(System.currentTimeMillis() * 1000);
}
/**
* Generate signature
*
* @param path URI path
* @param nonce
* @param postData POST data
* @return generated signature
* @throws KrakenApiException
*/
private String generateSignature(String path, String nonce, String postData) throws KrakenApiException {
// Algorithm: HMAC-SHA512 of (URI path + SHA256(nonce + POST data)) and base64 decoded secret API key
String hmacDigest = null;
try {
byte[] bytePath = ByteUtils.stringToBytes(path);
byte[] sha256 = CryptoUtils.sha256(nonce + postData);
byte[] hmacMessage = ByteUtils.concatArrays(bytePath, sha256);
| byte[] hmacKey = Base64Utils.base64Decode(this.secret); |
sbouclier/kraken-java-api-client | src/test/java/com/github/sbouclier/result/OHLCResultTest.java | // Path: src/test/java/com/github/sbouclier/mock/MockInitHelper.java
// public class MockInitHelper {
//
// private MockInitHelper() {
// }
//
// public static RecentTradeResult buildRecentTradeResult() {
// RecentTradeResult mockResult = new RecentTradeResult();
// Map<String, List<RecentTradeResult.RecentTrade>> map = new HashMap<>();
//
// List<RecentTradeResult.RecentTrade> trades = new ArrayList<>();
// RecentTradeResult.RecentTrade trade1 = new RecentTradeResult.RecentTrade();
// trade1.price = BigDecimal.TEN;
// trade1.volume = BigDecimal.ONE;
//
// RecentTradeResult.RecentTrade trade2 = new RecentTradeResult.RecentTrade();
// trade2.price = BigDecimal.valueOf(20);
// trade2.volume = BigDecimal.valueOf(2);
//
// trades.add(trade1);
// trades.add(trade2);
//
// map.put("XXBTZEUR", trades);
// mockResult.setResult(map);
// mockResult.setLastId(123456L);
//
// return mockResult;
// }
//
// public static RecentSpreadResult buildRecentSpreadResult() {
// RecentSpreadResult mockResult = new RecentSpreadResult();
// Map<String, List<RecentSpreadResult.Spread>> map = new HashMap<>();
//
// List<RecentSpreadResult.Spread> spreads = new ArrayList<>();
// RecentSpreadResult.Spread spread1 = new RecentSpreadResult.Spread(1, BigDecimal.valueOf(10), BigDecimal.valueOf(11));
// RecentSpreadResult.Spread spread2 = new RecentSpreadResult.Spread(2, BigDecimal.valueOf(20), BigDecimal.valueOf(21));
//
// spreads.add(spread1);
// spreads.add(spread2);
//
// map.put("XXBTZEUR", spreads);
// mockResult.setResult(map);
// mockResult.setLastId(123456L);
//
// return mockResult;
// }
//
// public static OHLCResult buildOHLCResult() {
// OHLCResult mockResult = new OHLCResult();
// Map<String, List<OHLCResult.OHLC>> map = new HashMap<>();
//
// List<OHLCResult.OHLC> ohlcs = new ArrayList<>();
//
// OHLCResult.OHLC ohlc1 = new OHLCResult.OHLC();
// ohlc1.time = 1000;
// ohlc1.low = BigDecimal.valueOf(2000);
// ohlc1.high = BigDecimal.valueOf(2500);
//
// OHLCResult.OHLC ohlc2 = new OHLCResult.OHLC();
// ohlc2.time = 2000;
// ohlc2.low = BigDecimal.valueOf(1800);
// ohlc2.high = BigDecimal.valueOf(2100);
//
// ohlcs.add(ohlc1);
// ohlcs.add(ohlc2);
//
// map.put("XXBTZEUR", ohlcs);
// mockResult.setResult(map);
// mockResult.setLastId(23456L);
//
// return mockResult;
// }
// }
| import com.github.sbouclier.mock.MockInitHelper;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith; | package com.github.sbouclier.result;
/**
* OHLCResult test
*
* @author Stéphane Bouclier
*/
public class OHLCResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | // Path: src/test/java/com/github/sbouclier/mock/MockInitHelper.java
// public class MockInitHelper {
//
// private MockInitHelper() {
// }
//
// public static RecentTradeResult buildRecentTradeResult() {
// RecentTradeResult mockResult = new RecentTradeResult();
// Map<String, List<RecentTradeResult.RecentTrade>> map = new HashMap<>();
//
// List<RecentTradeResult.RecentTrade> trades = new ArrayList<>();
// RecentTradeResult.RecentTrade trade1 = new RecentTradeResult.RecentTrade();
// trade1.price = BigDecimal.TEN;
// trade1.volume = BigDecimal.ONE;
//
// RecentTradeResult.RecentTrade trade2 = new RecentTradeResult.RecentTrade();
// trade2.price = BigDecimal.valueOf(20);
// trade2.volume = BigDecimal.valueOf(2);
//
// trades.add(trade1);
// trades.add(trade2);
//
// map.put("XXBTZEUR", trades);
// mockResult.setResult(map);
// mockResult.setLastId(123456L);
//
// return mockResult;
// }
//
// public static RecentSpreadResult buildRecentSpreadResult() {
// RecentSpreadResult mockResult = new RecentSpreadResult();
// Map<String, List<RecentSpreadResult.Spread>> map = new HashMap<>();
//
// List<RecentSpreadResult.Spread> spreads = new ArrayList<>();
// RecentSpreadResult.Spread spread1 = new RecentSpreadResult.Spread(1, BigDecimal.valueOf(10), BigDecimal.valueOf(11));
// RecentSpreadResult.Spread spread2 = new RecentSpreadResult.Spread(2, BigDecimal.valueOf(20), BigDecimal.valueOf(21));
//
// spreads.add(spread1);
// spreads.add(spread2);
//
// map.put("XXBTZEUR", spreads);
// mockResult.setResult(map);
// mockResult.setLastId(123456L);
//
// return mockResult;
// }
//
// public static OHLCResult buildOHLCResult() {
// OHLCResult mockResult = new OHLCResult();
// Map<String, List<OHLCResult.OHLC>> map = new HashMap<>();
//
// List<OHLCResult.OHLC> ohlcs = new ArrayList<>();
//
// OHLCResult.OHLC ohlc1 = new OHLCResult.OHLC();
// ohlc1.time = 1000;
// ohlc1.low = BigDecimal.valueOf(2000);
// ohlc1.high = BigDecimal.valueOf(2500);
//
// OHLCResult.OHLC ohlc2 = new OHLCResult.OHLC();
// ohlc2.time = 2000;
// ohlc2.low = BigDecimal.valueOf(1800);
// ohlc2.high = BigDecimal.valueOf(2100);
//
// ohlcs.add(ohlc1);
// ohlcs.add(ohlc2);
//
// map.put("XXBTZEUR", ohlcs);
// mockResult.setResult(map);
// mockResult.setLastId(23456L);
//
// return mockResult;
// }
// }
// Path: src/test/java/com/github/sbouclier/result/OHLCResultTest.java
import com.github.sbouclier.mock.MockInitHelper;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith;
package com.github.sbouclier.result;
/**
* OHLCResult test
*
* @author Stéphane Bouclier
*/
public class OHLCResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | OHLCResult mockResult = MockInitHelper.buildOHLCResult(); |
sbouclier/kraken-java-api-client | src/test/java/com/github/sbouclier/result/RecentTradeResultTest.java | // Path: src/test/java/com/github/sbouclier/mock/MockInitHelper.java
// public class MockInitHelper {
//
// private MockInitHelper() {
// }
//
// public static RecentTradeResult buildRecentTradeResult() {
// RecentTradeResult mockResult = new RecentTradeResult();
// Map<String, List<RecentTradeResult.RecentTrade>> map = new HashMap<>();
//
// List<RecentTradeResult.RecentTrade> trades = new ArrayList<>();
// RecentTradeResult.RecentTrade trade1 = new RecentTradeResult.RecentTrade();
// trade1.price = BigDecimal.TEN;
// trade1.volume = BigDecimal.ONE;
//
// RecentTradeResult.RecentTrade trade2 = new RecentTradeResult.RecentTrade();
// trade2.price = BigDecimal.valueOf(20);
// trade2.volume = BigDecimal.valueOf(2);
//
// trades.add(trade1);
// trades.add(trade2);
//
// map.put("XXBTZEUR", trades);
// mockResult.setResult(map);
// mockResult.setLastId(123456L);
//
// return mockResult;
// }
//
// public static RecentSpreadResult buildRecentSpreadResult() {
// RecentSpreadResult mockResult = new RecentSpreadResult();
// Map<String, List<RecentSpreadResult.Spread>> map = new HashMap<>();
//
// List<RecentSpreadResult.Spread> spreads = new ArrayList<>();
// RecentSpreadResult.Spread spread1 = new RecentSpreadResult.Spread(1, BigDecimal.valueOf(10), BigDecimal.valueOf(11));
// RecentSpreadResult.Spread spread2 = new RecentSpreadResult.Spread(2, BigDecimal.valueOf(20), BigDecimal.valueOf(21));
//
// spreads.add(spread1);
// spreads.add(spread2);
//
// map.put("XXBTZEUR", spreads);
// mockResult.setResult(map);
// mockResult.setLastId(123456L);
//
// return mockResult;
// }
//
// public static OHLCResult buildOHLCResult() {
// OHLCResult mockResult = new OHLCResult();
// Map<String, List<OHLCResult.OHLC>> map = new HashMap<>();
//
// List<OHLCResult.OHLC> ohlcs = new ArrayList<>();
//
// OHLCResult.OHLC ohlc1 = new OHLCResult.OHLC();
// ohlc1.time = 1000;
// ohlc1.low = BigDecimal.valueOf(2000);
// ohlc1.high = BigDecimal.valueOf(2500);
//
// OHLCResult.OHLC ohlc2 = new OHLCResult.OHLC();
// ohlc2.time = 2000;
// ohlc2.low = BigDecimal.valueOf(1800);
// ohlc2.high = BigDecimal.valueOf(2100);
//
// ohlcs.add(ohlc1);
// ohlcs.add(ohlc2);
//
// map.put("XXBTZEUR", ohlcs);
// mockResult.setResult(map);
// mockResult.setLastId(23456L);
//
// return mockResult;
// }
// }
| import com.github.sbouclier.mock.MockInitHelper;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith; | package com.github.sbouclier.result;
/**
* RecentTradeResultTest test
*
* @author Stéphane Bouclier
*/
public class RecentTradeResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | // Path: src/test/java/com/github/sbouclier/mock/MockInitHelper.java
// public class MockInitHelper {
//
// private MockInitHelper() {
// }
//
// public static RecentTradeResult buildRecentTradeResult() {
// RecentTradeResult mockResult = new RecentTradeResult();
// Map<String, List<RecentTradeResult.RecentTrade>> map = new HashMap<>();
//
// List<RecentTradeResult.RecentTrade> trades = new ArrayList<>();
// RecentTradeResult.RecentTrade trade1 = new RecentTradeResult.RecentTrade();
// trade1.price = BigDecimal.TEN;
// trade1.volume = BigDecimal.ONE;
//
// RecentTradeResult.RecentTrade trade2 = new RecentTradeResult.RecentTrade();
// trade2.price = BigDecimal.valueOf(20);
// trade2.volume = BigDecimal.valueOf(2);
//
// trades.add(trade1);
// trades.add(trade2);
//
// map.put("XXBTZEUR", trades);
// mockResult.setResult(map);
// mockResult.setLastId(123456L);
//
// return mockResult;
// }
//
// public static RecentSpreadResult buildRecentSpreadResult() {
// RecentSpreadResult mockResult = new RecentSpreadResult();
// Map<String, List<RecentSpreadResult.Spread>> map = new HashMap<>();
//
// List<RecentSpreadResult.Spread> spreads = new ArrayList<>();
// RecentSpreadResult.Spread spread1 = new RecentSpreadResult.Spread(1, BigDecimal.valueOf(10), BigDecimal.valueOf(11));
// RecentSpreadResult.Spread spread2 = new RecentSpreadResult.Spread(2, BigDecimal.valueOf(20), BigDecimal.valueOf(21));
//
// spreads.add(spread1);
// spreads.add(spread2);
//
// map.put("XXBTZEUR", spreads);
// mockResult.setResult(map);
// mockResult.setLastId(123456L);
//
// return mockResult;
// }
//
// public static OHLCResult buildOHLCResult() {
// OHLCResult mockResult = new OHLCResult();
// Map<String, List<OHLCResult.OHLC>> map = new HashMap<>();
//
// List<OHLCResult.OHLC> ohlcs = new ArrayList<>();
//
// OHLCResult.OHLC ohlc1 = new OHLCResult.OHLC();
// ohlc1.time = 1000;
// ohlc1.low = BigDecimal.valueOf(2000);
// ohlc1.high = BigDecimal.valueOf(2500);
//
// OHLCResult.OHLC ohlc2 = new OHLCResult.OHLC();
// ohlc2.time = 2000;
// ohlc2.low = BigDecimal.valueOf(1800);
// ohlc2.high = BigDecimal.valueOf(2100);
//
// ohlcs.add(ohlc1);
// ohlcs.add(ohlc2);
//
// map.put("XXBTZEUR", ohlcs);
// mockResult.setResult(map);
// mockResult.setLastId(23456L);
//
// return mockResult;
// }
// }
// Path: src/test/java/com/github/sbouclier/result/RecentTradeResultTest.java
import com.github.sbouclier.mock.MockInitHelper;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith;
package com.github.sbouclier.result;
/**
* RecentTradeResultTest test
*
* @author Stéphane Bouclier
*/
public class RecentTradeResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | RecentTradeResult mockResult = MockInitHelper.buildRecentTradeResult(); |
sbouclier/kraken-java-api-client | src/main/java/com/github/sbouclier/HttpApiClient.java | // Path: src/main/java/com/github/sbouclier/result/Result.java
// public class Result<T> {
//
// private ArrayList<String> error = new ArrayList<>();
// private T result;
//
// /**
// * Get errors
// *
// * @return errors
// */
// public ArrayList<String> getError() {
// return error;
// }
//
// /**
// * Get result
// *
// * @return result
// */
// public T getResult() {
// return result;
// }
//
// /**
// * Set result
// *
// * @param result
// */
// public void setResult(T result) {
// this.result = result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
// .append("error", error)
// .append("result", result)
// .toString();
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/ResultWithLastId.java
// public class ResultWithLastId<T> extends Result<T> {
// private Long lastId = 0L;
//
// public Long getLastId() {
// return lastId;
// }
//
// public void setLastId(Long lastId) {
// this.lastId = lastId;
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.result.Result;
import com.github.sbouclier.result.ResultWithLastId;
import java.io.IOException;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | final String responseString = this.client.executePublicQuery(baseUrl, method.getUrl(apiVersion), params);
T res = new ObjectMapper().readValue(responseString, result);
if (!res.getError().isEmpty()) {
throw new KrakenApiException(res.getError());
}
return res;
} catch (IOException ex) {
throw new KrakenApiException("unable to query Kraken API", ex);
}
}
/**
* Call public kraken method and extract last id
*
* @param baseUrl kraken base url
* @param method kraken method
* @param result result class
* @param params method parameters
* @return result
* @throws KrakenApiException
*/
public T callPublicWithLastId(String baseUrl, KrakenApiMethod method, Class<T> result, Map<String, String> params) throws KrakenApiException {
try {
final String responseString = this.client.executePublicQuery(baseUrl, method.getUrl(apiVersion), params);
LastIdExtractedResult extractedResult = extractLastId(responseString);
T res = new ObjectMapper().readValue(extractedResult.responseWithoutLastId, result); | // Path: src/main/java/com/github/sbouclier/result/Result.java
// public class Result<T> {
//
// private ArrayList<String> error = new ArrayList<>();
// private T result;
//
// /**
// * Get errors
// *
// * @return errors
// */
// public ArrayList<String> getError() {
// return error;
// }
//
// /**
// * Get result
// *
// * @return result
// */
// public T getResult() {
// return result;
// }
//
// /**
// * Set result
// *
// * @param result
// */
// public void setResult(T result) {
// this.result = result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
// .append("error", error)
// .append("result", result)
// .toString();
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/ResultWithLastId.java
// public class ResultWithLastId<T> extends Result<T> {
// private Long lastId = 0L;
//
// public Long getLastId() {
// return lastId;
// }
//
// public void setLastId(Long lastId) {
// this.lastId = lastId;
// }
// }
// Path: src/main/java/com/github/sbouclier/HttpApiClient.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.result.Result;
import com.github.sbouclier.result.ResultWithLastId;
import java.io.IOException;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String responseString = this.client.executePublicQuery(baseUrl, method.getUrl(apiVersion), params);
T res = new ObjectMapper().readValue(responseString, result);
if (!res.getError().isEmpty()) {
throw new KrakenApiException(res.getError());
}
return res;
} catch (IOException ex) {
throw new KrakenApiException("unable to query Kraken API", ex);
}
}
/**
* Call public kraken method and extract last id
*
* @param baseUrl kraken base url
* @param method kraken method
* @param result result class
* @param params method parameters
* @return result
* @throws KrakenApiException
*/
public T callPublicWithLastId(String baseUrl, KrakenApiMethod method, Class<T> result, Map<String, String> params) throws KrakenApiException {
try {
final String responseString = this.client.executePublicQuery(baseUrl, method.getUrl(apiVersion), params);
LastIdExtractedResult extractedResult = extractLastId(responseString);
T res = new ObjectMapper().readValue(extractedResult.responseWithoutLastId, result); | ((ResultWithLastId) res).setLastId(extractedResult.lastId); |
sbouclier/kraken-java-api-client | src/main/java/com/github/sbouclier/result/LedgersInformationResult.java | // Path: src/main/java/com/github/sbouclier/result/common/LedgerInformation.java
// public class LedgerInformation {
//
// @JsonProperty("refid")
// public String referenceId;
//
// @JsonProperty("time")
// public Long timestamp;
//
// public String type;
//
// @JsonProperty("aclass")
// public String assetClass;
//
// public String asset;
//
// public BigDecimal amount;
//
// public BigDecimal fee;
//
// public BigDecimal balance;
//
// @Override
// public String toString() {
// return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
// .append("referenceId", referenceId)
// .append("timestamp", timestamp)
// .append("type", type)
// .append("assetClass", assetClass)
// .append("asset", asset)
// .append("amount", amount)
// .append("fee", fee)
// .append("balance", balance)
// .toString();
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.sbouclier.result.common.LedgerInformation;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.util.Map; | package com.github.sbouclier.result;
/**
* Result from getLedgersInformation
*
* @author Stéphane Bouclier
*/
public class LedgersInformationResult extends Result<LedgersInformationResult.LedgersInformation> {
public static class LedgersInformation {
@JsonProperty("ledger") | // Path: src/main/java/com/github/sbouclier/result/common/LedgerInformation.java
// public class LedgerInformation {
//
// @JsonProperty("refid")
// public String referenceId;
//
// @JsonProperty("time")
// public Long timestamp;
//
// public String type;
//
// @JsonProperty("aclass")
// public String assetClass;
//
// public String asset;
//
// public BigDecimal amount;
//
// public BigDecimal fee;
//
// public BigDecimal balance;
//
// @Override
// public String toString() {
// return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
// .append("referenceId", referenceId)
// .append("timestamp", timestamp)
// .append("type", type)
// .append("assetClass", assetClass)
// .append("asset", asset)
// .append("amount", amount)
// .append("fee", fee)
// .append("balance", balance)
// .toString();
// }
// }
// Path: src/main/java/com/github/sbouclier/result/LedgersInformationResult.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.sbouclier.result.common.LedgerInformation;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.util.Map;
package com.github.sbouclier.result;
/**
* Result from getLedgersInformation
*
* @author Stéphane Bouclier
*/
public class LedgersInformationResult extends Result<LedgersInformationResult.LedgersInformation> {
public static class LedgersInformation {
@JsonProperty("ledger") | public Map<String, LedgerInformation> ledger; |
sbouclier/kraken-java-api-client | src/test/java/com/github/sbouclier/result/OrderBookResultTest.java | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import java.math.BigDecimal;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.StringStartsWith.startsWith; | package com.github.sbouclier.result;
/**
* OrderBookResult test
*
* @author Stéphane Bouclier
*/
public class OrderBookResultTest {
@Test
public void should_construct_market() {
OrderBookResult.Market market = new OrderBookResult.Market(BigDecimal.TEN, BigDecimal.ONE, 5000);
assertThat(market.price, equalTo(BigDecimal.TEN));
assertThat(market.volume, equalTo(BigDecimal.ONE));
assertThat(market.timestamp, equalTo(5000));
}
@Test
public void should_return_to_string() throws IOException {
// Given | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
// Path: src/test/java/com/github/sbouclier/result/OrderBookResultTest.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import java.math.BigDecimal;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.StringStartsWith.startsWith;
package com.github.sbouclier.result;
/**
* OrderBookResult test
*
* @author Stéphane Bouclier
*/
public class OrderBookResultTest {
@Test
public void should_construct_market() {
OrderBookResult.Market market = new OrderBookResult.Market(BigDecimal.TEN, BigDecimal.ONE, 5000);
assertThat(market.price, equalTo(BigDecimal.TEN));
assertThat(market.volume, equalTo(BigDecimal.ONE));
assertThat(market.timestamp, equalTo(5000));
}
@Test
public void should_return_to_string() throws IOException {
// Given | final String jsonResult = StreamUtils.getResourceAsString(this.getClass(), "json/order_book.mock.json"); |
sbouclier/kraken-java-api-client | src/test/java/com/github/sbouclier/result/AssetsInformationResultTest.java | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith; | package com.github.sbouclier.result;
/**
* AssetInformationResult test
*
* @author Stéphane Bouclier
*/
public class AssetsInformationResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
// Path: src/test/java/com/github/sbouclier/result/AssetsInformationResultTest.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith;
package com.github.sbouclier.result;
/**
* AssetInformationResult test
*
* @author Stéphane Bouclier
*/
public class AssetsInformationResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | final String jsonResult = StreamUtils.getResourceAsString(this.getClass(), "json/assets_information.mock.json"); |
sbouclier/kraken-java-api-client | src/main/java/com/github/sbouclier/result/OpenOrdersResult.java | // Path: src/main/java/com/github/sbouclier/result/common/OrderDirection.java
// public enum OrderDirection {
//
// BUY("buy"),
// SELL("sell");
//
// private String value;
//
// OrderDirection(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/common/OrderType.java
// public enum OrderType {
// MARKET("market"),
// LIMIT("limit"),
// STOP_LOSS("stop-loss"),
// TAKE_PROFIT("take-profit"),
// STOP_LOSS_PROFIT("stop-loss-profit"),
// STOP_LOSS_PROFIT_LIMIT("stop-loss-profit-limit"),
// STOP_LOSS_LIMIT("stop-loss-limit"),
// TAKE_PROFIT_LIMIT("take-profit-limit"),
// TRAILING_STOP("trailing-stop"),
// TRAILING_STOP_LIMIT("trailing-stop-limit"),
// STOP_LOSS_AND_LIMIT("stop-loss-and-limit"),
// SETTLE_POSITION("settle-position");
//
// private String value;
//
// OrderType(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.github.sbouclier.result.common.OrderDirection;
import com.github.sbouclier.result.common.OrderType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
import java.util.Map; | }
}
public static class OpenOrder {
public enum Status {
PENDING("pending"),
OPEN("open"),
CLOSED("closed"),
CANCELED("canceled"),
EXPIRED("expired");
private String value;
Status(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
}
public static class Description {
@JsonProperty("pair")
public String assetPair;
@JsonProperty("type") | // Path: src/main/java/com/github/sbouclier/result/common/OrderDirection.java
// public enum OrderDirection {
//
// BUY("buy"),
// SELL("sell");
//
// private String value;
//
// OrderDirection(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/common/OrderType.java
// public enum OrderType {
// MARKET("market"),
// LIMIT("limit"),
// STOP_LOSS("stop-loss"),
// TAKE_PROFIT("take-profit"),
// STOP_LOSS_PROFIT("stop-loss-profit"),
// STOP_LOSS_PROFIT_LIMIT("stop-loss-profit-limit"),
// STOP_LOSS_LIMIT("stop-loss-limit"),
// TAKE_PROFIT_LIMIT("take-profit-limit"),
// TRAILING_STOP("trailing-stop"),
// TRAILING_STOP_LIMIT("trailing-stop-limit"),
// STOP_LOSS_AND_LIMIT("stop-loss-and-limit"),
// SETTLE_POSITION("settle-position");
//
// private String value;
//
// OrderType(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
// Path: src/main/java/com/github/sbouclier/result/OpenOrdersResult.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.github.sbouclier.result.common.OrderDirection;
import com.github.sbouclier.result.common.OrderType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
import java.util.Map;
}
}
public static class OpenOrder {
public enum Status {
PENDING("pending"),
OPEN("open"),
CLOSED("closed"),
CANCELED("canceled"),
EXPIRED("expired");
private String value;
Status(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
}
public static class Description {
@JsonProperty("pair")
public String assetPair;
@JsonProperty("type") | public OrderDirection orderDirection; |
sbouclier/kraken-java-api-client | src/main/java/com/github/sbouclier/result/OpenOrdersResult.java | // Path: src/main/java/com/github/sbouclier/result/common/OrderDirection.java
// public enum OrderDirection {
//
// BUY("buy"),
// SELL("sell");
//
// private String value;
//
// OrderDirection(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/common/OrderType.java
// public enum OrderType {
// MARKET("market"),
// LIMIT("limit"),
// STOP_LOSS("stop-loss"),
// TAKE_PROFIT("take-profit"),
// STOP_LOSS_PROFIT("stop-loss-profit"),
// STOP_LOSS_PROFIT_LIMIT("stop-loss-profit-limit"),
// STOP_LOSS_LIMIT("stop-loss-limit"),
// TAKE_PROFIT_LIMIT("take-profit-limit"),
// TRAILING_STOP("trailing-stop"),
// TRAILING_STOP_LIMIT("trailing-stop-limit"),
// STOP_LOSS_AND_LIMIT("stop-loss-and-limit"),
// SETTLE_POSITION("settle-position");
//
// private String value;
//
// OrderType(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.github.sbouclier.result.common.OrderDirection;
import com.github.sbouclier.result.common.OrderType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
import java.util.Map; | public static class OpenOrder {
public enum Status {
PENDING("pending"),
OPEN("open"),
CLOSED("closed"),
CANCELED("canceled"),
EXPIRED("expired");
private String value;
Status(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
}
public static class Description {
@JsonProperty("pair")
public String assetPair;
@JsonProperty("type")
public OrderDirection orderDirection;
@JsonProperty("ordertype") | // Path: src/main/java/com/github/sbouclier/result/common/OrderDirection.java
// public enum OrderDirection {
//
// BUY("buy"),
// SELL("sell");
//
// private String value;
//
// OrderDirection(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/common/OrderType.java
// public enum OrderType {
// MARKET("market"),
// LIMIT("limit"),
// STOP_LOSS("stop-loss"),
// TAKE_PROFIT("take-profit"),
// STOP_LOSS_PROFIT("stop-loss-profit"),
// STOP_LOSS_PROFIT_LIMIT("stop-loss-profit-limit"),
// STOP_LOSS_LIMIT("stop-loss-limit"),
// TAKE_PROFIT_LIMIT("take-profit-limit"),
// TRAILING_STOP("trailing-stop"),
// TRAILING_STOP_LIMIT("trailing-stop-limit"),
// STOP_LOSS_AND_LIMIT("stop-loss-and-limit"),
// SETTLE_POSITION("settle-position");
//
// private String value;
//
// OrderType(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
// Path: src/main/java/com/github/sbouclier/result/OpenOrdersResult.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.github.sbouclier.result.common.OrderDirection;
import com.github.sbouclier.result.common.OrderType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
import java.util.Map;
public static class OpenOrder {
public enum Status {
PENDING("pending"),
OPEN("open"),
CLOSED("closed"),
CANCELED("canceled"),
EXPIRED("expired");
private String value;
Status(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
}
public static class Description {
@JsonProperty("pair")
public String assetPair;
@JsonProperty("type")
public OrderDirection orderDirection;
@JsonProperty("ordertype") | public OrderType orderType; |
sbouclier/kraken-java-api-client | src/test/java/com/github/sbouclier/result/OpenPositionsResultTest.java | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith; | package com.github.sbouclier.result;
/**
* OpenPositionsResult test
*
* @author Stéphane Bouclier
*/
public class OpenPositionsResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
// Path: src/test/java/com/github/sbouclier/result/OpenPositionsResultTest.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith;
package com.github.sbouclier.result;
/**
* OpenPositionsResult test
*
* @author Stéphane Bouclier
*/
public class OpenPositionsResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | final String jsonResult = StreamUtils.getResourceAsString(this.getClass(), "json/open_positions.mock.json"); |
sbouclier/kraken-java-api-client | src/test/java/com/github/sbouclier/result/TradesHistoryResultTest.java | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith; | package com.github.sbouclier.result;
/**
* TradesHistoryResult test
*
* @author Stéphane Bouclier
*/
public class TradesHistoryResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
// Path: src/test/java/com/github/sbouclier/result/TradesHistoryResultTest.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith;
package com.github.sbouclier.result;
/**
* TradesHistoryResult test
*
* @author Stéphane Bouclier
*/
public class TradesHistoryResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | final String jsonResult = StreamUtils.getResourceAsString(this.getClass(), "json/trades_history.mock.json"); |
sbouclier/kraken-java-api-client | src/main/java/com/github/sbouclier/result/TradesHistoryResult.java | // Path: src/main/java/com/github/sbouclier/result/common/OrderDirection.java
// public enum OrderDirection {
//
// BUY("buy"),
// SELL("sell");
//
// private String value;
//
// OrderDirection(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/common/OrderType.java
// public enum OrderType {
// MARKET("market"),
// LIMIT("limit"),
// STOP_LOSS("stop-loss"),
// TAKE_PROFIT("take-profit"),
// STOP_LOSS_PROFIT("stop-loss-profit"),
// STOP_LOSS_PROFIT_LIMIT("stop-loss-profit-limit"),
// STOP_LOSS_LIMIT("stop-loss-limit"),
// TAKE_PROFIT_LIMIT("take-profit-limit"),
// TRAILING_STOP("trailing-stop"),
// TRAILING_STOP_LIMIT("trailing-stop-limit"),
// STOP_LOSS_AND_LIMIT("stop-loss-and-limit"),
// SETTLE_POSITION("settle-position");
//
// private String value;
//
// OrderType(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.sbouclier.result.common.OrderDirection;
import com.github.sbouclier.result.common.OrderType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
import java.util.Map; | package com.github.sbouclier.result;
/**
* Result from getTradesHistory
*
* @author Stéphane Bouclier
*/
public class TradesHistoryResult extends Result<TradesHistoryResult.TradesHistory> {
public static class TradesHistory {
@JsonProperty("trades")
public Map<String, TradeHistory> trades;
public Long count;
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
.append("trades", trades)
.append("count", count)
.toString();
}
}
// TODO extract to TradeInformation
public static class TradeHistory {
@JsonProperty("ordertxid")
public String orderTransactionId;
@JsonProperty("pair")
public String assetPair;
@JsonProperty("time")
public Long tradeTimestamp;
@JsonProperty("type") | // Path: src/main/java/com/github/sbouclier/result/common/OrderDirection.java
// public enum OrderDirection {
//
// BUY("buy"),
// SELL("sell");
//
// private String value;
//
// OrderDirection(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/common/OrderType.java
// public enum OrderType {
// MARKET("market"),
// LIMIT("limit"),
// STOP_LOSS("stop-loss"),
// TAKE_PROFIT("take-profit"),
// STOP_LOSS_PROFIT("stop-loss-profit"),
// STOP_LOSS_PROFIT_LIMIT("stop-loss-profit-limit"),
// STOP_LOSS_LIMIT("stop-loss-limit"),
// TAKE_PROFIT_LIMIT("take-profit-limit"),
// TRAILING_STOP("trailing-stop"),
// TRAILING_STOP_LIMIT("trailing-stop-limit"),
// STOP_LOSS_AND_LIMIT("stop-loss-and-limit"),
// SETTLE_POSITION("settle-position");
//
// private String value;
//
// OrderType(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
// Path: src/main/java/com/github/sbouclier/result/TradesHistoryResult.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.sbouclier.result.common.OrderDirection;
import com.github.sbouclier.result.common.OrderType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
import java.util.Map;
package com.github.sbouclier.result;
/**
* Result from getTradesHistory
*
* @author Stéphane Bouclier
*/
public class TradesHistoryResult extends Result<TradesHistoryResult.TradesHistory> {
public static class TradesHistory {
@JsonProperty("trades")
public Map<String, TradeHistory> trades;
public Long count;
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
.append("trades", trades)
.append("count", count)
.toString();
}
}
// TODO extract to TradeInformation
public static class TradeHistory {
@JsonProperty("ordertxid")
public String orderTransactionId;
@JsonProperty("pair")
public String assetPair;
@JsonProperty("time")
public Long tradeTimestamp;
@JsonProperty("type") | public OrderDirection orderDirection; |
sbouclier/kraken-java-api-client | src/main/java/com/github/sbouclier/result/TradesHistoryResult.java | // Path: src/main/java/com/github/sbouclier/result/common/OrderDirection.java
// public enum OrderDirection {
//
// BUY("buy"),
// SELL("sell");
//
// private String value;
//
// OrderDirection(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/common/OrderType.java
// public enum OrderType {
// MARKET("market"),
// LIMIT("limit"),
// STOP_LOSS("stop-loss"),
// TAKE_PROFIT("take-profit"),
// STOP_LOSS_PROFIT("stop-loss-profit"),
// STOP_LOSS_PROFIT_LIMIT("stop-loss-profit-limit"),
// STOP_LOSS_LIMIT("stop-loss-limit"),
// TAKE_PROFIT_LIMIT("take-profit-limit"),
// TRAILING_STOP("trailing-stop"),
// TRAILING_STOP_LIMIT("trailing-stop-limit"),
// STOP_LOSS_AND_LIMIT("stop-loss-and-limit"),
// SETTLE_POSITION("settle-position");
//
// private String value;
//
// OrderType(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.sbouclier.result.common.OrderDirection;
import com.github.sbouclier.result.common.OrderType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
import java.util.Map; | package com.github.sbouclier.result;
/**
* Result from getTradesHistory
*
* @author Stéphane Bouclier
*/
public class TradesHistoryResult extends Result<TradesHistoryResult.TradesHistory> {
public static class TradesHistory {
@JsonProperty("trades")
public Map<String, TradeHistory> trades;
public Long count;
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
.append("trades", trades)
.append("count", count)
.toString();
}
}
// TODO extract to TradeInformation
public static class TradeHistory {
@JsonProperty("ordertxid")
public String orderTransactionId;
@JsonProperty("pair")
public String assetPair;
@JsonProperty("time")
public Long tradeTimestamp;
@JsonProperty("type")
public OrderDirection orderDirection;
@JsonProperty("ordertype") | // Path: src/main/java/com/github/sbouclier/result/common/OrderDirection.java
// public enum OrderDirection {
//
// BUY("buy"),
// SELL("sell");
//
// private String value;
//
// OrderDirection(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/common/OrderType.java
// public enum OrderType {
// MARKET("market"),
// LIMIT("limit"),
// STOP_LOSS("stop-loss"),
// TAKE_PROFIT("take-profit"),
// STOP_LOSS_PROFIT("stop-loss-profit"),
// STOP_LOSS_PROFIT_LIMIT("stop-loss-profit-limit"),
// STOP_LOSS_LIMIT("stop-loss-limit"),
// TAKE_PROFIT_LIMIT("take-profit-limit"),
// TRAILING_STOP("trailing-stop"),
// TRAILING_STOP_LIMIT("trailing-stop-limit"),
// STOP_LOSS_AND_LIMIT("stop-loss-and-limit"),
// SETTLE_POSITION("settle-position");
//
// private String value;
//
// OrderType(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
// Path: src/main/java/com/github/sbouclier/result/TradesHistoryResult.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.sbouclier.result.common.OrderDirection;
import com.github.sbouclier.result.common.OrderType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
import java.util.Map;
package com.github.sbouclier.result;
/**
* Result from getTradesHistory
*
* @author Stéphane Bouclier
*/
public class TradesHistoryResult extends Result<TradesHistoryResult.TradesHistory> {
public static class TradesHistory {
@JsonProperty("trades")
public Map<String, TradeHistory> trades;
public Long count;
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
.append("trades", trades)
.append("count", count)
.toString();
}
}
// TODO extract to TradeInformation
public static class TradeHistory {
@JsonProperty("ordertxid")
public String orderTransactionId;
@JsonProperty("pair")
public String assetPair;
@JsonProperty("time")
public Long tradeTimestamp;
@JsonProperty("type")
public OrderDirection orderDirection;
@JsonProperty("ordertype") | public OrderType orderType; |
sbouclier/kraken-java-api-client | src/main/java/com/github/sbouclier/result/OpenPositionsResult.java | // Path: src/main/java/com/github/sbouclier/result/common/OrderDirection.java
// public enum OrderDirection {
//
// BUY("buy"),
// SELL("sell");
//
// private String value;
//
// OrderDirection(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/common/OrderType.java
// public enum OrderType {
// MARKET("market"),
// LIMIT("limit"),
// STOP_LOSS("stop-loss"),
// TAKE_PROFIT("take-profit"),
// STOP_LOSS_PROFIT("stop-loss-profit"),
// STOP_LOSS_PROFIT_LIMIT("stop-loss-profit-limit"),
// STOP_LOSS_LIMIT("stop-loss-limit"),
// TAKE_PROFIT_LIMIT("take-profit-limit"),
// TRAILING_STOP("trailing-stop"),
// TRAILING_STOP_LIMIT("trailing-stop-limit"),
// STOP_LOSS_AND_LIMIT("stop-loss-and-limit"),
// SETTLE_POSITION("settle-position");
//
// private String value;
//
// OrderType(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.sbouclier.result.common.OrderDirection;
import com.github.sbouclier.result.common.OrderType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
import java.util.Map; | package com.github.sbouclier.result;
/**
* Result from getOpenPositions
*
* @author Stéphane Bouclier
*/
public class OpenPositionsResult extends Result<Map<String, OpenPositionsResult.OpenPosition>> {
public static class OpenPosition {
@JsonProperty("ordertxid")
public String orderTransactionId;
@JsonProperty("posstatus")
public String positionStatus;
@JsonProperty("pair")
public String assetPair;
@JsonProperty("time")
public Long tradeTimestamp;
@JsonProperty("type") | // Path: src/main/java/com/github/sbouclier/result/common/OrderDirection.java
// public enum OrderDirection {
//
// BUY("buy"),
// SELL("sell");
//
// private String value;
//
// OrderDirection(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/common/OrderType.java
// public enum OrderType {
// MARKET("market"),
// LIMIT("limit"),
// STOP_LOSS("stop-loss"),
// TAKE_PROFIT("take-profit"),
// STOP_LOSS_PROFIT("stop-loss-profit"),
// STOP_LOSS_PROFIT_LIMIT("stop-loss-profit-limit"),
// STOP_LOSS_LIMIT("stop-loss-limit"),
// TAKE_PROFIT_LIMIT("take-profit-limit"),
// TRAILING_STOP("trailing-stop"),
// TRAILING_STOP_LIMIT("trailing-stop-limit"),
// STOP_LOSS_AND_LIMIT("stop-loss-and-limit"),
// SETTLE_POSITION("settle-position");
//
// private String value;
//
// OrderType(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
// Path: src/main/java/com/github/sbouclier/result/OpenPositionsResult.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.sbouclier.result.common.OrderDirection;
import com.github.sbouclier.result.common.OrderType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
import java.util.Map;
package com.github.sbouclier.result;
/**
* Result from getOpenPositions
*
* @author Stéphane Bouclier
*/
public class OpenPositionsResult extends Result<Map<String, OpenPositionsResult.OpenPosition>> {
public static class OpenPosition {
@JsonProperty("ordertxid")
public String orderTransactionId;
@JsonProperty("posstatus")
public String positionStatus;
@JsonProperty("pair")
public String assetPair;
@JsonProperty("time")
public Long tradeTimestamp;
@JsonProperty("type") | public OrderDirection orderDirection; |
sbouclier/kraken-java-api-client | src/main/java/com/github/sbouclier/result/OpenPositionsResult.java | // Path: src/main/java/com/github/sbouclier/result/common/OrderDirection.java
// public enum OrderDirection {
//
// BUY("buy"),
// SELL("sell");
//
// private String value;
//
// OrderDirection(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/common/OrderType.java
// public enum OrderType {
// MARKET("market"),
// LIMIT("limit"),
// STOP_LOSS("stop-loss"),
// TAKE_PROFIT("take-profit"),
// STOP_LOSS_PROFIT("stop-loss-profit"),
// STOP_LOSS_PROFIT_LIMIT("stop-loss-profit-limit"),
// STOP_LOSS_LIMIT("stop-loss-limit"),
// TAKE_PROFIT_LIMIT("take-profit-limit"),
// TRAILING_STOP("trailing-stop"),
// TRAILING_STOP_LIMIT("trailing-stop-limit"),
// STOP_LOSS_AND_LIMIT("stop-loss-and-limit"),
// SETTLE_POSITION("settle-position");
//
// private String value;
//
// OrderType(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.sbouclier.result.common.OrderDirection;
import com.github.sbouclier.result.common.OrderType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
import java.util.Map; | package com.github.sbouclier.result;
/**
* Result from getOpenPositions
*
* @author Stéphane Bouclier
*/
public class OpenPositionsResult extends Result<Map<String, OpenPositionsResult.OpenPosition>> {
public static class OpenPosition {
@JsonProperty("ordertxid")
public String orderTransactionId;
@JsonProperty("posstatus")
public String positionStatus;
@JsonProperty("pair")
public String assetPair;
@JsonProperty("time")
public Long tradeTimestamp;
@JsonProperty("type")
public OrderDirection orderDirection;
@JsonProperty("ordertype") | // Path: src/main/java/com/github/sbouclier/result/common/OrderDirection.java
// public enum OrderDirection {
//
// BUY("buy"),
// SELL("sell");
//
// private String value;
//
// OrderDirection(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/common/OrderType.java
// public enum OrderType {
// MARKET("market"),
// LIMIT("limit"),
// STOP_LOSS("stop-loss"),
// TAKE_PROFIT("take-profit"),
// STOP_LOSS_PROFIT("stop-loss-profit"),
// STOP_LOSS_PROFIT_LIMIT("stop-loss-profit-limit"),
// STOP_LOSS_LIMIT("stop-loss-limit"),
// TAKE_PROFIT_LIMIT("take-profit-limit"),
// TRAILING_STOP("trailing-stop"),
// TRAILING_STOP_LIMIT("trailing-stop-limit"),
// STOP_LOSS_AND_LIMIT("stop-loss-and-limit"),
// SETTLE_POSITION("settle-position");
//
// private String value;
//
// OrderType(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
// Path: src/main/java/com/github/sbouclier/result/OpenPositionsResult.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.sbouclier.result.common.OrderDirection;
import com.github.sbouclier.result.common.OrderType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
import java.util.Map;
package com.github.sbouclier.result;
/**
* Result from getOpenPositions
*
* @author Stéphane Bouclier
*/
public class OpenPositionsResult extends Result<Map<String, OpenPositionsResult.OpenPosition>> {
public static class OpenPosition {
@JsonProperty("ordertxid")
public String orderTransactionId;
@JsonProperty("posstatus")
public String positionStatus;
@JsonProperty("pair")
public String assetPair;
@JsonProperty("time")
public Long tradeTimestamp;
@JsonProperty("type")
public OrderDirection orderDirection;
@JsonProperty("ordertype") | public OrderType orderType; |
sbouclier/kraken-java-api-client | src/test/java/com/github/sbouclier/result/RecentSpreadResultTest.java | // Path: src/test/java/com/github/sbouclier/mock/MockInitHelper.java
// public class MockInitHelper {
//
// private MockInitHelper() {
// }
//
// public static RecentTradeResult buildRecentTradeResult() {
// RecentTradeResult mockResult = new RecentTradeResult();
// Map<String, List<RecentTradeResult.RecentTrade>> map = new HashMap<>();
//
// List<RecentTradeResult.RecentTrade> trades = new ArrayList<>();
// RecentTradeResult.RecentTrade trade1 = new RecentTradeResult.RecentTrade();
// trade1.price = BigDecimal.TEN;
// trade1.volume = BigDecimal.ONE;
//
// RecentTradeResult.RecentTrade trade2 = new RecentTradeResult.RecentTrade();
// trade2.price = BigDecimal.valueOf(20);
// trade2.volume = BigDecimal.valueOf(2);
//
// trades.add(trade1);
// trades.add(trade2);
//
// map.put("XXBTZEUR", trades);
// mockResult.setResult(map);
// mockResult.setLastId(123456L);
//
// return mockResult;
// }
//
// public static RecentSpreadResult buildRecentSpreadResult() {
// RecentSpreadResult mockResult = new RecentSpreadResult();
// Map<String, List<RecentSpreadResult.Spread>> map = new HashMap<>();
//
// List<RecentSpreadResult.Spread> spreads = new ArrayList<>();
// RecentSpreadResult.Spread spread1 = new RecentSpreadResult.Spread(1, BigDecimal.valueOf(10), BigDecimal.valueOf(11));
// RecentSpreadResult.Spread spread2 = new RecentSpreadResult.Spread(2, BigDecimal.valueOf(20), BigDecimal.valueOf(21));
//
// spreads.add(spread1);
// spreads.add(spread2);
//
// map.put("XXBTZEUR", spreads);
// mockResult.setResult(map);
// mockResult.setLastId(123456L);
//
// return mockResult;
// }
//
// public static OHLCResult buildOHLCResult() {
// OHLCResult mockResult = new OHLCResult();
// Map<String, List<OHLCResult.OHLC>> map = new HashMap<>();
//
// List<OHLCResult.OHLC> ohlcs = new ArrayList<>();
//
// OHLCResult.OHLC ohlc1 = new OHLCResult.OHLC();
// ohlc1.time = 1000;
// ohlc1.low = BigDecimal.valueOf(2000);
// ohlc1.high = BigDecimal.valueOf(2500);
//
// OHLCResult.OHLC ohlc2 = new OHLCResult.OHLC();
// ohlc2.time = 2000;
// ohlc2.low = BigDecimal.valueOf(1800);
// ohlc2.high = BigDecimal.valueOf(2100);
//
// ohlcs.add(ohlc1);
// ohlcs.add(ohlc2);
//
// map.put("XXBTZEUR", ohlcs);
// mockResult.setResult(map);
// mockResult.setLastId(23456L);
//
// return mockResult;
// }
// }
| import com.github.sbouclier.mock.MockInitHelper;
import org.junit.Test;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith;
import static org.junit.Assert.assertTrue; | package com.github.sbouclier.result;
/**
* RecentSpreadResult test
*
* @author Stéphane Bouclier
*/
public class RecentSpreadResultTest {
@Test
public void should_not_access_private_constructor() throws Throwable {
final Constructor<RecentSpreadResult.Spread> constructor = RecentSpreadResult.Spread.class.getDeclaredConstructor();
assertTrue(Modifier.isPrivate(constructor.getModifiers()));
constructor.setAccessible(true);
constructor.newInstance();
}
@Test
public void should_return_to_string() throws IOException {
// Given | // Path: src/test/java/com/github/sbouclier/mock/MockInitHelper.java
// public class MockInitHelper {
//
// private MockInitHelper() {
// }
//
// public static RecentTradeResult buildRecentTradeResult() {
// RecentTradeResult mockResult = new RecentTradeResult();
// Map<String, List<RecentTradeResult.RecentTrade>> map = new HashMap<>();
//
// List<RecentTradeResult.RecentTrade> trades = new ArrayList<>();
// RecentTradeResult.RecentTrade trade1 = new RecentTradeResult.RecentTrade();
// trade1.price = BigDecimal.TEN;
// trade1.volume = BigDecimal.ONE;
//
// RecentTradeResult.RecentTrade trade2 = new RecentTradeResult.RecentTrade();
// trade2.price = BigDecimal.valueOf(20);
// trade2.volume = BigDecimal.valueOf(2);
//
// trades.add(trade1);
// trades.add(trade2);
//
// map.put("XXBTZEUR", trades);
// mockResult.setResult(map);
// mockResult.setLastId(123456L);
//
// return mockResult;
// }
//
// public static RecentSpreadResult buildRecentSpreadResult() {
// RecentSpreadResult mockResult = new RecentSpreadResult();
// Map<String, List<RecentSpreadResult.Spread>> map = new HashMap<>();
//
// List<RecentSpreadResult.Spread> spreads = new ArrayList<>();
// RecentSpreadResult.Spread spread1 = new RecentSpreadResult.Spread(1, BigDecimal.valueOf(10), BigDecimal.valueOf(11));
// RecentSpreadResult.Spread spread2 = new RecentSpreadResult.Spread(2, BigDecimal.valueOf(20), BigDecimal.valueOf(21));
//
// spreads.add(spread1);
// spreads.add(spread2);
//
// map.put("XXBTZEUR", spreads);
// mockResult.setResult(map);
// mockResult.setLastId(123456L);
//
// return mockResult;
// }
//
// public static OHLCResult buildOHLCResult() {
// OHLCResult mockResult = new OHLCResult();
// Map<String, List<OHLCResult.OHLC>> map = new HashMap<>();
//
// List<OHLCResult.OHLC> ohlcs = new ArrayList<>();
//
// OHLCResult.OHLC ohlc1 = new OHLCResult.OHLC();
// ohlc1.time = 1000;
// ohlc1.low = BigDecimal.valueOf(2000);
// ohlc1.high = BigDecimal.valueOf(2500);
//
// OHLCResult.OHLC ohlc2 = new OHLCResult.OHLC();
// ohlc2.time = 2000;
// ohlc2.low = BigDecimal.valueOf(1800);
// ohlc2.high = BigDecimal.valueOf(2100);
//
// ohlcs.add(ohlc1);
// ohlcs.add(ohlc2);
//
// map.put("XXBTZEUR", ohlcs);
// mockResult.setResult(map);
// mockResult.setLastId(23456L);
//
// return mockResult;
// }
// }
// Path: src/test/java/com/github/sbouclier/result/RecentSpreadResultTest.java
import com.github.sbouclier.mock.MockInitHelper;
import org.junit.Test;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith;
import static org.junit.Assert.assertTrue;
package com.github.sbouclier.result;
/**
* RecentSpreadResult test
*
* @author Stéphane Bouclier
*/
public class RecentSpreadResultTest {
@Test
public void should_not_access_private_constructor() throws Throwable {
final Constructor<RecentSpreadResult.Spread> constructor = RecentSpreadResult.Spread.class.getDeclaredConstructor();
assertTrue(Modifier.isPrivate(constructor.getModifiers()));
constructor.setAccessible(true);
constructor.newInstance();
}
@Test
public void should_return_to_string() throws IOException {
// Given | RecentSpreadResult mockResult = MockInitHelper.buildRecentSpreadResult(); |
sbouclier/kraken-java-api-client | src/test/java/com/github/sbouclier/result/LedgersInformationResultTest.java | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith; | package com.github.sbouclier.result;
/**
* LedgersInformationResult test
*
* @author Stéphane Bouclier
*/
public class LedgersInformationResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
// Path: src/test/java/com/github/sbouclier/result/LedgersInformationResultTest.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith;
package com.github.sbouclier.result;
/**
* LedgersInformationResult test
*
* @author Stéphane Bouclier
*/
public class LedgersInformationResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | final String jsonResult = StreamUtils.getResourceAsString(this.getClass(), "json/ledgers_information.mock.json"); |
sbouclier/kraken-java-api-client | src/test/java/com/github/sbouclier/mock/MockInitHelper.java | // Path: src/main/java/com/github/sbouclier/result/OHLCResult.java
// public class OHLCResult extends ResultWithLastId<Map<String, List<OHLCResult.OHLC>>> {
//
// @JsonFormat(shape = JsonFormat.Shape.ARRAY)
// @JsonPropertyOrder({"time", "open", "high", "low", "close", "vwap", "volume", "count"})
// public static class OHLC {
// public Integer time;
// public BigDecimal open;
// public BigDecimal high;
// public BigDecimal low;
// public BigDecimal close;
// public BigDecimal vwap;
// public BigDecimal volume;
// public Integer count;
//
// @Override
// public String toString() {
// return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
// .append("time", time)
// .append("open", open)
// .append("low", low)
// .append("close", close)
// .append("vwap", vwap)
// .append("volume", volume)
// .append("count", count)
// .toString();
// }
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/RecentSpreadResult.java
// public class RecentSpreadResult extends ResultWithLastId<Map<String, List<RecentSpreadResult.Spread>>> {
//
// @JsonFormat(shape = JsonFormat.Shape.ARRAY)
// @JsonPropertyOrder({"time", "bid", "ask"})
// public static class Spread {
// public Integer time;
// public BigDecimal bid;
// public BigDecimal ask;
//
// private Spread() {}
//
// public Spread(Integer time, BigDecimal bid, BigDecimal ask) {
// this.time = time;
// this.bid = bid;
// this.ask = ask;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
// .append("time", time)
// .append("bid", bid)
// .append("ask", ask)
// .toString();
// }
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/RecentTradeResult.java
// public class RecentTradeResult extends ResultWithLastId<Map<String, List<RecentTradeResult.RecentTrade>>> {
//
// @JsonFormat(shape = JsonFormat.Shape.ARRAY)
// @JsonPropertyOrder({"price", "volume", "time", "buySell", "marketLimit", "miscellaneous"})
// public static class RecentTrade {
// public BigDecimal price;
// public BigDecimal volume;
// public BigDecimal time;
//
// public Object buySell;
// public String marketLimit;
// public String miscellaneous;
//
// @Override
// public String toString() {
// return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
// .append("price", price)
// .append("volume", volume)
// .append("time", time)
// .append("buySell", buySell)
// .append("marketLimit", marketLimit)
// .append("miscellaneous", miscellaneous)
// .toString();
// }
// }
// }
| import com.github.sbouclier.result.OHLCResult;
import com.github.sbouclier.result.RecentSpreadResult;
import com.github.sbouclier.result.RecentTradeResult;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | package com.github.sbouclier.mock;
/**
* Helper for building {@link com.github.sbouclier.result.Result} mocks
*
* @author Stéphane Bouclier
*/
public class MockInitHelper {
private MockInitHelper() {
}
| // Path: src/main/java/com/github/sbouclier/result/OHLCResult.java
// public class OHLCResult extends ResultWithLastId<Map<String, List<OHLCResult.OHLC>>> {
//
// @JsonFormat(shape = JsonFormat.Shape.ARRAY)
// @JsonPropertyOrder({"time", "open", "high", "low", "close", "vwap", "volume", "count"})
// public static class OHLC {
// public Integer time;
// public BigDecimal open;
// public BigDecimal high;
// public BigDecimal low;
// public BigDecimal close;
// public BigDecimal vwap;
// public BigDecimal volume;
// public Integer count;
//
// @Override
// public String toString() {
// return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
// .append("time", time)
// .append("open", open)
// .append("low", low)
// .append("close", close)
// .append("vwap", vwap)
// .append("volume", volume)
// .append("count", count)
// .toString();
// }
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/RecentSpreadResult.java
// public class RecentSpreadResult extends ResultWithLastId<Map<String, List<RecentSpreadResult.Spread>>> {
//
// @JsonFormat(shape = JsonFormat.Shape.ARRAY)
// @JsonPropertyOrder({"time", "bid", "ask"})
// public static class Spread {
// public Integer time;
// public BigDecimal bid;
// public BigDecimal ask;
//
// private Spread() {}
//
// public Spread(Integer time, BigDecimal bid, BigDecimal ask) {
// this.time = time;
// this.bid = bid;
// this.ask = ask;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
// .append("time", time)
// .append("bid", bid)
// .append("ask", ask)
// .toString();
// }
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/RecentTradeResult.java
// public class RecentTradeResult extends ResultWithLastId<Map<String, List<RecentTradeResult.RecentTrade>>> {
//
// @JsonFormat(shape = JsonFormat.Shape.ARRAY)
// @JsonPropertyOrder({"price", "volume", "time", "buySell", "marketLimit", "miscellaneous"})
// public static class RecentTrade {
// public BigDecimal price;
// public BigDecimal volume;
// public BigDecimal time;
//
// public Object buySell;
// public String marketLimit;
// public String miscellaneous;
//
// @Override
// public String toString() {
// return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
// .append("price", price)
// .append("volume", volume)
// .append("time", time)
// .append("buySell", buySell)
// .append("marketLimit", marketLimit)
// .append("miscellaneous", miscellaneous)
// .toString();
// }
// }
// }
// Path: src/test/java/com/github/sbouclier/mock/MockInitHelper.java
import com.github.sbouclier.result.OHLCResult;
import com.github.sbouclier.result.RecentSpreadResult;
import com.github.sbouclier.result.RecentTradeResult;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
package com.github.sbouclier.mock;
/**
* Helper for building {@link com.github.sbouclier.result.Result} mocks
*
* @author Stéphane Bouclier
*/
public class MockInitHelper {
private MockInitHelper() {
}
| public static RecentTradeResult buildRecentTradeResult() { |
sbouclier/kraken-java-api-client | src/test/java/com/github/sbouclier/mock/MockInitHelper.java | // Path: src/main/java/com/github/sbouclier/result/OHLCResult.java
// public class OHLCResult extends ResultWithLastId<Map<String, List<OHLCResult.OHLC>>> {
//
// @JsonFormat(shape = JsonFormat.Shape.ARRAY)
// @JsonPropertyOrder({"time", "open", "high", "low", "close", "vwap", "volume", "count"})
// public static class OHLC {
// public Integer time;
// public BigDecimal open;
// public BigDecimal high;
// public BigDecimal low;
// public BigDecimal close;
// public BigDecimal vwap;
// public BigDecimal volume;
// public Integer count;
//
// @Override
// public String toString() {
// return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
// .append("time", time)
// .append("open", open)
// .append("low", low)
// .append("close", close)
// .append("vwap", vwap)
// .append("volume", volume)
// .append("count", count)
// .toString();
// }
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/RecentSpreadResult.java
// public class RecentSpreadResult extends ResultWithLastId<Map<String, List<RecentSpreadResult.Spread>>> {
//
// @JsonFormat(shape = JsonFormat.Shape.ARRAY)
// @JsonPropertyOrder({"time", "bid", "ask"})
// public static class Spread {
// public Integer time;
// public BigDecimal bid;
// public BigDecimal ask;
//
// private Spread() {}
//
// public Spread(Integer time, BigDecimal bid, BigDecimal ask) {
// this.time = time;
// this.bid = bid;
// this.ask = ask;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
// .append("time", time)
// .append("bid", bid)
// .append("ask", ask)
// .toString();
// }
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/RecentTradeResult.java
// public class RecentTradeResult extends ResultWithLastId<Map<String, List<RecentTradeResult.RecentTrade>>> {
//
// @JsonFormat(shape = JsonFormat.Shape.ARRAY)
// @JsonPropertyOrder({"price", "volume", "time", "buySell", "marketLimit", "miscellaneous"})
// public static class RecentTrade {
// public BigDecimal price;
// public BigDecimal volume;
// public BigDecimal time;
//
// public Object buySell;
// public String marketLimit;
// public String miscellaneous;
//
// @Override
// public String toString() {
// return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
// .append("price", price)
// .append("volume", volume)
// .append("time", time)
// .append("buySell", buySell)
// .append("marketLimit", marketLimit)
// .append("miscellaneous", miscellaneous)
// .toString();
// }
// }
// }
| import com.github.sbouclier.result.OHLCResult;
import com.github.sbouclier.result.RecentSpreadResult;
import com.github.sbouclier.result.RecentTradeResult;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | package com.github.sbouclier.mock;
/**
* Helper for building {@link com.github.sbouclier.result.Result} mocks
*
* @author Stéphane Bouclier
*/
public class MockInitHelper {
private MockInitHelper() {
}
public static RecentTradeResult buildRecentTradeResult() {
RecentTradeResult mockResult = new RecentTradeResult();
Map<String, List<RecentTradeResult.RecentTrade>> map = new HashMap<>();
List<RecentTradeResult.RecentTrade> trades = new ArrayList<>();
RecentTradeResult.RecentTrade trade1 = new RecentTradeResult.RecentTrade();
trade1.price = BigDecimal.TEN;
trade1.volume = BigDecimal.ONE;
RecentTradeResult.RecentTrade trade2 = new RecentTradeResult.RecentTrade();
trade2.price = BigDecimal.valueOf(20);
trade2.volume = BigDecimal.valueOf(2);
trades.add(trade1);
trades.add(trade2);
map.put("XXBTZEUR", trades);
mockResult.setResult(map);
mockResult.setLastId(123456L);
return mockResult;
}
| // Path: src/main/java/com/github/sbouclier/result/OHLCResult.java
// public class OHLCResult extends ResultWithLastId<Map<String, List<OHLCResult.OHLC>>> {
//
// @JsonFormat(shape = JsonFormat.Shape.ARRAY)
// @JsonPropertyOrder({"time", "open", "high", "low", "close", "vwap", "volume", "count"})
// public static class OHLC {
// public Integer time;
// public BigDecimal open;
// public BigDecimal high;
// public BigDecimal low;
// public BigDecimal close;
// public BigDecimal vwap;
// public BigDecimal volume;
// public Integer count;
//
// @Override
// public String toString() {
// return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
// .append("time", time)
// .append("open", open)
// .append("low", low)
// .append("close", close)
// .append("vwap", vwap)
// .append("volume", volume)
// .append("count", count)
// .toString();
// }
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/RecentSpreadResult.java
// public class RecentSpreadResult extends ResultWithLastId<Map<String, List<RecentSpreadResult.Spread>>> {
//
// @JsonFormat(shape = JsonFormat.Shape.ARRAY)
// @JsonPropertyOrder({"time", "bid", "ask"})
// public static class Spread {
// public Integer time;
// public BigDecimal bid;
// public BigDecimal ask;
//
// private Spread() {}
//
// public Spread(Integer time, BigDecimal bid, BigDecimal ask) {
// this.time = time;
// this.bid = bid;
// this.ask = ask;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
// .append("time", time)
// .append("bid", bid)
// .append("ask", ask)
// .toString();
// }
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/RecentTradeResult.java
// public class RecentTradeResult extends ResultWithLastId<Map<String, List<RecentTradeResult.RecentTrade>>> {
//
// @JsonFormat(shape = JsonFormat.Shape.ARRAY)
// @JsonPropertyOrder({"price", "volume", "time", "buySell", "marketLimit", "miscellaneous"})
// public static class RecentTrade {
// public BigDecimal price;
// public BigDecimal volume;
// public BigDecimal time;
//
// public Object buySell;
// public String marketLimit;
// public String miscellaneous;
//
// @Override
// public String toString() {
// return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
// .append("price", price)
// .append("volume", volume)
// .append("time", time)
// .append("buySell", buySell)
// .append("marketLimit", marketLimit)
// .append("miscellaneous", miscellaneous)
// .toString();
// }
// }
// }
// Path: src/test/java/com/github/sbouclier/mock/MockInitHelper.java
import com.github.sbouclier.result.OHLCResult;
import com.github.sbouclier.result.RecentSpreadResult;
import com.github.sbouclier.result.RecentTradeResult;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
package com.github.sbouclier.mock;
/**
* Helper for building {@link com.github.sbouclier.result.Result} mocks
*
* @author Stéphane Bouclier
*/
public class MockInitHelper {
private MockInitHelper() {
}
public static RecentTradeResult buildRecentTradeResult() {
RecentTradeResult mockResult = new RecentTradeResult();
Map<String, List<RecentTradeResult.RecentTrade>> map = new HashMap<>();
List<RecentTradeResult.RecentTrade> trades = new ArrayList<>();
RecentTradeResult.RecentTrade trade1 = new RecentTradeResult.RecentTrade();
trade1.price = BigDecimal.TEN;
trade1.volume = BigDecimal.ONE;
RecentTradeResult.RecentTrade trade2 = new RecentTradeResult.RecentTrade();
trade2.price = BigDecimal.valueOf(20);
trade2.volume = BigDecimal.valueOf(2);
trades.add(trade1);
trades.add(trade2);
map.put("XXBTZEUR", trades);
mockResult.setResult(map);
mockResult.setLastId(123456L);
return mockResult;
}
| public static RecentSpreadResult buildRecentSpreadResult() { |
sbouclier/kraken-java-api-client | src/test/java/com/github/sbouclier/mock/MockInitHelper.java | // Path: src/main/java/com/github/sbouclier/result/OHLCResult.java
// public class OHLCResult extends ResultWithLastId<Map<String, List<OHLCResult.OHLC>>> {
//
// @JsonFormat(shape = JsonFormat.Shape.ARRAY)
// @JsonPropertyOrder({"time", "open", "high", "low", "close", "vwap", "volume", "count"})
// public static class OHLC {
// public Integer time;
// public BigDecimal open;
// public BigDecimal high;
// public BigDecimal low;
// public BigDecimal close;
// public BigDecimal vwap;
// public BigDecimal volume;
// public Integer count;
//
// @Override
// public String toString() {
// return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
// .append("time", time)
// .append("open", open)
// .append("low", low)
// .append("close", close)
// .append("vwap", vwap)
// .append("volume", volume)
// .append("count", count)
// .toString();
// }
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/RecentSpreadResult.java
// public class RecentSpreadResult extends ResultWithLastId<Map<String, List<RecentSpreadResult.Spread>>> {
//
// @JsonFormat(shape = JsonFormat.Shape.ARRAY)
// @JsonPropertyOrder({"time", "bid", "ask"})
// public static class Spread {
// public Integer time;
// public BigDecimal bid;
// public BigDecimal ask;
//
// private Spread() {}
//
// public Spread(Integer time, BigDecimal bid, BigDecimal ask) {
// this.time = time;
// this.bid = bid;
// this.ask = ask;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
// .append("time", time)
// .append("bid", bid)
// .append("ask", ask)
// .toString();
// }
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/RecentTradeResult.java
// public class RecentTradeResult extends ResultWithLastId<Map<String, List<RecentTradeResult.RecentTrade>>> {
//
// @JsonFormat(shape = JsonFormat.Shape.ARRAY)
// @JsonPropertyOrder({"price", "volume", "time", "buySell", "marketLimit", "miscellaneous"})
// public static class RecentTrade {
// public BigDecimal price;
// public BigDecimal volume;
// public BigDecimal time;
//
// public Object buySell;
// public String marketLimit;
// public String miscellaneous;
//
// @Override
// public String toString() {
// return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
// .append("price", price)
// .append("volume", volume)
// .append("time", time)
// .append("buySell", buySell)
// .append("marketLimit", marketLimit)
// .append("miscellaneous", miscellaneous)
// .toString();
// }
// }
// }
| import com.github.sbouclier.result.OHLCResult;
import com.github.sbouclier.result.RecentSpreadResult;
import com.github.sbouclier.result.RecentTradeResult;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | trade2.volume = BigDecimal.valueOf(2);
trades.add(trade1);
trades.add(trade2);
map.put("XXBTZEUR", trades);
mockResult.setResult(map);
mockResult.setLastId(123456L);
return mockResult;
}
public static RecentSpreadResult buildRecentSpreadResult() {
RecentSpreadResult mockResult = new RecentSpreadResult();
Map<String, List<RecentSpreadResult.Spread>> map = new HashMap<>();
List<RecentSpreadResult.Spread> spreads = new ArrayList<>();
RecentSpreadResult.Spread spread1 = new RecentSpreadResult.Spread(1, BigDecimal.valueOf(10), BigDecimal.valueOf(11));
RecentSpreadResult.Spread spread2 = new RecentSpreadResult.Spread(2, BigDecimal.valueOf(20), BigDecimal.valueOf(21));
spreads.add(spread1);
spreads.add(spread2);
map.put("XXBTZEUR", spreads);
mockResult.setResult(map);
mockResult.setLastId(123456L);
return mockResult;
}
| // Path: src/main/java/com/github/sbouclier/result/OHLCResult.java
// public class OHLCResult extends ResultWithLastId<Map<String, List<OHLCResult.OHLC>>> {
//
// @JsonFormat(shape = JsonFormat.Shape.ARRAY)
// @JsonPropertyOrder({"time", "open", "high", "low", "close", "vwap", "volume", "count"})
// public static class OHLC {
// public Integer time;
// public BigDecimal open;
// public BigDecimal high;
// public BigDecimal low;
// public BigDecimal close;
// public BigDecimal vwap;
// public BigDecimal volume;
// public Integer count;
//
// @Override
// public String toString() {
// return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
// .append("time", time)
// .append("open", open)
// .append("low", low)
// .append("close", close)
// .append("vwap", vwap)
// .append("volume", volume)
// .append("count", count)
// .toString();
// }
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/RecentSpreadResult.java
// public class RecentSpreadResult extends ResultWithLastId<Map<String, List<RecentSpreadResult.Spread>>> {
//
// @JsonFormat(shape = JsonFormat.Shape.ARRAY)
// @JsonPropertyOrder({"time", "bid", "ask"})
// public static class Spread {
// public Integer time;
// public BigDecimal bid;
// public BigDecimal ask;
//
// private Spread() {}
//
// public Spread(Integer time, BigDecimal bid, BigDecimal ask) {
// this.time = time;
// this.bid = bid;
// this.ask = ask;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
// .append("time", time)
// .append("bid", bid)
// .append("ask", ask)
// .toString();
// }
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/RecentTradeResult.java
// public class RecentTradeResult extends ResultWithLastId<Map<String, List<RecentTradeResult.RecentTrade>>> {
//
// @JsonFormat(shape = JsonFormat.Shape.ARRAY)
// @JsonPropertyOrder({"price", "volume", "time", "buySell", "marketLimit", "miscellaneous"})
// public static class RecentTrade {
// public BigDecimal price;
// public BigDecimal volume;
// public BigDecimal time;
//
// public Object buySell;
// public String marketLimit;
// public String miscellaneous;
//
// @Override
// public String toString() {
// return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
// .append("price", price)
// .append("volume", volume)
// .append("time", time)
// .append("buySell", buySell)
// .append("marketLimit", marketLimit)
// .append("miscellaneous", miscellaneous)
// .toString();
// }
// }
// }
// Path: src/test/java/com/github/sbouclier/mock/MockInitHelper.java
import com.github.sbouclier.result.OHLCResult;
import com.github.sbouclier.result.RecentSpreadResult;
import com.github.sbouclier.result.RecentTradeResult;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
trade2.volume = BigDecimal.valueOf(2);
trades.add(trade1);
trades.add(trade2);
map.put("XXBTZEUR", trades);
mockResult.setResult(map);
mockResult.setLastId(123456L);
return mockResult;
}
public static RecentSpreadResult buildRecentSpreadResult() {
RecentSpreadResult mockResult = new RecentSpreadResult();
Map<String, List<RecentSpreadResult.Spread>> map = new HashMap<>();
List<RecentSpreadResult.Spread> spreads = new ArrayList<>();
RecentSpreadResult.Spread spread1 = new RecentSpreadResult.Spread(1, BigDecimal.valueOf(10), BigDecimal.valueOf(11));
RecentSpreadResult.Spread spread2 = new RecentSpreadResult.Spread(2, BigDecimal.valueOf(20), BigDecimal.valueOf(21));
spreads.add(spread1);
spreads.add(spread2);
map.put("XXBTZEUR", spreads);
mockResult.setResult(map);
mockResult.setLastId(123456L);
return mockResult;
}
| public static OHLCResult buildOHLCResult() { |
sbouclier/kraken-java-api-client | src/main/java/com/github/sbouclier/result/OrdersInformationResult.java | // Path: src/main/java/com/github/sbouclier/result/common/OrderDirection.java
// public enum OrderDirection {
//
// BUY("buy"),
// SELL("sell");
//
// private String value;
//
// OrderDirection(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/common/OrderType.java
// public enum OrderType {
// MARKET("market"),
// LIMIT("limit"),
// STOP_LOSS("stop-loss"),
// TAKE_PROFIT("take-profit"),
// STOP_LOSS_PROFIT("stop-loss-profit"),
// STOP_LOSS_PROFIT_LIMIT("stop-loss-profit-limit"),
// STOP_LOSS_LIMIT("stop-loss-limit"),
// TAKE_PROFIT_LIMIT("take-profit-limit"),
// TRAILING_STOP("trailing-stop"),
// TRAILING_STOP_LIMIT("trailing-stop-limit"),
// STOP_LOSS_AND_LIMIT("stop-loss-and-limit"),
// SETTLE_POSITION("settle-position");
//
// private String value;
//
// OrderType(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.github.sbouclier.result.common.OrderDirection;
import com.github.sbouclier.result.common.OrderType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
import java.util.Map; | package com.github.sbouclier.result;
/**
* Result from getOrdersInformation
*
* @author Stéphane Bouclier
*/
public class OrdersInformationResult extends Result<Map<String, OrdersInformationResult.OrderInfo>> {
public static class OrderInfo {
public enum Status {
PENDING("pending"),
OPEN("open"),
CLOSED("closed"),
CANCELED("canceled"),
EXPIRED("expired");
private String value;
Status(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
}
public static class Description {
@JsonProperty("pair")
public String assetPair;
@JsonProperty("type") | // Path: src/main/java/com/github/sbouclier/result/common/OrderDirection.java
// public enum OrderDirection {
//
// BUY("buy"),
// SELL("sell");
//
// private String value;
//
// OrderDirection(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/common/OrderType.java
// public enum OrderType {
// MARKET("market"),
// LIMIT("limit"),
// STOP_LOSS("stop-loss"),
// TAKE_PROFIT("take-profit"),
// STOP_LOSS_PROFIT("stop-loss-profit"),
// STOP_LOSS_PROFIT_LIMIT("stop-loss-profit-limit"),
// STOP_LOSS_LIMIT("stop-loss-limit"),
// TAKE_PROFIT_LIMIT("take-profit-limit"),
// TRAILING_STOP("trailing-stop"),
// TRAILING_STOP_LIMIT("trailing-stop-limit"),
// STOP_LOSS_AND_LIMIT("stop-loss-and-limit"),
// SETTLE_POSITION("settle-position");
//
// private String value;
//
// OrderType(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
// Path: src/main/java/com/github/sbouclier/result/OrdersInformationResult.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.github.sbouclier.result.common.OrderDirection;
import com.github.sbouclier.result.common.OrderType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
import java.util.Map;
package com.github.sbouclier.result;
/**
* Result from getOrdersInformation
*
* @author Stéphane Bouclier
*/
public class OrdersInformationResult extends Result<Map<String, OrdersInformationResult.OrderInfo>> {
public static class OrderInfo {
public enum Status {
PENDING("pending"),
OPEN("open"),
CLOSED("closed"),
CANCELED("canceled"),
EXPIRED("expired");
private String value;
Status(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
}
public static class Description {
@JsonProperty("pair")
public String assetPair;
@JsonProperty("type") | public OrderDirection orderDirection; |
sbouclier/kraken-java-api-client | src/main/java/com/github/sbouclier/result/OrdersInformationResult.java | // Path: src/main/java/com/github/sbouclier/result/common/OrderDirection.java
// public enum OrderDirection {
//
// BUY("buy"),
// SELL("sell");
//
// private String value;
//
// OrderDirection(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/common/OrderType.java
// public enum OrderType {
// MARKET("market"),
// LIMIT("limit"),
// STOP_LOSS("stop-loss"),
// TAKE_PROFIT("take-profit"),
// STOP_LOSS_PROFIT("stop-loss-profit"),
// STOP_LOSS_PROFIT_LIMIT("stop-loss-profit-limit"),
// STOP_LOSS_LIMIT("stop-loss-limit"),
// TAKE_PROFIT_LIMIT("take-profit-limit"),
// TRAILING_STOP("trailing-stop"),
// TRAILING_STOP_LIMIT("trailing-stop-limit"),
// STOP_LOSS_AND_LIMIT("stop-loss-and-limit"),
// SETTLE_POSITION("settle-position");
//
// private String value;
//
// OrderType(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.github.sbouclier.result.common.OrderDirection;
import com.github.sbouclier.result.common.OrderType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
import java.util.Map; | package com.github.sbouclier.result;
/**
* Result from getOrdersInformation
*
* @author Stéphane Bouclier
*/
public class OrdersInformationResult extends Result<Map<String, OrdersInformationResult.OrderInfo>> {
public static class OrderInfo {
public enum Status {
PENDING("pending"),
OPEN("open"),
CLOSED("closed"),
CANCELED("canceled"),
EXPIRED("expired");
private String value;
Status(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
}
public static class Description {
@JsonProperty("pair")
public String assetPair;
@JsonProperty("type")
public OrderDirection orderDirection;
@JsonProperty("ordertype") | // Path: src/main/java/com/github/sbouclier/result/common/OrderDirection.java
// public enum OrderDirection {
//
// BUY("buy"),
// SELL("sell");
//
// private String value;
//
// OrderDirection(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/common/OrderType.java
// public enum OrderType {
// MARKET("market"),
// LIMIT("limit"),
// STOP_LOSS("stop-loss"),
// TAKE_PROFIT("take-profit"),
// STOP_LOSS_PROFIT("stop-loss-profit"),
// STOP_LOSS_PROFIT_LIMIT("stop-loss-profit-limit"),
// STOP_LOSS_LIMIT("stop-loss-limit"),
// TAKE_PROFIT_LIMIT("take-profit-limit"),
// TRAILING_STOP("trailing-stop"),
// TRAILING_STOP_LIMIT("trailing-stop-limit"),
// STOP_LOSS_AND_LIMIT("stop-loss-and-limit"),
// SETTLE_POSITION("settle-position");
//
// private String value;
//
// OrderType(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
// Path: src/main/java/com/github/sbouclier/result/OrdersInformationResult.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.github.sbouclier.result.common.OrderDirection;
import com.github.sbouclier.result.common.OrderType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
import java.util.Map;
package com.github.sbouclier.result;
/**
* Result from getOrdersInformation
*
* @author Stéphane Bouclier
*/
public class OrdersInformationResult extends Result<Map<String, OrdersInformationResult.OrderInfo>> {
public static class OrderInfo {
public enum Status {
PENDING("pending"),
OPEN("open"),
CLOSED("closed"),
CANCELED("canceled"),
EXPIRED("expired");
private String value;
Status(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
}
public static class Description {
@JsonProperty("pair")
public String assetPair;
@JsonProperty("type")
public OrderDirection orderDirection;
@JsonProperty("ordertype") | public OrderType orderType; |
sbouclier/kraken-java-api-client | src/test/java/com/github/sbouclier/result/LedgersResultTest.java | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith; | package com.github.sbouclier.result;
/**
* LedgersResultTest test
*
* @author Stéphane Bouclier
*/
public class LedgersResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
// Path: src/test/java/com/github/sbouclier/result/LedgersResultTest.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith;
package com.github.sbouclier.result;
/**
* LedgersResultTest test
*
* @author Stéphane Bouclier
*/
public class LedgersResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | final String jsonResult = StreamUtils.getResourceAsString(this.getClass(), "json/ledgers.mock.json"); |
sbouclier/kraken-java-api-client | src/main/java/com/github/sbouclier/HttpApiClientFactory.java | // Path: src/main/java/com/github/sbouclier/result/LedgersInformationResult.java
// public class LedgersInformationResult extends Result<LedgersInformationResult.LedgersInformation> {
//
// public static class LedgersInformation {
//
// @JsonProperty("ledger")
// public Map<String, LedgerInformation> ledger;
//
// public Long count;
//
// @Override
// public String toString() {
// return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
// .append("ledger", ledger)
// .append("count", count)
// .toString();
// }
// }
// }
| import com.github.sbouclier.result.*;
import com.github.sbouclier.result.LedgersInformationResult; | case ORDER_BOOK:
return new HttpApiClient<OrderBookResult>();
case RECENT_TRADES:
return new HttpApiClient<RecentTradeResult>();
case RECENT_SPREADS:
return new HttpApiClient<RecentSpreadResult>();
default:
throw new IllegalArgumentException("Unknown Kraken API method");
}
}
public HttpApiClient<? extends Result> getHttpApiClient(String apiKey, String apiSecret, KrakenApiMethod method) {
switch(method) {
case ACCOUNT_BALANCE:
return new HttpApiClient<AccountBalanceResult>(apiKey, apiSecret);
case TRADE_BALANCE:
return new HttpApiClient<TradeBalanceResult>(apiKey, apiSecret);
case OPEN_ORDERS:
return new HttpApiClient<OpenOrdersResult>(apiKey, apiSecret);
case CLOSED_ORDERS:
return new HttpApiClient<ClosedOrdersResult>(apiKey, apiSecret);
case ORDERS_INFORMATION:
return new HttpApiClient<OrdersInformationResult>(apiKey, apiSecret);
case TRADES_HISTORY:
return new HttpApiClient<TradesHistoryResult>(apiKey, apiSecret);
case TRADES_INFORMATION:
return new HttpApiClient<TradesInformationResult>(apiKey, apiSecret);
case OPEN_POSITIONS:
return new HttpApiClient<OpenPositionsResult>(apiKey, apiSecret);
case LEDGERS_INFORMATION: | // Path: src/main/java/com/github/sbouclier/result/LedgersInformationResult.java
// public class LedgersInformationResult extends Result<LedgersInformationResult.LedgersInformation> {
//
// public static class LedgersInformation {
//
// @JsonProperty("ledger")
// public Map<String, LedgerInformation> ledger;
//
// public Long count;
//
// @Override
// public String toString() {
// return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
// .append("ledger", ledger)
// .append("count", count)
// .toString();
// }
// }
// }
// Path: src/main/java/com/github/sbouclier/HttpApiClientFactory.java
import com.github.sbouclier.result.*;
import com.github.sbouclier.result.LedgersInformationResult;
case ORDER_BOOK:
return new HttpApiClient<OrderBookResult>();
case RECENT_TRADES:
return new HttpApiClient<RecentTradeResult>();
case RECENT_SPREADS:
return new HttpApiClient<RecentSpreadResult>();
default:
throw new IllegalArgumentException("Unknown Kraken API method");
}
}
public HttpApiClient<? extends Result> getHttpApiClient(String apiKey, String apiSecret, KrakenApiMethod method) {
switch(method) {
case ACCOUNT_BALANCE:
return new HttpApiClient<AccountBalanceResult>(apiKey, apiSecret);
case TRADE_BALANCE:
return new HttpApiClient<TradeBalanceResult>(apiKey, apiSecret);
case OPEN_ORDERS:
return new HttpApiClient<OpenOrdersResult>(apiKey, apiSecret);
case CLOSED_ORDERS:
return new HttpApiClient<ClosedOrdersResult>(apiKey, apiSecret);
case ORDERS_INFORMATION:
return new HttpApiClient<OrdersInformationResult>(apiKey, apiSecret);
case TRADES_HISTORY:
return new HttpApiClient<TradesHistoryResult>(apiKey, apiSecret);
case TRADES_INFORMATION:
return new HttpApiClient<TradesInformationResult>(apiKey, apiSecret);
case OPEN_POSITIONS:
return new HttpApiClient<OpenPositionsResult>(apiKey, apiSecret);
case LEDGERS_INFORMATION: | return new HttpApiClient<LedgersInformationResult>(apiKey, apiSecret); |
sbouclier/kraken-java-api-client | src/test/java/com/github/sbouclier/HttpApiClientTest.java | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
| import com.github.sbouclier.result.*;
import com.github.sbouclier.utils.StreamUtils;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*; | package com.github.sbouclier;
/**
* HttpAPIClient test
*
* @author Stéphane Bouclier
*/
public class HttpApiClientTest {
private HttpJsonClient mockHttpJsonClient;
@Before
public void setUp() throws IOException {
mockHttpJsonClient = mock(HttpJsonClient.class);
}
@After
public void tearDown() throws Exception {
verifyNoMoreInteractions(mockHttpJsonClient);
}
@Test
public void should_call_valid_public_method() throws IOException, KrakenApiException {
// Given | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
// Path: src/test/java/com/github/sbouclier/HttpApiClientTest.java
import com.github.sbouclier.result.*;
import com.github.sbouclier.utils.StreamUtils;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
package com.github.sbouclier;
/**
* HttpAPIClient test
*
* @author Stéphane Bouclier
*/
public class HttpApiClientTest {
private HttpJsonClient mockHttpJsonClient;
@Before
public void setUp() throws IOException {
mockHttpJsonClient = mock(HttpJsonClient.class);
}
@After
public void tearDown() throws Exception {
verifyNoMoreInteractions(mockHttpJsonClient);
}
@Test
public void should_call_valid_public_method() throws IOException, KrakenApiException {
// Given | final String mockResponseBody = StreamUtils.getResourceAsString(this.getClass(), "json/server_time.mock.json"); |
sbouclier/kraken-java-api-client | src/test/java/com/github/sbouclier/result/ServerTimeResultTest.java | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith; | package com.github.sbouclier.result;
/**
* ServerTimeResult test
*
* @author Stéphane Bouclier
*/
public class ServerTimeResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
// Path: src/test/java/com/github/sbouclier/result/ServerTimeResultTest.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith;
package com.github.sbouclier.result;
/**
* ServerTimeResult test
*
* @author Stéphane Bouclier
*/
public class ServerTimeResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | final String jsonResult = StreamUtils.getResourceAsString(this.getClass(), "json/server_time.mock.json"); |
sbouclier/kraken-java-api-client | src/test/java/com/github/sbouclier/HttpJsonClientTest.java | // Path: src/test/java/com/github/sbouclier/mock/MockHttpsURLConnection.java
// public class MockHttpsURLConnection extends HttpsURLConnection {
// public MockHttpsURLConnection(URL url) {
// super(url);
// }
//
// @Override
// public String getCipherSuite() {
// return null;
// }
//
// @Override
// public Certificate[] getLocalCertificates() {
// return new Certificate[0];
// }
//
// @Override
// public Certificate[] getServerCertificates() throws SSLPeerUnverifiedException {
// return new Certificate[0];
// }
//
// @Override
// public void disconnect() {
//
// }
//
// @Override
// public boolean usingProxy() {
// return false;
// }
//
// @Override
// public void connect() throws IOException {
//
// }
//
// @Override
// public OutputStream getOutputStream() throws IOException {
// return new OutputStream() {
// @Override
// public void write(int b) throws IOException {
//
// }
// };
// }
//
// @Override
// public InputStream getInputStream() throws IOException {
// return new ByteArrayInputStream("read inputstream".getBytes("UTF-8"));
// }
// }
| import com.github.sbouclier.mock.MockHttpsURLConnection;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.mockito.ArgumentMatchers.any; | package com.github.sbouclier;
/**
* HttpJsonClient test
*
* @author Stéphane Bouclier
*/
public class HttpJsonClientTest {
@Test
public void should_execute_public_query_without_params() throws IOException, KrakenApiException {
// Given
HttpJsonClient spyClient = Mockito.spy(HttpJsonClient.class);
Mockito.doReturn("response").when(spyClient).getPublicJsonResponse(new URL("https://baseUrl/urlMethod?"));
// When
String result = spyClient.executePublicQuery("https://baseUrl", "/urlMethod");
// Then
assertThat(result, equalTo("response"));
}
@Test
public void should_execute_public_query_with_params() throws IOException, KrakenApiException {
// Given
HttpJsonClient spyClient = Mockito.spy(HttpJsonClient.class);
Map<String, String> params = new HashMap<>();
params.put("a", "A");
params.put("b", "B");
params.put("c", "C");
Mockito.doReturn("response").when(spyClient).getPublicJsonResponse(new URL("https://baseUrl/urlMethod?a=A&b=B&c=C&"));
// When
String result = spyClient.executePublicQuery("https://baseUrl", "/urlMethod", params);
// Then
assertThat(result, equalTo("response"));
}
@Test
public void should_execute_public_query_with_empty_params() throws IOException, KrakenApiException {
// Given
HttpJsonClient spyClient = Mockito.spy(HttpJsonClient.class);
Mockito.doReturn("response").when(spyClient).getPublicJsonResponse(new URL("https://baseUrl/urlMethod?"));
// When
String result = spyClient.executePublicQuery("https://baseUrl", "/urlMethod", new HashMap<>());
// Then
assertThat(result, equalTo("response"));
}
@Test
public void should_retrieve_public_json_response() throws IOException, KrakenApiException {
// Given
URL url = null; | // Path: src/test/java/com/github/sbouclier/mock/MockHttpsURLConnection.java
// public class MockHttpsURLConnection extends HttpsURLConnection {
// public MockHttpsURLConnection(URL url) {
// super(url);
// }
//
// @Override
// public String getCipherSuite() {
// return null;
// }
//
// @Override
// public Certificate[] getLocalCertificates() {
// return new Certificate[0];
// }
//
// @Override
// public Certificate[] getServerCertificates() throws SSLPeerUnverifiedException {
// return new Certificate[0];
// }
//
// @Override
// public void disconnect() {
//
// }
//
// @Override
// public boolean usingProxy() {
// return false;
// }
//
// @Override
// public void connect() throws IOException {
//
// }
//
// @Override
// public OutputStream getOutputStream() throws IOException {
// return new OutputStream() {
// @Override
// public void write(int b) throws IOException {
//
// }
// };
// }
//
// @Override
// public InputStream getInputStream() throws IOException {
// return new ByteArrayInputStream("read inputstream".getBytes("UTF-8"));
// }
// }
// Path: src/test/java/com/github/sbouclier/HttpJsonClientTest.java
import com.github.sbouclier.mock.MockHttpsURLConnection;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.mockito.ArgumentMatchers.any;
package com.github.sbouclier;
/**
* HttpJsonClient test
*
* @author Stéphane Bouclier
*/
public class HttpJsonClientTest {
@Test
public void should_execute_public_query_without_params() throws IOException, KrakenApiException {
// Given
HttpJsonClient spyClient = Mockito.spy(HttpJsonClient.class);
Mockito.doReturn("response").when(spyClient).getPublicJsonResponse(new URL("https://baseUrl/urlMethod?"));
// When
String result = spyClient.executePublicQuery("https://baseUrl", "/urlMethod");
// Then
assertThat(result, equalTo("response"));
}
@Test
public void should_execute_public_query_with_params() throws IOException, KrakenApiException {
// Given
HttpJsonClient spyClient = Mockito.spy(HttpJsonClient.class);
Map<String, String> params = new HashMap<>();
params.put("a", "A");
params.put("b", "B");
params.put("c", "C");
Mockito.doReturn("response").when(spyClient).getPublicJsonResponse(new URL("https://baseUrl/urlMethod?a=A&b=B&c=C&"));
// When
String result = spyClient.executePublicQuery("https://baseUrl", "/urlMethod", params);
// Then
assertThat(result, equalTo("response"));
}
@Test
public void should_execute_public_query_with_empty_params() throws IOException, KrakenApiException {
// Given
HttpJsonClient spyClient = Mockito.spy(HttpJsonClient.class);
Mockito.doReturn("response").when(spyClient).getPublicJsonResponse(new URL("https://baseUrl/urlMethod?"));
// When
String result = spyClient.executePublicQuery("https://baseUrl", "/urlMethod", new HashMap<>());
// Then
assertThat(result, equalTo("response"));
}
@Test
public void should_retrieve_public_json_response() throws IOException, KrakenApiException {
// Given
URL url = null; | final MockHttpsURLConnection mockHttpURLConnection = new MockHttpsURLConnection(url); |
sbouclier/kraken-java-api-client | src/test/java/com/github/sbouclier/result/TradeVolumeResultTest.java | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith; | package com.github.sbouclier.result;
/**
* TradeVolumeResult test
*
* @author Stéphane Bouclier
*/
public class TradeVolumeResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
// Path: src/test/java/com/github/sbouclier/result/TradeVolumeResultTest.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith;
package com.github.sbouclier.result;
/**
* TradeVolumeResult test
*
* @author Stéphane Bouclier
*/
public class TradeVolumeResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | final String jsonResult = StreamUtils.getResourceAsString(this.getClass(), "json/trade_volume.mock.json"); |
sbouclier/kraken-java-api-client | src/test/java/com/github/sbouclier/result/TradeBalanceResultTest.java | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith; | package com.github.sbouclier.result;
/**
* TradeBalanceResult test
*
* @author Stéphane Bouclier
*/
public class TradeBalanceResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
// Path: src/test/java/com/github/sbouclier/result/TradeBalanceResultTest.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith;
package com.github.sbouclier.result;
/**
* TradeBalanceResult test
*
* @author Stéphane Bouclier
*/
public class TradeBalanceResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | final String jsonResult = StreamUtils.getResourceAsString(this.getClass(), "json/trade_balance.mock.json"); |
sbouclier/kraken-java-api-client | src/test/java/com/github/sbouclier/result/ClosedOrdersResultTest.java | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith; | package com.github.sbouclier.result;
/**
* ClosedOrdersResult test
*
* @author Stéphane Bouclier
*/
public class ClosedOrdersResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
// Path: src/test/java/com/github/sbouclier/result/ClosedOrdersResultTest.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith;
package com.github.sbouclier.result;
/**
* ClosedOrdersResult test
*
* @author Stéphane Bouclier
*/
public class ClosedOrdersResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | final String jsonResult = StreamUtils.getResourceAsString(this.getClass(), "json/closed_orders.mock.json"); |
sbouclier/kraken-java-api-client | src/test/java/com/github/sbouclier/result/AssetPairsResultTest.java | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; | package com.github.sbouclier.result;
/**
* AssetPairsResult test
*
* @author Stéphane Bouclier
*/
public class AssetPairsResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
// Path: src/test/java/com/github/sbouclier/result/AssetPairsResultTest.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
package com.github.sbouclier.result;
/**
* AssetPairsResult test
*
* @author Stéphane Bouclier
*/
public class AssetPairsResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | final String jsonResult = StreamUtils.getResourceAsString(this.getClass(), "json/asset_pairs.mock.json"); |
sbouclier/kraken-java-api-client | src/test/java/com/github/sbouclier/result/TickerInformationResultTest.java | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith; | package com.github.sbouclier.result;
/**
* TickerInformationResult test
*
* @author Stéphane Bouclier
*/
public class TickerInformationResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
// Path: src/test/java/com/github/sbouclier/result/TickerInformationResultTest.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith;
package com.github.sbouclier.result;
/**
* TickerInformationResult test
*
* @author Stéphane Bouclier
*/
public class TickerInformationResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | final String jsonResult = StreamUtils.getResourceAsString(this.getClass(), "json/ticker_information.mock.json"); |
sbouclier/kraken-java-api-client | src/test/java/com/github/sbouclier/result/OpenOrdersResultTest.java | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith; | package com.github.sbouclier.result;
/**
* OpenOrdersResult test
*
* @author Stéphane Bouclier
*/
public class OpenOrdersResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | // Path: src/main/java/com/github/sbouclier/utils/StreamUtils.java
// public class StreamUtils {
//
// /**
// * Private constructor
// */
// private StreamUtils() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Load a resource as string
// *
// * @param clazz
// * @param path
// * @return string
// * @throws IOException
// */
// public static String getResourceAsString(Class clazz, String path) throws IOException {
// return convert(getResourceAsStream(clazz, path));
// }
//
// /**
// * Load a resource as input stream
// *
// * @param path
// * @return resource as input stream
// */
// public static InputStream getResourceAsStream(Class clazz, String path) {
// return clazz.getClassLoader().getResourceAsStream(path);
// }
//
// /**
// * Convert an input stream to string
// *
// * @param inputStream
// * @return input stream as string
// * @throws IOException
// */
// public static String convert(InputStream inputStream) throws IOException {
// ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// int nRead;
// byte[] data = new byte[1024];
// while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
// buffer.write(data, 0, nRead);
// }
//
// buffer.flush();
// byte[] byteArray = buffer.toByteArray();
//
// return new String(byteArray, StandardCharsets.UTF_8);
// }
// }
// Path: src/test/java/com/github/sbouclier/result/OpenOrdersResultTest.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.sbouclier.utils.StreamUtils;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith;
package com.github.sbouclier.result;
/**
* OpenOrdersResult test
*
* @author Stéphane Bouclier
*/
public class OpenOrdersResultTest {
@Test
public void should_return_to_string() throws IOException {
// Given | final String jsonResult = StreamUtils.getResourceAsString(this.getClass(), "json/open_orders.mock.json"); |
sbouclier/kraken-java-api-client | src/main/java/com/github/sbouclier/result/TradesInformationResult.java | // Path: src/main/java/com/github/sbouclier/result/common/OrderDirection.java
// public enum OrderDirection {
//
// BUY("buy"),
// SELL("sell");
//
// private String value;
//
// OrderDirection(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/common/OrderType.java
// public enum OrderType {
// MARKET("market"),
// LIMIT("limit"),
// STOP_LOSS("stop-loss"),
// TAKE_PROFIT("take-profit"),
// STOP_LOSS_PROFIT("stop-loss-profit"),
// STOP_LOSS_PROFIT_LIMIT("stop-loss-profit-limit"),
// STOP_LOSS_LIMIT("stop-loss-limit"),
// TAKE_PROFIT_LIMIT("take-profit-limit"),
// TRAILING_STOP("trailing-stop"),
// TRAILING_STOP_LIMIT("trailing-stop-limit"),
// STOP_LOSS_AND_LIMIT("stop-loss-and-limit"),
// SETTLE_POSITION("settle-position");
//
// private String value;
//
// OrderType(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.sbouclier.result.common.OrderDirection;
import com.github.sbouclier.result.common.OrderType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
import java.util.Map; | package com.github.sbouclier.result;
/**
* Result from getTradesInformation
*
* @author Stéphane Bouclier
*/
public class TradesInformationResult extends Result<Map<String, TradesInformationResult.TradeInformation>> {
public static class TradeInformation {
@JsonProperty("ordertxid")
public String orderTransactionId;
@JsonProperty("pair")
public String assetPair;
@JsonProperty("time")
public Long tradeTimestamp;
@JsonProperty("type") | // Path: src/main/java/com/github/sbouclier/result/common/OrderDirection.java
// public enum OrderDirection {
//
// BUY("buy"),
// SELL("sell");
//
// private String value;
//
// OrderDirection(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/common/OrderType.java
// public enum OrderType {
// MARKET("market"),
// LIMIT("limit"),
// STOP_LOSS("stop-loss"),
// TAKE_PROFIT("take-profit"),
// STOP_LOSS_PROFIT("stop-loss-profit"),
// STOP_LOSS_PROFIT_LIMIT("stop-loss-profit-limit"),
// STOP_LOSS_LIMIT("stop-loss-limit"),
// TAKE_PROFIT_LIMIT("take-profit-limit"),
// TRAILING_STOP("trailing-stop"),
// TRAILING_STOP_LIMIT("trailing-stop-limit"),
// STOP_LOSS_AND_LIMIT("stop-loss-and-limit"),
// SETTLE_POSITION("settle-position");
//
// private String value;
//
// OrderType(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
// Path: src/main/java/com/github/sbouclier/result/TradesInformationResult.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.sbouclier.result.common.OrderDirection;
import com.github.sbouclier.result.common.OrderType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
import java.util.Map;
package com.github.sbouclier.result;
/**
* Result from getTradesInformation
*
* @author Stéphane Bouclier
*/
public class TradesInformationResult extends Result<Map<String, TradesInformationResult.TradeInformation>> {
public static class TradeInformation {
@JsonProperty("ordertxid")
public String orderTransactionId;
@JsonProperty("pair")
public String assetPair;
@JsonProperty("time")
public Long tradeTimestamp;
@JsonProperty("type") | public OrderDirection orderDirection; |
sbouclier/kraken-java-api-client | src/main/java/com/github/sbouclier/result/TradesInformationResult.java | // Path: src/main/java/com/github/sbouclier/result/common/OrderDirection.java
// public enum OrderDirection {
//
// BUY("buy"),
// SELL("sell");
//
// private String value;
//
// OrderDirection(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/common/OrderType.java
// public enum OrderType {
// MARKET("market"),
// LIMIT("limit"),
// STOP_LOSS("stop-loss"),
// TAKE_PROFIT("take-profit"),
// STOP_LOSS_PROFIT("stop-loss-profit"),
// STOP_LOSS_PROFIT_LIMIT("stop-loss-profit-limit"),
// STOP_LOSS_LIMIT("stop-loss-limit"),
// TAKE_PROFIT_LIMIT("take-profit-limit"),
// TRAILING_STOP("trailing-stop"),
// TRAILING_STOP_LIMIT("trailing-stop-limit"),
// STOP_LOSS_AND_LIMIT("stop-loss-and-limit"),
// SETTLE_POSITION("settle-position");
//
// private String value;
//
// OrderType(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.sbouclier.result.common.OrderDirection;
import com.github.sbouclier.result.common.OrderType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
import java.util.Map; | package com.github.sbouclier.result;
/**
* Result from getTradesInformation
*
* @author Stéphane Bouclier
*/
public class TradesInformationResult extends Result<Map<String, TradesInformationResult.TradeInformation>> {
public static class TradeInformation {
@JsonProperty("ordertxid")
public String orderTransactionId;
@JsonProperty("pair")
public String assetPair;
@JsonProperty("time")
public Long tradeTimestamp;
@JsonProperty("type")
public OrderDirection orderDirection;
@JsonProperty("ordertype") | // Path: src/main/java/com/github/sbouclier/result/common/OrderDirection.java
// public enum OrderDirection {
//
// BUY("buy"),
// SELL("sell");
//
// private String value;
//
// OrderDirection(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/result/common/OrderType.java
// public enum OrderType {
// MARKET("market"),
// LIMIT("limit"),
// STOP_LOSS("stop-loss"),
// TAKE_PROFIT("take-profit"),
// STOP_LOSS_PROFIT("stop-loss-profit"),
// STOP_LOSS_PROFIT_LIMIT("stop-loss-profit-limit"),
// STOP_LOSS_LIMIT("stop-loss-limit"),
// TAKE_PROFIT_LIMIT("take-profit-limit"),
// TRAILING_STOP("trailing-stop"),
// TRAILING_STOP_LIMIT("trailing-stop-limit"),
// STOP_LOSS_AND_LIMIT("stop-loss-and-limit"),
// SETTLE_POSITION("settle-position");
//
// private String value;
//
// OrderType(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
// Path: src/main/java/com/github/sbouclier/result/TradesInformationResult.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.sbouclier.result.common.OrderDirection;
import com.github.sbouclier.result.common.OrderType;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
import java.util.Map;
package com.github.sbouclier.result;
/**
* Result from getTradesInformation
*
* @author Stéphane Bouclier
*/
public class TradesInformationResult extends Result<Map<String, TradesInformationResult.TradeInformation>> {
public static class TradeInformation {
@JsonProperty("ordertxid")
public String orderTransactionId;
@JsonProperty("pair")
public String assetPair;
@JsonProperty("time")
public Long tradeTimestamp;
@JsonProperty("type")
public OrderDirection orderDirection;
@JsonProperty("ordertype") | public OrderType orderType; |
sbouclier/kraken-java-api-client | src/main/java/com/github/sbouclier/KrakenAPIClient.java | // Path: src/main/java/com/github/sbouclier/input/InfoInput.java
// public enum InfoInput {
//
// ALL("info"),
// LEVERAGE("leverage"),
// FEES("fees"),
// MARGIN("margin");
//
// private String value;
//
// InfoInput(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/input/Interval.java
// public enum Interval {
//
// ONE_MINUTE(1),
// FIVE_MINUTES(5),
// FIFTEEN_MINUTES(15),
// THIRTY_MINUTES(30),
// ONE_HOUR(60),
// FOUR_HOURS(240),
// ONE_DAY(1440),
// ONE_WEEK(10080),
// FIFTEEN_DAYS(21600);
//
// private int minutes;
//
// Interval(int minutes) {
// this.minutes = minutes;
// }
//
// public int getMinutes() {
// return minutes;
// }
// }
| import com.github.sbouclier.input.InfoInput;
import com.github.sbouclier.input.Interval;
import com.github.sbouclier.result.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors; | * @throws KrakenApiException
*/
public AssetsInformationResult getAssetsInformation(String... assets) throws KrakenApiException {
HttpApiClient<AssetsInformationResult> client = (HttpApiClient<AssetsInformationResult>) this.clientFactory.getHttpApiClient(KrakenApiMethod.ASSET_INFORMATION);
Map<String, String> params = new HashMap<>();
params.put("asset", String.join(",", assets));
return client.callPublic(BASE_URL, KrakenApiMethod.ASSET_INFORMATION, AssetsInformationResult.class, params);
}
/**
* Get tradable asset pairs
*
* @return asset pairs
* @throws KrakenApiException
*/
public AssetPairsResult getAssetPairs() throws KrakenApiException {
HttpApiClient<AssetPairsResult> client = (HttpApiClient<AssetPairsResult>) this.clientFactory.getHttpApiClient(KrakenApiMethod.ASSET_PAIRS);
return client.callPublic(BASE_URL, KrakenApiMethod.ASSET_PAIRS, AssetPairsResult.class);
}
/**
* Get tradable asset pairs
*
* @param info informations to retrieve
* @param assetPairs asset pairs to retrieve
* @return asset pairs
* @throws KrakenApiException
*/ | // Path: src/main/java/com/github/sbouclier/input/InfoInput.java
// public enum InfoInput {
//
// ALL("info"),
// LEVERAGE("leverage"),
// FEES("fees"),
// MARGIN("margin");
//
// private String value;
//
// InfoInput(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/input/Interval.java
// public enum Interval {
//
// ONE_MINUTE(1),
// FIVE_MINUTES(5),
// FIFTEEN_MINUTES(15),
// THIRTY_MINUTES(30),
// ONE_HOUR(60),
// FOUR_HOURS(240),
// ONE_DAY(1440),
// ONE_WEEK(10080),
// FIFTEEN_DAYS(21600);
//
// private int minutes;
//
// Interval(int minutes) {
// this.minutes = minutes;
// }
//
// public int getMinutes() {
// return minutes;
// }
// }
// Path: src/main/java/com/github/sbouclier/KrakenAPIClient.java
import com.github.sbouclier.input.InfoInput;
import com.github.sbouclier.input.Interval;
import com.github.sbouclier.result.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
* @throws KrakenApiException
*/
public AssetsInformationResult getAssetsInformation(String... assets) throws KrakenApiException {
HttpApiClient<AssetsInformationResult> client = (HttpApiClient<AssetsInformationResult>) this.clientFactory.getHttpApiClient(KrakenApiMethod.ASSET_INFORMATION);
Map<String, String> params = new HashMap<>();
params.put("asset", String.join(",", assets));
return client.callPublic(BASE_URL, KrakenApiMethod.ASSET_INFORMATION, AssetsInformationResult.class, params);
}
/**
* Get tradable asset pairs
*
* @return asset pairs
* @throws KrakenApiException
*/
public AssetPairsResult getAssetPairs() throws KrakenApiException {
HttpApiClient<AssetPairsResult> client = (HttpApiClient<AssetPairsResult>) this.clientFactory.getHttpApiClient(KrakenApiMethod.ASSET_PAIRS);
return client.callPublic(BASE_URL, KrakenApiMethod.ASSET_PAIRS, AssetPairsResult.class);
}
/**
* Get tradable asset pairs
*
* @param info informations to retrieve
* @param assetPairs asset pairs to retrieve
* @return asset pairs
* @throws KrakenApiException
*/ | public AssetPairsResult getAssetPairs(InfoInput info, String... assetPairs) throws KrakenApiException { |
sbouclier/kraken-java-api-client | src/main/java/com/github/sbouclier/KrakenAPIClient.java | // Path: src/main/java/com/github/sbouclier/input/InfoInput.java
// public enum InfoInput {
//
// ALL("info"),
// LEVERAGE("leverage"),
// FEES("fees"),
// MARGIN("margin");
//
// private String value;
//
// InfoInput(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/input/Interval.java
// public enum Interval {
//
// ONE_MINUTE(1),
// FIVE_MINUTES(5),
// FIFTEEN_MINUTES(15),
// THIRTY_MINUTES(30),
// ONE_HOUR(60),
// FOUR_HOURS(240),
// ONE_DAY(1440),
// ONE_WEEK(10080),
// FIFTEEN_DAYS(21600);
//
// private int minutes;
//
// Interval(int minutes) {
// this.minutes = minutes;
// }
//
// public int getMinutes() {
// return minutes;
// }
// }
| import com.github.sbouclier.input.InfoInput;
import com.github.sbouclier.input.Interval;
import com.github.sbouclier.result.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors; |
return client.callPublic(BASE_URL, KrakenApiMethod.ASSET_PAIRS, AssetPairsResult.class, params);
}
/**
* Get ticker information of pairs
*
* @param pairs list of pair
* @return ticker information
* @throws KrakenApiException
*/
public TickerInformationResult getTickerInformation(List<String> pairs) throws KrakenApiException {
HttpApiClient<TickerInformationResult> client = (HttpApiClient<TickerInformationResult>) this.clientFactory.getHttpApiClient(KrakenApiMethod.TICKER_INFORMATION);
Map<String, String> params = new HashMap<>();
params.put("pair", String.join(",", pairs));
return client.callPublic(BASE_URL, KrakenApiMethod.TICKER_INFORMATION, TickerInformationResult.class, params);
}
/**
* Get OHLC data
*
* @param pair currency pair
* @param interval interval of time
* @param since data since given id
* @return data (OHLC + last id)
* @throws KrakenApiException
*/ | // Path: src/main/java/com/github/sbouclier/input/InfoInput.java
// public enum InfoInput {
//
// ALL("info"),
// LEVERAGE("leverage"),
// FEES("fees"),
// MARGIN("margin");
//
// private String value;
//
// InfoInput(String value) {
// this.value = value;
// }
//
// @JsonValue
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/com/github/sbouclier/input/Interval.java
// public enum Interval {
//
// ONE_MINUTE(1),
// FIVE_MINUTES(5),
// FIFTEEN_MINUTES(15),
// THIRTY_MINUTES(30),
// ONE_HOUR(60),
// FOUR_HOURS(240),
// ONE_DAY(1440),
// ONE_WEEK(10080),
// FIFTEEN_DAYS(21600);
//
// private int minutes;
//
// Interval(int minutes) {
// this.minutes = minutes;
// }
//
// public int getMinutes() {
// return minutes;
// }
// }
// Path: src/main/java/com/github/sbouclier/KrakenAPIClient.java
import com.github.sbouclier.input.InfoInput;
import com.github.sbouclier.input.Interval;
import com.github.sbouclier.result.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
return client.callPublic(BASE_URL, KrakenApiMethod.ASSET_PAIRS, AssetPairsResult.class, params);
}
/**
* Get ticker information of pairs
*
* @param pairs list of pair
* @return ticker information
* @throws KrakenApiException
*/
public TickerInformationResult getTickerInformation(List<String> pairs) throws KrakenApiException {
HttpApiClient<TickerInformationResult> client = (HttpApiClient<TickerInformationResult>) this.clientFactory.getHttpApiClient(KrakenApiMethod.TICKER_INFORMATION);
Map<String, String> params = new HashMap<>();
params.put("pair", String.join(",", pairs));
return client.callPublic(BASE_URL, KrakenApiMethod.TICKER_INFORMATION, TickerInformationResult.class, params);
}
/**
* Get OHLC data
*
* @param pair currency pair
* @param interval interval of time
* @param since data since given id
* @return data (OHLC + last id)
* @throws KrakenApiException
*/ | public OHLCResult getOHLC(String pair, Interval interval, Integer since) throws KrakenApiException { |
goerlitz/rdffederator | src/de/uni_koblenz/west/splendid/estimation/AbstractCardinalityEstimator.java | // Path: src/de/uni_koblenz/west/splendid/model/RemoteQuery.java
// public class RemoteQuery extends UnaryTupleOperator {
//
// public RemoteQuery(TupleExpr expr) {
// super(expr);
// }
//
// @Override
// public <X extends Exception> void visit(QueryModelVisitor<X> visitor) throws X {
// visitor.meetOther(this);
// }
//
// public Set<Graph> getSources() {
// StatementPattern p = StatementPatternCollector.process(this).get(0);
// if (p instanceof MappedStatementPattern)
// return ((MappedStatementPattern) p).getSources();
// else
// return null;
// }
//
// }
| import java.util.HashMap;
import java.util.Map;
import org.openrdf.query.algebra.Filter;
import org.openrdf.query.algebra.TupleExpr;
import org.openrdf.query.algebra.UnaryTupleOperator;
import org.openrdf.query.algebra.helpers.QueryModelVisitorBase;
import de.uni_koblenz.west.splendid.model.RemoteQuery; | /*
* This file is part of RDF Federator.
* Copyright 2011 Olaf Goerlitz
*
* RDF Federator is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* RDF Federator 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with RDF Federator. If not, see <http://www.gnu.org/licenses/>.
*
* RDF Federator uses libraries from the OpenRDF Sesame Project licensed
* under the Aduna BSD-style license.
*/
package de.uni_koblenz.west.splendid.estimation;
/**
* @author Olaf Goerlitz
*/
public abstract class AbstractCardinalityEstimator extends QueryModelVisitorBase<RuntimeException> implements ModelEvaluator {
protected Map<TupleExpr, Double> cardIndex = new HashMap<TupleExpr, Double>();
@Override
public Double process(TupleExpr expr) {
synchronized (this) {
expr.visit(this);
return cardIndex.get(expr);
}
}
@Override
public void meet(Filter filter) {
// check cardinality index first
if (getIndexCard(filter) != null)
return;
// TODO: include condition in estimation
// for now use same card as sub expression
filter.getArg().visit(this);
// add same cardinality as filter argument
setIndexCard(filter, getIndexCard(filter.getArg()));
}
@Override
protected void meetUnaryTupleOperator(UnaryTupleOperator node)
throws RuntimeException { | // Path: src/de/uni_koblenz/west/splendid/model/RemoteQuery.java
// public class RemoteQuery extends UnaryTupleOperator {
//
// public RemoteQuery(TupleExpr expr) {
// super(expr);
// }
//
// @Override
// public <X extends Exception> void visit(QueryModelVisitor<X> visitor) throws X {
// visitor.meetOther(this);
// }
//
// public Set<Graph> getSources() {
// StatementPattern p = StatementPatternCollector.process(this).get(0);
// if (p instanceof MappedStatementPattern)
// return ((MappedStatementPattern) p).getSources();
// else
// return null;
// }
//
// }
// Path: src/de/uni_koblenz/west/splendid/estimation/AbstractCardinalityEstimator.java
import java.util.HashMap;
import java.util.Map;
import org.openrdf.query.algebra.Filter;
import org.openrdf.query.algebra.TupleExpr;
import org.openrdf.query.algebra.UnaryTupleOperator;
import org.openrdf.query.algebra.helpers.QueryModelVisitorBase;
import de.uni_koblenz.west.splendid.model.RemoteQuery;
/*
* This file is part of RDF Federator.
* Copyright 2011 Olaf Goerlitz
*
* RDF Federator is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* RDF Federator 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with RDF Federator. If not, see <http://www.gnu.org/licenses/>.
*
* RDF Federator uses libraries from the OpenRDF Sesame Project licensed
* under the Aduna BSD-style license.
*/
package de.uni_koblenz.west.splendid.estimation;
/**
* @author Olaf Goerlitz
*/
public abstract class AbstractCardinalityEstimator extends QueryModelVisitorBase<RuntimeException> implements ModelEvaluator {
protected Map<TupleExpr, Double> cardIndex = new HashMap<TupleExpr, Double>();
@Override
public Double process(TupleExpr expr) {
synchronized (this) {
expr.visit(this);
return cardIndex.get(expr);
}
}
@Override
public void meet(Filter filter) {
// check cardinality index first
if (getIndexCard(filter) != null)
return;
// TODO: include condition in estimation
// for now use same card as sub expression
filter.getArg().visit(this);
// add same cardinality as filter argument
setIndexCard(filter, getIndexCard(filter.getArg()));
}
@Override
protected void meetUnaryTupleOperator(UnaryTupleOperator node)
throws RuntimeException { | if (node instanceof RemoteQuery) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.